我正在尝试做出if声明,如果阵列板与2之前的更改相同,它将通过说“不合法的非法比赛”来警告我。
但是,每个数组在转3圈后都会变得相同(由于if(boardHistory.length >= 3){
),但它总是警告我,而我却没有理由警告我,因为它总是在变化并且永远不会变成相同的值。
我怎么了?
var turn;
var boardSize;
var board;
var boardHistory;
var changer;
function setup() {
createCanvas(400, 400);
boardSize = 8;
turn = false;
board = [];
boardHistory = [];
changer = 0;
for (var y = 0; y < boardSize; y++) {
for (var x = 0; x < boardSize; x++) {
board.push(new Piece(x, y, 0));
}
}
boardHistory.push(board);
}
function mouseClicked() {
for (var y = 0; y < boardSize; y++) {
for (var x = 0; x < boardSize; x++) {
board[y * boardSize + x].colour = changer;
}
}
var play = true;
if (boardHistory.length >= 3) {
if (board == boardHistory[(boardHistory.length - 3)]) {
play = false;
}
}
if (play) {
turn = !turn;
boardHistory.push(board);
console.log("played");
} else {
console.log("undid illegal play, " + (boardHistory.length - 3));
console.log(boardHistory[(boardHistory.length - 3)]);
}
console.log(board);
changer++;
}
function Piece(x, y, colour) {
this.x = x;
this.y = y;
this.colour = colour;
this.arrayNum = this.y * boardSize + this.x;
}
var turn;
var boardSize;
var board;
var boardHistory;
var changer;
function setup() {
createCanvas(400, 400);
boardSize = 8;
turn = false;
board = [];
boardHistory = [];
changer = 0;
for(var y = 0; y < boardSize; y++){
for(var x = 0; x < boardSize; x++){
board.push(new Piece(x,y,0));
}
}
boardHistory.push(board);
}
function mouseClicked(){
for(var y = 0; y < boardSize; y++){
for(var x = 0; x < boardSize; x++){
board[y*boardSize+x].colour = changer;
}
}
var play = true;
if(boardHistory.length >= 3){ if(board == boardHistory[(boardHistory.length-3)]){ play = false; } }
if(play){
turn = !turn;
boardHistory.push(board);
console.log("played");
} else {
console.log("undid illegal play, ");
}
changer++;
}
function Piece(x, y, colour) {
this.x = x;
this.y = y;
this.colour = colour;
this.arrayNum = this.y*boardSize+this.x;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
答案 0 :(得分:1)
我相信您面临的问题在两个不同的地方:
boardHistory.push(board);
和
if (board == boardHistory[(boardHistory.length - 3)])
但是,尽管您在函数中单击了board的值进行了修改,但变量包含对象的引用,而不是对象的副本。因此,如果您在一个地方进行更改,则会在另一地方看到它。
我想举一个例子会更清楚:
var board = [1,2,3]
var boardHist = []
boardHist[0] = board; //This is similar of what you are doing
console.log(board == boardHist[0]); //Obviously we are getting true
board[0] = 5; //Now we change the first value of board
console.log(board == boardHist[0]); //This is still true
console.log(boardHist[0]); //We will get [5,2,3]