JS实现贪吃蛇小游戏

本文介绍了如何使用JavaScript来实现经典贪吃蛇小游戏。首先分析食物对象,包括其属性如宽、高、坐标和背景颜色,以及随机生成和移除食物的方法。接着讨论蛇对象,包含其初始长度、方向等属性,以及生成、吃食物和移动的功能。最后,分析了游戏对象,包括游戏状态和交互。整个过程以逐步构建游戏页面和实现功能为线索。
摘要由CSDN通过智能技术生成
  1. 分析食物

    对象:食物
    属性:宽(width)、高(height)、水平坐标(x)、垂直坐标(y)、背景颜色(bgcolor)
    方法:随机生成、移除食物
    (在此之前可以完成一个小任务,相当于为这一步做铺垫)
    例题:随机生成十个方块,每一秒刷新一次,位置随机,颜色随机

  2. 分析蛇

    对象:蛇
    属性:初始长度(一个个蛇节构成:x,y,color)、方向:(direction)
    方法:生成蛇、吃食物、移动

  3. 分析游戏

    对象:游戏
    属性:蛇、食物、方向
    方法:开始游戏

建成页面 index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
		#container {
		    position: relative;
		    width: 800px;
		    height: 800px;
		    margin: 0 auto;
		    background-color: lightgray;
		}
		#container div {
		    position: absolute;
		}
	</style>
</head>
<body>
    <div id="container">

    </div>

    <script src="js/tools.js"></script>
    <script src="js/food.js"></script>
    <script src="js/snake.js"></script>
    <script src="js/game.js"></script>
    <script>
        var container = document.getElementById('container');
        var game = new Game(container);
        game.startGame(container);
    </script>
</body>
</html>
一个工具 tools.js

将此函数修改为允许接收小数

	var Tools = {
    random: function(min, max) {
        return Math.round(Math.random() * (max - min)) + min;
    }
}
分析食物 food.js
function Food(options) {
    var options = options || {};
    this.width = options.width||20;
    this.height = options.height||20;
    this.x = options.x||0;
    this.y = options.y||0;
    this.bgColor = options.bgColor||'red';
}

// 随机生成
Food.prototype.randomGenerateTo = function(container) {
    // 在生成食物之前,应该将蛇吃的那个食物移除
    var foodId = document.getElementById('food');
    if (foodId) {
        foodId.parentNode.removeChild(foodId);
    }

    // 创建div(document.createElement('div')),添加到父容器当中(appendChild())
    var foodDiv = document.createElement('div');
    foodDiv.setAttribute("id", "food");

    this.x = Tools.random(0, Math.floor(container.offsetWidth / this.width - 1));
    this.y = Tools.random(0, Math.floor(container.offsetHeight / this.height - 1));

    foodDiv.style.width = this.width + 'px';
    foodDiv.style.height = this.height + 'px';
    foodDiv.style.left = this.x * this.width + 'px'; // 位置永远在父容器中
    foodDiv.style.top = this.y * this.height + 'px';
    foodDiv.style.backgroundColor = this.bgColor;

    container.appendChild(foodDiv);
}

分析蛇 snake.js
function Snake(options, container) {
    var options = options||{};

    // 蛇节的宽高,目的是方便将蛇节添加地图,建议蛇节的宽高与食物宽高要一致
    this.width = options.width || 20;
    this.height = options.height || 20;
    this.direction = options.direction || 'right';

    this.body = [
        {x: 3, y: 2, color: '#ff0000'},
        {x: 2, y: 2, color: '#0000ff'},
        {x: 1, y: 2, color: '#0000ff'}
    ];

    // 初始化
    this.init(container);
}

// 将蛇初始化,添加到地图
Snake.prototype.init = function(container) {
    for (var i = 0; i < this.body.length; i++) {
        var bodyItem = this.body[i];

        createNode(container, this, bodyItem);
    }
}

function createNode(container, obj, bodyItem) {
    var item = document.createElement('div');
    item.setAttribute('class', 'snakeNode');
    item.style.width = obj.width + 'px';
    item.style.height = obj.height + 'px';
    item.style.left = bodyItem.x * obj.width + 'px';
    item.style.top = bodyItem.y * obj.height + 'px';
    item.style.backgroundColor = bodyItem.color;
    container.appendChild(item);
};

// 让蛇动起来
// 方法:修改蛇节的位置(x,y),但是并没有动
//       因为蛇节的本质是一个div,因此我们本质是要修改div的位置(left,top)
//  如何拿到蛇节的div?
//  方法一:给蛇节添加class属性,通过getElementByClass()获取所有蛇节
//  方法二:把蛇节放到数组中,从数组中获取
Snake.prototype.move = function(oldDirection) {
    // 蛇的身体也要跟着一起动
    // 蛇的身体的位置是上一个蛇节的位置
    for (var i = this.body.length - 1; i > 0; i--) {
        this.body[i].x = this.body[i-1].x;
        this.body[i].y = this.body[i-1].y;
    }

    switch(this.direction) {
        case 'left':
            if (oldDirection == 'right') {
                this.body[0].x++;
                this.direction = oldDirection;
            }else {
                this.body[0].x--;
            }
        break;
        case 'up':
        if (oldDirection == 'down') {
            this.body[0].y++;
            this.direction = oldDirection;
        }else {
            this.body[0].y--;
        }
        break;
        case 'right':
            if (oldDirection == 'left') {
                this.body[0].x--;
                this.direction = oldDirection;
            } else {
                this.body[0].x++;
            }
        break;
        case 'down':
        if (oldDirection == 'up') {
            this.body[0].y--;
            this.direction = oldDirection;
        } else {
            this.body[0].y++;
        }
        break;
    }

    // 渲染
    this.renderTo();
};

// 重新渲染
Snake.prototype.renderTo = function() {
    var bodys = document.getElementsByClassName('snakeNode');
    for (var i = 0; i < bodys.length; i++ ){
        var bodyDIv = bodys[i];

        bodyDIv.style.left = this.body[i].x * this.width + 'px';
        bodyDIv.style.top = this.body[i].y * this.height + 'px';
    }
}

// 吃食物
// 分析:蛇头与食物的坐标相同,食物重新生成,蛇节增加一节
Snake.prototype.eatFood = function(food, container) {
    var snakeHead = this.body[0];

    if (snakeHead.x == food.x && snakeHead.y == food.y) {
        food.randomGenerateTo(container);

        var nodeX = this.body[this.body.length - 1].x;
        var nodeY = this.body[this.body.length - 1].y;

        var snakeNode = {
            x: nodeX,
            y: nodeY,
            color: '#0000ff'
        }

        this.body.push(snakeNode);

        createNode(container, this, snakeNode);
    }
};
分析游戏 game.js
	function Game(container){
    this.snake = new Snake(null, container);
    this.food = new Food();
    this.food.randomGenerateTo(container);
}

// 开始游戏
Game.prototype.startGame = function(container) {
    
    // 蛇动起来
    snakeRun(this, container);
    // 通过键盘控制蛇的移动
    bindKey(this);
};

// 蛇动起来
function snakeRun(obj, container) {
    var timer = setInterval(function() {
        // 调用蛇的move方法
        obj.snake.move(oldDirection);
        // 边移动,边判断是否吃到食物
        obj.snake.eatFood(obj.food, container);

        // 有没有撞墙壁
        if (obj.snake.body[0].x < 0 || obj.snake.body[0].x * obj.snake.width >= container.offsetWidth) {
            alert("the game is over");
            // 清除定时器
            clearInterval(timer);
        }
        if (obj.snake.body[0].y < 0 || obj.snake.body[0].y * obj.snake.height >= container.offsetHeight) {
            alert("the game is over");
            // 清除定时器
            clearInterval(timer);
        }
        // 撞自己
        for (var i = 1; i < obj.snake.body.length; i++) {
            if (obj.snake.body[0].x == obj.snake.body[i].x && obj.snake.body[0].y == obj.snake.body[i].y) {
                alert("the game is over");
                // 清除定时器
                clearInterval(timer);

                break;
            }
        }
    }, 500);
}

var oldDirection = '';

var preTime = new Date().getTime();

// 监听键盘事件
function bindKey(obj) {
    // 不能反着走
    // 原来的方向是向右,当我按下相反的方向键时,判断如果新的方向与原来的方向相反,判断这次按键无效,并且继续上一次的方向

    // 按键时间小于刷新的时间
    // 如果两次按键的时间小于我刷新的时间,我认为按键无效
    // 

    document.onkeydown = function(ev) {
        var nextTime = new Date().getTime();

        if (Math.abs(nextTime - preTime) > 500) {
            preTime = new Date().getTime();

            oldDirection = obj.snake.direction;
        
            switch(ev.keyCode) {
                case 37:
                // 左
                obj.snake.direction = 'left';
                break;
                case 38:
                // 上
                obj.snake.direction = 'up';
                break;
                case 39:
                // 右
                obj.snake.direction = 'right';
                break;
                case 40:
                // 下
                obj.snake.direction = 'down';
                break;
            }
        }
    };
}

页面显示
在这里插入图片描述

吃食物撞到墙壁
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值