[英]Is it possible to convert the old Rally Task Board to the new Cardboard
[英]New to Reactjs, Building a Game of Life, but the old board is updating with the new board
首先,我想拉一個隨機的棋盤,以便游戲在渲染后立即開始運行,但是在這種情況下,我有一個預先分配的布局用於調試。 這三個正方形的排列將從水平切換到垂直,然后無限地切換。
getInitialState: function() {
var state = {
rows: 5,
cols: 5,
generation: 0,
active: false
};
var cellMatrix = [];
var cellRow = [];
/* for (var i = 0; i < state.rows; i++) {
for (var j = 0; j < state.cols; j++) {
cellRow.push(Math.round(Math.random()));
}
cellMatrix.push(cellRow);
cellRow = [];
}*/
cellMatrix = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
];
state.board = cellMatrix;
return state;
},
到目前為止非常簡單。 我用一個按鈕渲染頁面,該按鈕使我可以執行this.gameStep,它模擬了另一個世代。 更新后的值分配給newBoard,並且state.board在循環后更新。 問題是state.board每次循環都會更新到當前的板狀態(在這種情況下為25次)。 如果要插入(newBoard == this.state.board)布爾值,則每次循環迭代都返回true。
gameStep: function() {
var newBoard = this.state.board;
for (var i = 0; i < this.state.rows; i++) {
for (var j = 0; j < this.state.cols; j++) {
console.log(this.state.board);
var check = this.checkNeighborSum(i, j, this.state.board);
if (check == 3) {
newBoard[i][j] = 1;
} else if (check == 4) {
newBoard[i][j] = this.state.board[i][j];
} else {
newBoard[i][j] = 0;
}
}
}
this.setState({
board: newBoard
});
},
作為參考,checkNeighborSum只是實際的數學函數。 3是保證生命,4是生命,只有當它已經活着(也就是復制狀態),其他任何東西都已經死亡時。
checkNeighborSum: function(x, y, board) { // x is row index, y is column index
var xMinus = x - 1;
var xPlus = x + 1;
var yMinus = y - 1;
var yPlus = y + 1;
if (x === 0) {
xMinus = this.state.cols - 1;
}
if (x === this.state.cols - 1) {
xPlus = 0;
}
if (y === 0) {
yMinus = this.state.rows - 1;
}
if (y === this.state.rows - 1) {
yPlus = 0;
}
return (board[xMinus][yMinus] +
board[xMinus][y] +
board[xMinus][yPlus] +
board[x][yMinus] +
board[x][y] +
board[x][yPlus] +
board[xPlus][yMinus] +
board[xPlus][y] +
board[xPlus][yPlus]);
},
如果希望查看整個頁面,請鏈接 :
也許檢查一下: 如何正確克隆JavaScript對象?
var newBoard = this.state.board只是創建另一個引用相同的變量。 它不會克隆您的對象
在gameStep
,您正在更改this.state.board
本身。 我建議使用不可變的結構,例如immutable.js。 但是,由於您才剛剛開始,可以嘗試使用Object.assign將狀態克隆到newState中-
var newBoard = Object.assign({}, this.state.board);
將board
添加到newBoard
時,這應該與board
newBoard
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.