效果演示: 文末获取源码
![]()
代码目录:
主要代码实现:
部分代码 :
<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) {//一组方向键 一组字母 WASDcase 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天
大家可以点赞、收藏、关注、评论我啦 、需要完整文件随时或交流查看下方微信获取哟~!