当前位置: 代码迷 >> Web开发 >> 也发个容易的小游戏,贪吃蛇.
  详细解决方案

也发个容易的小游戏,贪吃蛇.

热度:408   发布时间:2013-01-06 15:44:47.0
也发个简单的小游戏,贪吃蛇...

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>贪吃蛇 by freewind</title>
<style type="text/css">
html, body{ margin:0px; padding:0px; font-size:12px; font-family:"Courier New";}
#snake{ width:550px; height:400px; margin:50px auto; overflow:hidden;}
#game{ float:left; width:402px; height:302px; border:1px solid #004578;}
#game table{ width:401px; height:301px; border-collapse:collapse; }
#game table td{ width:9px; height:9px; line-height:9px; font-size:2px; overflow:hidden; border:1px solid #fff;}
#game .bg{ background:#0a0;}
#game .food{ background:#c00;}
#info{ float:right; width:128px; line-height:35px;}
#info input{ margin-top:10px; margin-bottom:10px;}
</style>
<script type="text/javascript">
var $ = function(id){
return typeof id == "string" ? document.getElementById(id) : id;
}
var Snake = {
init : function(){
var self = this;
$("start").onclick = function(){
self.start();
this.blur();
};
$("pause").onclick = function(){
self.pause();
this.blur();
};
document.onkeydown = function(event){ 
self.control(event) 
};
this.maxRow = 30;
this.maxCol = 40;
},
initHtml : function(){
$("game").innerHTML = "<table cellpadding='0' cellspacing='0' border='0'>" + new Array(31).join("<tr>"+new Array(41).join("<td>&nbsp;</td>")+"</tr>") + "</table>";
this.table = $("game").getElementsByTagName("table")[0];
$("score").innerHTML = 0;
$("pause").value = "暂停";
},
start : function(){
var self = this;
this.initHtml();
this.food = [];
this.dir = 39;
this.data = [[15,21],[15,20],[15,19],[15,18]];
this.status = 1;
this.speed = 200;
this.score = 0;

this.stop();
this.timerID = setInterval(function(){self.timer();}, this.speed);
this.next();
this.draw();
},
pause : function(){
var self = this;
if(this.status == 1){
this.stop();
this.status = 2;
$("pause").value = "继续";
}else if(this.status == 2){
this.timerID = setInterval(function(){self.timer();}, this.speed);
this.status = 1;
$("pause").value = "暂停";
}
},
stop : function(){
clearInterval(this.timerID);
},
setCss : function(row, col, css){
this.table.rows[row].cells[col].className = css;
},
getCss : function(row, col){
return this.table.rows[row].cells[col].className;
},
timer : function(){
var d = this.data, self = this;
var first = [d[0][0], d[0][1]];
switch(this.dir){
case 37: //left
first[1] = first[1] - 1 < 0 ? this.maxCol-1 : first[1] - 1; break;
case 39: //right
first[1] = first[1] + 1 >= this.maxCol ? 0 : first[1] + 1;  break;
  相关解决方案