Refactor Board

This commit is contained in:
Alice Gaudon 2022-03-13 19:08:37 +01:00
parent 2a7fe34019
commit 2c77245889

View File

@ -3,7 +3,6 @@ import ReactDOM from 'react-dom';
import './index.css'; import './index.css';
/*TODO /*TODO
Rewrite Board to use two loops to make the squares instead of hardcoding them.
Add a toggle button that lets you sort the moves in either ascending or descending order. Add a toggle button that lets you sort the moves in either ascending or descending order.
When someone wins, highlight the three squares that caused the win. When someone wins, highlight the three squares that caused the win.
When no one wins, display a message about the result being a draw. When no one wins, display a message about the result being a draw.
@ -17,35 +16,28 @@ function Square(props) {
); );
} }
class Board extends React.Component { function Board(props) {
renderSquare(i) { const rows = [];
return <Square for (let y = 0; y < 3; y++) {
value={this.props.squares[i]} const squares = [];
onClick={() => this.props.handleClick(i)} for (let x = 0; x < 3; x++) {
/>; const index = y * 3 + x;
} squares.push(
<Square
render() { key={index}
return ( value={props.squares[index]}
<div> onClick={() => props.handleClick(index)}
<div className="board-row"> />
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
); );
} }
rows.push(
<div key={y} className="board-row">{squares}</div>
);
}
return (
<div>{rows}</div>
);
} }
class Game extends React.Component { class Game extends React.Component {
@ -150,7 +142,7 @@ function calculateWinner(squares) {
return null; return null;
} }
function squareIndexToPosition(index){ function squareIndexToPosition(index) {
return [ return [
index % 3, index % 3,
Math.floor(index / 3), Math.floor(index / 3),