HTML Game Game Intro Game. You can edit the code, and click on a button to view the result. Examples might be simplified to improve reading and basic.
I created a classic snake game in the canvas element. I have not considered best practices when doing this, I just wanted to finish it first. Snake game with canvas element code. Ask Question Asked 5 years, 3 months ago. In general, it would be more efficient to stroke one complex shape instead of a bunch of simple ones. HTML Cheat Sheet - A simple, quick reference list of basic HTML tags, codes and attributes. The screen for the game looks like this: About the Code. To understand it, we can divide the code in 3 parts. HTML, CSS and JavaScript. HTML part contains simple tags to form the layout of the game. CSS provides a bit of responsive design and JavaScript part contains the main logic of the game. Few of the important steps of the game are as follows.
$begingroup$I created a classic snake game in the canvas element. I have not considered best practices when doing this, I just wanted to finish it first. Now it's time to improve the coding practice. You can help me out by mentioning bad practices, giving code improvements and suggesting anything else.
You can see a live version of the game here.
Pimgd4 Answers
$begingroup$From a once over:
Good
- I like how you use an IIFE
- I really like how you use
direction = keys[event.keyCode];
Not so good
You are not consistently applying the 2nd good technique, for example this:
could simply have been
I will leave deep thoughts to on whether
- You want to specify that
'left'
is the opposite of'right'
, since you already specified'right'
is the opposite of'left'
- Whether you would want to merge
oppositeDirection
andkeys
- You want to specify that
You copy pasted some code in
giveLife
andgrow
that could also benefit from the above approach. I would have written this:as
The advantages here are:
- If you wanted to play snake with 8 directions, you could
- No silent failure if an invalid direction is passed along
The following code gives me the creeps:
have you considered using something like
This is also is not a pretty sight:
That should at least be
and really there has to be a better way than to subscribe to every browser event ;) I am assuming you are not simply providing
snake.game.adjust
because it is not yet initialized at that point. I would rather solve that problem then creating functions to deal with that problem.
Some thoughts on your general code style (some points might depend on personal preference):
- I suggest splitting HTML/CSS/JS into different files
Your use of indention and whitespaces is inconsistent
has an indention of two spaces
has an indention of four spaces
has an indention of eight spaces
You have two times:
Method names are inconsistent
is_catched
,setWay
,todraw
.Consider writing constants in uppercase to differentiate them from variables you intend to modify:
BLOCK
instead ofblock
or in this case something likeBLOCK_SIZE
is more appriopriateYou declare and assign your
food
variable the first time somewhere between all the functions, although you have acreatfood
methodThere are several magic numbers, that you could/should turn into variables Teamviewer 7 free download for windows 7 free.
Some parameter names are rather cryptic:
is_catched(ax,ay,awidth,aheight,bx,by,bwidth,bheight)
You could use objects instead of arrays for some variables. E.g.:
food
is an array with 2 elements (probably x/y pos). You could turn this into an object{ x: XXX, y: XXX }
. That might improve readability in some places.Currently your update logic seems to be mixed with your draw logic. It is probably better (and easier to maintain), if you seperate these. Also, you check for game over inside your draw call..
I would suggest drawing the snake as a single polyline instead of as a bunch of blocks, so that you only call stroke
once instead of calling fillRect
as many times as blocks has the snake.
In general, it would be more efficient to stroke one complex shape instead of a bunch of simple ones. You can see that in this test.
Another option that I would consider is to clearRect
only the last block of the snake and then draw (fillRect
) only the new one, so that you don't have to redraw all the scene, only the parts that have changed. Another test here.
You will have to test both options and see which is better for you, but I would go for the second one.
I would also consider using requestAnimationFrame
insted of setTimeout
. From the MDN doc:
The window.requestAnimationFrame()
method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. The method takes as an argument a callback to be invoked before the repaint.
Also check this post about that. It explains the basics and also how to set a custom frame rate, so that you can still use refresh_rate
in your code.
There are two options:
Wrapping the requestAnimationFrame
in a setTimeout
:
Or using deltas:
Microsoft genuine diagnostics tool downlo…. .The Debug Diagnostic Tool (DebugDiag) is designed to assist in troubleshooting issues such as hangs, slow performance, memory leaks or memory fragmentation, and crashes in any user-mode process.
In your case I think it would be better the first option because the snake can only be drawn in certain blocks, so it doesn't make much sense to me to use deltas here.
To @Sykin's answer, I would add:
If you press down and then left faster than the snake takes to slither 'one step', the snake turns around and slithers over itself.
I find that JSLint really helps me get a consistent code style.
Dj serato free full version. I suggest you use strict mode in your JS, by starting with a line 'use strict';
protected by Jamal♦Dec 2 '15 at 16:26
Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
Not the answer you're looking for? Browse other questions tagged javascripthtml5canvassnake-game or ask your own question.
Snake is a fun game to make as it doesn't require a lot of code (less than 100 lines with all comments removed). This is a basic implementation of the snake game, but it's missing a few things intentionally and they're left as further exploration for the reader.
Further Exploration
- Score
- When the snake eats an apple, the score should increase by one. Use context.fillText() to display the score to the screen
- Mobile and touchscreen support
- Allow the game to be scalled down to a phone size. See https://codepen.io/straker/pen/VazMaL
- Support touch controls
- Better apple spawning
- Currently the apple spawns in any random grid in the game, even if the snake is already on that spot. Improve it so it only spanws in empty grid locations
License
(CC0 1.0 Universal) You're free to use this game and code in any project, personal or commercial. There's no need to ask permission before using these. Giving attribution is not required, but appreciated.