01-使用Javascript和Canvas写一个贪吃蛇

2021.2.10 Canvas+js实现贪吃蛇

贪吃蛇

完成贪吃蛇主要有如下几件事情

  • 利用canvas创建画布,即蛇和食物的活动范围
  • 创建蛇
    • 画出蛇
    • 蛇可以自己动起来 setInterval
    • 蛇可以根据键盘控制方向移动 键盘监听&改变蛇的坐标
    • 蛇吃到食物会增长 蛇要更新
    • 蛇碰到自己会死
    • 蛇从边界出去可以从另一边进来
  • 创建食物
    • 在随机位置生成食物
    • 画出食物

完成这几件事情,就完成了贪吃蛇。

教程参考b站:前端酱的日常

目前版本有以下问题

  • 起始蛇只有一节,应该有一节蛇身,一节蛇头
  • 当蛇吃掉一个食物只有两节长度大小的时候,蛇吃自己的尾巴不会死
  • 食物出现的位置可能在蛇身位置没有排除
  • 当蛇走到边界比如向右快到边界的时候立刻向上或者向下蛇会消失可以在边界游走
  • 当蛇吃掉自己身子的时候死了蛇应该重置回到起始位置并且暂停等待下一轮开始
  • 只有点击start按钮蛇才会开始动,应该按方向键向右或者向下也可以开始游戏
  • 当蛇身长度>=2时,比如向右走时突然向左,相当于蛇吃到自己它会死,而应该直接禁用或者按左没有反应
  • 蛇的控制键只有上下左右,应该按w、a、s、d也可以
  • 蛇死掉后有弹窗,弹窗上除了游戏结束,还应该有分数
  • 贪吃蛇右边栏button底下可以有游戏分数排行榜。
  • 可以有随机时间随机地点出现的特殊食物,吃到后有不同的奖励。

目前代码有点不理解的地方在于函数传参传的是对象,在解构赋值时有点不理解。
然后今天,看电脑脖子肩膀很酸痛很累,要注意休息。

index.html

<!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>贪吃蛇</title>
    <link rel="stylesheet" href="./style.css">

    <body>
        <h2>Snake Game</h2>
        <div class="container">
            <canvas class="canvas" width="400" height="400"></canvas>
            <div class="operations">
                <div class="score">
                    Score:<span id="score">0</span>
                </div>
                <button id="start">Start</button>
                <button id="pause">Pause</button>
            </div>
        </div>

        <script src="./Target.js"></script>
        <script src="./snake.js"></script>
        <script src="./index.js"></script>

    </body>

</html>

style.css

body {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    height: 100vh;
    margin: 0;
}

.container {
    display: flex;
    align-items: flex-start;
}

.canvas {
    background-color: #3e3e3e;
    box-shadow: 0 1px 10px #3e3e3e;
    margin-right: 10px;
}

.operations {
    display: flex;
    flex-direction: column;
    width: 85px;
}

.score {
    margin-bottom: 15px;
}

button {
    margin-bottom: 10px;
    height: 25px;
    background-color: #55c4d0;
    border: none;
    box-shadow: 0 1px 5px #55c4d0;
    outline: none;
    cursor: pointer;
    color: #fff;
}

button:active {
    transform: scale(0.9);
    background-color: #04def7;
}

index.js

const canvas = document.querySelector('.canvas');
const ctx = canvas.getContext('2d');

//设置小方块大小
const size = 10;
const rows = canvas.height / size;
const columns = canvas.width / size;

//点击start按钮的时候小蛇开始移动
//获取start按钮
const startBtn = document.getElementById('start')
const pauseBtn = document.getElementById('pause')

//让蛇拿到canvas画笔
let snake = new Snake(size, { canvas, ctx })
let target = new Target(size, { canvas, ctx, rows, columns })
let timer = null

function init() {
    target.genRandomLocation()
    target.draw()
    snake.draw()
}
init();

//写一个让小蛇开始动的start方法
function start() {
    //用定时器让他动起来
    timer = setInterval(() => {
        //移动之前要清除一下canvas画布
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        target.draw();
        snake.update();
        snake.draw()

        //如果蛇吃掉食物
        if (snake.eatTarget(target)) {
            target.genRandomLocation();
        }

        //给蛇添加结束条件
        snake.checkCollision()
            //设置分数
        document.getElementById('score').innerText = snake.targetNum * 10;
    }, 100);
}

//给start按钮添加一个事件监听函数
startBtn.addEventListener('click', () => {
        start()
    })
    //暂停就是取消定时器
pauseBtn.addEventListener('click', () => {
    clearInterval(timer)
})

//给window添加事件监听函数,处理keydown
window.addEventListener('keydown', (event) => {
    //console.log(event.key);
    const direction = event.key.replace('Arrow', '');
    console.log('direction:', direction);
    snake.changeDirection(direction);
})

snake.js

function Snake(size = 10, canvasOptions) {
    this.x = 0;
    this.y = 0;
    this.size = size;
    this.xSpeed = size * 1;
    this.ySpeed = 0;
    //吃的食物总数
    this.targetNum = 0;
    //尾巴坐标值
    this.tails = [];
    this.canvasOptions = canvasOptions;
}

//蛇的draw()方法,画一条蛇
Snake.prototype.draw = function() {
    const { ctx } = this.canvasOptions;
    /* console.log(this.canvasOptions)
    console.log(ctx); */
    //console.log(ctx);
    ctx.fillStyle = '#fff'

    for (let i = 0; i < this.tails.length; i++) {
        const { x, y } = this.tails[i];
        ctx.fillRect(x, y, this.size, this.size)
    }

    ctx.fillRect(this.x, this.y, this.size, this.size)
}

//蛇的更新函数
Snake.prototype.update = function() {
    for (let i = 0; i < this.tails.length - 1; i++) {
        //console.log(this.tails.length);
        this.tails[i] = this.tails[i + 1];
    }

    if (this.targetNum > 0) {
        this.tails[this.targetNum - 1] = { x: this.x, y: this.y }
    }

    this.x += this.xSpeed;
    this.y += this.ySpeed;
    console.log(this.targetNum);

    //判断边界
    const { width, height } = this.canvasOptions.canvas
    if (this.x > width) {
        this.x = 0
    }
    if (this.y > height) {
        this.y = 0
    }
    if (this.x < 0) {
        this.x = width
    }
    if (this.y < 0) {
        this.y = height
    }
}

Snake.prototype.changeDirection = function(direction) {
    switch (direction) {
        //根据方向来修改横坐标与纵坐标的速度
        case 'Up':
            this.xSpeed = 0;
            this.ySpeed = -size * 1;
            break;
        case 'Left':
            this.xSpeed = -size * 1;
            this.ySpeed = 0;
            break;
        case 'Down':
            this.xSpeed = 0;
            this.ySpeed = size * 1;
            break;
        case 'Right':
            this.xSpeed = size * 1;
            this.ySpeed = 0;
            break;
            /* case 'w':
                this.xSpeed = 0;
                this.ySpeed = -size * 1; */

    }
}

Snake.prototype.eatTarget = function(target) {
        if (this.x === target.x && this.y === target.y) {
            this.targetNum++;
            console.log(this.targetNum);
            return true;
        }
        return false;
    }
    //蛇吃到自己就结束
Snake.prototype.checkCollision = function() {
    for (let i = 0; i < this.tails.length; i++) {
        if (this.x === this.tails[i].x && this.y === this.tails[i].y) {
            this.targetNum = 0;
            this.tails = []
            alert('u are dead')
        }

    }
}

Target.js

const colors = ['#e74c3c', '#8e44ad', '#3498db', '#e67e22', '#2ecc71']
    //食物随机颜色
function getRandomColor() {
    return colors[Math.floor(Math.random() * colors.length)]
}
//蛇要吃的东西
function Target(size = 10, canvasOptions) {
    this.x;
    this.y;
    this.size = size;
    this.canvasOptions = canvasOptions;

}

//生成随机位置
Target.prototype.genRandomLocation = function() {
        const { rows, columns } = this.canvasOptions;
        this.x = (Math.floor(Math.random() * columns - 1) + 1) * this.size;
        this.y = (Math.floor(Math.random() * rows - 1) + 1) * this.size;
        this.color = getRandomColor();
    }
    //画食物
Target.prototype.draw = function() {
    const { ctx } = this.canvasOptions;
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.size, this.size)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以给你提供一个简单的贪吃蛇游戏的代码,你可以在网页上运行它。 HTML 代码: ``` <!DOCTYPE html> <html> <head> <title>贪吃蛇游戏</title> <style> canvas { border: 1px solid #000; } </style> </head> <body> <h1>贪吃蛇游戏</h1> <canvas id="gameCanvas" width="400" height="400"></canvas> <script src="snake.js"></script> </body> </html> ``` JavaScript 代码: ```javascript // 获取 canvas 元素 var canvas = document.getElementById("gameCanvas"); var ctx = canvas.getContext("2d"); // 定义游戏参数 var blockSize = 10; // 方块大小 var widthInBlocks = canvas.width / blockSize; var heightInBlocks = canvas.height / blockSize; var score = 0; // 定义绘制方块的函数 var drawBlock = function(ctx, position) { var x = position[0] * blockSize; var y = position[1] * blockSize; ctx.fillRect(x, y, blockSize, blockSize); }; // 定义绘制分数的函数 var drawScore = function() { ctx.font = "20px Arial"; ctx.fillStyle = "Black"; ctx.textAlign = "left"; ctx.textBaseline = "top"; ctx.fillText("Score: " + score, blockSize, blockSize); }; // 定义清除画布的函数 var clearCanvas = function() { ctx.clearRect(0, 0, canvas.width, canvas.height); }; // 定义游戏结束的函数 var gameOver = function() { clearInterval(intervalId); ctx.font = "60px Arial"; ctx.fillStyle = "Black"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText("Game Over", canvas.width / 2, canvas.height / 2); }; // 定义方块的构造函数 var Block = function(col, row) { this.col = col; this.row = row; }; // 定义判断方块是否在画布内的函数 Block.prototype.insideCanvas = function() { return (this.col >= 0 && this.col < widthInBlocks && this.row >= 0 && this.row < heightInBlocks); }; // 定义判断方块是否在同一个位置的函数 Block.prototype.equal = function(otherBlock) { return (this.col === otherBlock.col && this.row === otherBlock.row); }; // 定义蛇的构造函数 var Snake = function() { this.segments = [ new Block(7, 5), new Block(6, 5), new Block(5, 5) ]; this.direction = "right"; this.nextDirection = "right"; }; // 定义绘制蛇的函数 Snake.prototype.draw = function() { for (var i = 0; i < this.segments.length; i++) { drawBlock(ctx, this.segments[i].position()); } }; // 定义移动蛇的函数 Snake.prototype.move = function() { var head = this.segments[0]; var newHead; this.direction = this.nextDirection; if (this.direction === "right") { newHead = new Block(head.col + 1, head.row); } else if (this.direction === "down") { newHead = new Block(head.col, head.row + 1); } else if (this.direction === "left") { newHead = new Block(head.col - 1, head.row); } else if (this.direction === "up") { newHead = new Block(head.col, head.row - 1); } if (this.checkCollision(newHead)) { gameOver(); return; } this.segments.unshift(newHead); if (newHead.equal(apple.position())) { score++; apple.move(); } else { this.segments.pop(); } }; // 定义检查蛇是否碰到边界或自己的函数 Snake.prototype.checkCollision = function(head) { var leftCollision = (head.col === 0); var topCollision = (head.row === 0); var rightCollision = (head.col === widthInBlocks - 1); var bottomCollision = (head.row === heightInBlocks - 1); var wallCollision = leftCollision || topCollision || rightCollision || bottomCollision; var selfCollision = false; for (var i = 0; i < this.segments.length; i++) { if (head.equal(this.segments[i])) { selfCollision = true; } } return wallCollision || selfCollision; }; // 定义改变蛇的方向的函数 Snake.prototype.setDirection = function(newDirection) { if (this.direction === "up" && newDirection === "down") { return; } else if (this.direction === "right" && newDirection === "left") { return; } else if (this.direction === "down" && newDirection === "up") { return; } else if (this.direction === "left" && newDirection === "right") { return; } this.nextDirection = newDirection; }; // 定义苹果的构造函数 var Apple = function() { this.position = function() { var col = Math.floor(Math.random() * (widthInBlocks - 2)) + 1; var row = Math.floor(Math.random() * (heightInBlocks - 2)) + 1; return new Block(col, row); }; this.move = function() { this.block = this.position(); }; this.block = this.position(); }; // 创建蛇和苹果对象 var snake = new Snake(); var apple = new Apple(); // 定义游戏循环 var intervalId = setInterval(function() { clearCanvas(); drawScore(); snake.move(); snake.draw(); apple.draw(); }, 100); // 定义键盘按下事件 var directions = { 37: "left", 38: "up", 39: "right", 40: "down" }; document.addEventListener("keydown", function(event) { var newDirection = directions[event.keyCode]; if (newDirection !== undefined) { snake.setDirection(newDirection); } }); ``` 这个代码实现了一个简单的贪吃蛇游戏,你可以在浏览器中打开 HTML 文件,就可以运行游戏了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值