react入门教程案例井字棋(包含改进代码)
生活随笔
收集整理的這篇文章主要介紹了
react入门教程案例井字棋(包含改进代码)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
react入門教程案例井字棋(包含改進代碼)
- 1、index.js
- 2、index.css
- 3、index.html
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 <Squarekey = {j}/*索引規律index j 棋盤數組索引0 0 00 1 10 2 21 0 31 1 41 2 52 0 62 1 72 2 83*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"><BoardwinBtn={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>小白學習記錄,有建議或不明白的小伙伴歡迎評論!
總結
以上是生活随笔為你收集整理的react入门教程案例井字棋(包含改进代码)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机软件工程考研考哪些专业,软件工程考
- 下一篇: 写在Doris毕业后的第一天