1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
| <!DOCTYPE html>
<html lang="en">
<head>
<mata charset="UTF-8">
<title>zdz</title>
</head>
<script>
var COLS=6,ROWS=26;
var EMPTY=0,SNAKE=1,FRUIT=2;
var LEFT=0,UP=1, REIGHT=2,DOWN=3;
var grid={
width:null,
height:null,
_grid:null,
init:function(d,c,r){
this.width=c;
this.height=r;
this._grid=[];
for(var x=0;x<c;x++){
this._grid.push([]);
for(var y=0;y<r;y++){
this._grid[x].push(d);
}
}
},
set:function(val,x,y){
this._grid[x][y]=val;
},
get:function(x,y){
return this._grid[x][y];
},
}
var snake={
direction null,
last:null,
_queue:null,
init:function(d,x,y){
this.direction=0;
this._queue=[];
this.insert(x,y);
},
insert: function(x,y){
this._queue.unshift({x:x,y:y});
this.last=this._queue[0];
},
remove:function(){
return this._queue.pop();
}
}
function setFood(){
var empty=[];
for(var x=0; x<grid.width;x++){
for(var y=0;y<grid.height;y++){
if(grid.get(x,y)==EMPTY){
empty.push({x:x,y:y})
}
}
}
var randpos=empty[Math.floor(Math.random()*empty.length)];
grid.set(FRUIT.randpos.x,randpos.y);
}
var canvas,ctx,keystate,frames;
function main(){
canvas=document.createElement("canvas");
canvas.width=COLS*20;
canvas.height=ROWS*20;
ctx=canvas.getContent("2d");
document.body.appendchild(canvas);
frames=0;
keystate={};
init();
loop();
}
function init(){
grid.init(EMPTY,COLS,ROWS);
var sp= {x:Math.floor(COLS/2),y:ROWS-1};
snake.init(UP,sp-x,sp-y);
grid.set(SNAKE,sp.x,sp.y);
setfood();
}
function loop(){
update();
draw();
window.requestAnimationFrame(loop,canvas);
}
function update(){
frames++;
}
function draw(){
var tw=canvas.width/grid.width;
var th=canvas.height/grid.height;
for(var x=0; x<grid.width;x++){
for(var y=0;y<grid.height;y++){
switch (grid.get(x,y)){
case EMPTY:
ctx.fillStyle="#ffff";
break;
case SNAKE:
ctx.fillStyle="#f0ff";
break;
case FRUIT:
ctx.fillStyle="#ff00";
break;
}
ctx.fillRect(x*tw,y*th,tw,th);
}
}
}
main();
</script>
</body>
</html> |
Partager