贪食蛇
最近 dan 有在油管上直播,播放量最多的就是手写一个贪食蛇。
本来想学一下大佬写代码的姿势,看了几分钟就没了耐性,心想我为什么不能自己写一个呢。
一步一步跟着敲代码,我实践了一段时间但是收效甚微,因为中间少了自己的思考。
初期可能有些作用,可以学到一些技巧和规范。
但是自己实现一个东西带来的成就感,你不断的 debug 和查文档查资料留下的记忆和习惯,这大概就是这个玩意带给我最大的收获吧。
![图片[1]-canvas贪吃蛇?canvas实现贪食蛇的实践-森戈教程网](https://www.sdfnhw.com/wp-content/uploads/2023/11/20231103040238-654470de3f578.gif)
我的 github 一直是单机模式,如果这篇文章对您有所帮助的话欢迎点个 star
数据结构及变量
const canvas = document.getElementById("canvas") const ctx = canvas.getContext("2d") const width = 400 const height = 400 const cellLength = 20 let foodPosition let initSnake = [ [0, 0], [1, 0], [2, 0], ] let snake = [...initSnake] let direction = "right" let canChangeDirection = true
canvas 绘制页面
// 背景 function drawBackground() { ctx.strokeStyle = "#bfbfbf" for (let i = 0; i <= height / cellLength; i++) { ctx.beginPath() ctx.moveTo(0, cellLength * i) ctx.lineTo(width, cellLength * i) ctx.stroke() } for (let i = 0; i <= width / cellLength; i++) { ctx.beginPath() ctx.moveTo(cellLength * i, 0) ctx.lineTo(cellLength * i, height) ctx.stroke() } } // 蛇 function drawSnake() { let step = 100 / (snake.length - 1) for (let i = 0; i < snake.length; i++) { // 这里做了渐变色的蛇,添加动态色彩。尾部有个最小白色阀值,免得跟背景混为一体 const percent = Math.min(100 - step * i, 90) ctx.fillStyle = `hsl(0,0%,${percent}%)` ctx.fillRect( snake[i][0] * cellLength, snake[i][1] * cellLength, cellLength, cellLength ) } } // 绘制食物 // 随机生成食物的位置 function generateRandomFood() { // 如果没有位置可以生成 if (snake.length > width * height) { return alert("you win") } const randomX = Math.floor(Math.random() * (width / cellLength)) const randomY = Math.floor(Math.random() * (height / cellLength)) // 生成的位置如果跟蛇体积碰撞,则重新生成。 for (let i = 0; i < snake.length; i++) { if (snake[i][0] === randomX && snake[i][1] === randomY) { return generateRandomFood() } } foodPosition = [randomX, randomY] } // 绘制 function drawFood() { ctx.fillStyle = "#ff7875" ctx.fillRect( foodPosition[0] * cellLength, foodPosition[1] * cellLength, cellLength, cellLength ) }
暂无评论内容