Skip to content

Instantly share code, notes, and snippets.

@franknmungai
Created October 23, 2020 14:05
Show Gist options
  • Save franknmungai/95160a2f62ac38a8489d83caebbc0485 to your computer and use it in GitHub Desktop.
Save franknmungai/95160a2f62ac38a8489d83caebbc0485 to your computer and use it in GitHub Desktop.
The complete code snippet for the Game component in section 10 at https://stack-chess-tutorial.netlify.app/docs/10-game-over
import React, { useState, useRef, useEffect, useContext } from 'react';
import Chess from 'chess.js';
import { createBoard } from '../../functions';
import Board from '../../components/board';
import { GameContext } from '../../context/GameContext';
import { types } from '../../context/actions';
import getGameOverState from '../../functions/game-over.js';
import GameOver from '../../components/gameover';
const FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
const Game = () => {
const [fen, setFen] = useState(FEN);
const { current: chess } = useRef(new Chess(fen));
const [board, setBoard] = useState(createBoard(fen));
const { dispatch, gameOver } = useContext(GameContext);
useEffect(() => {
setBoard(createBoard(fen));
}, [fen]);
useEffect(() => {
const [gameOver, status] = getGameOverState(chess);
if (gameOver) {
dispatch({ type: types.GAME_OVER, status, player: chess.turn() });
return;
}
dispatch({
type: types.SET_TURN,
player: chess.turn(),
check: chess.in_check(),
});
}, [fen, dispatch, chess]);
const fromPos = useRef();
const makeMove = (pos) => {
const from = fromPos.current;
chess.move({ from, to: pos });
dispatch({ type: types.CLEAR_POSSIBLE_MOVES });
setFen(chess.fen());
};
const setFromPos = (pos) => {
fromPos.current = pos;
dispatch({
type: types.SET_POSSIBLE_MOVES,
moves: chess.moves({ square: pos }),
});
};
if (gameOver) {
return <GameOver />;
}
return (
<div className="game">
<Board cells={board} makeMove={makeMove} setFromPos={setFromPos} />
</div>
);
};
export default Game;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment