Javascript中的生命游戏:检查邻居不工作

时间:2018-02-10 12:35:42

标签: javascript reactjs conways-game-of-life

我试图实施康威的生命游戏并且它无法正常工作,但我无法找到问题所在。目前我每次都使用setInterval()来获取新一代主板,但我尝试使用setTimeout()进行错误检查,然后使用console.table检查前后表,并且无法弄明白。我的检查邻居功能正常工作(即,确定一些细胞的出生死亡和死亡),但不是全部。

任何人都可以帮我找出问题所在吗?

(我从newBoard函数中获取新板,我在mapDispatchToProps函数中调用它。)

这是我的代码和指向Codepen的链接:https://codepen.io/lieberscott/pen/qxrVbE?editors=0110

// React & Redux libraries setup
const { Component } = React;
const { createStore, applyMiddleware } = Redux;
const { Provider } = ReactRedux;
const { connect } = ReactRedux;
const { combineReducers } = Redux;

let grid = [];
let width = 25;
let height = 50;

for (let i = 0; i < height; i++) {
  grid.push([]);
  for (let j = 0; j < width; j++) {
    grid[i][j] = Math.random() > 0.85;
  }
}

const initState = {
  arr: grid
};


const reducer = (state = initState, action) => {
  let newState;
  // console.table(state.arr);
  switch (action.type) {
    case "NEW_ARR":
      newState = {
        arr: action.arr
      };
      // console.table(newState.arr);
      return newState;
      break;

    default:
      return state;
      break;
  }
}

const store = createStore(reducer);

const newBoard = (arr, newArr) => {
  for (let i = 0; i < height; i++) {
    for (let j = 0; j < width; j++) {
      let score = checkNeighbors(arr, i, j);
      if (arr[i][j] == false && score == 3) {
        newArr[i][j] = true;
      }
      else if (arr[i][j] == true && (score > 3 || score < 2)) {
        newArr[i][j] = false;
      }
      else { // unessential line since already set newArr = arr
        newArr[i][j] = arr[i][j];
      }
    }
  }
  return newArr;
}

function checkNeighbors(array, x, y) {
  let score = 0;
  for (let i = -1; i <= 1; i++) {
    let h = (i + x + height) % height;
    for (let j = -1; j <= 1; j++) {
      let w = (j + y + width) % width;
      score += array[h][w];
    }
  }
  score -= array[x][y];
  return score;
}

const Cell = (props) => {
  return (
    <td className={props.black ? "black" : ""}>
    </td>
  );
}

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    setInterval(() => this.props.newGeneration(this.props.data.arr), 90)
  }

  render() {

    return (
      <table onClick={this.toggle}>
        <thead>
        </thead>
          <tbody>
            {this.props.data.arr.map((row, i) =>
              <tr key={i}> {row.map((cell, j) =>
                <Cell key={j} black={cell}/>)}
              </tr> )}
          </tbody>
      </table>
    );
  }
}


const mapStateToProps = (state) => {
  return {
    data: state
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    newGeneration: (array) => {
      let arr1 = array.slice(0);
      let arr2 = array.slice(0);
      let newArr = newBoard(arr1, arr2);
      dispatch(newGeneration(newArr));
    }
  }
}

function newGeneration(newArr) {
  return {
    type: "NEW_ARR",
    arr: newArr
  };
}

App = connect(mapStateToProps, mapDispatchToProps)(App); // use same name as class apparently?







const main = window.document.getElementById("main");

// Provider wraps our app
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
    main);

1 个答案:

答案 0 :(得分:0)

我设法搞清楚了。在我的newBoard函数中,原始数组(arr)中的值被更改(即使在我的代码中,我表面上只是更改newArr值)。

所以我改变了newBoard函数,在函数中创建了一个新的数组,而不是传入一个。这有效:

https://codepen.io/lieberscott/pen/EQWGXW?editors=0110

const newBoard = (arr) => {
  let newArr = [];
  for (let i = 0; i < height; i++) {
    newArr.push([]);
    for (let j = 0; j < width; j++) {
      let score = checkNeighbors(arr, i, j);
      if (arr[i][j] == false && score == 3) {
        newArr[i].push(true);
      }
      else if (arr[i][j] == true && (score > 3 || score < 2)) {
        newArr[i].push(false);
      }
      else {
        newArr[i].push(arr[i][j]);
      }
    }
  }
  return newArr;
}

关于为什么原始行为发生的任何评论,但我认为这将是有价值的。