效果演示:
代码目录:
主要代码实现:
<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> canvas { border: 1px solid #000000; } </style> </head> <body> <canvas width="980" height="600" id="canvas"></canvas> <script> //初始化变量 var foods = new Array(); //存放食物坐标 var gameover = false; //游戏结束 var gridWidth = 10; //正方形长度 var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); //构建画布 //食物定时器、蛇定时器、场景、蛇对象 var food_interval, snake_interval, Farm, Snake; //方格对象 function node(x, y, w) { var self = this; self.x = x; self.y = y; self.w = w; //食物初始化 self.foodInit = function() { ctx.fillStyle = "#FF0000"; ctx.fillRect(self.x, self.y, self.w, self.w); } //蛇的初始化 self.snakeInit = function() { ctx.fillStyle = "#000000"; ctx.strokeStyle = "#FFFFFF"; ctx.fillRect(x, y, w, w); ctx.strokeRect(x, y, w, w); } //判断两个方块是否重合 self.equals = function(node) { if (self.x == node.x && self.y == node.y) { return true; } else { return false; } } //清除格子 让格子跟背景颜色一样 self.clear = function() { ctx.fillStyle = "#E8FFFF"; ctx.strokeStyle = "#E8FFFF"; ctx.fillRect(x, y, w, w); ctx.strokeRect(x, y, w, w); } } //创建场景对象 function farm() { //保存作用域 var self = this; ctx.fillStyle = "#E8FFFF"; //填充的场景颜色 ctx.fillRect(0, 0, canvas.width, canvas.height); //增加食物的方法 self.addFood = function() { if (gameover) { return gameOver(); //游戏结束方法 } else { //计算随机位置 var x = parseInt(canvas.width / gridWidth * Math.random()) * gridWidth; var y = parseInt(canvas.height / gridWidth * Math.random()) * gridWidth; //实例化一个方格对象 var food = new node(x, y, gridWidth); //得到对象之后,要把食物画到界面上面 food.foodInit(); //追加到数组里面 foods.push(food); } } } //蛇对象 function snake(x, y, len, speed) { var self = this; self.init = function() { self.len = len; //身体长度 self.nodes = new Array(); //蛇的身体数组 self.dir = "R"; //方向 self.speed = speed; //速度 //从右往左,逐格把蛇画出来 var nx = x, ny = y; //蛇的坐标点 for (var i = 0; i < len; i++) { //创建一个方格对象 var tmpNode = new node(nx, ny, gridWidth); //把蛇的身体存放起来 self.nodes[i] = tmpNode; //存放完了之后,把蛇画出来 tmpNode.snakeInit(); nx -= gridWidth; //往左边画 } //让蛇动起来定时器 snake_interval = setInterval(self.move, self.speed); //给蛇绑定方向按键 document.onkeydown = function(e) { //按键的值 var code = e.keyCode; //记录一下旧的方向 self.odir = self.dir; switch (code) { //一组方向键 一组字母 WASD case 65: self.dir = "L"; break; case 87: self.dir = "U"; break; case 68: self.dir = "R"; break; case 83: self.dir = "D"; break; case 37: self.dir = "L"; break; case 38: self.dir = "U"; break; case 39: self.dir = "R"; break; case 40: self.dir = "D"; break; } } }
源码获取
查看博主主页或私信博主获取
精彩推荐更新中:
HTML5大作业实战100套
打卡 文章 更新 40 / 100天
大家可以点赞、收藏、关注、评论我啦 、需要完整文件随时联系我或交流哟~!