Coding JavaScript Snake Game (Plain Vanilla JavaScript & HTML Canvas)
HTML-код
- Опубликовано: 6 фев 2025
- Learn how to build a the iconic Snake game using JavaScript in the browser! We will be using plain vanilla JS to code this fun game.
We use a html5 canvas to create this snake game. We draw on the canvas using drawrect and other methods provided by the canvas. We will be tracking our score based on how many fruit the snake eats. We us an object orientated approach to build this game.
Code on GitHub: github.com/kri...
Don't forget to Subscribe here: / @krisfoster1
PART 2: ruclips.net/video/AVQKOz99Biw/видео.html
Could you please create a video concerning the part of shifting arrays...For trial purposes I shifted them right(You shifted left) and got a runtime error could you please explain more if you could please
it keeps saying snake is not defined
Awesome
You probably dont give a shit but does someone know of a tool to log back into an instagram account??
I was stupid forgot the login password. I love any help you can give me
@Rex Juelz Instablaster ;)
I wish you could explain a bit more, i'm kinda lost as to what happens with the part of the code for making the snake grow, also you should boost the volume a bit for later videos, thank you
Thank you for the feedback @Scorpio
About to sleep(7:17) and have an assignment due 23:59. If the magic walls code where you come in opposite side if you go off the canvas helps me.. you are truly my savior. Because I feel the code you wrote actually made me realize how it worked, and you’re the one person I’ve found having that. I’ve not seen much more but if you have a poisonous food type too now. Im set 😂
Thank you, glad it helped you! Hope you got your assignment finished
@@KrisFoster1 yeah! I think i’m managing now. It wasn’t completely what I needed. But As I mentioned you made something click in my brain so I understand a bit more at least! I appreciate that a lot 🤝
Hey Chris if I am being honest, This Snake game is the tutorial that I most understood. Thanks and do more tutorial's just like this, Thanks again! 😁😁😁👍👍👍👍
Thank you for the kind words @Programming!
Congratulations!!! You did it without arr.pop() and arr.shift()
Awesome video for somebody just starting to get into coding!!!
Very simple and clear. 👍👍
Well explained and very clean coding structure. Thank you Sir :)
Glad it helped you out @piu paul
GREAT VIDEO! Watching it in 2021
Thank you @urgen tenzing sherpa!
Thanks very help full, I like soo much how you draw the tail, it is very clever idea!!!
I would really like seeing the continuation
Thanks for letting me know, I will work on this
PART 2 Uploaded here: ruclips.net/video/AVQKOz99Biw/видео.html
That's a mighty fine snek you got there
"snek needs a snek so let's make a snek... "
i'm dead
My ears are doing that "Ken Jeong looking at a tiny note" meme.
hey @CodeWithKris this might be an old video to answer to, but whenever i run the code the fruit keeps on moving everywhere i think the program reads the "this.total++;" for the fruit not for the snake or something.. i am really confused, it would be a great help if you would help
I get the same error, when I replace the this.total++ with console.log('Eating') the code functions as expected, however when I try to add to the total it seems to be causing the function to return true every time the window updates and the fruit moves. Not sure how these are connected as it seems to work for the console.log but not the this.total++. Let me know if anyone else has found a solution to this, I am using VS code in a xubuntu VM.
I Tried to make snake using grid and , but it felt so buggy. I will Probobly redo games using canvas.
It's like trying to read Chinese, but I'm determined to learn though
huh what if u are from china😶😶
@@sumanboi it's like reading french
@@nomapech7300 whats if ur from france?
@@sumanboi it's like reading turkish
@@nomapech7300 what if u were born in trukey?
Hey, I have an issue that I run the code in chrome but nothing appears. No canvas, no snake, nothin. But when I open up the chrome console, it says there is no errors and that everything is functioning properly. Currently I am at 8:06 in the tutorial, and I have followed all instructions other than change the name of the 'snake' variable to 'snek'. I would love any help I can get. TIA
some bug where you back the direction.
yeah its a good tutorial for me
keep going......
This is a very helpful tutorial but I'm having trouble at the begining of making the snake. I copied your code but google keeps saying that snake is undeifined and it doesn't show up in the box. Can you help me with this?
Me also
same
put the snake.js source before the source of draw.js in the script in the html file.
great vid!
I was stuck at increasing the snakes length so i watched this video , it works my tail is increasing but not at the correct behaviour
Whenever I try to run the program after the snake is applied onto the canvas, i get a console error that ctx is not defined. Would that be due to a previous mistake or something else.
HOW DO YOU DO SHORTCUTS TO MAKE CODE APPEAR
Thanks for the great tutorial👌🏼I tried so much to figure out the usage of THIS. Sometimes it is so hard to understand it😒
The idea of this simply put is to cover a scope. Now what is a scope so u seen the way he writes function () { something here} the something here is the scope. The region within which this searches for “stuff” anytime it’s called. If he did not put this in front of a variable before calling it Javascript will look for it in the global scope ie outside of the function. I hope I haven’t confused u more with scope but to understand scope is to understand this and also trying Learning about namespace 😁
@@nanakoab thank you
what is the place you code?
What app are u useing?
does this use an older version of javsscript
I am confused as to why when we press UP key, we need to add -scale, aint the y coordinate above plus and down it is minus?
For anyonoe who got the same question, it is because of document object, document height starts from 0 at the top, to its length to the bottom, so thats why we are in minus when we go up. Flies away
Yeah that's exactly it @Makro Phoenix, thanks for explaining
im trying to make this work using Visual Studio 2017 for my assignment, I am going to adapt the code to my needs, but when I run it, it just displays the canvas without the Snake and fruit. I changed your draw.js to Collision.js, I want to know how i can make it show the snake and fruit
also in visual studio i created a folder that links the JS files with the HTML page, thats how Visual studio works
can you tell how to increase the snake's speed
Hi kris, I know this is an old video for you to reply to, but I made a text file and turned it into fruit.js, but for some reason it still says fruit is not defined. I have linked the script and everything you did in the video, but it is not working.
I keep getting the error message "Snake is not defined"
It draws a rectangle, if I give a width/height to the canvas (without it draws a square). Which doesn't make any f.....
sense, cuz I give it same dimensions!
Hey CodeWithKris, is there an easy solution for the snake not to turn to opposite direction? Like if going up, can't turn down, only left and right. I tried to mess around with the switch case, but i couldn't get the if statements to work. Any ideas? Thanks!
Hi @Palofar, if you want to edit the existing switch statement to make opposite movements impossible you could so something like this:
case 'Up':
if (!this.ySpeed > 0) {
this.xSpeed = 0;
this.ySpeed = -scale * 1;
}
break;
....
This means we are only changing the direction to 'Up' if the snake is not going down already. Hope this helps.
@@KrisFoster1 woow weee! It works. Thanks a lot man!
very well explained, thanks mate!
Nice!! Please push the code example to git
Hey Cassio, thanks for your comment. I've updated the description to include the GitHub repo: github.com/kriscfoster/Snake-Game :)
Man, can you explain the logic behind the pickLocation method? Great tutorial, just can't understand, why we do all this: * rows - 1) + 1) * scale; Appreciate your work!!!
me too
i think even if we delete -1 ) +1 wont be problem because is is same this.y = (Math.floor(Math.random() *
rows) ) * scale;
When my snake grows to three for some reason the last one gets left behind
me too
@@fonta22 I did manage to get it fixed, but I do t know what did it. I would say look at it very carefully to see if you accidentally pressed an extra button or put the wrong symbol.
what is the app that he uses for the coding I want it
sublime text
I always get the error "Snake is not defined as Setup" what am I doing wrong??
I had the same problem. Make sure that the Snake.js file is refferenced before the draw.js file in the index.html
what is ctx
I am getting the following error,
Uncaught ReferenceError: Snake is not defined
at setup (draw.js:10)
at draw.js:12
The error is at the part where the code says, "snake = new Snake();" after the "(function setup() {" in the draw.js file.
Please any help will be greatly appreciated. Thanks
Also on the "const rows = canvas.height / scale;" and "const columns = canvas.width / scale;" of the draw.js file, the height and width stay white and don't change to blue like yours did. I don't know if this could be causing the error. I am also using Sublime Text.
@Jackson have you looked at the source code on GitHub to see if you're missing anything?
@@KrisFoster1 It is fixed now, thanks.
@@jackson5186 hey I m having the problem height and width stays white what to do please help me out?
You already solved it but, in the HTML file try putting the snake.js file first then the draw.js file
Thanks sir! very helpful
how do we use fruit as a variable, you never define it
Hi @Blazeben10, we create a script called fruit.js & add it to our html file before snake.js & draw.js. This means we can use the class defined in fruit.js in the other files. Take a look at 13:31 to see this part of the video. Thank you!
@@KrisFoster1 Not very useful as I made this and it still doesn't work :(
Hi Kris! How about doing it class based way? I think some more of ES6 would be nice.
Hi MrRaziPL, yeah you could definitely do it like that, it's just a matter of which you prefer
I keep getting an error that i didn't define Snake in draw.js, what do I do
Have you got the script tags in the html file? If you have that already note that the order of these is important. snake.js needs to be before draw.js so it is defined first.
@@KrisFoster1 Thanks 😀
bit late but my code are grey out is there a reason?
Hi @AT97 thanks for the comment, I'm not sure I understand your question.
what program is this?
Hi Qayl Maherali, I'm using sublime text 3 as a video editor in this video. Thank you
When is javascript loaded into the file by the browsers? Does it follow the flow of the document or does the browser pick our scripts at a certain point?
@nick it is loaded at the point you add it in the HTML. If script A is a line before script B then A will be loaded first
@@KrisFoster1 thank you Kris I finally found that answer. Just couldn't figure out how to ask my question.
yo thanks was my problem too
how u make the snake move faster??
I think this was answered below already but if you decrease the value of your setInterval it will speed the game up. This is the value we are talking about: github.com/kriscfoster/Snake-Game/blob/master/draw.js#L27.
How to make it stop when it hits the borders??!! Someoneee plsss help
Object Oriented JavaScript is so hard I'm actually gonna cry
I can't do it man
Keep going @SmellTheL, we all believe in you!
hi :D why do you use the setup function inside of ( ) ? is it already exist the setup function?
its to call it as soon as the program opens
Thank you so much
Hello i wanted to speed up my snake and make it moove smoother. What can i change?
You have to change the time interval in the function setup()
Example:
(function setup() {
snake = new snake();
window.setInterval(() => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
snake.update();
snale.draw();
}, 250);
//
@@SpairutAlfa im kinda lost at the part where he use arrays in this.update and this.draw function,can you help me with this?
THANK YOU KRIS!
This is my first javascript project that I haven't given up on after a few hours!
Your tutorials are very insightful!
I've been making new versions of Snake Game with my own ideas!
I've learned so much from these two tutorials so thank yo so much!
Here is all of the versions of my snake game if anyone wants to play them or learn from my code!
drive.google.com/drive/folders/19fMqMuWwXxGuGvMsaYqz8ket-QB2lM5v?usp=sharing
Well done @Lastered, that's great to hear!
Hello Good day, How to add an another fruit in this game? What code should I type?
Btw. This video was amazing I learned a lot, thanks for helping us
I'm so confuse on how the snake adds another tail, everything from there doesn't make sense at all to me. Though this is an amazing tutorial, thanks!
this might be a bit of an old video for you to answer this, but i'm using notepad for this and i'm not sure how to add the draw file any suggestions?
@Killerfrog it should be the same. If you create the file on your computer you can open it in notepad then
@@KrisFoster1 yes thank you, I did try and it does work thank you I'm just new to this so I was worried xd
I have this problem:
Uncaught ReferenceError: Snake is not defined
what can i do?
i got too but i ve had error somewhere in snake.js so i fixed errors in snake.js and it worked. So try to control snake.js if everything there is correct.(sorry for bad english)
@@noTmeDev yeah, just checked, only one little mistake :D
Glad you got this sorted out @Sami Ketola!
Woow, this is definitely not beginner friendly ''''xD
i have a mac, i dont know how to open an editor so i can even start. what software do you use to make this?
Hi Jonah, I'm also using a Mac. There are many different code editors you can use. For getting started I'd suggest doing a Google search for Sublime Text 3 & downloading it from there.
Try VS Code and then download the 'open in browser' extension!
How did you get your file to open in crome?
You can either right click on the HTML file and click open in chrome, or you can open the chrome browser -> click file in the top menu -> click open
What program do you use
Hi Zoomer, I use sublime text 3 as my code editor.
when i do this, the snake wont move but everything else works
Thank you @Mateo If you have your code anywhere I can have a quick look & see if I notice anything
I got these errors when trying to test the snake hitting the width:
Uncaught SyntaxError: Unexpected end of input snake%20.js:38
Uncaught ReferenceError: Snake is not defined draw.js:10
try ordering the script-src tags in your HTML file
snake.js:52 Uncaught TypeError: Cannot read property 'log' of undefined
at Snake.eat (snake.js:52)
at draw.js:20
Snake.eat @ snake.js:52
(anonymous) @ draw.js:20
setInterval (async)
setup @ draw.js:14
(anonymous) @ draw.js:25
owo when we started to add the eating it becomes an error
Do you have a console.log statement on that line? If you do, make sure you haven't misspelt console
@@KrisFoster1 hehe thank you i finally got it uwu
mine is saying
Uncaught TypeError: Cannot read property 'getContext' of draw.js:2 null
at draw.js:2
can someone help me?
I downloaded his files from the second part but i still get the error
Hi @Max, if you didn't solve this I think it could be related to your html file. Does yours have a canvas element with class="canvas" like this github.com/kriscfoster/Snake-Game/blob/master/index.html?
@@KrisFoster1 yes it does have class="canvas"
What editor is that?
@William sublime text, it's my go to for web development
I use light table ide
.getContext doesnt work for me
SAME
man, thanks for the effort and all, but i cannot hear anything... Sorry.
Sorry to hear that @DownWithTheShip Media. Will try to make sure future videos have clearer audio
@@KrisFoster1 Man, it´s really not that big of a deal, I really apreciate the effort of what you have done. For real. Tnks for answering my comment!
Can i have your source code?
Hi @Mohtasim Shovon, the source code is here: github.com/kriscfoster/Snake-Game
17:55
after eating two fruits no more spawn T.T
after two more mine stops working
Too quite, can't hear anything