1、index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css'
function Square (props){
if(props.winBtn){
/*每当有人获胜时,高亮显示连成一线的 3 颗棋子。*/
return (
<button style={{backgroundColor:"MediumSpringGreen"}} className="square" onClick={props.onClick}>
{props.value}
</button>
);
}else {
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
);
}
}
class Board extends React.Component {
render() {
return (
<div>
{/*<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>*/
/*使用两个循环来渲染出棋盘的格子,而不是在代码里写死(hardcode)*/
Array(3).fill(null).map((rowitem,index)=>
<div key={'row'+index} className="board-row">
{
Array(3).fill(null).map((columitem,j) =>
{return <Square
key = {j}
/*索引规律
index j 棋盘数组索引
0 0 0
0 1 1
0 2 2
1 0 3
1 1 4
1 2 5
2 0 6
2 1 7
2 2 8
3*index+j = 棋盘数组索引*/
winBtn = {this.props.winBtn[3*index+j]}
value={this.props.squares[3*index+j]}
onClick={()=> this.props.onClick(3*index+j)}
/>}
)
}
</div>
)}
</div>
);
}
}
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
history: [{
squares: Array(9).fill(null),
}],
xys:[],//坐标
stepNumber: 0,
xIsNext: true,
isDesc:true,
};
}
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const xys = this.state.xys.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice();
if (calculateWinner(squares,this) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({
history: history.concat([{
squares: squares,
}]),
xys:xys.concat(this.getXYByIndex(i)),
stepNumber: history.length,
xIsNext: !this.state.xIsNext
});
}
jumpTo(step) {
this.setState({
stepNumber: step,
xIsNext: (step % 2) === 0,
});
}
/**
* 根据数据做引获取坐标
*/
getXYByIndex(index){
let xy = "";
switch (index) {
case 0:xy="1,1";break;
case 1:xy="2,1";break;
case 2:xy="3,1";break;
case 3:xy="1,2";break;
case 4:xy="2,2";break;
case 5:xy="3,2";break;
case 6:xy="1,3";break;
case 7:xy="2,3";break;
case 8:xy="3,3";break;
default:break;
}
return xy;
}
/**
* 历史记录排序
*/
order (){
const isDesc = this.state.isDesc;
this.setState({
isDesc: !isDesc,
});
}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
let winMap = calculateWinner(current.squares,this);
let winner;
if(winMap == null){
winner = null;
winMap = {};
winMap['winBtn'] = Array(9).fill(null);
}else {
winner = winMap.winner;
}
const moves = history.map((step, move) => {
const discrib = move ?
'Go to move #' + move + '('+this.state.xys[move-1]+')':/*在游戏历史记录列表显示每一步棋的坐标,格式为 (列号, 行号)。*/
'Go to game start';
let history_btn = "";
if(move === this.state.stepNumber){
//在历史记录列表中加粗显示当前选择的项目。
history_btn = <button style={{fontWeight:600}} onClick={() => this.jumpTo(move)}>{discrib}</button>
}else {
history_btn = <button onClick={() => this.jumpTo(move)}>{discrib}</button>;
}
return (
<li key={move}>{history_btn}</li>
);
});
let status;//操作提示
if (winner) {
status = 'Winner: ' + winner ;
} else {
status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
}
let buttonName;//历史记录顺序按钮名称
let finalMoves;//历史记录数据
if(this.state.isDesc){
buttonName = '升序';
finalMoves = moves;
}else {
buttonName = '降序';
finalMoves = moves.reverse();
}
return (
<div className="game">
<div className="game-board">
<Board
winBtn={winMap == null ? null : winMap.winBtn}
squares={current.squares}
onClick={(i) => this.handleClick(i)}
/>
</div>
<div className="game-info">
<div>{status}
/*添加一个可以升序或降序显示历史记录的按钮。*/
<button onClick={() =>this.order()}>{buttonName}</button></div>
<ol>{finalMoves}</ol>
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);
function calculateWinner(squares,obj) {
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]) {
let winBtn = Array(9).fill(null);
if(winBtn.indexOf(true) < 0){
winBtn[a] = true;
winBtn[b] = true;
winBtn[c] = true;
}
const result = {"winner":squares[a],"winBtn":winBtn};
return result;
}else {
/*当无人获胜时,显示一个平局的消息。*/
let endFlag = true;
for(let j in squares){
if(squares[j] == null){
endFlag = false;
}
}
if(endFlag){
const result = {"winner":'平局',"winBtn":Array(9).fill(null)};
return result;
}
}
}
return null;
}
2、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;
}
.square:focus {
outline: none;
}
.kbd-navigation .square:focus {
background: #ddd;
}
.game {
display: flex;
flex-direction: row;
}
.game-info {
margin-left: 20px;
}
3、index.html
<div id="errors" style="
background: #c00;
color: #fff;
display: none;
margin: -20px -20px 20px;
padding: 20px;
white-space: pre-wrap;
"></div>
<div id="root"></div>
<script>
window.addEventListener('mousedown', function(e) {
document.body.classList.add('mouse-navigation');
document.body.classList.remove('kbd-navigation');
});
window.addEventListener('keydown', function(e) {
if (e.keyCode === 9) {
document.body.classList.add('kbd-navigation');
document.body.classList.remove('mouse-navigation');
}
});
window.addEventListener('click', function(e) {
if (e.target.tagName === 'A' && e.target.getAttribute('href') === '#') {
e.preventDefault();
}
});
window.onerror = function(message, source, line, col, error) {
var text = error ? error.stack || error : message + ' (at ' + source + ':' + line + ':' + col + ')';
errors.textContent += text + '\n';
errors.style.display = '';
};
console.error = (function(old) {
return function error() {
errors.textContent += Array.prototype.slice.call(arguments).join(' ') + '\n';
errors.style.display = '';
old.apply(this, arguments);
}
})(console.error);
</script>
小白学习记录,有建议或不明白的小伙伴欢迎评论!