Share Code

贪吃蛇 The Snake Game -- 使用Javascri

2018-06-25  本文已影响0人  JKol123

过程

搭建环境

  1. index.html
  2. main.js
<html>
    <head>
        <meta charset="utf8">
        <title>Snake Game</title>
    </head>

    <body>
        <canvas id="game" width="600" height="600"></canvas>

        <script src="./main.js"></script>
    </body>
</html>

设置使用utf8编码,title根据自己的情况设置,添加一个canvas元素,设置id为game,width为600,height为600, 最后引入main.js,我们一会要把我们的游戏逻辑写在main.js里面。

window.onload = function () {
    start();
}

function start() {
    console.log('游戏开始!!!');   
}

完成上面几步之后,在浏览器中打开index.html,控制台中会显示"游戏开始!!!"


01.png

绘制游戏背景

function draw(snake, food)
{
    var canvas = document.getElementById('game');
    var ctx = canvas.getContext('2d');

    // 背景
    ctx.fillStyle = 'black';
    ctx.fillRect(0, 0, areaWidth, areaHeight);
}

这一步我们用来绘制游戏背景。

Snake函数

function Snake()
{
    this.xspeed = 1;
    this.yspeed = 0;
    this.tail = [{x: 0, y: 0}];

    this.update = function () {
        var previousX = this.tail[this.tail.length - 1].x;
        var previousY = this.tail[this.tail.length - 1].y;

        var x = previousX + this.xspeed * scal;
        var y = previousY + this.yspeed * scal;

        // is game over
        if (this.isGameOver(x, y)) {
            finish = true;
            console.log('游戏结束!');
            return;
        }

        if (x === food.x && y == food.y) {
            this.eat();
            this.tail.push({ x: x, y: y });
        } else if (!(x === previousX && y === previousY)) {
            this.tail.shift();
            this.tail.push({ x: x, y: y });
        }
    }

    this.eat = function () {
        food = new Food();
    }

    this.dir = function(xspeed, yspeed) {
        this.xspeed = xspeed;
        this.yspeed = yspeed;
    }

    this.isGameOver = function (nextX, nextY) {
        if (nextX > areaWidth || nextX < 0 || nextY > areaHeight || nextY < 0) {
            return true;
        }

        var found = this.tail.find(function (element) {
            return element.x == nextX && element.y == nextY;
        });

        if (found !== undefined) {
            return true;
        }

        return false;
    }
}

Food函数

function Food()
{
    // 设置随机位置
    this.x = getRandom(0, Math.floor(areaWidth / scal)) * scal;
    this.y = getRandom(0, Math.floor(areaWidth / scal)) * scal;
}  

function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

绘制snake和food

更新draw函数

function draw(snake, food)
{
    var canvas = document.getElementById('game');
    var ctx = canvas.getContext('2d');

    // 背景
    ctx.fillStyle = 'black';
    ctx.fillRect(0, 0, areaWidth, areaHeight);

    // snake
    ctx.fillStyle = 'green';
    for (var i = 0; i < snake.tail.length; i++) {
        ctx.fillRect(snake.tail[i].x, snake.tail[i].y, scal, scal);
    }
    
    // food
    ctx.fillStyle = 'red';
    ctx.fillRect(food.x, food.y, scal, scal);
}

最终代码

<html>
    <head>
        <meta charset="utf8">
        <title>Snake Game</title>
    </head>

    <body>
        <canvas id="game" width="600" height="600"></canvas>

        <script src="./main.js"></script>
    </body>
</html>
window.onload = function() {
    start();
}

var areaWidth = 600;
var areaHeight = 600;
var scal = 20;
var snake = null;
var food = null;
var speed = 200;
var finish = false;
var updateInterval;

function start()
{
    // 初始化游戏
    init();
}

function init()
{
    console.log('Game start!!!');

    snake = new Snake();

    food = new Food();

    // set up
    window.addEventListener('keyup', go);

    update();

    updateInterval = window.setInterval(update, speed);
}

function update()
{
    if (finish) {
        window.clearInterval(updateInterval);
        return;
    }

    draw(snake, food);

    snake.update();
}

function go(e)
{
    switch (e.key) {
        case 'ArrowLeft':
            snake.dir(-1, 0);
            break;
        case 'ArrowRight':
            snake.dir(1, 0);
            break;
        case 'ArrowUp':
            snake.dir(0, -1);
            break;
        case 'ArrowDown':
            snake.dir(0, 1);
            break;
    }
}

function draw(snake, food)
{
    var canvas = document.getElementById('game');
    var ctx = canvas.getContext('2d');

    // 背景
    ctx.fillStyle = 'black';
    ctx.fillRect(0, 0, areaWidth, areaHeight);

    // snake
    ctx.fillStyle = 'green';
    for (var i = 0; i < snake.tail.length; i++) {
        ctx.fillRect(snake.tail[i].x, snake.tail[i].y, scal, scal);
    }
    
    // food
    ctx.fillStyle = 'red';
    ctx.fillRect(food.x, food.y, scal, scal);
}

function Snake()
{
    this.xspeed = 1;
    this.yspeed = 0;
    this.tail = [{x: 0, y: 0}];

    this.update = function () {
        var previousX = this.tail[this.tail.length - 1].x;
        var previousY = this.tail[this.tail.length - 1].y;

        var x = previousX + this.xspeed * scal;
        var y = previousY + this.yspeed * scal;

        // is game over
        if (this.isGameOver(x, y)) {
            finish = true;
            console.log('游戏结束!');
            return;
        }

        if (x === food.x && y == food.y) {
            this.eat();
            this.tail.push({ x: x, y: y });
        } else if (!(x === previousX && y === previousY)) {
            this.tail.shift();
            this.tail.push({ x: x, y: y });
        }
    }

    this.eat = function () {
        food = new Food();
    }

    this.dir = function(xspeed, yspeed) {
        this.xspeed = xspeed;
        this.yspeed = yspeed;
    }

    this.isGameOver = function (nextX, nextY) {
        if (nextX > areaWidth || nextX < 0 || nextY > areaHeight || nextY < 0) {
            return true;
        }

        var found = this.tail.find(function (element) {
            return element.x == nextX && element.y == nextY;
        });

        if (found !== undefined) {
            return true;
        }

        return false;
    }
}

function Food()
{
    this.x = getRandom(0, Math.floor(areaWidth / scal)) * scal;
    this.y = getRandom(0, Math.floor(areaWidth / scal)) * scal;
}

function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

下载链接: http://www.man-ing.com/going

上一篇下一篇

猜你喜欢

热点阅读