之前自己写着玩,写了一个,不完美,仅仅是实现了。代码如下
这是index.html
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />
<title>New Web Project</title>
<script src="js/base.js" type="text/javascript"></script>
<script src="js/application.js" type="text/javascript"></script>
</head>
<body style="width: 100%height:800pxmargin:0text-align: center">
<div id="gameZone" style="position:relativemargin-left: automargin-right: auto"></div>
</body>
</html>
以下是html中引用的两个js文件
/*** @author bsnpbda
*/
var Class = function(parent){
var klass = function(){
this.init.apply(this,arguments)
}
//change klass's prototype'
if(parent){
var subclass = function(){}
subclass.prototype = parent.prototype
klass.prototype = new subclass
klass.prototype._super = parent.prototype
}
klass.prototype.init = function(){}
//define surname for the prototype
klass.fn = klass.prototype
//add class attribute
klass.extend = function(obj){
var extended = obj.extended
for(var i in obj){
klass[i] = obj[i]
}
if(extended) extended(klass)
}
//add instance attribute
klass.include = function(obj){
var included = obj.included
for(var i in obj){
klass.fn[i] = obj[i]
}
if(included) included(klass)
}
//add proxy method
klass.proxy = function(func){
var self = this
return (function(){
return func.apply(self,arguments)
})
}
//add instance proxy method
klass.fn.proxy = klass.proxy
return klass
} /**
* @author bsnpbda
*/
var configuration = {
unit:15,
interval:200
}
var Context = new Class
Context.extend({
context:null,
getContext:function(){
if(!this.context)
this.context = new Context
return this.context
}
})
Context.include({
init:function(){
var w = document.body.clientHeight
var h = document.body.clientWidth
this.unit = h <w?h/configuration.unit:w/configuration.unit
this.interval = configuration.interval
var gameZone = document.getElementById("gameZone")
this.gameZone = gameZone
var line = this.unit * configuration.unit
gameZone.style.width = gameZone.style.lineHeight = gameZone.style.height = line + "px"
gameZone.style.borderWidth = "1px"
gameZone.style.borderStyle = "solid"
},
setGame:function(game){
this.game = game
},
getGame:function(){
return this.game
}
})
var Dom = new Class
Dom.include({
init:function(style){
var element = document.createElement("div")
this.element = element
this.style = style
for(var s in style){
element.style[s] = this.style[s]
}
},
attach:function(){
Context.getContext().gameZone.appendChild(this.element)
},
remove:function(){
Context.getContext().gameZone.removeChild(this.element)
},
refresh:function(){
for(var s in this.style){
this.element.style[s] = this.style[s]
}
}
})
var PaintModule = {
paint:function(){
this.element = new Dom(this.style)
this.element.attach()
},
repaint:function(){
this.element.refresh()
},
wipeOff:function(){
this.element.remove()
}
}
var Sprite = new Class
Sprite.include(PaintModule)
Sprite.include({
default_cfg:{
id:0,
axisX:0,
axisY:0,
background:"black"
},
init:function(cfg){
var unit = Context.getContext().unit
this.id = cfg.id || this.default_cfg.id
this.style = {}
this.style.position = "absolute"
this.style.width = unit+'px'
this.style.height = unit+'px'
this.axisX = (cfg.axisX || this.default_cfg.axisX)
this.style.left = this.axisX*unit + 'px'
this.axisY = (cfg.axisY || this.default_cfg.axisY)
this.style.top = this.axisY*unit + 'px'
this.style.background = cfg.background || this.default_cfg.background
},
collideWith:function(sprite){
if(this.axisX == sprite.axisX &&this.axisY == sprite.axisY){
return true
}else{
return false
}
}
})
var SnakeNode = new Class(Sprite)
SnakeNode.include({
init:function(cfg){
this._super.init.call(this,cfg)
this.direction = cfg.direction || this.default_cfg.direction
this.lastDirc = cfg.lastDirc || this.default_cfg.lastDirc
this.paint()
},
march:function(){
var unit = Context.getContext().unit
if(this.direction == 0){
this.axisY -= 1
}else if(this.direction == 6){
this.axisY += 1
}else if(this.direction == 9){
this.axisX -= 1
}else if(this.direction == 3){
this.axisX += 1
}
this.style.left = this.axisX*unit + "px"
this.style.top = this.axisY*unit + "px"
this.lastDirc = this.direction
this.repaint()
},
isOutOfBound:function(){
if(this.axisX <0 || this.axisY <0 || this.axisX >= configuration.unit || this.axisY >= configuration.unit)
return true
return false
}
})
var Snake = new Class
Snake.include({
init:function(){
this.nodes = []
this.addNode()
this.lock = false
document.onkeydown = window.onkeydown = this.proxy(function(event){
event = event?event:window.event
if(this.lock)return//prevent push button too fast
this.lock = true
var head = this.nodes[0]
var direction = head.direction
if(event.keyCode == 37){
if(direction != 3){
head.direction = 9
}
}else if(event.keyCode == 38){
if(direction != 6){
head.direction = 0
}
}else if(event.keyCode == 39){
if(direction != 9){
head.direction = 3
}
}else if(event.keyCode == 40){
if(direction != 0){
head.direction = 6
}
}
this.nodes[0].lastDirc = direction
})
},
addNode:function(){
var lastNode = this.nodes[this.nodes.length-1]
var direction = 3
var axisX = 0,axisY = 0
if(lastNode){
direction = lastNode.direction
if(lastNode.direction==0){
axisY = lastNode.axisY + 1
axisX = lastNode.axisX
}else if(lastNode.direction==6){
axisY = lastNode.axisY - 1
axisX = lastNode.axisX
}else if(lastNode.direction == 9){
axisX = lastNode.axisX + 1
axisY = lastNode.axisY
}else if(lastNode.direction == 3){
axisX = lastNode.axisX - 1
axisY = lastNode.axisY
}
}
this.nodes.push(new SnakeNode({
id:this.nodes.length+1,
direction:direction,
axisX:axisX,
axisY:axisY
}))
},
march:function(){
for(var i=0i<this.nodes.lengthi++){
var curNode = this.nodes[i]
var nextDirc = curNode.lastDirc
curNode.march()
if(i == 0){
if(curNode.isOutOfBound()){
alert("游戏结束!")
Context.getContext().game.end()
}
for(var j=1j<this.nodes.lengthj++){
if(curNode.collideWith(this.nodes[j])){
alert("游戏结束")
Context.getContext().game.end()
break
}
}
}
if(i+1 <this.nodes.length){
this.nodes[i+1].lastDirc = this.nodes[i+1].direction
this.nodes[i+1].direction = nextDirc
}
}
var game = Context.getContext().getGame()
if(this.nodes[0].collideWith(game.randomNode)){
this.addNode()
game.randomNodeFn()
}
this.lock = false
}
})
var Game = new Class
Game.include({
init:function(){
this.snake = new Snake
Context.getContext().setGame(this)
},
start:function(){
this.randomNodeFn()
var _this = this
this.interval = setInterval(function(){
_this.snake.march()
},Context.getContext().interval)
},
end:function(){
window.clearInterval(this.interval)
},
randomNodeFn:function(){
if(this.randomNode)this.randomNode.wipeOff()
while(true){
var rd_x = Math.floor(configuration.unit * Math.random())
var rd_y = Math.floor(configuration.unit * Math.random())
var isCrash = false
for(var i=0i<this.snake.nodes.lengthi++){
if(rd_x == this.snake.nodes[i].axisX &&rd_y == this.snake.nodes[i].axisY){
isCrash = true
break
}
}
if(!isCrash){
this.randomNode = new SnakeNode({
background:'red',
axisX:rd_x,
axisY:rd_y
})
break
}
}
}
})
window.onload = function(){
var game = new Game()
game.start()
}
snake.js代码如下:::
复制代码
代码如下:
var canvas
var ctx
var timer
//measures
var x_cnt = 15
var y_cnt = 15
var unit = 48
var box_x = 0
var box_y = 0
var box_width = 15 * unit
var
box_height = 15 * unit
var bound_left = box_x
var bound_right = box_x
+ box_width
var bound_up = box_y
var bound_down = box_y + box_height
//images
var image_sprite
//objects
var snake
var food
var food_x
var food_y
//functions
function Role(sx, sy, sw,
sh, direction, status, speed, image, flag)
{
this.x = sx
this.y =
sy
this.w = sw
this.h = sh
this.direction = direction
this.status = status
this.speed = speed
this.image = image
this.flag = flag
}
function transfer(keyCode)
{
switch
(keyCode)
{
case 37:
return 1
case 38:
return 3
case
39:
return 2
case 40:
return 0
}
}
function addFood()
{
//food_x=box_x+Math.floor(Math.random()*(box_width-unit))
//food_y=box_y+Math.floor(Math.random()*(box_height-unit))
food_x =
unit * Math.floor(Math.random() * x_cnt)
food_y = unit *
Math.floor(Math.random() * y_cnt)
food = new Role(food_x, food_y, unit,
unit, 0, 0, 0, image_sprite, true)
}
function play(event)
{
var
keyCode
if (event == null)
{
keyCode = window.event.keyCode
window.event.preventDefault()
}
else
{
keyCode =
event.keyCode
event.preventDefault()
}
var cur_direction =
transfer(keyCode)
snake[0].direction = cur_direction
}
function
update()
{
//add a new part to the snake before move the snake
if
(snake[0].x == food.x &&snake[0].y == food.y)
{
var length =
snake.length
var tail_x = snake[length - 1].x
var tail_y =
snake[length - 1].y
var tail = new Role(tail_x, tail_y, unit, unit,
snake[length - 1].direction, 0, 0, image_sprite, true)
snake.push(tail)
addFood()
}
//modify attributes
//move the head
switch
(snake[0].direction)
{
case 0: //down
snake[0].y += unit
if
(snake[0].y >bound_down - unit)
snake[0].y = bound_down - unit
break
case 1: //left
snake[0].x -= unit
if (snake[0].x <
bound_left)
snake[0].x = bound_left
break
case 2: //right
snake[0].x += unit
if (snake[0].x >bound_right - unit)
snake[0].x = bound_right - unit
break
case 3: //up
snake[0].y
-= unit
if (snake[0].y <bound_up)
snake[0].y = bound_up
break
}
//move other part of the snake
for (var i = snake.length - 1i
>= 0i--)
{
if (i >0)
//snake[i].direction=snake[i-1].direction
{
snake[i].x = snake[i -
1].x
snake[i].y = snake[i - 1].y
}
}
}
function
drawScene()
{
ctx.clearRect(box_x, box_y, box_width, box_height)
ctx.strokeStyle = "rgb(0,0,0"
ctx.strokeRect(box_x, box_y, box_width,
box_height)
//detection collisions
//draw images
for (var i = 0i
<snake.lengthi++)
{
ctx.drawImage(image_sprite, snake[i].x,
snake[i].y)
}
ctx.drawImage(image_sprite, food.x, food.y)
}
function init()
{
canvas = document.getElementById("scene")
ctx
= canvas.getContext('2d')
//images
image_sprite = new Image()
image_sprite.src = "images/sprite.png"
image_sprite.onLoad = function
()
{}
//ojects
snake = new Array()
var head = new Role(0 *
unit, 0 * unit, unit, unit, 5, 0, 1, image_sprite, true)
snake.push(head)
window.addEventListener('keydown', play, false)
addFood()
setInterval(update, 300)//note
setInterval(drawScene, 30)
}
望采纳!!!!
我这边有代码是JSP的
你试验一下
需要有JSP环境,我试验了下,可以玩!
<HTML>
<head>
<meta http-equiv="Content-Type" content="text/htmlcharset=gb2312">
<title>贪吃蛇</title>
</head>
<STYLE>
.Food { background-color: green}
.Snake {background-color: red}
.grid {border:1px solid #000}
</STYLE>
<SCRIPT langyage="javascript">
var Rows=10
var Cells=15
var Num=20 //正方形格子的边长
var BorderWidth=5
var SpeedUp=5000
//创建地图
function CreateMap()
{
BW = eval(Cells*Num + 2*BorderWidth) //宽度
BH = eval(Rows*Num + 2*BorderWidth) //高度
document.body.innerHTML+='<div id=MainMap style=position:absoluteleft:'+(document.body.clientWidth-BW)/2+'top:'+(document.body.clientHeight-BH)/2+'width:'+BW+'height:'+BH+'border-width:'+BorderWidth+'border-style:outsetborder-color:#0000ff></div>'
Map = new Array() //创建全局数组Map[]
for(y=0y<Rowsy++)
{
Map[y]=new Array() //创建全局二维数组Map[][],初始值为'0'
for(x=0x<Cellsx++)
Map[y][x] = '0' //'0'值表示“空地”
}
//ShowGrid() //显示地图内格子
Sx = parseInt(Math.random()*Cells) //创建全局变量Sx,赋予随机数
Sy = parseInt(Math.random()*Rows) //创建全局变量Sy,赋予随机数
CreateSnake() //生成蛇 - div
CreatFood()//生成食物 - span
AllDiv = MainMap.all.tags('DIV') //创建全局数组AllDiv,只有一个元素AllDiv[0]。MainMap是div的ID
AllSpan = MainMap.all.tags('SPAN') //创建全局数组AllSpan,只有一个元素AllSpan[0]
}
//显示地图内格子
function ShowGrid()
{
for(r=0r<Rowsr++) //行
{
t = r*Num
for(c=0c<Cellsc++) //列
{
l = c*Num
MainMap.innerHTML += '<table style="position:absoluteleft:'+ l +'top:'+ t +'width:'+Num+'height:'+Num+'" cellpadding=0 cellspacing=0><tr><td align=center valign=middle class=grid>O</td></tr><table>'
}
}
}
//创建蛇的初始位置,赋予初始值'S'
function CreateSnake()
{
//<div>表示蛇身,通过调用本函数,可以累加到若干个,蛇身变长
//注意 y 和 x 是“蛇”<div>的自定义属性。一直保存着蛇尾(!)的当前位置
//初始时,蛇头、蛇尾是同一个位置
MainMap.innerHTML += '<div x='+Sx+' y='+Sy+' style=position:absoluteleft:'+Sx*Num+'top:'+Sy*Num+'width:'+Num+'height:'+Num+'overflow:hidden class=Snake></div>'
Map[Sy][Sx]='S' //Snake首字母
}
//创建食物的位置,赋予初始值'F'
//食物的初始位置不能与蛇的初始位置相同,只能在空地放置食物。
//若随机产生的2位置相同,则递归执行,直到不相同为止
function CreatFood()
{
Fx = parseInt(Math.random()*Cells)
Fy = parseInt(Math.random()*Rows)
if(Map[Fy][Fx]=='0') //如果是空地
{
MainMap.innerHTML += '<span style=position:absoluteleft:'+Fx*Num+'top:'+Fy*Num+'width:'+Num+'height:'+Num+'overflow:hidden class=Food></span>'
Map[Fy][Fx]='F' //Food首字母
}
else
CreatFood() //递归
}
//主移动--判断蛇头前面的是什么
function Move()
{
Sx += GoX //自动行走,Map[Sy][Sx]为当前位置
Sy += GoY
if(Sy<0||Sy>=Rows) //碰墙,重新开始
Move1()
else
{
SnakeFront = Map[Sy][Sx]
if(SnakeFront=='0') //蛇前是空地
Move2()
else
{
if(SnakeFront=='F') //蛇前面是食物
Move3()
else
Move1()
}
}
}
//重新开始
function Move1()
{
if(confirm("Game Over,重新开始?"))
window.location.reload()
}
var Times=200
//蛇行走到的当前位置是空地时
function Move2()
{
Map[AllDiv[0].y][AllDiv[0].x]='0' //蛇走开后,把原位置设置为'0',表示是空地
AllDiv[0].removeNode(true) //把蛇数组当前元素删除,在下面的 CreateSnake()语句重新生成
CreateSnake() //在新的位置生成蛇的<div>
setTimeout('Move()',Times) //再次移动
}
//蛇行走到的当前位置是食物时
function Move3()
{
CreateSnake() //蛇数组当前元素不删除,<div>累加一次,蛇长长一节
AllSpan[0].removeNode(true) //把食物数组当前元素删除,在下面的 CreatFood()语句重新生成
CreatFood() //再次随机生成食物
setTimeout('Move()',Times) //再次移动
}
//蛇越行越快
function oTimes()
{
Times -= 5
if(Times>5)
setTimeout('oTimes()', SpeedUp)
}
document.onkeydown=KeyDown
//方向
function KeyDown()
{
Key=event.keyCode
switch(Key){
case 37:
Dir(-1,0)break //左方向键
case 39:
Dir(1,0)break //右方向键
case 38:
Dir(0,-1)break //上方向键
case 40:
Dir(0,1)break} //下方向键
return false
}
var Star=0
function Dir(x,y)
{
GoX=x
GoY=y
if(Star==0)
{
oTimes()
Star=1
Move()
}
}
//页面打开时运行
onload = CreateMap //注意无"()",不是 CreateMap()
//在<body>中调用的语法是:<BODY onload="CreateMap()">,必须加"()"
</SCRIPT>
<BODY>
<div id="help">
红色方块表示蛇,绿色方块表示食物。按方向键开始。<br>
</div>
</BODY>
</HTML>