浏览器绘制后反应触发功能

时间:2018-11-11 22:40:50

标签: javascript reactjs

我正在使用react和javascript构建国际象棋引擎,并且我试图实现一种功能,在您自己移动后,引擎即可移动。我有一个函数“ change_states”,每当用户移动时,该函数都会更改国际象棋游戏的状态。我还有一个函数“ engine_move”,它可以根据游戏的当前状态使引擎在板上移动。

当我将“ engine_move”作为setState的回调,ComponentDidUpdate中的函数甚至是requestAnimationFrame调用时,“ engine_move”函数将在浏览器中反映“ change_state”函数的更改之前运行。这意味着在engine_move函数运行期间,移动的棋子就会消失,然后立即在板上渲染两个棋子(原始玩家和引擎都在移动)。我不知道如何获得它,以便浏览器在用户移动和引擎移动之间重新绘制。任何帮助将不胜感激。谢谢!

class Chess extends Component {
constructor(props) {
super(props);
this.state = {
  history: [{ position: new Position('white', initialize_engine_board(), [95, 
  25], [1, 1, 1, 1], 0) }],
  drag_end: null,
  promotion:{class:'hidden',start: null, end: null, player: null},
  status:null
  }
}


change_states(history, position, start, end, promotion_piece) {
  let possible_moves = legal_moves(position);
  let move = create_move(start, end, position, promotion_piece);
  let status = null;
  if (is_legal(move, possible_moves)) {
    let new_position = make_move(position, move);
    let new_moves = legal_moves(new_position);

    if (new_moves.length === 0) {
        status = 'Game Over'
    }
    this.setState({
      history: history.concat([{position: new_position}]),
      drag_end: null,
      status: status,
    });
  }
}

engine_move() {
    const history = this.state.history.slice();
    const position = history[history.length - 1].position;
    //Time in milliseconds
    let search_time = 1000;
    let engine_move = alphabeta_search(position,10,search_time).move;

    if (engine_move === null) {
        this.setState({
            status: 'Game Over',
        });
        return;
    }

    let new_position = make_move(position, engine_move);
    this.setState({
      history: history.concat([{position: new_position}]),
      engine_turn: false
    });
  }

0 个答案:

没有答案