【问题标题】:how to check dynamically changing boolean value using three js如何使用三个js检查动态变化的布尔值
【发布时间】:2019-05-17 15:28:54
【问题描述】:

我正在用三个 js 制作一个 3D 4x4x4 tic tac toe,为了检查获胜组合条件,我创建了一个布尔数组。由于有 16*4=64 个块,我创建了一个大小为 64 的布尔数组,并默认将其设置为 false。然后,每当用户单击其中一个块时,它就会动态地将单击的对象更改为 true。 为了检查水平获胜条件,我使用了这个,

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

// var projector, mouse = { x: 0, y: 0 };
var projecter;
var mouse = new THREE.Vector2(),
  INTERSECTED;
init();
animate();

addCubes();
render();


function addCubes() {
  var xDistance = 30;
  var zDistance = 15;
  var geometry = new THREE.BoxBufferGeometry(10, 10, 10);
  var material = new THREE.MeshBasicMaterial({
    color: 0x6C70A8
  });

  //initial offset so does not start in middle.
  var xOffset = -80;
  //1
  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < 4; j++) {
      var mesh = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
        color: 0xadc9f4
      }));
      mesh.position.x = (xDistance * (i)) + xOffset;
      mesh.position.z = (zDistance * (j));
      scene.add(mesh);
      targetList.push(mesh);
    }
    //2
    for (let j = 0; j < 4; j++) {
      var mesh2 = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
        color: 0xadc9f4
      }));
      mesh2.position.x = (xDistance * (i)) + xOffset;
      mesh2.position.z = (zDistance * (j));
      mesh2.position.y = 15;
      scene.add(mesh2);
      targetList.push(mesh2);
    }
    //3
    for (let j = 0; j < 4; j++) {
      var mesh3 = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
        color: 0xadc9f4
      }));
      mesh3.position.x = (xDistance * (i)) + xOffset;
      mesh3.position.z = (zDistance * (j));
      mesh3.position.y = 30;
      scene.add(mesh3);
      targetList.push(mesh3);
    }
    //4
    for (let j = 0; j < 4; j++) {
      var mesh4 = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
        color: 0xadc9f4
      }));
      mesh4.position.x = (xDistance * (i)) + xOffset;
      mesh4.position.z = (zDistance * (j));
      mesh4.position.y = 45;
      scene.add(mesh4);
      targetList.push(mesh4);
    }
  }


  for (var i = 0; i < targetList.length; i++) {
    targetList[i].name = i;
  }

}




function init() {
  // Renderer.
  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  // renderer = new THREE.WebGLRenderer();
  //renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  // Add renderer to page
  document.body.appendChild(renderer.domElement);

  // Create camera.
  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
  camera.position.z = 150;


  // Add controls
  controls = new THREE.TrackballControls(camera);
  controls.addEventListener('change', render);
  controls.target.set(0, 0, -50);

  // Create scene.
  scene = new THREE.Scene();
  scene.background = new THREE.Color(0xffffff);

  // Create directional light and add to scene.
  var pointLight = new THREE.PointLight(0xFFFFFF, 1, 100000);
  pointLight.position.set(1, 1, 1).normalize();
  scene.add(pointLight);
  var directionalLight = new THREE.DirectionalLight(0xffffff);
  directionalLight.position.set(1, 1, 1).normalize();
  scene.add(directionalLight);

  // Add listener for window resize.
  window.addEventListener('resize', onWindowResize, false);
}


// initialize object to perform world/screen calculations
projector = new THREE.Projector();
// when the mouse moves, call the given function
document.addEventListener('mousedown', onDocumentMouseDown, false);


function onDocumentMouseDown(event) {
  // the following line would stop any other event handler from firing
  // (such as the mouse's TrackballControls)
  event.preventDefault();

  console.log("Click.");

  // update the mouse variable
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

  // find intersections

  // create a Ray with origin at the mouse position
  //   and direction into the scene (camera direction)
  var vector = new THREE.Vector3(mouse.x, mouse.y, 1);
  projector.unprojectVector(vector, camera);
  var ray = new THREE.Raycaster();
  ray.setFromCamera(mouse, camera);

  // create an array containing all objects in the scene with which the ray intersects
  var intersects = ray.intersectObjects(targetList);

  // if there is one (or more) intersections
  if (intersects.length > 0 && INTERSECTED != intersects[0].object) {


    INTERSECTED = intersects[0].object;
    INTERSECTED.material.emissive.setHex(0xff0000);
    console.log(INTERSECTED.name);

    // console.log("Hit @ " + toString( intersects[0].point ) );
    // change the color of the closest face.
    // intersects[ 0 ].face.color.setHex(0xffa500);
    // intersects[ 0 ].object.geometry.colorsNeedUpdate = true;
    for (var i = 0; i < targetList.length; i++) {

      if (INTERSECTED.name == i) {
        targetListBool[i] = true;

      }
    }
    console.log(targetListBool);
  }

}


// $(intersec).click(function(){
//   alert('you clicked number 1 block');
// });


function toString(v) {
  return "[ " + v.x + ", " + v.y + ", " + v.z + " ]";
}

function animate() {
  requestAnimationFrame(animate);
  render();
  controls.update();

}

function render() {
  renderer.render(scene, camera);
}

function onWindowResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
  controls.handleResize();
}


for (let i = 0; i <targetListBool.length ; i+=4) {
  if(targetListBool[i]
  &&targetListBool[i+1]
  &&targetListBool[i+2]
  &&targetListBool[i+3]){
      alert('win');
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Tic tac toe</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  <style>
    body {
      font-family: Monospace;
      background-color: #f0f0f0;
      margin: 0px;
      overflow: hidden;
    }
    
    .info {
      position: absolute;
      background-color: black;
      opacity: 0.8;
      color: white;
      text-align: center;
      top: 0px;
      width: 100%;
    }
    
    .info a {
      color: #00ffff;
    }
    
    button {
      display: hidden;
    }
  </style>
</head>

<body>



  <div id="container">
    <div>
      <!-- <button id="restart">Restart</button> -->
    </div>
  </div>


<script src="https://ajax.googleapis.com/ajax/libs/threejs/r84/three.min.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/examples/js/controls/TrackballControls.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/examples/js/utils/BufferGeometryUtils.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/examples/js/libs/dat.gui.min.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/examples/js/renderers/Projector.js"></script>


</body>

</html>

我现在正在尝试只检查水平获胜组合作为首发。

 for (let i = 0; i <targetListBool.length ; i+=4) {
  if(targetListBool[i]
  &&targetListBool[i+1]
  &&targetListBool[i+2]
  &&targetListBool[i+3]){
      alert('win');
  }

}

但它不知道一些值已经被点击事件更早的改变了。 澄清一下,如果在每个平面上单击 4 个连续的水平块,它应该会提示“获胜”。但我猜在 sn-p 末尾的 for 循环中的 if 语句有问题。

这是我第一次使用三个 js,我对 javaScript 也不是很熟悉。我将不胜感激任何帮助。谢谢。

【问题讨论】:

  • 请您添加您的 html 文件并在 SO 问题中创建一个 sn-p。
  • “既然有 16*4=52 块” O_o 16 * 4 = 64。我坚持:)
  • 你的 sn-p 对我有用。
  • @LloydNicholson 我输入了代码 sn-p,谢谢!
  • @MarkBaijens 真的吗?它应该提醒'赢',但它不是..!我设法通过事件将数组中单击的元素变为真,但这就是我卡住的地方..

标签: javascript arrays three.js boolean


【解决方案1】:

如果您的系统在 x、y 或 z 轴上连续有 4 个,则您的系统获胜。您的函数只检查一个方向的布尔值。所以最好是以 3 维的方式跟踪数据。这是一个例子。我手动在 z 轴上连续设置 4,然后进行检查。

不过,检查可以而且应该改进。这是非常低效的,但是对于示例来说很容易,因为我不知道你的确切意图。例如,是否也应该检查对角线?

//Fill a variable with x,y,z coordinates with a boolean value that is 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;


//Test if there are 4 on a row - note this can be done more efficient with a bit more thought and does not work 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;
        }
      }
    }
  }
}

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

【讨论】:

  • 将数组更改为对象以修复数组索引的错误并使代码更清晰。
  • 我的问题已解决,这是因为 win 组合检查器不在点击功能中。感谢 3d 数组的想法,我一定会将我的代码更改为 3d 数组!
猜你喜欢
  • 1970-01-01
  • 2011-05-23
  • 2019-01-02
  • 1970-01-01
  • 2019-05-22
  • 2019-04-27
  • 2023-01-03
  • 1970-01-01
  • 2013-09-12
相关资源
最近更新 更多