JavaScript Snake Little Game code
<style>
. Food{background-color:red}
. Snake{background-color:blue}
</style>
<script>
var rows=20
var cells=30
var num=15
var borderwidth=5
var speedup=5000
Create a map
function Createmap () {
Bw=eval (Cells*num+2*borderwidth)
Bh=eval (Rows*num+2*borderwidth)
Document.body.innerhtml= ' <div id=mainmap style=position:absolute;left: ' +20+ '; top: ' +20+ '; width: ' +BW+ '; height: ' +bh+ '; border-width: ' +borderwidth+ '; Border-style:inset;border-color: #0000cc ></div> '
Map=new Array ()
for (y=0;y<rows;y++) {
Map[y]=new Array ()
for (x=0;x<cells;x++) {
map[y][x]= ' 0 '
}
}
Sx=parseint (Math.random () *cells)
Sy=parseint (Math.random () *rows)
Createsnake ()
Creatfood ()
Alldiv=mainmap.all.tags (' DIV ')
Allspan=mainmap.all.tags (' SPAN ')
}
Where to create food
function Creatfood () {
Fx=parseint (Math.random () *cells)
Fy=parseint (Math.random () *rows)
if (map[fy][fx]== ' 0 ') {
mainmap.innerhtml+= ' <span style=position:absolute;left: ' +fx*num+ '; top: ' +fy*num+ '; width: ' +num+ '; height: ' +Num+ '; Overflow:hidden class=food></span> '
map[fy][fx]= ' F '
}
else Creatfood ()
}
Create the position of the snake
function Createsnake () {
mainmap.innerhtml+= ' <div x= ' +sx+ ' y= ' +sy+ ' style=position:absolute;left: ' +sx*num+ '; top: ' +sy*num+ '; width: ' +Num+ '; height: ' +num+ '; Overflow:hidden class=snake></div> '
map[sy][sx]= ' S '
}
Master Move--judge what is in front of the snake's head
function Move () {
Sx+=gox
Sy+=goy
if (sy<0| | sy>=rows) Move1 ()
else{
SNAKEFRONT=MAP[SY][SX]
if (snakefront== ' 0 ') Move2 ()
else{
if (snakefront== ' F ') Move3 ()
else Move1 ()
}
}
}
Start again
function Move1 () {
Restart=confirm ("Game over, start again?") ")
if (restart) window.location.reload ()
}
var times=200
When the snake is in front of the open space
function Move2 () {
map[alldiv[0].y][alldiv[0].x]= ' 0 '
Alldiv[0].removenode (True)
Createsnake ()
SetTimeout (' Move () ', times)
}
When the snake is in front of the food
function Move3 () {
Createsnake ()
Allspan[0].removenode (True)
Creatfood ()
SetTimeout (' Move () ', times)
}
Snakes move faster.
function Otimes () {
Times-=5
if (times>5) settimeout (' Otimes () ', speedup)
}
Document.onkeydown=keydown
Direction
function KeyDown () {
Key=event.keycode
Switch (Key) {
Case 37:dir ( -1,0); break//left
Case 39:dir (1,0); break//right
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 ()
}
}
Run at start
Onload=createmap
</script>