代码摘要
下面的代码适用于我正在设计的基于网格的游戏 - 出于学习目的而不是其他任何目的。游戏在 8 x 8 网格上进行。玩家将从一个牢房移动到另一个牢房。可能有也可能没有墙阻止他们移动。
游戏变量
玩家对象 保持游戏中的当前位置。
var player = {
location: {
x: 3,
y: 3
}
}
网格
board[x][y] // An individual cell in the game
路线
const NORTH = 0;
const EAST = 1;
const SOUTH = 2;
const WEST = 3;
墙壁
board[x][y][NORTH] = 1; // A wall on north wall
初始测试
当我只是测试玩家是否移出棋盘时,测试进展顺利,如下面的 SWITCH 语句所示。但当我开始检查那里是否有一堵墙时,事情就爆炸了。
我通过重置游戏板并移除所有墙壁来开始测试。我相信,这就是正在发生的事情。我收到此错误:
代码
const NORTH = 0;
const EAST = 1;
const SOUTH = 2;
const WEST = 3;
const ROOMWIDTH = 7; // 0 array
const ROOMHEIGHT = 7;
var moveResonse = {
valid: 0,
reason: "",
helpText: ""
}
var player = {
location: {
x: 3,
y: 3
}
}
var board = [];
for(var x=0; x<8; x++){
for(y=0; y<8; y++){
for(var d=0; d<4;d++){
board[x][y][d] = 0;
}
}
}
// Testing. Put a WALL on WEST wall of 3,3
board[3][3][0] = 0;
board[3][3][1] = 0;
board[3][3][2] = 0;
board[3][3][3] = 1;
// Same WALL on EAST 2,3
board[2][3][0] = 0;
board[2][3][1] = 1;
board[2][3][2] = 0;
board[2][3][3] = 0;
function move(d) {
// 1. Is user trying to move off board?
switch (d) {
case NORTH:
if (player.location.y - 1 < 0) {
moveResonse = {
valid: 0,
reason: "Out of bounds",
helpText: "You can't move NORTH off the grid!"
}
}
return moveResonse;
break;
case EAST:
if (player.location.x + 1 > ROOMWIDTH) {
moveResonse = {
valid: 0,
reason: "Out of bounds",
helpText: "You can't move EAST off the grid!"
}
}
return moveResonse;
break;
case SOUTH:
if (player.location.y + 1 > ROOMHEIGHT) {
moveResonse = {
valid: 0,
reason: "Out of bounds",
helpText: "You can't move SOUTH off the grid!"
}
}
return moveResonse;
break;
case WEST:
if (player.location.x - 1 < 0) {
moveResonse = {
valid: 0,
reason: "Out of bounds",
helpText: "You can't move WEST off the grid!"
}
}
return moveResonse;
break;
}
//2. Is there a wall there?
if(board[player.location.x][player.location.y][d] == 1){
moveResonse = {
valid: 0,
reason: "Obstacle",
helpText: "You can't move there, a WALL there!"
}
return moveResonse;
}
}
//alert(`Moving North: ${move(NORTH).helpText}`);
//alert(`Moving SOUTH: ${move(SOUTH).helpText}`);
//alert(`Moving EAST: ${move(EAST).helpText}`);
alert(`Moving WEST: ${move(WEST).helpText}`);
最近我关闭了一个问题,因为有些人认为它是基于意见的。我不是在寻求“意见”,我是在寻求帮助以找到问题的解决方案。如果这意味着采取不同的方向,那就这样吧。我非常感谢您帮助我学习。
董事会视觉
最佳答案
您只声明了一维数组,执行 var board = [];
for(var x=0; x<8; x++){
board[x] = []; // Added this line to create an empty array
for(var y=0; y<8; y++){
board[x][y] = []; // Added this line to create an empty array
for(var d=0; d<4;d++){
board[x][y][d] = 0;
}
}
}
您还在第二个 for next 循环中错过了 var 。如果不包含它,它将成为全局变量。
关于javascript - 为什么这个 3 维数组不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60783609/