用HTML做一个贪吃蛇?

发布网友 发布时间:2022-04-22 05:45

我来回答

4个回答

懂视网 时间:2022-05-12 07:30

本篇小编为大家分享一个用html5实现的简单贪吃蛇特效代码,喜欢的小伙伴们可以看一下

<html>
 <head>
 <meta charset='utf-8'/>
 <title>Snake</title>
 </head>
 <body>
 <canvas id="plank" style="border"></canvas>
 <script type="text/javascript">
  //内置大量BUG,I'm sorry.
  var lev=100;  //定时器间隔时间
  var num=30;  //网格大小,现在是30x30
  var direction=3;  //0:up 1:down 2:left 3:right
  var handle;  //用于管理定时器
  var score=0;  //分数
  var pause=true;  //暂停使用
  var canvas = document.getElementById('plank');
  var context = canvas.getContext('2d');
  var snakex=new Array(); //存储蛇身x坐标,下同
  var snakey=new Array();
  var prize=new Array(-1,-1); //食物的位置
 
  function rand(){  //产生随机数
  return parseInt(Math.random()*num);
  }
 
  function chk(x,y){  //检查是否结束,包括越界
  if(x<0||y<0) return false;
  if(x>num-1||y>num-1) return false;
  for (var i=0; i!=snakex.length-1;i++) {
   if(snakex[i]==x&&snakey[i]==y) {return false;}
  };
  return true;
  }
 
  function drawScore(text){ //打印分数
  context.clearRect(0,0,300,25);
  context.fillText("Score:"+text,5,5);
  }
 
  function makeprize(){  //产生食物的位置
  var flag=false;
  var prizepre=new Array(2); //使用链表会更好
  while(!flag){  //食物位置不能在蛇体内
   flag=true;
   prizepre[0]=rand();prizepre[1]=rand();
   for (var i=0; i!=snakex.length;i++) {
   if((snakex[i]==prizepre[0])&&(snakey[i]==prizepre[1])) {flag=false;}
   }
  }
  prize=prizepre;
  }
 
  function runscore(x,y){ //判断是否吃到食物,并做处理
  if(prize[0]==x&&prize[1]==y){
   score=score+1;
   drawScore(score);
   snakex[snakex.length]=prize[0];
   snakey[snakey.length]=prize[1];
   makeprize();
   drawNode(prize[0],prize[1]);
   return true;
  }
  return false;
  }
 
  function run(){  //定时器用来判断snake行进方向等等
  switch(direction){  //方向
   case 0: snakex[snakex.length]=snakex[snakex.length-1];snakey[snakey.length]=snakey[snakey.length-1]-1;break;
   case 1: snakex[snakex.length]=snakex[snakex.length-1];snakey[snakey.length]=snakey[snakey.length-1]+1;break;
   case 2: snakex[snakex.length]=snakex[snakex.length-1]-1;snakey[snakey.length]=snakey[snakey.length-1];break;
   case 3: snakex[snakex.length]=snakex[snakex.length-1]+1;snakey[snakey.length]=snakey[snakey.length-1];break;
  }
  if(!runscore(snakex[snakex.length-1],snakey[snakey.length-1])){
   if(chk(snakex[snakex.length-1],snakey[snakey.length-1])==false) {
   clearInterval(handle);
   drawScore('\tGame over');
   return;
   }
   drawNode(snakex[snakex.length-1],snakey[snakey.length-1]);
  }
  clearNode(snakex[0],snakey[0]);
  snakex.shift();
  snakey.shift();
  }
 
  function drawNode(x,y){ //画点,共30X30个点(10*10像素算1个点)
  context.fillRect(x*10+1,y*10+31,10,10);
  }
 
  function clearNode(x,y){
  context.clearRect(x*10+1,y*10+31,10,10);
  }
 
  function init(){ //初始化,设置画布大小,启动定时器等等
  canvas.width = 510;
  canvas.height = 600;
  context.font = "normal 20px Airl";
  context.textBaseline = "top";
  context.fillText('P键开始/暂停,方向键控制',0,350);
  drawScore('');
  context.strokeRect(0,30,302,302);
  makeprize();
  drawNode(prize[0],prize[1]);
  snakex[0]=0;snakex[1]=1;snakex[2]=2;
  snakey[0]=0;snakey[1]=0;snakey[2]=0;
  drawNode(snakex[0],snakey[0]);drawNode(snakex[1],snakey[1]);drawNode(snakex[2],snakey[2]);
  }
 
  document.onkeydown=function(event){ //注册键盘事件,up,down,left,right,暂停键p
  var e = event || window.event;
  if(e&&e.keyCode==38){
   direction=0;
  }
  if(e&&e.keyCode==40){
   direction=1;
  }
  if(e&&e.keyCode==37){
   direction=2;
  }
  if(e&&e.keyCode==39){
   direction=3;
  }
  if(e&&e.keyCode==80){
   if(pause) {pause=false;handle=setInterval(run,lev);}
   else {pause=true;clearInterval(handle);}
  }
  }
 
 
  init();
 </script>
 </body>
</html>

【相关推荐】

1. 免费h5在线视频教程

2. HTML5 完整版手册

3. php.cn原创html5视频教程

热心网友 时间:2022-05-12 04:38

之前自己写着玩,写了一个,不完美,仅仅是实现了。代码如下

这是index.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=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:800px;margin:0;text-align: center">
<div id="gameZone" style="position:relative;margin-left: auto;margin-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 PaintMole = {
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(PaintMole);
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=0;i<this.nodes.length;i++){
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=1;j<this.nodes.length;j++){
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=0;i<this.snake.nodes.length;i++){
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();
}

热心网友 时间:2022-05-12 05:56

//蛇行走到的当前位置是空地时
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()">,必须加"()"

(JS关键代码,)

热心网友 时间:2022-05-12 07:31

http://blog.csdn.net/uucai/article/details/9999911

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com