search
HomeWeb Front-endHTML TutorialThe output tag and canvas tag in html5 implement greedy snake

Operation method:
Press the keyboard up, down, left, right or WASD movement direction.
Scoring rules:
For each additional section of the snake body, the score will be increased by 10. Each time the direction is changed before eating the next food, one point will be subtracted.
ps: The score may be negative {:4_105:}

HTML5 tag canvas:
The canvas element is used to draw graphics on the web page.
Use canvas to draw the background grid in Snake:

  //清空整个画布
                                ctx.clearRect(0,0,480,480);
                                //绘制网格
                                for(var i=0;i<30;i++){
                                        ctx.strokeStyle="#ccc";//线条颜色
                                        ctx.beginPath();
                                        //绘制横线
                                        ctx.moveTo(0,i*width);
                                        ctx.lineTo(480,i*width);
                                        //绘制竖线
                                        ctx.moveTo(i*width,0);
                                        ctx.lineTo(i*width,480);
                                        ctx.closePath();
                                        ctx.stroke();
                                }

Use canvas to draw snake body and food in Snake:

   //绘制蛇的身体
                                for(var i=0;i<snake.length;i++){
                                        ctx.fillStyle="black";//填充颜色
                                        //蛇的头部
                                        if(i==snake.length-1){
                                                ctx.fillStyle="red";
                                        }
                                        ctx.beginPath();
                                        ctx.rect(snake[i].x*width,snake[i].y*width,width,width);
                                        ctx.closePath();
                                        ctx.fill();
                                        ctx.stroke();
                                }

HTML5 tag output:
output Elements are used for different types of output, such as calculation or script output:

 <div>
                        <output id="result" onforminput="resCalc()"></output>
                </div>
                <script>
                        document.getElementById(&#39;result&#39;).value = score;
                </script>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html">
<meta name="Keywords" content="Html5">
<meta name="Desciption" content="贪吃蛇V1.0">
<meta name="Author" content="沙漠胡杨">
    <meta name="Time" content="2015/4/14">
    <title>贪吃蛇</title>
<style type="text/css">
*{margin:0;padding:0;}
body{font-size:12px;font-family:"微软雅黑";background:#CCC;}
h1{font-size:36px;color:#fff;text-shadow:1px 1px 5px #000;margin:30px auto;text-align:center;position:relative;}
#snakeCanvas{background:#fff;box-shadow:3px 3px 5px #666;margin:0 auto;display:block;}
#score,#result{font-size:32px;color:#fff;text-shadow:1px 1px 5px #000;}
#score{position:absolute;top:150px;right:300px;}
#result{position:absolute;top:150px;right:240px;}

</style>
  </head>
  <body>
    <h1 id="贪吃蛇游戏">贪吃蛇游戏</h1>
<div>
<p id="score">得分:<p>
<output id="result"></output>
</div>
<!--画布-->
<canvas id="snakeCanvas" width="480" height="480"></canvas>
  </body>

<script type="text/javascript">
/*
第一步:准备画布
1、分成N个方格,为每个小方格设定为16px*16px 30*30个
2、初始化一条蛇
3、初始化一个食物
第二步:实现动画
1、让蛇移动(监听键盘事件,上下左右或WASD控制方向)
2、捕捉食物(蛇身体增长,另外产生一个食物)
第三步:让蛇自动前行
*/
var canvas=document.getElementById("snakeCanvas");
var ctx=canvas.getContext("2d");//画笔
var width=16;
//移动速度
var speed=200;
//计分
/*计分规则:蛇身每增加一节,分数加10,在吃到下一个食物前每改变一次方向,减一分*/
var score=0;
document.getElementById(&#39;result&#39;).value = score; 

//蛇的身体
var snake=[];
//指定初始长度为6
var snakelen=6;
//初始化
for(var i=0;i<snakelen;i++)
{
snake[i]=new Cell(i,0,-1);
}
var head=snake[snakelen-1];
//蛇的身体构成的元素,x坐标,y坐标,d方向:1左 -1右 2上 -2下
function Cell(x,y,d){
this.x=x;
this.y=y;
this.d=d;
return this;
}
//食物对象
function Food(x,y){
this.x=x;
this.y=y;
return this;
}
//初始食物的出现位置
var foodX=Math.ceil(Math.random()*28+1);
var foodY=Math.ceil(Math.random()*28+1);
//定义食物
var food=new Food(foodX,foodY);
//绘制游戏基本元素
function draw(){
//清空整个画布
ctx.clearRect(0,0,480,480);
//绘制网格
for(var i=0;i<30;i++){

ctx.strokeStyle="#ccc";//线条颜色
ctx.beginPath();

//绘制横线
ctx.moveTo(0,i*width);
ctx.lineTo(480,i*width);

//绘制竖线
ctx.moveTo(i*width,0);
ctx.lineTo(i*width,480);

ctx.closePath();
ctx.stroke();
}

//绘制蛇的身体
for(var i=0;i<snake.length;i++){
ctx.fillStyle="black";//填充颜色
//蛇的头部
if(i==snake.length-1){
ctx.fillStyle="red";
}
ctx.beginPath();
ctx.rect(snake[i].x*width,snake[i].y*width,width,width);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
//绘制食物
drawFood();

//判断是否吃到食物
if(head.x==food.x&&head.y==food.y){

//增加蛇身的长度

var newCell=new Cell(food.x,food.y,head.d);
snake[snake.length]=newCell;
head=newCell;

//随机产生一个食物
initFood();
food=new Food(foodX,foodY);
drawFood();

score=score+10;
document.getElementById(&#39;result&#39;).value = score; 

}
}
//初始化食物的x,y坐标,随机位置
function initFood(){
//Math.random()返回一个0-1之间的随机数
//Math.ceil()向上取整
foodX=Math.ceil(Math.random()*28+1);
foodY=Math.ceil(Math.random()*28+1);
//判断是否跟蛇的身体有重叠
for(var i=0;i<snake.length;i++){
if(snake[i].x==foodX&&snake[i].y==foodY){
initFood();//递归产生食物坐标
}
}
}
//绘制食物
function drawFood(){
ctx.fillStyle="green";
ctx.beginPath();
ctx.rect(food.x*width,food.y*width,width,width);
ctx.closePath();
ctx.fill();
}

draw();
//监听键盘的事件
document.onkeydown=function(e){
//keyCode 上38下40左37右39
//W87 S83 A65 D68
var keyCode=e.keyCode;
var direction;
//alert(keyCode);
switch(keyCode){
case 38:
case 87:
direction=2;break;//上
case 40:
case 83:
direction=-2;break;//下
case 37:
case 65:
direction=1;break;//左
case 39:
case 68:
direction=-1;break;//右

default:break;
}
//控制蛇的移动方向
if(head.d+direction!=0&&(keyCode==37||keyCode==38||keyCode==39||keyCode==40||keyCode==65||keyCode==68||keyCode==37||keyCode==83||keyCode==87)){
if(head.d!=direction){score--;document.getElementById(&#39;result&#39;).value = score; }
moveSnake(direction);

}
}

//移动蛇的方法
function moveSnake(direction){
var newSnake=[];
var newCell=new Cell(head.x,head.y,head.d);
//循环除开头以外的身体部分
for(var i=0;i<snake.length;i++){
newSnake[i-1]=snake[i]
}
newSnake[snake.length-1]=newCell;
newCell.d=direction;

switch(direction){
case 2:
newCell.y--;break;//上
case -2:
newCell.y++;break;//下
case 1:
newCell.x--;break;//左
case -1:
newCell.x++;break;//右
}

snake=newSnake;
head=snake[snake.length-1];
checkDeath();
draw();

}
//自动移动
function moveClock(){
moveSnake(head.d);
}

setInterval(moveClock,speed);

//判断游戏是否结束
function checkDeath(){
//判断是否出边界
if(head.x>=30||head.y>=30||head.x<0||head.y<0){
alert("很遗憾,您输了!" + "\n" + "您的得分为:"+"\n"+score);
window.location.reload();
}
//判断是否碰到自己
for(var i=0;i<snake.length-2;i++){
if(head.x==snake[i].x&&head.y==snake[i].y){
alert("很遗憾,您输了!" + "\n" + "您的得分为:"+"\n"+score);
window.location.reload();
}
}
}

 
</script>
</html>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html">
<meta name="Keywords" content="Html5">
<meta name="Desciption" content="贪吃蛇V1.0">
<meta name="Author" content="沙漠胡杨">
    <meta name="Time" content="2015/4/14">
    <title>贪吃蛇</title>
<style type="text/css">
*{margin:0;padding:0;}
body{font-size:12px;font-family:"微软雅黑";background:#CCC;}
h1{font-size:36px;color:#fff;text-shadow:1px 1px 5px #000;margin:30px auto;text-align:center;position:relative;}
#snakeCanvas{background:#fff;box-shadow:3px 3px 5px #666;margin:0 auto;display:block;}
#score,#result{font-size:32px;color:#fff;text-shadow:1px 1px 5px #000;}
#score{position:absolute;top:150px;right:300px;}
#result{position:absolute;top:150px;right:240px;}

</style>
  </head>
  <body>
    <h1 id="贪吃蛇游戏">贪吃蛇游戏</h1>
<div>
<p id="score">得分:<p>
<output id="result"></output>
</div>
<!--画布-->
<canvas id="snakeCanvas" width="480" height="480"></canvas>
  </body>

<script type="text/javascript">
/*
第一步:准备画布
1、分成N个方格,为每个小方格设定为16px*16px 30*30个
2、初始化一条蛇
3、初始化一个食物
第二步:实现动画
1、让蛇移动(监听键盘事件,上下左右或WASD控制方向)
2、捕捉食物(蛇身体增长,另外产生一个食物)
第三步:让蛇自动前行
*/
var canvas=document.getElementById("snakeCanvas");
var ctx=canvas.getContext("2d");//画笔
var width=16;
//移动速度
var speed=200;
//计分
/*计分规则:蛇身每增加一节,分数加10,在吃到下一个食物前每改变一次方向,减一分*/
var score=0;
document.getElementById(&#39;result&#39;).value = score; 

//蛇的身体
var snake=[];
//指定初始长度为6
var snakelen=6;
//初始化
for(var i=0;i<snakelen;i++)
{
snake[i]=new Cell(i,0,-1);
}
var head=snake[snakelen-1];
//蛇的身体构成的元素,x坐标,y坐标,d方向:1左 -1右 2上 -2下
function Cell(x,y,d){
this.x=x;
this.y=y;
this.d=d;
return this;
}
//食物对象
function Food(x,y){
this.x=x;
this.y=y;
return this;
}
//初始食物的出现位置
var foodX=Math.ceil(Math.random()*28+1);
var foodY=Math.ceil(Math.random()*28+1);
//定义食物
var food=new Food(foodX,foodY);
//绘制游戏基本元素
function draw(){
//清空整个画布
ctx.clearRect(0,0,480,480);
//绘制网格
for(var i=0;i<30;i++){

ctx.strokeStyle="#ccc";//线条颜色
ctx.beginPath();

//绘制横线
ctx.moveTo(0,i*width);
ctx.lineTo(480,i*width);

//绘制竖线
ctx.moveTo(i*width,0);
ctx.lineTo(i*width,480);

ctx.closePath();
ctx.stroke();
}

//绘制蛇的身体
for(var i=0;i<snake.length;i++){
ctx.fillStyle="black";//填充颜色
//蛇的头部
if(i==snake.length-1){
ctx.fillStyle="red";
}
ctx.beginPath();
ctx.rect(snake[i].x*width,snake[i].y*width,width,width);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
//绘制食物
drawFood();

//判断是否吃到食物
if(head.x==food.x&&head.y==food.y){

//增加蛇身的长度

var newCell=new Cell(food.x,food.y,head.d);
snake[snake.length]=newCell;
head=newCell;

//随机产生一个食物
initFood();
food=new Food(foodX,foodY);
drawFood();

score=score+10;
document.getElementById(&#39;result&#39;).value = score; 

}
}
//初始化食物的x,y坐标,随机位置
function initFood(){
//Math.random()返回一个0-1之间的随机数
//Math.ceil()向上取整
foodX=Math.ceil(Math.random()*28+1);
foodY=Math.ceil(Math.random()*28+1);
//判断是否跟蛇的身体有重叠
for(var i=0;i<snake.length;i++){
if(snake[i].x==foodX&&snake[i].y==foodY){
initFood();//递归产生食物坐标
}
}
}
//绘制食物
function drawFood(){
ctx.fillStyle="green";
ctx.beginPath();
ctx.rect(food.x*width,food.y*width,width,width);
ctx.closePath();
ctx.fill();
}

draw();
//监听键盘的事件
document.onkeydown=function(e){
//keyCode 上38下40左37右39
//W87 S83 A65 D68
var keyCode=e.keyCode;
var direction;
//alert(keyCode);
switch(keyCode){
case 38:
case 87:
direction=2;break;//上
case 40:
case 83:
direction=-2;break;//下
case 37:
case 65:
direction=1;break;//左
case 39:
case 68:
direction=-1;break;//右

default:break;
}
//控制蛇的移动方向
if(head.d+direction!=0&&(keyCode==37||keyCode==38||keyCode==39||keyCode==40||keyCode==65||keyCode==68||keyCode==37||keyCode==83||keyCode==87)){
if(head.d!=direction){score--;document.getElementById(&#39;result&#39;).value = score; }
moveSnake(direction);

}
}

//移动蛇的方法
function moveSnake(direction){
var newSnake=[];
var newCell=new Cell(head.x,head.y,head.d);
//循环除开头以外的身体部分
for(var i=0;i<snake.length;i++){
newSnake[i-1]=snake[i]
}
newSnake[snake.length-1]=newCell;
newCell.d=direction;

switch(direction){
case 2:
newCell.y--;break;//上
case -2:
newCell.y++;break;//下
case 1:
newCell.x--;break;//左
case -1:
newCell.x++;break;//右
}

snake=newSnake;
head=snake[snake.length-1];
checkDeath();
draw();

}
//自动移动
function moveClock(){
moveSnake(head.d);
}

setInterval(moveClock,speed);

//判断游戏是否结束
function checkDeath(){
//判断是否出边界
if(head.x>=30||head.y>=30||head.x<0||head.y<0){
alert("很遗憾,您输了!" + "\n" + "您的得分为:"+"\n"+score);
window.location.reload();
}
//判断是否碰到自己
for(var i=0;i<snake.length-2;i++){
if(head.x==snake[i].x&&head.y==snake[i].y){
alert("很遗憾,您输了!" + "\n" + "您的得分为:"+"\n"+score);
window.location.reload();
}
}
}

 
</script>
</html>

The above is the detailed content of The output tag and canvas tag in html5 implement greedy snake. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between an HTML tag and an HTML attribute?What is the difference between an HTML tag and an HTML attribute?May 14, 2025 am 12:01 AM

HTMLtagsdefinethestructureofawebpage,whileattributesaddfunctionalityanddetails.1)Tagslike,,andoutlinethecontent'splacement.2)Attributessuchassrc,class,andstyleenhancetagsbyspecifyingimagesources,styling,andmore,improvingfunctionalityandappearance.

The Future of HTML: Evolution and TrendsThe Future of HTML: Evolution and TrendsMay 13, 2025 am 12:01 AM

The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools