用前端技术实现贪吃蛇的小游戏

用前端技术实现贪吃蛇的小游戏

  • 前言
    • 游戏功能
    • 游戏设计
    • 游戏主页代码
    • 游戏中的js代码(snake.js)
    • 游戏运行界面

前言

周末大热天窝在家里无聊,想温习一下前端开发,所以用javascript + css + html开发了个贪吃蛇小有效,分享给大家,一起进步。

游戏功能

绿色方块的食物会每隔3秒出现在一个长方形的地图框里面,蛇是一个由红色的方块(代表头)和两个黄色的小方块(代表身体)组成,如果蛇在移动的过程中撞到食物,就代表把食物吃了,身体长长一块,分数也得一分。蛇撞到地图的边框,游戏结束。
游戏有个开始按钮,点击开始,然后按钮变灰色,等游戏结束后重新使能。

游戏设计

游戏设计有两个对象,一个蛇对象,有绘制方法和移动方法;另一个对象是食物对象,有删除方法和绘制方法。
游戏一启动,5个食物随机出现在地图上,小蛇出现在开始位置,玩家可以通过方向键改变蛇游动的方向,食物每隔3秒消失,然后再次随机出现。

游戏主页代码

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>Snake Food Game.title>
    <style>
        .map {
            height: 600px;
            width: 800px;
            position: relative;
            background-color: whitesmoke;
            border-width: 2px;
            border: 2px solid black;
        }

        .title {
            vertical-align: middle;
            line-height: 100%;
            margin: 20px 0px;
        }
        .title h2 {
            display: inline;
        }
        .title span {
            font-size: 1.5em;
        }

        #start {
            position:absolute;
            top: 20px;
            left: 730px;
            width: 80px;
        }
        
    style>
head>
<body>
    <div class="title">
        <h2>得分:h2>
        <span>0span>
        <input type="button" value="Sart" id="start">
    div>
    <div class="map">div>
    <script src="snake.js">script>
body>
html>

游戏中的js代码(snake.js)

function Food(width, height, color, x, y) {

    this.width = width || 20;
    this.height = height || 20;
    this.color = color || "green";
    this.x = x || 0;
    this.y = y || 0;
    this.food = document.createElement("div");
    this.food.style.position = "absolute"

}

Food.prototype.draw = function (map) {

    this.x = parseInt( Math.random() * (map.scrollWidth / this.width) );
    this.y = parseInt( Math.random() * (map.scrollHeight / this.height) );
    this.food.style.width = this.width + "px";
    this.food.style.height = this.height + "px";
    this.food.style.backgroundColor = this.color;
    this.food.style.left = (this.x * this.width) + "px";
    this.food.style.top = (this.y * this.height) + "px";
    map.appendChild(this.food)

};

Food.prototype.remove = function (map) {

    this.food.remove();
}


function Snake(x, y, direction) {

    this.width = 20;
    this.height = 20;
    this.headx = x || 3;
    this.heady = y || 1;
    this.direction = direction || "right";

    this.body = [
        {x:3,y:1,color:"red"},
        {x:2,y:1,color:"yellow"},
        {x:1,y:1,color:"yellow"}
    ];

    this.body.forEach(part => {
        var bodypart_div = document.createElement("div")
        bodypart_div.style.position = "absolute";
        part.bodydiv = bodypart_div;
    });
}

Snake.prototype.draw = function ( map ) {

    this.body.forEach(part => {
        var bodypart_div = part.bodydiv
        bodypart_div.style.width = this.width + "px";
        bodypart_div.style.height = this.height + "px";
        bodypart_div.style.backgroundColor = part.color;
        bodypart_div.style.left = part.x * this.width + "px";
        bodypart_div.style.top = part.y * this.height + "px";
        bodypart_div.style.position = "absolute";
        map.appendChild(bodypart_div);
    });
};

Snake.prototype.remove = function () {
    
    this.body.forEach(part => {
        if( part.bodydiv ) {
            part.bodydiv.remove();
        }
    });

};

Snake.prototype.move = function ( map, interval, foods, scorediv, btn) {

    var that = this;

    
    var foodtimer = setInterval(function () {
        foods.forEach( food => {
            food.draw(map);
        });
    }, 3000);

    var fun = function () {

        that.remove(map);
        var index = that.body.length - 1;
        while (index > 0) {
            that.body[index].x = that.body[index-1].x;
            that.body[index].y = that.body[index-1].y;
            index--;
        }

        switch(that.direction) {
            case "right":
                that.headx ++;
                break;
            case "left":
                that.headx --;
                break;
            case "top":
                that.heady --;
                break;
            case "bottom":
                that.heady ++;
                break;
            default:
                console.log(that.direction);
        }

        if (that.headx >= map.scrollWidth / that.width ||
            that.heady >= map.scrollHeight / that.height ||
            that.headx < 0 ||
            that.heady < 0 
        ) {
            clearInterval(foodtimer);
            clearInterval(timerid);
            that.remove();
            foods.forEach(food => {
                food.remove();
            });
            btn.removeAttribute("disabled");
            scorediv.textContent = "0";
            alert("Game over!");
        } else {

            for( var i=0; i < foods.length; i++) {

                if (foods[i].x == that.headx && foods[i].y == that.heady) {

                    var obj = {color:"green"};
                    obj.x = that.body[that.body.length - 1].x;
                    obj.y = that.body[that.body.length - 1].y;

                    var bodypart_div = document.createElement("div")
                    bodypart_div.style.position = "absolute";
                    obj.bodydiv = bodypart_div;

                    that.body.push(obj);
                    scorediv.textContent = `${that.body.length - 3}`;

                    foods[i].draw(map)

                    break;
                }
            }
            that.body[0].x = that.headx;
            that.body[0].y = that.heady;
    
            that.draw(map);
        }
    };

    var timerid = setInterval(fun, interval);
};

(function () {

    var startbtn = document.querySelector("#start");

    startbtn.addEventListener('click', (event) => {

        var foodcount = 5
        var snake = new Snake();
        var foods = new Array();
    
        var scorediv = document.querySelector(".title span");
        var map = document.getElementsByClassName("map")[0];
    
        startbtn.setAttribute("disabled", true);

        for(var i=0; i < foodcount; i++) {
            foods.push(new Food());
        }
      
        document.addEventListener("keydown",function (evt) {
            switch (evt.key) {
                case "ArrowUp":
                    snake.direction = "top";
                    break;
                case "ArrowDown":
                    snake.direction = "bottom";
                    break;
                case "ArrowLeft":
                    snake.direction = "left";
                    break;
                case "ArrowRight":
                    snake.direction = "right";
                    break;
            }
    
        });

        foods.forEach( food => {
            food.draw(map);
        });

        snake.move(map, 200, foods, scorediv, startbtn);
      });

} ());

游戏运行界面

用前端技术实现贪吃蛇的小游戏_第1张图片

你可能感兴趣的:(前端开发,前端,javascript,开发语言)