javascript 贪食蛇
我的程序用javascript与Html中的table结合,实现的简单的贪食蛇游戏,游戏的主要特点,可调整蛇移动速度,可调整蛇移动范围,碰壁、咬到身体则“Game Over!”并且有关卡加速功能。游戏并不完善,只是实现了主要的功用,有设计不合理的地方,欢迎您感大家提意见!
实现方法:由javascript语言中的setInterval方法驱动整个游戏程序,设置“nowDirection”即蛇的当前移动方向为全局变量,由setInterval方法定时获取蛇的移动方向,由document.onkeydown()捕捉当前按键(上、下、左、右)以修改nowDirection,这样就可以用方向按键控制蛇周期时间的定向移动。蛇的行走轨迹实现个人觉的实现的还算比较简单,蛇身的每一节存在数组中,数组中的元素为蛇的坐标,移动的时候数组根据方向在数组头部加一个元素,并且将数组最后一个元素删除,这样table就可以准确的显示蛇的行走轨迹,游戏结束比较容易判断,只需根据方向判断蛇的下一个移动单元的坐标是否超出范围(碰壁),或者下一个移动单元的坐标是否存在于蛇身的数组中(咬到身体)。游戏的关卡设计一蛇身数组的长度计算,不能关卡贮蓄改变全局变量speed并且重新启动setInterval方法即可。
主要技术点:一、蛇的移动
二、蛇的移动轨迹显示
三、周期内不能接受两次按键指令
四、随机生成蛇的食物
(大体写写,其实根本没什么技术含量!)
IE测试环境;
截图
源码如下:
<html>
<head>
<title></title>
<script language="javascript" type="text/javascript">
var maxScope =30;
var interval;
var nowDirection ='left';
var speed =300;
var cellWeight =10;
var snakeBody =new Array();
var foodStation =null;
var freeCell_x =new Array();
var freeCell_y =new Array();
var cornerList =new Array();
var cycleCount =0;
function $(x) {
return document.getElementById(x);
}
//页面加载
function init() {
_table = document.getElementById("table");
for (var i =0; i <= maxScope; i++) {
var row = document.createElement("tr");
row.id = i;
for (var j =0; j <= maxScope; j++) {
var cell = document.createElement("td");
cell.id = i +"_"+ j;
cell.width = cellWeight;
cell.height = cellWeight;
row.appendChild(cell);
}
document.getElementById("newbody").appendChild(row);
}
initSnake();
initFood();
snakeInterval();
}
//移动动作驱动方法
function snakeInterval() {
interval = window.setInterval('snakeMove();cycleCount=0', speed);
}
//初始化蛇
function initSnake() {
var x = parseInt(Math.random() * (parseInt(maxScope) -1) +1);
var y = parseInt(Math.random() * (parseInt(maxScope) -1) +1);
var nowHeadStation = x +"_"+ y;
snakeBody.push(nowHeadStation);
tdState(nowHeadStation);
}
//设置食物位置
function initFood() {
var allCells =new Array();
for (var i =0; i < maxScope +1; i++) {
for (var j =0; j < maxScope +1; j++) {
allCells.push(i +'_'+ j);
}
}
var addCellsString = allCells.join(',') +',';
for (var i =0; i < snakeBody.length; i++) {
_snakeBodyCell = snakeBody[i] +',';
addCellsString = addCellsString.replace(_snakeBodyCell, "");
}
addCellsString = addCellsString.substr(0, addCellsString.length -1);
var _allCells = addCellsString.split(',');
foodStation = _allCells[parseInt(Math.random() * (_allCells.length -1) +0)]
try {
foodState(foodStation);
} catch (e) {
alert(foodStation);
}
}
//接受按钮指令
document.onkeydown = function () {
cycleCount = cycleCount +1;
if (cycleCount <2) {
switch (event.keyCode) {
case37:
if (nowDirection !='right') {
nowDirection ='left';
}
break;
case38:
if (nowDirection !='down') {
nowDirection ='up';
}
break;
case39:
if (nowDirection !='left') {
nowDirection ='right';
}
break;
case40:
if (nowDirection !='up') {
nowDirection ='down';
}
break;
}
}
}
//获取单元格坐标
function coordinate(i) {
switch (i) {
case'x':
return $(snakeBody[0]).id.split('_')[0];
case'y':
return $(snakeBody[0]).id.split('_')[1];
}
}
//蛇移动
function snakeMove() {
foodX = foodStation.split('_')[0];
foodY = foodStation.split('_')[1];
var _xy;
switch (nowDirection) {
case'left':
_x = coordinate('x');
_y = Math.floor(coordinate('y')) -1;
_xy = _y;
break;
case'right':
_x = coordinate('x');
_y = Math.floor(coordinate('y')) +1;
_xy = _y;
break;
case'up':
_x = Math.floor(coordinate('x')) -1;
_y = coordinate('y');
_xy = _x;
break;
case'down':
_x = Math.floor(coordinate('x')) +1;
_y = coordinate('y');
_xy = _x;
break;
default:
_x = coordinate('x');
_y = Math.floor(coordinate('y')) -1;
_xy = _y;
}
if (_xy <0|| _xy > maxScope) {
overCoordinate();
}
elseif (rearEnd(_x, _y)) {
rearEndState();
}
elseif (_x == foodX && _y == foodY) {
snakeBody.unshift(_x +'_'+ _y);
level(snakeBody.length);
$('score').innerHTML = snakeBody.length *10;
tdState(snakeBody[0]);
initFood();
}
else {
snakeBody.unshift(_x +'_'+ _y);
tdState(snakeBody[0]);
tdStateBack(snakeBody.pop());
}
}
//咬到蛇身
function rearEnd(x, y) {
var t = x +'_'+ y;
for (var i =0; i < snakeBody.length; i++) {
if (t == snakeBody[i]) {
returntrue;
}
}
returnfalse;
}
//咬到蛇身状态变化
function rearEndState() {
window.clearInterval(interval);
alert('game over')
}
//碰壁状态变化
function overCoordinate() {
window.clearInterval(interval);
alert("game over");
}
function tdState(targetTd) {
$(targetTd).style.background ="red";
}
function foodState(targetTd) {
$(targetTd).style.background ="green";
}
function tdStateBack(targetTd) {
$(targetTd).style.background ="";
}
//关卡设置
function level(max) {
switch (max) {
case10:
levelShow("Second");
break;
case20:
levelShow("Third");
break;
case30:
levelShow("Forth");
break;
case40:
levelShow("Fifth");
break;
case70:
window.clearInterval(interval);
alert("NB!"); window.close();
break;
}
}
//设置不同关卡速度变化
function levelShow(_show){
window.clearInterval(interval);
alert(_show);
speed = speed -50;
snakeInterval();
}
</script>
</head>
<body onload="init()">
<table id="table" align="center" bgcolor="pink">
<tbody id="newbody">
</tbody>
</table>
<table align="center">
<tr>
<td style="font-size: 12px">
score:<span id="score">0</span>
</td>
</tr>
</table>
</body>
</html>