Skip to content

Instantly share code, notes, and snippets.

@franknmungai
Created October 22, 2020 11:05
Show Gist options
  • Save franknmungai/2fe4c9024cada721482b800078864f86 to your computer and use it in GitHub Desktop.
Save franknmungai/2fe4c9024cada721482b800078864f86 to your computer and use it in GitHub Desktop.
Source code for the Game component in lesson 9 on https://stack-chess-tutorial.netlify.app/docs/09-highlight-check
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';
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 } = useContext(GameContext);
useEffect(() => {
setBoard(createBoard(fen));
}, [fen]);
useEffect(() => {
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;
const to = pos;
chess.move({ from, to });
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 }),
});
};
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