对于官方给出的如下优化建议进行了优化:
- 在游戏历史记录列表显示每一步棋的坐标,格式为 (列号, 行号)。
- 在历史记录列表中加粗显示当前选择的项目。
- 使用两个循环来渲染出棋盘的格子,而不是在代码里写死(hardcode)。
- 添加一个可以升序或降序显示历史记录的按钮。
- 每当有人获胜时,高亮显示连成一线的 3 颗棋子。
- 当无人获胜时,显示一个平局的消息。
1. 在游戏历史记录列表显示每一步棋的坐标,格式为 (列号, 行号)。
在Game组件中新增属性index,用来记录当前落子位置。
this.state = {
history: [
{
...
index: -1,
}
],
};
当落子时,该值改变。
handleClick(i) {
...
this.setState({
history: history.concat([
{
...
index: i,
}
]),
});
}
改变历史记录的文字,添加上坐标。
const desc = move ?
`Go to move #${move}: (${Math.floor(step.index/3)+1},${step.index%3 +1})`
:
'Go to game start';
2. 在历史记录列表中加粗显示当前选择的项目。
css文件添加字体加粗样式。
.bold-font{
font-weight: 900;
}
Game组件state中添加用来控制每一个历史记录按钮的属性数组。
this.state = {
...
boldClass: Array(9).fill(null),
};
为每一个历史记录按钮绑定该属性。
const moves = history.map((step, move) => {
...
return (
<li key={move}>
<button
variant="outlined"
className={this.state.boldClass[move]}
onClick={() => this.jumpTo(move)}>
{desc}
</button>
</li>
);
});
点击该历史记录按钮时将其属性改变为字体加粗属性。
jumpTo(step) {
const boldClass = Array(9).fill(null);
boldClass[step] = 'bold-font';
this.setState({
stepNumber: step,
xIsNext: (step % 2) === 0,
boldClass: boldClass
});
}
3. 使用两个循环来渲染出棋盘的格子,而不是在代码里写死(hardcode)。
在Board组件的render函数中用两个循环进行渲染,注意加上key。
render() {
const board = Array(3).fill(null).map((item,index1)=>{
const boardRow = Array(3).fill(null).map((item,index2)=>{
return (
this.renderSquare(index1*3+index2)
);
});
return (
<div className="board-row" key={index1}>
{boardRow}
</div>
);
})
return (
<div>
{board}
</div>
);
}
4. 添加一个可以升序或降序显示历史记录的按钮。
在Game组件的render函数中添加一对按钮。(这里引入了material-ui组件)
import {Button,ButtonGroup } from '@material-ui/core';
...
<div className="game-info">
<div>{status}</div>
<div className="game-sort">
<span>历史记录排序:</span>
<ButtonGroup size="small" color="primary" aria-label="large outlined primary button group">
<Button onClick={()=>{this.setState({isAsc: true})}}>升序</Button>
<Button onClick={()=>{this.setState({isAsc: false})}}> 降序</Button>
</ButtonGroup>
</div>
<ol>{moves}</ol>
实现降序升序功能:
添加isAsc变量判断降序还是升序。如果是升序,什么都不做。如果是降序,就改变历史记录的下标,使其为倒叙。
const moves = history.map((step, move) => {
if(!this.state.isAsc){
move = history.length - move - 1;
}
...
return (
<li key={move}>
<button
variant="outlined"
className={this.state.boldClass[move]}
onClick={() => this.jumpTo(move)}>
{desc}
</button>
</li>
);
});
5. 每当有人获胜时,高亮显示连成一线的 3 颗棋子。
添加高亮属性。
.x-line{
background: lightcyan;
}
.o-line{
background: peachpuff;
}
当有赢家出现时,添加相应属性:
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice();
const oClass = current.oClass.slice();
if (calculateWinner(squares)||squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? "X" : "O";
oClass[i] = this.state.xIsNext ? 'square' : 'square o-font';
const winner = calculateWinner(squares);
if(winner){
winner.line.map((item) => {
if(winner.who ==='X'){
oClass[item] = oClass[item].concat(' x-line');
} else{
oClass[item] = oClass[item].concat(' o-line');
}
});
console.log(33, oClass);
}
this.setState({
history: history.concat([
{
squares: squares,
index: i,
oClass: oClass
}
]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext,
});
}
6. 当无人获胜时,显示一个平局的消息。
如果没有出现赢家且棋下满了则为平局。
if (winner) {
status = "Winner: " + winner.who;
} else if(!current.squares.includes(null)) {
status = 'no one win ~'
}
else {
status = "Next player: " + (this.state.xIsNext ? "X" : "O");
}
完整代码如下:
index.css
body {
font: 14px "Century Gothic", Futura, sans-serif;
margin: 20px;
}
ol, ul {
padding-left: 30px;
}
.board-row:after {
clear: both;
content: "";
display: table;
}
.status {
margin-bottom: 10px;
}
.square {
background: #fff;
border: 1px solid #999;
float: left;
font-size: 24px;
font-weight: bold;
line-height: 34px;
height: 34px;
margin-right: -1px;
margin-top: -1px;
padding: 0;
text-align: center;
width: 34px;
color: skyblue;
}
.square:focus {
outline: none;
}
.kbd-navigation .square:focus {
background: #ddd;
}
.game {
display: flex;
flex-direction: row;
}
.game-info {
margin-left: 20px;
}
.game-sort{
margin-left: 20px;
margin-top: 20px;
}
.bold-font{
font-weight: 900;
}
.o-font{
color: coral;
}
.x-line{
background: lightcyan;
}
.o-line{
background: peachpuff;
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Button,ButtonGroup } from '@material-ui/core';
import './index.css';
function Square(props){
return (
<button
className={props.o}
onClick={props.onClick}>
{props.value}
</button>
);
}
class Board extends React.Component {
renderSquare(i) {
return (
<Square
value={this.props.squares[i]}
onClick={() => this.props.onClick(i)}
key={i}
o={this.props.o[i]}
/>
);
}
render() {
const board = Array(3).fill(null).map((item,index1)=>{
const boardRow = Array(3).fill(null).map((item,index2)=>{
return (
this.renderSquare(index1*3+index2)
);
});
return (
<div className="board-row" key={index1}>
{boardRow}
</div>
);
})
return (
<div>
{board}
</div>
);
}
}
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
history: [
{
squares: Array(9).fill(null),
index: -1,
oClass: Array(9).fill('square')
}
],
stepNumber: 0,
xIsNext: true,
boldClass: Array(9).fill(null),
isAsc: true,
};
}
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice();
const oClass = current.oClass.slice();
if (calculateWinner(squares)||squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? "X" : "O";
oClass[i] = this.state.xIsNext ? 'square' : 'square o-font';
const winner = calculateWinner(squares);
if(winner){
winner.line.map((item) => {
if(winner.who ==='X'){
oClass[item] = oClass[item].concat(' x-line');
} else{
oClass[item] = oClass[item].concat(' o-line');
}
});
console.log(33, oClass);
}
this.setState({
history: history.concat([
{
squares: squares,
index: i,
oClass: oClass
}
]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext,
});
}
jumpTo(step) {
const boldClass = Array(9).fill(null);
boldClass[step] = 'bold-font';
this.setState({
stepNumber: step,
xIsNext: (step % 2) === 0,
boldClass: boldClass
});
}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);
const moves = history.map((step, move) => {
if(!this.state.isAsc){
move = history.length - move - 1;
}
const desc = move ?
`Go to move #${move}: (${Math.floor(step.index/3) +1},${step.index%3 +1})` :
'Go to game start';
return (
<li key={move}>
<button
variant="outlined"
className={this.state.boldClass[move]}
onClick={() => this.jumpTo(move)}>
{desc}
</button>
</li>
);
});
let status;
if (winner) {
status = "Winner: " + winner.who;
} else if(!current.squares.includes(null)) {
status = 'no one win ~'
}
else {
status = "Next player: " + (this.state.xIsNext ? "X" : "O");
}
console.log(current);
console.log(this.state.history);
return (
<div className="game">
<div className="game-board">
<Board
squares={current.squares}
onClick={i => this.handleClick(i)}
o={current.oClass}
/>
</div>
<div className="game-info">
<div>{status}</div>
<div className="game-sort">
<span>历史记录排序:</span>
<ButtonGroup size="small" color="primary" aria-label="large outlined primary button group">
<Button onClick={()=>{this.setState({isAsc: true})}}>升序</Button>
<Button onClick={()=>{this.setState({isAsc: false})}}> 降序</Button>
</ButtonGroup>
</div>
<ol>{moves}</ol>
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(<Game />, document.getElementById("root"));
function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return {line:[a,b,c], who: squares[a]};
}
}
return null;
}