反应ES6运动问题(游戏项目)

时间:2018-01-25 22:55:02

标签: javascript reactjs events javascript-events keyboard-events

这次,由于我几乎修复了所有内容,因此我在简单的游戏中遇到了一个新的问题。如果你可以检查我做错了什么......我console.log(),每个方向负责运动,不知道该怎么做才能做到这一点"可移动",它会增长,自杀,一切反而运动是好的。

我会尝试将其放入代码段以避免垃圾邮件(新手风格)。

无论如何你可以检查:

if (this.nextDirection) {
    this.state.direction = this.nextDirection;
    this.nextDirection = null;
}

或者我的活动被破坏了:

handleKey(event) {
    let direction = event.nativeEvent.keyCode;
    console.log(direction);
    let difference = Math.abs(this.state.direction - direction);
    if (DIRS[direction] && difference !== 0 && difference !== 2) {
        this.nextDirection = direction;
    }
}

如果您需要任何细节,请告诉我们!



import ReactDOM from 'react-dom';
import React from "react";
import {Router, Route, Link, IndexLink, IndexRoute, hashHistory} from 'react-router';

const BODY = 1, FOOD = 2;
const KEYS = {left: 37, up: 38, right: 39, down: 40};
const DIRS = {37: true, 38: true, 39: true, 40: true};


export class SnakeGames extends React.Component {
    constructor(props) {
        super(props);

        const start = this.props.startIndex || 201;   
        const snake = [start];
        const board = [];
        board[start] = BODY;
        this.state = {
            snake: snake,
            board: board,
            growth: 0,
            paused: true,
            gameOver: false,
            direction: KEYS.right,
        }

    }

    componentDidMount() {
        this.resume();
        setTimeout(() => {
            this.tick();
        }, 100);
    }


    pause() {
        if (this.state.gameOver || this.state.paused) {
            return;
        }
        this.setState({paused: true});
    }

    resume() {
        if (this.state.gameOver || !this.state.paused) {
            return;
        }
        this.setState({paused: false});
        this.refs.board.focus();
        this.tick();
    }

    tick() {
        if (this.state.paused) {
            return;
        }


        const snake = this.state.snake;
        const board = this.state.board;
        let growth = this.state.growth;
        let direction = this.state.direction;

        let numRows = this.props.numRows || 20;
        let numCols = this.props.numCols || 20;
        let head = getNextIndex(snake[0], direction, numRows, numCols);

        if (snake.indexOf(head) !== -1) {
            this.setState({gameOver: true});
            return;
        }

        const needsFood = board[head] === FOOD || snake.length === 1;
        if (needsFood) {
            let ii;
            const numCells = numRows * numCols;
            do {
                ii = Math.floor(Math.random() * numCells);
            } while (board[ii]);
            board[ii] = FOOD;
            growth += 2;
        } else if (growth) {
            growth -= 1;
        } else {
            board[snake.pop()] = null;
        }
        snake.unshift(head);
        board[head] = BODY;

        if (this.nextDirection) {
            this.state.direction = this.nextDirection;
            this.nextDirection = null;
        }

        this.setState({
            snake: snake,
            board: board,
            growth: growth,
            direction: direction
        });

        setTimeout(() => {
            this.tick();
        }, 100);
    }

    handleKey(event) {
        let direction = event.nativeEvent.keyCode;
        console.log(direction);
        let difference = Math.abs(this.state.direction - direction);
        if (DIRS[direction] && difference !== 0 && difference !== 2) {
            this.nextDirection = direction;
        }
    }


    render() {
        const cells = [];
        const numRows = this.props.numRows || 20;
        const numCols = this.props.numCols || 20;
        const cellSize = this.props.cellSize || 30;


        for (let row = 0; row < numRows; row++) {
            for (let col = 0; col < numCols; col++) {
                let code = this.state.board[numCols * row + col];
                let type = code === BODY ? 'body' : code === FOOD ? 'food' : 'null';
                cells.push(<div className={type + '-cell'}/>);
            }
        }

        return (
            <div className="snake-game">
                <AudioGame/>
                <h1 className="snake-score">Score: {this.state.snake.length}</h1>
                <div
                    ref="board"
                    className={'snake-board' + (this.state.gameOver ? ' game-over' : '')}
                    tabIndex={0}
                    onBlur={this.pause.bind(this)}
                    onFocus={this.resume.bind(this)}
                    onKeyDown={this.handleKey.bind(this)}
                    style={{width: numCols * cellSize, height: numRows * cellSize}}>
                    {cells}
                </div>
                <div className="snake-controls">
                    {this.state.paused ?
                        <button onClick={this.resume.bind(this)} className="btn"><Link to="/snakemenu">RETURN</Link>
                        </button> : null}
                    {this.state.paused ?
                        <button onClick={this.resume.bind(this)} className="btn"><Link to="/snakegameover">SCORE</Link>
                        </button> : null}
                    {this.state.gameOver ?
                        <button onClick={this.resume.bind(this)} className="btn"><Link to="/snakegameover">SCORE</Link>
                        </button> : null}
                </div>
            </div>
        );
    }
}


function getNextIndex(head, direction, numRows, numCols) {
    let x = head % numCols;
    let y = Math.floor(head / numCols);

    switch (direction) {
        case KEYS.up:
            y = y <= 0 ? numRows - 1 : y - 1;
            break;
        case KEYS.down:
            y = y >= numRows - 1 ? 0 : y + 1;
            break;
        case KEYS.left:
            x = x <= 0 ? numCols - 1 : x - 1;
            break;
        case KEYS.right:
            x = x >= numCols - 1 ? 0 : x + 1;
            break;
        default:
            return;
    }

    return (numCols * y) + x;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
&#13;
&#13;
&#13;

0 个答案:

没有答案
相关问题