Understanding how to monitor a Boolean value that fluctuates in real-time within a three.js

Currently, I am working on developing a 3D 4x4x4 tic tac toe game using three.js. In order to determine the win condition for combinations, I have created a boolean array. With a total of 64 blocks (16*4), I have initialized a boolean array of size 64 with default values set to false. Whenever a user clicks on a block, it dynamically changes the corresponding object to true.

For checking the horizontal win condition, I have implemented the following logic:

var camera, scene, renderer, mesh, material, controls;
var targetList = [];
var targetListBool = new Array(64).fill(false);
console.log(targetListBool);

// Other code segments omitted for brevity 

However, I seem to be facing an issue with the final for loop that checks for horizontal win combinations. The goal is to alert 'win' if there are 4 consecutive horizontal blocks clicked in each plane. It appears that the if statement within the for loop is not properly detecting the changed values from the click events. Any assistance or guidance on resolving this would be greatly appreciated as I am relatively new to three.js and JavaScript. Thank you.

Answer №1

Your strategy for winning involves getting 4 in a row on either the x, y, or z axis. However, the current function only checks the booleans in one direction. To improve efficiency, it is recommended to track the data in a 3 dimensional manner. An example is provided where 4 values are manually set in a row on the z axis for testing purposes.

Although the check process can be enhanced, it is currently kept simple due to the lack of clarity on specific intentions. Consider whether diagonals should also be included in the check.

//Initialize a variable with x, y, z coordinates along with a boolean value set to false.
var locations = {};

for (var x = 1; x <= 4; x++) {
  locations[x] = {};
  for (var y = 1; y <= 4; y++) {
    locations[x][y] = {};
    for (var z = 1; z <= 4; z++) {
      locations[x][y][z] = false;
    }
  }
}

//Set 4 values on the X axis to true for testing
locations[1][2][3] = true;
locations[2][2][3] = true;
locations[3][2][3] = true;
locations[4][2][3] = true;

//Set 4 values on the Z axis to true for testing
locations[1][2][1] = true;
locations[1][2][2] = true;
locations[1][2][3] = true;
locations[1][2][4] = true;


//Check for four in a row - note that this could be optimized further and currently does not account for diagonals
var winX = false;
var winY = false;
var winZ = false;
for (var x = 1; x <= 4; x++) {
  for (var y = 1; y <= 4; y++) {
    for (var z = 1; z <= 4; z++) {
      if(locations[x][y][z]) {
        //check X for current position
        if(locations[1][y][z] && locations[2][y][z] && locations[3][y][z] && locations[4][y][z]) {
          winX = true;
        }
        //check Y for current position
        if(locations[x][1][z] && locations[x][2][z] && locations[x][3][z] && locations[x][4][z]) {
          winY = true;
        }
        //check Z for current position
        if(locations[x][y][1] && locations[x][y][2] && locations[x][y][3] && locations[x][y][4]) {
          winZ = true;
        }
      }
    }
  }
}

//Display the results, where X and Z should return true while Y should return false
console.log("Win X: " + winX);
console.log("Win Y: " + winY);
console.log("Win Z: " + winZ);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Building a collection of class pointers within a hierarchy

In the following hierarchy of classes, how can I create an array of pointers in C++ to store objects from all the classes? B1 B2 \ / C I attempted the following code but it is not working as expected: #include <iostream> using namespac ...

Vue component encounters issue with exporting JavaScript functions

I decided to streamline my code by moving some functions into a JavaScript file like this: [...] function changeToEditView(reportId) { let pathEdit="/edit/"+reportId; this.$router.push({ path: pathEdit, replace: true }); } [...] export {c ...

How can I use AJAX to read an image file and display it on a Canvas?

Is there a way to read an image from my server using Ajax and then display it on Canvas? I am aware that this can be achieved by using normal image tags and canvas draw methods, as shown below: <img id="myImage" src="./ColorTable.PNG" style="display:n ...

Having trouble with the unresponsive sticky top-bar feature in Zurb Foundation 5?

According to the information provided on this website, it is recommended to enclose the top-bar navigation within a div element that has both the class "contain-to-grid" and "sticky". However, I have noticed that while the "contain-to-grid" class exists in ...

The dropdown on my website is malfunctioning

There seems to be an issue with my dropdown button. Previously, it only appeared when clicking on a specific part of the button. I attempted to resolve this problem but unfortunately, the dropdown no longer works at all and I am unable to revert my changes ...

Enhance user experience with a dynamic Bootstrap combo box that updates based on

I am currently facing an issue with the bootstrap combobox plugin. I am having trouble changing the selection and sending that information from the view to the controller. $('#MyCombo').on('change', function () { var data = $(this) ...

Issue with Vue JS: e.preventDefault not functioning correctly when using Axios

I am facing an issue in my Laravel project where I have implemented a method in the Vue instance to validate resource availability upon form submission. The validation is done through an AJAX call using axios, and if any resources are unavailable, I receiv ...

Guide on utilizing getelementsbytagname for retrieving LI values

As I attempt to locate a specific product on amazon.com, my goal is to extract the ASIN for each item. This particular code snippet runs through various search options and retrieves the price of each product from Amazon one by one. However, in addition to ...

The $watch feature in AngularJS does not function properly within a directive when a controller is used to update data

I created a custom directive and also have a controller to bind data to the directive. The data is retrieved from the server and bound to the directive. However, I noticed that the data in the directive on the page does not update when I change the scope ...

Commitment of service within AngularJS controller using the "as" syntax

I'm experiencing an issue with the code snippet below. I prefer using the controller as syntax and assigning data to 'this' instead of $scope. The problem is that in this scenario, when using $scope.user everything works fine, but when tryin ...

Can you please provide a detailed list of all the events that are compatible with the updateOn feature in Angular's ngModelOptions?

The reference documentation notes the following: updateOn: a string that specifies which event should be bound to the input. Multiple events can be set using a space delimited list. There is also a special 'default' event that aligns with the ...

Tips for incorporating PHP $_SESSION data into a JavaScript file

What I've been doing is using $_SESSION['siteRoot'] to store the root address of my website (since it's part of a framework and can vary depending on how the site is accessed). The challenge now is incorporating this value into some of ...

Top scenario and illustration of utilizing clusters in nodejs

I've been exploring the concept of clusters and I'm still a bit unclear about the most effective use-case scenario for them. Can anyone provide an example to help clarify this for me? ...

Initializing start scripts in the package.json file

When launching my react app locally, I need to execute three commands: cd react-web npm run postinstall export REACT_APP_CUSTOMER_ENVIRONMENT=xxx npm start After running these commands, the application server starts on localhost:3000. For the start script ...

JavaScript allows you to set an expiration date for a specific item

I am facing an issue with a form that contains inputs. On clicking the submit button, I want to capture the current time and add 10 hours to it before updating the table cell named expdate. Although I have a function in place for this purpose, it seems to ...

Nodemon has encountered an issue: Unable to listen on port 5000. The address is already in use

During the creation of my project with nodejs and express for the backend, everything was running smoothly. However, whenever I made changes to a file, nodemon would encounter an error preventing the server from restarting: Error: listen EADDRINUSE: addre ...

Press on the div to reveal its content at the clicked position

Hello, I have a query that I need help with. I currently have a basic table with buttons in columns that act as filters. When you click on one of these buttons, it opens up a form. https://i.sstatic.net/nuEpq.png What I am trying to achieve is to make t ...

In Javascript, assign default values to an array and update them with new values upon the click of a

My goal is to create a quiz that populates an array. Initially, the quiz is empty but I aim to assign it a default value. This serves as my question navigation: /** * * @param {int} question * @returns {QuizPart} ...

Is there a need to remove whitespace for additional characters?

Is there a function available that can trim specified characters or strings? For example: var x = '@@@hello world@@'; console.log(x.trim('@')); // outputs 'hello world' var y = 'hellohellohelloworld'; console.log(y ...

In Perl, locate and store word and its surrounding context in a hash table

My array structure resembles the following (with over 2000 lines of similar content): @list = ( "affaire,chose,question", "cause,chose,matière", ); I aim to achieve the following output: %te = ( affaire => "chose", "question", chose ...