JavaScript实现贪吃蛇游戏

本文实例为大家分享了JavaScript实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下

通过JavaScript,我们可以实现贪吃蛇游戏,具体功能如下:

(1)通过按上下左右键来改变蛇的移动方向

(2)若蛇撞到自己,则游戏结束

(3)蛇移动出地图边缘时,会从地图的另一边进来

(4)长按方向键,蛇加速移动

(5)蛇吃到食物后,重新生成食物

完整代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //地图对象
        var Map;
        Map = {
            width: 990,
            height: 600,
            backgroundColor: 'rgba(36, 30, 225, 0.25)',
            map: null,
            createMap: function () {
                if (this.map == null) {
                    this.map = document.createElement("div");
                }
            },
            adornMap: function () {
                this.map.style.position = "relative";
                this.map.style.width = this.width + "px";
                this.map.style.height = this.height + "px";
                this.map.style.backgroundColor = this.backgroundColor;
            },
            initialize: function () {
                this.createMap();
                this.adornMap();
                document.body.appendChild(this.map);
            }
        };
        //蛇对象
        var Snake;
        Snake = {
            snakeWidth: 30,
            snakeHeight: 30,
            snake: [[3, 1, null, 'red'], [2, 1, null, 'black'], [1, 1, null, 'black']],
            maP: null,
            direct: "right",
            timer: null,
            createSnake: function () {
                for (var i = 0; i < this.snake.length; i++) {
                    if (this.snake[i][2] == null) {
                        this.snake[i][2] = document.createElement("div");
                    }
                    this.snake[i][2].style.width = this.snakeWidth + "px";
                    this.snake[i][2].style.height = this.snakeHeight + "px";
                    this.snake[i][2].style.backgroundColor = this.snake[i][3];
                    this.snake[i][2].style.position = "absolute";
                    this.snake[i][2].style.left = this.snake[i][0] * this.snakeWidth + "px";
                    this.snake[i][2].style.top = this.snake[i][1] * this.snakeHeight + "px";
                    this.maP.appendChild(this.snake[i][2]);
                }
            },
            move: function () {
                //蛇身移动
                for (var i = this.snake.length - 1; i > 0; i--) {
                    this.snake[i][0] = this.snake[i - 1][0];
                    this.snake[i][1] = this.snake[i - 1][1];
                }
                //蛇头移动
                switch (this.direct) {
                    case "left":
                        this.snake[0][0] -= 1;
                        break;
                    case "right":
                        this.snake[0][0] += 1;
                        break;
                    case "up":
                        this.snake[0][1] -= 1;
                        break;
                    case "down":
                        this.snake[0][1] += 1;
                        break;
                }
                //防止蛇移动至地图外
                if (this.snake[0][0] > 32) {
                    this.snake[0][0] = 0;
                }
                if (this.snake[0][0] < 0) {
                    this.snake[0][0] = 32;
                }
                if (this.snake[0][1] < 0) {
                    this.snake[0][1] = 19;
                }
                if (this.snake[0][1] > 19) {
                    this.snake[0][1] = 0;
                }
                //若蛇撞到自己,则游戏结束
                for (var i = 1; i < this.snake.length; i++) {
                    if (this.snake[0][0] == this.snake[i][0] && this.snake[0][1] == this.snake[i][1]) {
                        clearInterval(this.timer);
                        alert("游戏结束!");
                        return;
                    }
                }
                //蛇吃到食物时,重新生成食物位置,蛇身变长一节
                if (this.snake[0][0] == Food.left && this.snake[0][1] == Food.top) {
                    Food.createFood();
                    this.snake.push(
                        [
                            this.snake[this.snake.length - 1][0],
                            this.snake[this.snake.length - 1][1],
                            null,
                            "black"
                        ]
                    )
                }
                this.createSnake();
            },
            initialize: function () {
                var that = this;
                that.createSnake();
                that.timer = setInterval(function () {
                    that.move();
                }, 500)
            }
        };
        //食物对象
        var Food;
        Food = {
            foodWidth: 30,
            foodHeight: 30,
            backgroundColor: "orange",
            left: null,
            top: null,
            maP: null,
            snakE: null,
            food: null,
            //创建食物
            createFood: function () {
                this.randomPosition();
                if (this.food == null) {
                    this.food = document.createElement('div');
                    this.food.style.width = this.foodWidth + "px";
                    this.food.style.height = this.foodHeight + "px";
                    this.food.style.backgroundColor = this.backgroundColor;
                    this.food.style.position = "absolute";
                    this.maP.appendChild(this.food);
                }
                this.food.style.left = this.left * this.foodWidth + "px";
                this.food.style.top = this.top * this.foodHeight + "px";
            },
            //随机生成食物位置
            randomPosition: function () {
                var repeat;
                do {
                    repeat = false;
                    this.left = Math.floor(Math.random() * 33);
                    this.top = Math.floor(Math.random() * 20);
                    for (var i = 0; i < this.snakE.length; i++) {
                        if (this.left == this.snakE[i][0] && this.top == this.snakE[i][1]) {
                            repeat = true;
                        }
                    }
                } while (repeat)
            }
        };
        window.addEventListener('load', function () {
            Map.initialize();
            Snake.maP = Map.map;
            Snake.initialize();
            Food.maP = Map.map;
            Food.snakE = Snake.snake;
            Food.createFood();
            //按上下左右键,蛇改变移动方向
            window.addEventListener('keyup', function (e) {
                var direct = e.keyCode;
                switch (direct) {
                    case 37:
                        if (Snake.direct == "right") {
                            return;
                        }
                        Snake.direct = "left";
                        break;
                    case 38:
                        if (Snake.direct == "down") {
                            return;
                        }
                        Snake.direct = "up";
                        break;
                    case 39:
                        if (Snake.direct == "left") {
                            return;
                        }
                        Snake.direct = "right";
                        break;
                    case 40:
                        if (Snake.direct == "up") {
                            return;
                        }
                        Snake.direct = "down";
                        break;
                }
            })
            //长按方向键加速移动
            var lastKey = -1;
            window.addEventListener('keydown', function (e) {
                if (e.keyCode == lastKey) {
                    switch (e.keyCode) {
                        case 37:
                            if (Snake.direct == "right") {
                                return;
                            }
                            Snake.direct = "left";
                            break;
                        case 38:
                            if (Snake.direct == "down") {
                                return;
                            }
                            Snake.direct = "up";
                            break;
                        case 39:
                            if (Snake.direct == "left") {
                                return;
                            }
                            Snake.direct = "right";
                            break;
                        case 40:
                            if (Snake.direct == "up") {
                                return;
                            }
                            Snake.direct = "down";
                            break;
                    }
                    Snake.move();
                }
                lastKey = e.keyCode;
            })
        })
    </script>
</body>

</html>

效果图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • JS实现的贪吃蛇游戏完整实例

    本文实例讲述了JS实现的贪吃蛇游戏.分享给大家供大家参考,具体如下: 思想: 1.设计蛇:属性有宽.高.方向.状态(有多少节),方法:显示,跑 2.设计食物:属性宽.高 3.显示蛇:根据状态向地图里加元素 4.蛇跑起来:下一节到前一节的位置,蛇头根据方向变,删除原来的蛇,新建蛇:当出界时,死亡,初始化:当蛇头吃到自己的时候,死亡,初始化 5.食物被吃掉,蛇加一节,去掉原来的食物,生成新的食物 6.添加定时器,绑定按键 完整示例: <!doctype html> <html lang=&q

  • js贪吃蛇游戏实现思路和源码

    本文实例为大家分享了js贪吃蛇游戏的相关代码,供大家参考,具体内容如下 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>贪吃蛇小游戏</title> <style> *{margin:0; padding:0;} header { display: block; margin: 0 auto;

  • js实现贪吃蛇小游戏(容易理解)

    话不多说,请看代码: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>贪吃蛇</title> <link rel="stylesheet" href="style.css"> <script src="style.js" >

  • 20行js代码实现的贪吃蛇小游戏

    前言 最近在csdn上看到一位大神用20行代码就写出了一个贪吃蛇的小游戏,感觉被惊艳到了,就试着读了一下这段代码,阅读过程中不断为作者写法的巧妙而叫绝,其中我发现自己对运算符优先级和一些js的技巧不是很清楚,所以看完之后决定把思路分享出来,方便和我一样的小白学习. 我对代码稍稍做了些修改,并添加了一些注释,方便理解. 示例代码 <!DOCTYPE html> <html lang="en"> <head> <meta charset="

  • 原生js实现的贪吃蛇网页版游戏完整实例

    本文实例讲述了原生js实现的贪吃蛇网页版游戏.分享给大家供大家参考.具体实现方法如下: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>原生js写的贪吃蛇网页版游戏</title> </head> <body> </body> <sc

  • JS写的贪吃蛇游戏(个人练习)

    JS贪吃蛇游戏,个人练习之用,放在这备份一下,   复制代码 代码如下: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JS贪吃蛇-练习</t

  • javascript贪吃蛇完整版(源码)

    javascript贪吃蛇完整版 注释完整,面向对象 复制代码 代码如下: <html><head>    <title>贪吃蛇 Snake v2.4</title><style>    body{        font-size:9pt;    }    table{        border-collapse: collapse;        border:solid #333 1px;    }    td{        heigh

  • js编写“贪吃蛇”的小游戏

    贪吃蛇儿时的回忆,今天刚好学习到这了,就刚好做了一个,也是学习了吧,需要掌握的知识: 1.JS函数的熟练掌握, 2.JS数组的应用, 3.JS小部分AJAX的学习 4.JS中的splice.shift等一些函数的应用, 基本上就这些吧,下面提重点部分: 前端的页面,这里可自行布局,我这边提供一个我自己的布局: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org

  • javascript实现简单的贪吃蛇游戏

    javascript实现简单的贪吃蛇游戏,功能很简单,代码也很实用,就不多废话了,小伙伴们参考注释吧. <html> <head> <meta http-equiv='content-type' content='text/html;charset=utf-8'> <title>贪吃蛇</title> <script type="text/javascript"> var map; //地图 var snake;

  • javascript 贪吃蛇实现代码

    在习作的过程中尝试着贪吃蛇游戏用JS实现了.竟然成功了. 思路:使用10px*10px的div层担当"像素",然后使用40*40矩阵160个"像素"构成了游戏的界面. 下面是代码: 复制代码 代码如下: // JavaScript Document alert("键盘的方向键控制方向,空格键暂停.\nLIFE制作\nhttp://blog.csdn.net/anhulife"); // 添加基本的图形块,即160个10 * 10的层组成的二维矩阵

随机推荐