-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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