Показать сообщение отдельно
  #15 (permalink)  
Старый 25.11.2019, 10:57
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,068

react игрушка продолжение

сделай поле зелёным!

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        .cell{
            height: 50px;
            width: 50px;
            background-color: #FFFF00;
        }
        .game > div {
            width: 250px;
            display: flex;
            flex-wrap: wrap;
        }
    </style>
</head>
<body>
    <div id="root"></div>
    <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>
    <script type="text/babel">

const { createElement, Component } = React;

class Game extends Component {
    state = {
        randomCell: null,
        greenCells: new Set()
    }

    duel = Array.from(new Array(25), (_, i) => i);

    setGreen = () => {
        this.setState({
            randomCell: null,
            greenCells: this.state.greenCells.add(this.state.randomCell)
        });

    };

    numRandom = () => {
        const {greenCells} = this.state;
        const freeCell = this.duel.filter(i => !greenCells.has(i))
        const randomCell = freeCell[Math.floor(freeCell.length * Math.random())];
        this.setState({ randomCell });
        clearTimeout(this.timer);
        this.timer = setTimeout(this.numRandom, 1000);
    };

    render() {
        const { randomCell, greenCells } = this.state;
        if(greenCells.size == this.duel.length) return <h1>Game over</h1>;
        return <div className="game">
            <div>
                <button onClick={this.numRandom}>Play</button>
            </div>

            <div>{
                this.duel.map(i => {
                    const style = {};
                    if(greenCells.has(i))
                        style.backgroundColor = "green";
                    if(randomCell === i)
                        style.backgroundColor = "blue";
                    return <div
                        className="cell"
                        style={style}
                        onClick={randomCell === i ? this.setGreen : null}
                    ></div>
                })
            }</div>
        </div>
    }
}

ReactDOM.render(<Game />, document.getElementById("root"))

    </script>
</body>
</html>

Последний раз редактировалось рони, 25.11.2019 в 11:19.
Ответить с цитированием