-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Board.tsx
48 lines (42 loc) · 1.16 KB
/
Board.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { CSSProperties, FC, useEffect, useState } from 'react'
import { BoardSquare } from './BoardSquare'
import type { Game, Position } from './Game'
import { Piece } from './Piece'
export interface BoardProps {
game: Game
}
/** Styling properties applied to the board element */
const boardStyle: CSSProperties = {
width: '100%',
height: '100%',
display: 'flex',
flexWrap: 'wrap',
}
/** Styling properties applied to each square element */
const squareStyle: CSSProperties = { width: '12.5%', height: '12.5%' }
/**
* The chessboard component
* @param props The react props
*/
export const Board: FC<BoardProps> = ({ game }) => {
const [[knightX, knightY], setKnightPos] = useState<Position>(
game.knightPosition,
)
useEffect(() => game.observe(setKnightPos))
function renderSquare(i: number) {
const x = i % 8
const y = Math.floor(i / 8)
return (
<div key={i} style={squareStyle}>
<BoardSquare x={x} y={y} game={game}>
<Piece isKnight={x === knightX && y === knightY} />
</BoardSquare>
</div>
)
}
const squares = []
for (let i = 0; i < 64; i += 1) {
squares.push(renderSquare(i))
}
return <div style={boardStyle}>{squares}</div>
}