search
HomeWeb Front-endH5 TutorialHTML5 Snake game implementation ideas and source code_html5 tutorial skills


Game Operation Instructions

Use the direction keys to control the greedy snake to move up, down, left and right. A greedy snake will grow in length after eating food.

The specific implementation of the game

The difficulty of the game is how to simulate the movement of the greedy snake. It's obviously very simple if it's just a block. But when the length of the snake becomes longer, how to control the movement of each block

?

If you observe the movement of the snake, you can find that from the head to the tail of the snake, the position of each block at the next moment is the position of its previous block at the current moment

Location. So all we need to do is control the movement of the snake's head. The positions of other parts can be deduced by analogy.

Another issue worth noting is

After the greedy snake eats the food, where should the newly added blocks be placed.

The answer is that at the next moment, the newly added block should appear at the end of the current moment.

Therefore, after eating food, you should add a block before updating each position of the snake, and set its position to the tail position at the current moment.

Then the positions of all blocks except the newly added blocks are updated at the current moment

index.html
snake.js

The code is as follows:

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 - 1; i >= 0; i--) 
{ 
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 = 0; i < snake.length; i++) 
{ 
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(&#39;2d&#39;); 
//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(&#39;keydown&#39;, play, false); 
addFood(); 
setInterval(update, 300); //note 
setInterval(drawScene, 30); 
}


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
H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 Code: Accessibility and Semantic HTMLH5 Code: Accessibility and Semantic HTMLApr 09, 2025 am 12:05 AM

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

Is h5 same as HTML5?Is h5 same as HTML5?Apr 08, 2025 am 12:16 AM

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

What is the function of H5?What is the function of H5?Apr 07, 2025 am 12:10 AM

H5, or HTML5, is the fifth version of HTML. It provides developers with a stronger tool set, making it easier to create complex web applications. The core functions of H5 include: 1) elements that allow drawing graphics and animations on web pages; 2) semantic tags such as, etc. to make the web page structure clear and conducive to SEO optimization; 3) new APIs such as GeolocationAPI support location-based services; 4) Cross-browser compatibility needs to be ensured through compatibility testing and Polyfill library.

How to do h5 linkHow to do h5 linkApr 06, 2025 pm 12:39 PM

How to create an H5 link? Determine the link target: Get the URL of the H5 page or application. Create HTML anchors: Use the <a> tag to create an anchor and specify the link target URL. Set link properties (optional): Set target, title, and onclick properties as needed. Add to webpage: Add HTML anchor code to the webpage where you want the link to appear.

How to solve the h5 compatibility problemHow to solve the h5 compatibility problemApr 06, 2025 pm 12:36 PM

Solutions to H5 compatibility issues include: using responsive design that allows web pages to adjust layouts according to screen size. Use cross-browser testing tools to test compatibility before release. Use Polyfill to provide support for new APIs for older browsers. Follow web standards and use effective code and best practices. Use CSS preprocessors to simplify CSS code and improve readability. Optimize images, reduce web page size and speed up loading. Enable HTTPS to ensure the security of the website.

How to generate links with h5How to generate links with h5Apr 06, 2025 pm 12:33 PM

h5 pages can generate links in two ways: create links manually or use short link services. By manually creating, you just need to copy the URL of the h5 page; through the short link service, you need to paste the URL into the service and then get the shortened URL.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.