├── public ├── favicon.ico ├── logo192.png ├── logo512.png ├── robots.txt ├── manifest.json └── index.html ├── src ├── assets │ ├── b_b.png │ ├── b_w.png │ ├── k_b.png │ ├── k_w.png │ ├── n_b.png │ ├── n_w.png │ ├── p_b.png │ ├── p_w.png │ ├── q_b.png │ ├── q_w.png │ ├── r_b.png │ └── r_w.png ├── Square.jsx ├── index.js ├── Piece.jsx ├── Promote.jsx ├── App.jsx ├── Board.jsx ├── BoardSquare.jsx ├── App.css ├── Game.js └── serviceWorker.js ├── README.md ├── .gitignore └── package.json /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3stbn/react-chess/HEAD/public/favicon.ico -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3stbn/react-chess/HEAD/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3stbn/react-chess/HEAD/public/logo512.png -------------------------------------------------------------------------------- /src/assets/b_b.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3stbn/react-chess/HEAD/src/assets/b_b.png -------------------------------------------------------------------------------- /src/assets/b_w.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3stbn/react-chess/HEAD/src/assets/b_w.png -------------------------------------------------------------------------------- /src/assets/k_b.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3stbn/react-chess/HEAD/src/assets/k_b.png -------------------------------------------------------------------------------- /src/assets/k_w.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3stbn/react-chess/HEAD/src/assets/k_w.png -------------------------------------------------------------------------------- /src/assets/n_b.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3stbn/react-chess/HEAD/src/assets/n_b.png -------------------------------------------------------------------------------- /src/assets/n_w.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3stbn/react-chess/HEAD/src/assets/n_w.png -------------------------------------------------------------------------------- /src/assets/p_b.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3stbn/react-chess/HEAD/src/assets/p_b.png -------------------------------------------------------------------------------- /src/assets/p_w.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3stbn/react-chess/HEAD/src/assets/p_w.png -------------------------------------------------------------------------------- /src/assets/q_b.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3stbn/react-chess/HEAD/src/assets/q_b.png -------------------------------------------------------------------------------- /src/assets/q_w.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3stbn/react-chess/HEAD/src/assets/q_w.png -------------------------------------------------------------------------------- /src/assets/r_b.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3stbn/react-chess/HEAD/src/assets/r_b.png -------------------------------------------------------------------------------- /src/assets/r_w.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3stbn/react-chess/HEAD/src/assets/r_w.png -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React chess 2 | 3 | Starter code for the tutorial of building a chess application with react -------------------------------------------------------------------------------- /src/Square.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | export default function Square({ children, black }) { 4 | const bgClass = black ? 'square-black' : 'square-white' 5 | 6 | return ( 7 |
8 | {children} 9 |
10 | ) 11 | } 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | yarn.lock 25 | package-lock.json 26 | .vscode -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | import * as serviceWorker from './serviceWorker'; 5 | import { DndProvider } from 'react-dnd' 6 | import { HTML5Backend } from 'react-dnd-html5-backend' 7 | ReactDOM.render( 8 | 9 | 10 | 11 | 12 | , 13 | document.getElementById('root') 14 | ); 15 | 16 | // If you want your app to work offline and load faster, you can change 17 | // unregister() to register() below. Note this comes with some pitfalls. 18 | // Learn more about service workers: https://bit.ly/CRA-PWA 19 | serviceWorker.unregister(); 20 | -------------------------------------------------------------------------------- /src/Piece.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { useDrag, DragPreviewImage } from 'react-dnd' 3 | 4 | export default function Piece({ 5 | piece: { type, color }, 6 | position, 7 | }) { 8 | const [{ isDragging }, drag, preview] = useDrag({ 9 | item: { 10 | type: 'piece', 11 | id: `${position}_${type}_${color}`, 12 | }, 13 | collect: (monitor) => { 14 | return { isDragging: !!monitor.isDragging() } 15 | }, 16 | }) 17 | const pieceImg = require(`./assets/${type}_${color}.png`) 18 | return ( 19 | <> 20 | 21 |
26 | 27 |
28 | 29 | ) 30 | } 31 | -------------------------------------------------------------------------------- /src/Promote.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import Square from './Square' 3 | import { move } from './Game' 4 | const promotionPieces = ['r', 'n', 'b', 'q'] 5 | 6 | export default function Promote({ 7 | promotion: { from, to, color }, 8 | }) { 9 | return ( 10 |
11 | {promotionPieces.map((p, i) => ( 12 |
13 | 14 |
move(from, to, p)} 17 | > 18 | 23 |
24 |
25 |
26 | ))} 27 |
28 | ) 29 | } 30 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-chess", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^4.2.4", 7 | "@testing-library/react": "^9.3.2", 8 | "@testing-library/user-event": "^7.1.2", 9 | "chess.js": "^0.11.0", 10 | "react": "^16.13.1", 11 | "react-dnd": "^11.1.3", 12 | "react-dnd-html5-backend": "^11.1.3", 13 | "react-dom": "^16.13.1", 14 | "react-scripts": "3.4.3", 15 | "rxjs": "^6.6.2" 16 | }, 17 | "scripts": { 18 | "start": "react-scripts start", 19 | "build": "react-scripts build", 20 | "test": "react-scripts test", 21 | "eject": "react-scripts eject" 22 | }, 23 | "eslintConfig": { 24 | "extends": "react-app" 25 | }, 26 | "browserslist": { 27 | "production": [ 28 | ">0.2%", 29 | "not dead", 30 | "not op_mini all" 31 | ], 32 | "development": [ 33 | "last 1 chrome version", 34 | "last 1 firefox version", 35 | "last 1 safari version" 36 | ] 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/App.jsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react' 2 | import './App.css' 3 | import { gameSubject, initGame, resetGame } from './Game' 4 | import Board from './Board' 5 | 6 | function App() { 7 | const [board, setBoard] = useState([]) 8 | const [isGameOver, setIsGameOver] = useState() 9 | const [result, setResult] = useState() 10 | const [turn, setTurn] = useState() 11 | useEffect(() => { 12 | initGame() 13 | const subscribe = gameSubject.subscribe((game) => { 14 | setBoard(game.board) 15 | setIsGameOver(game.isGameOver) 16 | setResult(game.result) 17 | setTurn(game.turn) 18 | }) 19 | return () => subscribe.unsubscribe() 20 | }, []) 21 | return ( 22 |
23 | {isGameOver && ( 24 |

25 | GAME OVER 26 | 29 |

30 | )} 31 |
32 | 33 |
34 | {result &&

{result}

} 35 |
36 | ) 37 | } 38 | 39 | export default App 40 | -------------------------------------------------------------------------------- /src/Board.jsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react' 2 | import BoardSquare from './BoardSquare' 3 | export default function Board({ board, turn }) { 4 | const [currBoard, setCurrBoard] = useState([]) 5 | 6 | useEffect(() => { 7 | setCurrBoard( 8 | turn === 'w' ? board.flat() : board.flat().reverse() 9 | ) 10 | }, [board, turn]) 11 | 12 | function getXYPosition(i) { 13 | const x = turn === 'w' ? i % 8 : Math.abs((i % 8) - 7) 14 | const y = 15 | turn === 'w' 16 | ? Math.abs(Math.floor(i / 8) - 7) 17 | : Math.floor(i / 8) 18 | return { x, y } 19 | } 20 | 21 | function isBlack(i) { 22 | const { x, y } = getXYPosition(i) 23 | return (x + y) % 2 === 1 24 | } 25 | 26 | function getPosition(i) { 27 | const { x, y } = getXYPosition(i) 28 | const letter = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'][ 29 | x 30 | ] 31 | return `${letter}${y + 1}` 32 | } 33 | return ( 34 |
35 | {currBoard.map((piece, i) => ( 36 |
37 | 42 |
43 | ))} 44 |
45 | ) 46 | } 47 | -------------------------------------------------------------------------------- /src/BoardSquare.jsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react' 2 | import Square from './Square' 3 | import Piece from './Piece' 4 | import { useDrop } from 'react-dnd' 5 | import { handleMove } from './Game' 6 | import { gameSubject } from './Game' 7 | import Promote from './Promote' 8 | export default function BoardSquare({ 9 | piece, 10 | black, 11 | position, 12 | }) { 13 | const [promotion, setPromotion] = useState(null) 14 | const [, drop] = useDrop({ 15 | accept: 'piece', 16 | drop: (item) => { 17 | const [fromPosition] = item.id.split('_') 18 | handleMove(fromPosition, position) 19 | }, 20 | }) 21 | useEffect(() => { 22 | const subscribe = gameSubject.subscribe( 23 | ({ pendingPromotion }) => 24 | pendingPromotion && pendingPromotion.to === position 25 | ? setPromotion(pendingPromotion) 26 | : setPromotion(null) 27 | ) 28 | return () => subscribe.unsubscribe() 29 | }, [position]) 30 | return ( 31 |
32 | 33 | {promotion ? ( 34 | 35 | ) : piece ? ( 36 | 37 | ) : null} 38 | 39 |
40 | ) 41 | } 42 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | * { 2 | margin: 0; 3 | padding: 0; 4 | } 5 | 6 | .container { 7 | min-height: 100vh; 8 | display: flex; 9 | align-items: center; 10 | justify-content: center; 11 | background-color: rgb(34, 34, 34); 12 | } 13 | 14 | .board-container { 15 | width: 600px; 16 | height: 600px; 17 | } 18 | 19 | .board { 20 | width: 100%; 21 | height: 100%; 22 | display: flex; 23 | flex-wrap: wrap; 24 | } 25 | 26 | .square { 27 | width: 12.5%; 28 | height: 12.5%; 29 | } 30 | 31 | .promote-square { 32 | width: 50%; 33 | height: 50%; 34 | } 35 | 36 | .square-black { 37 | background: #B59963 38 | } 39 | 40 | .square-white { 41 | background: #F0D9B5 42 | } 43 | 44 | .board-square { 45 | width: 100%; 46 | height: 100%; 47 | } 48 | 49 | .cursor-pointer { 50 | cursor: pointer; 51 | } 52 | 53 | .piece-container { 54 | cursor: grab; 55 | width: 100%; 56 | height: 100%; 57 | display: flex; 58 | align-items: center; 59 | justify-content: center; 60 | } 61 | 62 | .piece { 63 | max-width: 70%; 64 | max-height: 70%; 65 | } 66 | 67 | .vertical-text { 68 | text-orientation: upright; 69 | writing-mode: vertical-lr; 70 | font-family: sans-serif; 71 | padding: 10px; 72 | color: white; 73 | } 74 | 75 | .vertical-text button { 76 | margin-top: 20px; 77 | cursor: pointer; 78 | background: rgb(63, 63, 63); 79 | border: 2px solid white; 80 | border-radius: 10px; 81 | 82 | } -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 10 | 11 | 15 | 19 | 23 | 27 | 36 | React Chess App 37 | 38 | 39 | 43 |
44 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /src/Game.js: -------------------------------------------------------------------------------- 1 | import * as Chess from 'chess.js' 2 | import { BehaviorSubject } from 'rxjs' 3 | 4 | 5 | 6 | const chess = new Chess() 7 | 8 | export const gameSubject = new BehaviorSubject() 9 | 10 | export function initGame() { 11 | const savedGame = localStorage.getItem('savedGame') 12 | if (savedGame) { 13 | chess.load(savedGame) 14 | } 15 | updateGame() 16 | } 17 | 18 | export function resetGame() { 19 | chess.reset() 20 | updateGame() 21 | } 22 | 23 | export function handleMove(from, to) { 24 | const promotions = chess.moves({ verbose: true }).filter(m => m.promotion) 25 | console.table(promotions) 26 | if (promotions.some(p => `${p.from}:${p.to}` === `${from}:${to}`)) { 27 | const pendingPromotion = { from, to, color: promotions[0].color } 28 | updateGame(pendingPromotion) 29 | } 30 | const { pendingPromotion } = gameSubject.getValue() 31 | 32 | if (!pendingPromotion) { 33 | move(from, to) 34 | } 35 | } 36 | 37 | 38 | export function move(from, to, promotion) { 39 | let tempMove = { from, to } 40 | if (promotion) { 41 | tempMove.promotion = promotion 42 | } 43 | const legalMove = chess.move(tempMove) 44 | 45 | if (legalMove) { 46 | updateGame() 47 | } 48 | } 49 | 50 | function updateGame(pendingPromotion) { 51 | const isGameOver = chess.game_over() 52 | 53 | const newGame = { 54 | board: chess.board(), 55 | pendingPromotion, 56 | isGameOver, 57 | turn: chess.turn(), 58 | result: isGameOver ? getGameResult() : null 59 | } 60 | 61 | localStorage.setItem('savedGame', chess.fen()) 62 | 63 | gameSubject.next(newGame) 64 | } 65 | function getGameResult() { 66 | if (chess.in_checkmate()) { 67 | const winner = chess.turn() === "w" ? 'BLACK' : 'WHITE' 68 | return `CHECKMATE - WINNER - ${winner}` 69 | } else if (chess.in_draw()) { 70 | let reason = '50 - MOVES - RULE' 71 | if (chess.in_stalemate()) { 72 | reason = 'STALEMATE' 73 | } else if (chess.in_threefold_repetition()) { 74 | reason = 'REPETITION' 75 | } else if (chess.insufficient_material()) { 76 | reason = "INSUFFICIENT MATERIAL" 77 | } 78 | return `DRAW - ${reason}` 79 | } else { 80 | return 'UNKNOWN REASON' 81 | } 82 | } -------------------------------------------------------------------------------- /src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl, { 104 | headers: { 'Service-Worker': 'script' }, 105 | }) 106 | .then(response => { 107 | // Ensure service worker exists, and that we really are getting a JS file. 108 | const contentType = response.headers.get('content-type'); 109 | if ( 110 | response.status === 404 || 111 | (contentType != null && contentType.indexOf('javascript') === -1) 112 | ) { 113 | // No service worker found. Probably a different app. Reload the page. 114 | navigator.serviceWorker.ready.then(registration => { 115 | registration.unregister().then(() => { 116 | window.location.reload(); 117 | }); 118 | }); 119 | } else { 120 | // Service worker found. Proceed as normal. 121 | registerValidSW(swUrl, config); 122 | } 123 | }) 124 | .catch(() => { 125 | console.log( 126 | 'No internet connection found. App is running in offline mode.' 127 | ); 128 | }); 129 | } 130 | 131 | export function unregister() { 132 | if ('serviceWorker' in navigator) { 133 | navigator.serviceWorker.ready 134 | .then(registration => { 135 | registration.unregister(); 136 | }) 137 | .catch(error => { 138 | console.error(error.message); 139 | }); 140 | } 141 | } 142 | --------------------------------------------------------------------------------