简体   繁体   English

此JavaScript Snake游戏中的错误是什么?

[英]What is the bug in this JavaScript Snake Game?

I used this tutorial: Snake Game HTML5 Game Programming Tutorial javascript to make a similar game. 我使用了本教程:Snake Game HTML5游戏编程教程javascript来制作类似的游戏。

The problem is about the movement of the snake: 问题在于蛇的运动:

The snake should move properly after pressing a arrow key but it doesn't and it moves automatically by itself. 按下箭头键后,蛇应该可以正确移动,但是不能移动,它会自动移动。 At the same time, the food (apple) is not visible in the game. 同时,食物(苹果)在游戏中不可见。 Here is the JS Fiddle with CSS and HTML file included: 这是包含CSS和HTML文件的JS小提琴:

https://jsfiddle.net/L734u1y9/#&togetherjs=SeiyP5qa1m https://jsfiddle.net/L734u1y9/#&togetherjs=SeiyP5qa1m

Can somebody help me to find the error? 有人可以帮我找到错误吗?

//Constants
            var COLS= 26, ROWS = 26;
//IDs
            var EMPTY = 0, SNAKE = 1, FRUIT = 2;
//Directions
            var LEFT = 0, UP = 1, RIGHT = 2, DOWN = 3;
//KeyCodes
            var KEY_LEFT = 27, KEY_UP = 38, KEY_RIGHT = 39, KEY_DOWN = 40;

            var grid= {

                width: null,
                height:null,
                _grid: null,


                init: function(d, c, r) {
                    this.width = c;
                    this.height = r;

                this._grid = [];
                for (var x = 0; x < c; x++) {
                this._grid.push([]);
                    for (var y = 0; y < r; y++){
                        this._grid[x].push(d);
                }
              }
            },

                set: function(val, x, y) {
                    this._grid[x][y] = val;

                },

                get: function (x, y) {
                    return this._grid[x][y]; 
                }
            };

            var snake= {
                direction:null,
                last: null,
                _queue: null,

                init: function (d, x, y) {
                    this.direction = d;

                    this._queue = [];
                    this.insert (x, y);

                },

                insert: function(x, y) {
                    this._queue.unshift({x:x, y:y});
                    this.last = this._queue[0];

                },

                remove: function() {
                    return this._queue.pop();


                }
            };

            function setFood() {
                var empty = [];
                for (var x = 0; x < grid.width; x++) {
                    for (var y = 0; y < grid.height; y++) {
                        if(grid.get(x, y) === EMPTY) {
                            empty.push({x:x, y:y});
                            }
                                    }
                    }
                var randpos = empty[Math.floor(Math.random()*empty.length)];
                grid.set(FRUIT, randpos.y);

                            }

//Game Objects
            var canvas, ctx, keystate, frames;


            function main() {
                canvas = document.createElement("canvas");
                canvas.width =COLS*20;
                canvas.height = ROWS*20;
                ctx = canvas.getContext("2d");
                document.body.appendChild(canvas);

                frames = 0;
                keystate = {};
                document.addEventListener("keydown", function(evt) {
                    keystate[evt.keyCode] = true;
                });
                document.addEventListener("keyup", function(evt) {
                    delete keystate[evt.keyCode];
                });

                init();
                loop();

            }

            function init () {

                grid.init(EMPTY,COLS, ROWS);

                var sp = {x:Math.floor(COLS/2), y:ROWS-1};
                snake.init (UP, sp.x, sp.y);
                grid.set(SNAKE, sp.x, sp.y);

                setFood();

            } 

            function loop() {
                update();
                draw();

                window.requestAnimationFrame(loop, canvas);

            }

            function update() {
                frames++;

                if (keystate[KEY_LEFT] && snake.direction !== RIGHT) 
                    snake.direction = LEFT;
                if (keystate[KEY_UP] && snake.direction !== DOWN) 
                    snake.direction = UP;
                if (keystate[KEY_RIGHT] && snake.direction !== LEFT) 
                    snake.direction = RIGHT;
                if (keystate[KEY_DOWN] && snake.direction !== UP) 
                    snake.direction = DOWN;



                if (frames%5 === 0 ) {
                    var nx = snake.last.x;
                    var ny = snake.last.x;

                    switch (snake.direction) {
                        case LEFT:
                            nx--;
                            break;
                        case UP:
                            ny--;
                            break;
                        case RIGHT:
                            nx++;
                            break;
                        case DOWN:
                            ny++;
                            break;
                    }

                if (nx < 0 || nx > grid.width-1 || 
                    ny < 0 || ny > grid.height-1 ||
                    grid.get(nx, ny) === SNAKE

                   ) {
                    return init();
                }
                    if (grid.get(nx, ny) === FRUIT) {
                        var tail = {x:nx, y:ny}; 
                        setFood(); 
                    } else {

                    var tail = snake.remove();
                    grid.set(EMPTY, tail.x, tail.y);
                    tail.x = nx;
                    tail.y = ny;

                }

                    grid.set(SNAKE, tail.x, tail.y);

                    snake.insert(tail.x, tail.y);
            }
            }


            function draw() {
                var tw = canvas.width/grid.width;
                var th = canvas.height/grid.height;

                for (var x = 0; x < grid.width; x++) {
                    for (var y = 0; y < grid.height; y++) {
                        switch (grid.get(x, y)) {
                            case EMPTY:
                                ctx.fillStyle = "#fff";
                                break;
                            case SNAKE:
                                ctx.fillStyle = "#0ff";
                                break;
                            case FRUIT:
                                ctx.fillStyle = "#f00";
                                break;
                        }
                        ctx.fillRect(x*tw, y*th, y*th, tw, th);
                                    }
                    }
            }
main();

Alright, I found part of your problem: 好吧,我发现了您的问题的一部分

if (nx < 0 || nx > grid.width-1 || 
                ny < 0 || ny > grid.height-1 ||
                grid.get(nx, ny) === SNAKE

               ) {
               return init();

This constantly calls init over and over which restores your snake to the default position. 不断地反复调用init ,将蛇恢复到默认位置。

Removing this line and your snake stays still until movement starts. 移开这条线,您的蛇将保持静止直到运动开始。

It still pulls down and two the right -- which hints to me that you want to check the direction handling code. 它仍然向下拉,向右两个,这向我暗示您要检查方向处理代码。 Use either the debugging tools built into the browser (or console.log) to ensure those values are what you think they are. 使用浏览器中内置的调试工具(或console.log)来确保这些值与您想的一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM