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);
}
}
//接受按钮指令
function document.onkeydown() {
cycleCount = cycleCount + 1;
if (cycleCount < 2) {
switch (event.keyCode) {
case 37:
if (nowDirection != 'right') {
nowDirection = 'left';
}
break;
case 38:
if (nowDirection != 'down') {
nowDirection = 'up';
}
break;
case 39:
if (nowDirection != 'left') {
nowDirection = 'right';
}
break;
case 40:
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();
}
else if (rearEnd(_x, _y)) {
rearEndState();
}
else if (_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]) {
return true;
}
}
return false;
}
//咬到蛇身状态变化
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) {
case 10:
levelShow("Second");
break;
case 20:
levelShow("Third");
break;
case 30:
levelShow("Forth");
break;
case 40:
levelShow("Fifth");
break;
case 70:
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>
作者: 杨伟明 发表于 2011-10-18 13:48 原文链接
最新新闻:
· 苹果周二发布第三季度财报 iPhone成信心保障(2011-10-18 20:46)
· 求解斯芬克斯之谜——《X光下看腾讯》序(2011-10-18 20:44)
· 预告:Android 4.0 将于明日香港首发(2011-10-18 20:39)
· Twitter活跃用户量超1亿 超50%用户每天登陆(2011-10-18 20:36)
· 调查称近八成人每天必登录Facebook(2011-10-18 20:33)