I'm trying to make an if statement, that if the array board is the same as 2 changes ago, it will warn me by saying "undid illegal play".
However every array becomes the same after 3 turns (because of if(boardHistory.length >= 3){
) but it warns me always while I see no reason for warning me since it's always changing and never becomes the same value.
What did I wrong?
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>