React 三子棋小游戏

demo来源:react教程 - 三子棋游戏

目录结构

Quick start

npx create-react-app game

Let's do it

  1. 删除 src/ 下所有文件

  2. 在 src/ 下创建一个 index.js + index.css

  3. 在 src/ 下创建一个 components 文件夹用来放需要用到的三个组件:Square Board Game Moves

  4. 在 /src/components 下创建 Square.js 写第一个组件 Square
    Square.js

import React from 'react';
import '../index.css'

class Square extends React.Component {
    constructor () {
        super();
        this.state = {
            squares: 1
        }
    }

    handleClick () {
        this.setState({
            squares: 'x'
        })
    }

    render () {
        return (
            <div>
                <span className='square'
                    onClick={() => {this.handleClick()}}>{this.state.squares}</span>
            </div>
        )
    }
}

export default Square;
  1. 将组件 Square 渲染到页面中
    index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

import Square from './components/Square';

  
// ========================================

ReactDOM.render(
  <Square />,
  document.getElementById('root')
);
  1. 在 /src/components 下创建 Board.js 写第二个组件 Board ,同时进行状态提升
    Board.js
import React from 'react';
import Square from './Square';
import '../index.css';

class Board extends React.Component {
    constructor () {
        super();
        this.state = {
            squares: [1,2,3,4,5,6,7,8,9]
        }
    }

    handleClick (i) {
        const squares = this.state.squares.slice();
        squares[i] = 'x';
        this.setState({
            squares: squares
        })
    }

    renderSquare (i) {
        return (
            <Square
                squares={this.state.squares[i]}
                onClick={() => this.handleClick(i)} />
        )
    }

    render () {
        return (
            <div>
                {this.state.squares.map((item, index) => {
                    if (index % 3 === 0) {
                        return (
                            <div key={index} className='board-row'>
                                {[0, 1, 2].map((item, i) => {
                                    return (
                                        <div key={index + i}>
                                            {this.renderSquare(index + i)}
                                        </div>
                                    )
                                })}
                            </div>
                        )
                    }
                })}
            </div>
        )
    }
}

export default Board;
  1. 在 /src/components 下创建 Moves.js 写第三个组件 Moves 用来显示历史记录
import React from 'react';
import '../index.css';

class Moves extends React.Component {
    render () {
        const moves = this.props.moves;
        return (
            <div className={this.props.orderStatus === 'ase' ? 'ascending' : 'descending'}>
                {moves.map((item, index) => {
                    const desc = index ? '返回第' + index + '步' : '开始游戏'; 
                    return (
                        <p className={this.props.step === index ? 'light-show' : null}
                            key={index} 
                            onClick={() => this.props.onClick(index)}>{desc}</p>
                    )
                })} 
            </div>
        )
    }
}

export default Moves;
  1. 在 /src/components 下创建 Game.js 写第四个组件 Game ,同时再次进行状态提升,实现以下功能:

    (1).进行胜利判断:有人胜出则显示胜利者并结束游戏,满足胜利条件的棋子高亮显示,无人胜出则显示游戏结束

    (2).实现显示历史记录并可以跳回历史记录操作,当前历史记录处高亮显示

    (3).实现历史记录正序或倒叙排列切换

import React from 'react';
import Board from './Board'
import Moves from './Moves'
import '../index.css'

class Game extends React.Component {
    constructor () {
        super();
        this.state = {
            history: [{
                square: Array(9).fill(null)
            }],
            stepNum: 0,
            isXTurn: true,
            orderStatus: 'ase'
        }
    }

    handleClick (i) {
        const history = this.state.history.slice(0, this.state.stepNum + 1);
        const current = history[history.length - 1];
        const squares = current.square.slice();

        if (whoIsWinner(squares) || squares[i]) {
            return;
        }

        squares[i] = this.state.isXTurn ? 'x' : 'o';
        this.setState({
            history: history.concat({
                square: squares
            }),
            stepNum: this.state.stepNum + 1,
            isXTurn: !this.state.isXTurn
        })
    }

    jumpTo (step) {
        this.setState({
            history: step === 0 ? [{square: Array(9).fill(null)}] : this.state.history,
            stepNum: step,
            isXTurn: step % 2 === 0
        })
    }

    orderChange () {
        this.setState({
            orderStatus: this.state.orderStatus === 'ase' ? 'desc' : 'ase'
        })
    }

    render () {
        const history = this.state.history;
        const current = history[this.state.stepNum];
        let status;
        const winner = whoIsWinner(current.square) ? whoIsWinner(current.square).winner : null;
        const winnerSquares = whoIsWinner(current.square) ? whoIsWinner(current.square).winnerSquares : [];
        const order = this.state.orderStatus === 'ase' ? '升序排列' : '降序排列';

        if (winner) {
            status = 'Winner is ' + winner;
        } else if (this.state.stepNum === 9) {
            status = 'Game is over';
        } else {
            status = this.state.isXTurn ? 'Next player is x' : 'Next player is o';
        }
        return (
            <div className='game'>
                <div className='game-board'>
                    <Board
                        winnerSquares={winnerSquares}
                        onClick={(i) => this.handleClick(i)}
                        squares={current.square} />
                </div>
                <div className='game-info'>
                    <p>{status}</p>
                    <button onClick={() => this.orderChange()}>
                        {order}
                    </button>
                    <ul>
                        <Moves
                            step={this.state.stepNum}
                            orderStatus={this.state.orderStatus}
                            moves={history}
                            onClick={(i) => this.jumpTo(i)} />
                    </ul>
                </div>
            </div>
        )
    }
}

function whoIsWinner (squares) {
    const winnerList = [
        [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 < winnerList.length; i++) {
        let [a, b, c] = winnerList[i];
        if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
            return {
                winner: squares[a],
                winnerSquares: winnerList[i]
            }
        }
    }
    return null;
}

export default Game;

完整代码见:https://github.com/direwolf512/react-demo/tree/feature/game

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,546评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,224评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,911评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,737评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,753评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,598评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,338评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,249评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,696评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,888评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,013评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,731评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,348评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,929评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,048评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,203评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,960评论 2 355

推荐阅读更多精彩内容

  • 安装 使用Create React App,最好的方式,但是必须node>6的版本全局安装 删除掉生成项目中 sr...
    水落斜阳阅读 690评论 0 0
  • Tutorial: Intro To React Before We Start What We’re Build...
    尘埃__阅读 1,370评论 0 1
  • 窗外雨声涌波涛, 屋内半夜多喧嚣。 大宝嫌热睡不着, 小宝断奶受煎熬。 周公不断把我召, 却是睁眼等逍遥。 夜深人...
    jwyyw雯阅读 125评论 0 0
  • 在一家青旅打工换宿,这里鲜有人烟,住户很少,有山有水有草原有牦牛,云很低天很蓝,四周很寂静,没有城市的喧闹,符合一...
    黏玉米阅读 406评论 3 4
  • 就是天使也要-落地几年前看过了一本书,叫"当和尚遇到钻石",描述一位佛学博士,将所学的佛法运用到钻石生意的过程;还...
    马可约伯阅读 112评论 0 0