效果图展示:
具体实现代码如下:
(1)html部分
1 !DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <title>贪吃蛇</title> 6 <link rel="stylesheet" type="text/css" href="main.css"> 7 </head> 8 <body onselectstart="return false"> 9 <h1 id="alerts">贪吃蛇</h1> 10 <div id="help"> 11 <span style="float:left">当前得分:<strong id="nowscore">0</strong></span> 12 <span style="float:right">最高分:<strong id="score">0</strong></span> 13 </div> 14 <div id="map"></div> 15 <input type="button" id="btnStart" value="开始游戏" /> 16 <script type="text/javascript" src="gamejs.js"></script> 17 </body> 18 </html>
(2)main.css文件代码
1 * {margin:0; padding:0} 2 body { 3 background:white; 4 -moz-user-select:none; 5 text-align:center; 6 font-size:12px; 7 } 8 9 table{ 10 margin:30px auto 10px auto; 11 overflow:hidden; 12 box-shadow:0px 0px 30px #4EFE93; 13 border:10px solid yellowgreen; 14 border-image: url(border.png); 15 border-image-slice:10; 16 border-image-width:10px; 17 border-image-outset:0; 18 border-image-repeat:repeat; 19 } 20 td { 21 width:20px; 22 height:20px; 23 border:1px solid white; 24 background:white; 25 } 26 .cover {background:url(body1.png);} 27 .food { 28 background:url(food.png); 29 background-repeat:no-repeat; 30 } 31 32 33 #nowscore{ 34 font-size:20px; 35 font-weight: 800; 36 color:blue; 37 } 38 #score{ 39 font-size:20px; 40 font-weight: 800; 41 color:red; 42 } 43 #alerts{ 44 margin-top:50px; 45 color:brown; 46 font-size:30px; 47 font-weight: 800; 48 } 49 #help { 50 width:420px; 51 margin:0 auto; 52 line-height:17px; 53 color:green; 54 } 55 #help span { 56 float:left; 57 font-size:15px; 58 font-weight: 800; 59 margin-right:10px} 60 #help .box { 61 width:15px; 62 height:15px; 63 margin-right:5px; 64 border:1px solid white;} 65 #btnStart { 66 clear:both; 67 width:100px; 68 height:30px; 69 margin-top:10px; 70 padding:0; 71 background:#4EFE93; 72 color:green; 73 border:1px solid #fff; 74 border-bottom-color:#000; 75 border-right-color:#000; 76 border-radius:15px; 77 cursor:pointer}
注意:具体图片可以自行改动
(3)game.js文件代码
1 /* 全局变量 */ 2 3 var WIDTH = 24; 4 var HEIGHT = 24; 5 var len ;//蛇的长度 6 var speed; //爬行速度 7 var gridElems = multiArray(WIDTH,HEIGHT); //地图坐标,table对应的数组 8 var carrier; //蛇标志二维数组 9 var snake; //蛇每节的坐标点 10 var btnStart; 11 var snakeTimer;//蛇行走计时器 12 var directkey; // 键盘按键类型 13 14 /* 其中gridElems和snake,carrier三个数组是完成表格和数组映射的关键 */ 15 16 window.onload = function(){ 17 //info = document.getElementById("alerts"); 18 btnStart = document.getElementById("btnStart"); 19 initGrid(); 20 document.onkeydown = attachEvents; //键盘事件获取,跨浏览器事件处理 21 btnStart.onclick = function (e) { 22 start(); 23 btnStart.setAttribute("disabled",true); 24 btnStart.style.color = "gray"; 25 } 26 } 27 28 29 30 31 32 33 34 35 36 37 38 //开始游戏 39 function start() { 40 len = 3; 41 speed = 10; 42 directkey = 39; 43 carrier = multiArray(WIDTH,HEIGHT); 44 snake = new Array(); 45 clear(); 46 initSnake(); //蛇初始化 47 addObject("food"); 48 walk(); 49 50 } 51 52 53 //创建地图,DOM节点创建增加 54 function initGrid() { 55 var body = document.getElementsByTagName("body")[0]; 56 var table = document.createElement("table"); 57 var tbody = document.createElement("tbody"); 58 for(var j = 0; j < HEIGHT; j++) { 59 var col = document.createElement("tr"); 60 for(var i = 0; i < WIDTH; i++) { 61 var row = document.createElement("td"); 62 gridElems[i][j] = col.appendChild(row); //完成表格和二维数组的映射 63 } 64 tbody.appendChild(col); 65 } 66 table.appendChild(tbody); 67 document.getElementById("map").appendChild(table);//向div中添加创建好的表格 68 } 69 70 71 //一开始创建蛇 72 function initSnake() { 73 var pointer = randomPointer(len-1, len-1, WIDTH/2); 74 for(var i = 0; i < len; i++) { 75 var x = pointer[0] - i;//产生三个相连的表格 76 var y = pointer[1]; 77 snake.push([x,y]);//采用数组压栈方法(js数组自带方法)将产生的蛇坐标压入坐标数组中 78 carrier[x][y] = "cover"; 79 } 80 } 81 82 83 //添加键盘事件,防止浏览器不兼容 84 function attachEvents(e) { 85 e = e || event; 86 directkey = Math.abs(e.keyCode - directkey) != 2 && e.keyCode > 36 && e.keyCode < 41 ? e.keyCode : directkey; //非方向键、反向无效 87 return false; 88 } 89 90 //设置间隔计时器,使蛇运动 91 function walk() { 92 if(snakeTimer) window.clearInterval(snakeTimer); 93 snakeTimer = window.setInterval(step, Math.floor(3000/speed));//3000/speed呈现速度效果 94 } 95 96 //核心部分 97 function step() { 98 //获取目标点 99 var headX = snake[0][0];//从坐标数组中获取蛇头坐标 100 var headY = snake[0][1]; 101 switch(directkey) { //进行按键位判断,蛇转向 102 case 37: headX -= 1; break; 103 case 38: headY -= 1; break; 104 case 39: headX += 1; break 105 case 40: headY += 1; break; 106 } 107 //死亡检测 108 if(headX >= WIDTH || headX < 0 || headY >= HEIGHT || headY < 0 || carrier[headX][headY] == "cover" ) { 109 alert("辣鸡高城,你挂了!"); 110 if((document.getElementById("score").innerHTML)*1 < len) 111 {document.getElementById("score").innerHTML=len;}//最高分信息 112 btnStart.removeAttribute("disabled");//释放“开始游戏”按钮 113 btnStart.style.color = "#000";//释放“开始游戏”按钮 114 window.clearInterval(snakeTimer);//清屏 115 return; 116 } 117 //加速,吃到食物后提速 118 if(len % 4 == 0 && speed < 60 && carrier[headX][headY] == "food") { 119 speed += 5; 120 walk(); 121 } 122 if(carrier[headX][headY] != "food") { 123 var lastX = snake[snake.length-1][0];//提取蛇的尾部坐标 124 var lastY = snake[snake.length-1][1];//提取蛇的尾部坐标 125 carrier[lastX][lastY] = false;//蛇尾移动 126 gridElems[lastX][lastY].className = "";//制空单元格背景色 127 snake.pop();//删除蛇尾坐标 128 } 129 else { 130 carrier[headX][headY] = false;//记录蛇头和食物重叠,碰撞处,碰撞后:蛇尾不减,false标志重叠 131 132 addObject("food");//添加新的食物; 133 } 134 snake.unshift([headX,headY]);//将食物作为新的蛇头坐标压入蛇坐标数组,unshift函数为头压入数据,snake长度增加1 135 carrier[headX][headY] = "cover";//cover代表为蛇身,此时将标志false改为正常caver 136 gridElems[headX][headY].className = "cover";//给移动后的蛇身修改相应的表格单元格颜色 137 len = snake.length; 138 document.getElementById(‘nowscore‘).innerHTML = len; 139 } 140 141 //添加物品 142 function addObject(name) { 143 var p = randomPointer(); 144 carrier[p[0]][p[1]] = name; 145 gridElems[p[0]][p[1]].className = name;//封装投放食物函数 146 } 147 148 //产生指定范围随机点,食物和蛇的初始值产生 149 function randomPointer(startX,startY,endX,endY) { 150 startX = startX || 0; 151 startY = startY || 0; 152 endX = endX || WIDTH; 153 endY = endY || HEIGHT; 154 var p = []; 155 var x = Math.floor(Math.random()*(endX - startX)) + startX;//控制产生数据在WIDTH即表格横向范围内 156 var y = Math.floor(Math.random()*(endY - startY)) + startY;//控制产生数据在HEIGHT即表格纵向范围内 157 if(carrier[x][y]) //如果产生数据和蛇身重复了,则递归再次产生 158 {return randomPointer(startX,startY,endX,endY);} 159 p[0] = x; 160 p[1] = y; 161 return p;//返回一个一维数组,仅两个数(坐标),传至坐标数组 162 } 163 164 //产生随机整数 165 function randowNum(start,end) { 166 return Math.floor(Math.random()*(end - start)) + start; 167 } 168 169 //创建二维数组 170 function multiArray(m,n) { 171 var arr = new Array(n); 172 for(var i=0; i<m; i++) 173 arr[i] = new Array(m);//数组套数组 174 return arr; 175 } 176 177 //清除画面,游戏开始时和死亡后刷新使用 178 function clear() { 179 for(var y = 0; y < gridElems.length; y++) { 180 for(var x = 0; x < gridElems[y].length; x++) { 181 gridElems[x][y].className = ""; 182 } 183 } 184 }
原文地址:https://www.cnblogs.com/TheGCC/p/8905872.html
时间: 2024-10-12 03:22:08