原生js实现一个简单的贪吃蛇小游戏效果代码
代码语言:html
所属分类:游戏
代码描述:原生js实现一个简单的贪吃蛇小游戏效果代码
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <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; } } } //蛇移动方法 self.move = function() { var len = self.len; //获取蛇的身体长度 var head = self.nodes[0];//头部 switch(self.dir) { //右边 case "R": if(head.x + head.w >=canvas.width) { //撞墙 return gameOver(); }else{ //新的头部 var newHead = new node(head.x+head.w,head.y,head.w); } break; //左边 case "L": if(head.x - head.w < 0) { //撞墙 return gameOver(); }else{ //新的头部 var newHead = new node(head.x-head.w,head.y,head.w); } break; case "U": if(head.y -head.w < 0).........完整代码请登录后点击上方下载按钮下载查看
网友评论0