Coding Challenge #115: Snake Game Redux

Published by Jan Heaney on

Coding Challenge #115: Snake Game Redux



100 Comments

twarug 28 · September 12, 2018 at 7:00 pm

Hey, try make a sudoku 😉

sshah93 · September 12, 2018 at 7:50 pm

Hello, thank you, I can finally hopefully learn P5 for once instead of simply watching you make some cool stuff for fun every week:

Please take a look from your code, i haven't changed much except for fixing the last bug where when you pressed the opposite direction of the direction your snake was moving, then the snake got killed. You can find the code here: https://editor.p5js.org/sshah/sketches/S1N7oyPu7 … hopefully later i can add like a reset function or end game screen. Thank you 🙂

Cezary Kamiński · September 12, 2018 at 7:54 pm

Next snake needs two additions: preventing food to spawn on top of it and no possibilty to backtrack i.e. if you're going left pressing right arrow does nothing instead of killing you because you ran into yourself

Qc Diamond · September 12, 2018 at 8:28 pm

What do you study/teach at school?

yeet yeet · September 12, 2018 at 8:35 pm

Can you make a part 2 about point scoring and a endgame text on screen maybe? and if you want to add textures (if that is possible) that you drew yourself, how is that possible?

Eli Frigo · September 12, 2018 at 10:29 pm

You should do a coding challenge where the program generates Hilbert Curve

Brewal Renault · September 12, 2018 at 11:27 pm

Hey. I've been refactoring and improving a bit the game just for fun : https://editor.p5js.org/brewal/sketches/HJcUnkP_Q

Tommy Phelps · September 12, 2018 at 11:54 pm

Snake game redux – Daniel Shiftman

Samuel Gunter · September 13, 2018 at 12:02 am

How do that zoom in thing?

Santiago Guzman · September 13, 2018 at 1:02 am

When are you gonna do python?

Novacane · September 13, 2018 at 1:53 am

I swear you’re reading my mind, the day after I start making flappy bird with genetic algorithms you make a video on it, now a week after I start my snake game you make a video on it. You’re a legend don’t stop please!

Vilhelm back · September 13, 2018 at 4:47 am

WHERE IS THE WHITEBOARD!!?!!??!?!?!

Sebastián Soto · September 13, 2018 at 4:56 am

So sad you cant like a video more than once.
Thanks for everything Dan.

Spongman · September 13, 2018 at 5:09 am

I made a version that simplifies some things a little. It separates the head from the body, so it can be referenced directly, it integrates the update and eat functions since eating is equivalent to NOT removing the end of the tail, and it uses a map of key->direction vectors to eliminate the if cascade/switch. https://editor.p5js.org/Spongman/sketches/Skebj9BOm

Shaun Dreclin · September 13, 2018 at 6:26 am

16:28 – 16:42 if anyone is interested in the "why" behind this, it's caused by a floating point rounding error.

For a great explanation of the issue, check out Computerphile's "Floating Point Numbers" video. watch?v=PZRI1IfStY0

Josh K · September 13, 2018 at 7:18 am

How do I do a lava lamp in javascript – webgl or d3 or anything?

Black Bird · September 13, 2018 at 8:54 am

It's not really necessary but you should use a getter for snake's head, you repeat that code to get head way too much ;p (also .slice(-1) would return last element too)

Matt Rose · September 13, 2018 at 10:35 am

I can't see the code in the first link. Is it also on github or somewhere else?

Cédric Floquet · September 13, 2018 at 12:38 pm

The p5js online editor is a nice idea. Even though it lacks some IDE features (such as code autocompletion), the direct integration of the canvas next to the editor, and especially the ability to share the result, are worth it.

Alex Devero · September 13, 2018 at 12:47 pm

Thank you for this great tutorial Dan. How could one take this tutorial implement machine learning -> let the snake learn to avoid obstacles, and itself, and find food?

NIETSCHE Crossout · September 13, 2018 at 3:01 pm

I think that I just watch your videos so that I can feel good about writing code in C# .NET

GoddersGaming · September 13, 2018 at 5:25 pm

You could have done it much quicker if you used an online tutorial, I like the Coding Train's tutorial most. Love you Dan, keep it up!

Abhishek Kumar · September 13, 2018 at 7:21 pm

Thank u for this awesome video

Demonism · September 13, 2018 at 8:12 pm

Hasn't the p5 web editor existed for like a year at least? I did notice that it isn't on the alpha sub domain anymore, but it has been fully functional for a while now along with saving sketches and etc.

morphman86 · September 13, 2018 at 8:43 pm

You CAN use a switch statement for the controls, but you really shouldn't. It's OK for smaller projects like this, but it's really easy to make it a habit, and the switch is a LOT less efficient to execute than a chained if statement. This is mostly due to a switch checking every possible outcome every time, while an if will skip an instruction that fails a check, meaning every statement in the rest of that chain will be skipped as well, saving you a TON of checks in the long run.

ES6 is especially good at this, as if you have AND statements, if any check to the left of the AND fails, it won't even try the right, it'll break and move on.

Imagine checking keyboard inputs for diagonal movements in a 30 frames per second game. That's 9 possible combinations (all button presses plus no button press) that will be checked 30 times per second. That's 270 checks per second in a switch, but only 8 in a chained if (because you don't need a check for the default in an if statement). Now add a shoot button or two, an action button, a jump button, a slide button, a few item buttons and some other interactions and you can see how quickly this adds up to a very resource heavy task for the code engine. And that's just the controls!

Emanuel Fontelles · September 14, 2018 at 12:17 am

Daniel, what is the math to animate this animation https://youtu.be/qlZlHr7jpOM?t=481 ? Do you wanna a challenge?

Numero7 Mojeangering · September 14, 2018 at 8:37 am

try making an bot that play it ! 🙂

Sayan Das · September 14, 2018 at 3:30 pm

Is the editor free?

SpaghettiKing · September 14, 2018 at 7:42 pm

Here is one version I made where the edge of the screen teleports you to the other side, like in Pac-Man. It's also a bit faster, and some colors have been changed.https://editor.p5js.org/Spooghetti420/sketches/ryi7f_Fum

Matas Valiūnas · September 14, 2018 at 11:19 pm

Can you do the same in Java or Python. Which one do you prefer and why?

The Zip Creator · September 15, 2018 at 12:20 am

what about OpenProcessing?

ZOLDIK · September 15, 2018 at 3:23 pm

27:22 : If you declared some variable in the constructor to be the head it would be better than typing this.body[this.body.length-1] everytime
like:
this.head = this.body[this.body.length-1];
and then use this.head.x or this.head.y or whatever you want from it … i think this would be better if it works ?

ZOLDIK · September 15, 2018 at 3:40 pm

30:56 eeyaaaaa XD

what you was gonna say ?

Red Hen dev · September 15, 2018 at 7:59 pm

3D Snake with voxel Perlin terrain: https://codepen.io/RedHenDev/full/NjWVVd/

Golden_Paper · September 16, 2018 at 10:00 pm

Make a Paper.io 2 coding Challenge Or in multiple videos. It would be fantastic

Tyler Dunphy · September 17, 2018 at 1:32 pm

I used your last coding challenge to make my own version, and I used an options array to make sure food spawned on available spaces 🙂

Brandon A. Rodriguez C. · September 17, 2018 at 10:47 pm

Does someone knows how can i move an ellipse when my mouse is pressed, and leave it in that position when i stop it? on P5

Matt Gipson · September 18, 2018 at 3:12 am

You should do a video on voronoi diagrams

Snoops Man · September 18, 2018 at 10:52 am

"Why was i doing this again?" lmao

Twitchi · September 18, 2018 at 4:09 pm

so.. why is a switch statement so much better than if?
EDIT: I get that it is probably more efficient, but why?

Eric Rovell · September 18, 2018 at 10:23 pm

Thanks a lot for remaking this tutorial! It was the first "The Coding Challenge" I have completed from your series. After that I have been learning a lot (just two months). This time my code looks much more better, it is so pleasurable to revisit some of your code from time to time and see the progress you have made.

For anyone who do this game: try to use getter in your snake class for getting the latest element in your body array:

class Snake {
constructor() {
this.body = [createVector()]; // initializing head as the 1st element
this.direction = createVector(0, 0);
}

get head() {
return this.body[this.body.length – 1];
}
}

after that when you need the head => just call it like snake.head, no ( ) is needed. This will make your code compact.

Tomáš Růžička · September 19, 2018 at 2:24 pm

How the hell is the text editor done on web??? 🙁

Gabriel · September 19, 2018 at 3:26 pm

Why don't you keep the head to index 0 and then add the body to 1, 2, etc…

ShokeR · September 20, 2018 at 3:25 am

Can someone help me and tell me how exactly the update function work? I don't really understand how all the body parts get updated and i've followed it frame by frame. There is must be something behind the scene with the shift function. Thanks

Keytron Quabius · September 20, 2018 at 3:51 pm

What is the difference between pre process JavaScript or process JavaScript AKA PJs, I've been seeing that everywhere, especially when it comes to drawing tutorials.
How do you implement PJs versus regular vanilla JavaScript?, is it some type of package management, or can you do it by CDN?
That might seem like Anubis question of some but for someone who is just picking up vanilla it is pretty decent at vanilla Js, what would they have to do to get started in PJs? Because I see a lot of code for drawing that works in PJs but doesn't work in plain vanilla JavaScript, so I imagine it's just adding a library somewhere? Or is there more to it? Sorry for the new question, it might sound kind of dumb but I'm definitely interested in seeing what PJs can do, and adding it as one of the Frameworks that I commonly use, because it seems like it has a lot of power when it comes to drawing or certain aspects like that.
Do people usually Implement PJs into websites at all?

Keytron Quabius · September 20, 2018 at 3:53 pm

A lot of newer people do have trouble when people write their code in those dry functions. Is there any way to actually write that code a little more sloppily so beginners can get it? 0:40?
This may also seem silly but one of the things I see on ww3 all the time is there examples are always something something my function call function, and that can be just a little confusing when it's only a few lines of code, I wish more tutorials would show us the sloppy way, and then the dry way.
Sometimes for lack of a better word we want something to happen or an event to fire without a function and usually beginners and intermediate should learn that first before they begin to get into the more functional type of programming. Because what you see someone more advanced writing all these functions it kind of becomes unclear as to what they're doing, at least in some cases this guy is a super great teacher but that's just something I've noticed with JavaScript as a whole. It's been far better in my experience that people learn to make certain things run without having to call them inside of function, and then showing the way when you do call the function that weigh more is explained and more of a big picture of the language can be understood.

Keytron Quabius · September 20, 2018 at 3:59 pm

Is there a way to make snake using completely vanilla JavaScript, without the canvas.
Just using something like on key up on key down or some type of event listeners, IDK I'm sure the tutorials are out there fam. But some people usually watching these channels are such experts they could pretty much write that out in vanilla in like 5 minutes, or at least read out what events you should be using if you're using or taking the vanilla JavaScript throughout and not using the canvas

Keytron Quabius · September 20, 2018 at 4:01 pm

2:25 I know it's super hard for people to make successful clones of websites, example would be something like gab for Twitter. There's an issue with medium while it's a great site it tends to cater to people with only one kinds of worldview on one side of the spectrum.
Sometimes a lot of that s*** in programming doesn't matter but if you do that for a living it can kind of add up.
Like I get kind of bummed when I have to go to medium to read certain things because I know the people at the top when it comes to medium have an agenda.
I wish a successful clone of medium could be done in the right people on the other side of the spectrum could actually populate the site and make it something, because a good percentage of the population is being completely ignored and scrutinized for not having the same consensus worldview that a lot of people want them to have, aka the same view the people at the top on medium have.
Those parts of the tech world could be way better as they only satisfy less than half of the population, USA wise.

Tim MacDonald · September 29, 2018 at 10:34 am

Hey Daniel, how about doing a simple version of a falling-sand game (there's a wikipedia article that describes what they are.) Note that this is different from sandpiles, which you've already done.

Eletrônica Hoje · September 30, 2018 at 3:10 pm

Hi Dan, I've made some changes on your game, check it out! List of changes: score system, speed variable based on progress, head separated from body, round fruit, high score db with firebase, got rid of "scale" so I can draw thinner lines, "switch" for key pressed, combo-like animation, booster key to speed things up for a while, some other things I don't remember anymore.
I don't know why the firebase couldn't work with the "gstatic" link on index, I had to put a copy of the firebase.js on the project to make it work. If anyone can fix this please let me know. Hope you enjoy! https://editor.p5js.org/full/rkVDxv3F7 or https://editor.p5js.org/[email protected]/sketches/rkVDxv3F7

DJ Dadz Eleco · October 1, 2018 at 9:21 am

Hi sir Dan, You're my inspiration. Thank you sharing your knowledge.

DJ Dadz Eleco · October 1, 2018 at 9:22 am

Hi sir, Can you do a Closest Pair Algorithm Challenge?

Sketch Algorithms · October 4, 2018 at 8:25 am

I made it using canvas and vanilla js if anyone is interested. https://www.sketchalgorithms.com/games/snake-game

Pianochess 1 · October 8, 2018 at 8:13 am

Nice and quick coding!
I think in foodLocation() you might want to check that the food and snake are not overlapping.

Dominic Hofer · October 9, 2018 at 6:36 pm

i couldnt seem to find your shirt anywhere, can you tell me please where you got it from? c:

Diallo Yacine · October 13, 2018 at 2:03 pm

Hello Coding Challenge man. I have something for you. And I want we make money out of it.

James Smith · October 14, 2018 at 10:14 am

pop() is deliting and returning the last element of an array

OrangeC7 · October 20, 2018 at 1:48 am

I added some stuff to your code! https://editor.p5js.org/OrangeC7/sketches/Syl9OjIdQ
(To see most of the changes I made, look in the settings.js file and read the comments)
Edit: I made it so it's best played in fullscreen, although you can change the size of the canvas to make it small enough for the editor

Toke Friis · October 20, 2018 at 8:11 am

Play 16:15 over

Liza Beti · November 12, 2018 at 3:02 pm

Well I learnt my answer on the question “Where do you think we should start learning coding” hihi <3 thank you so much!

Morszczux · November 24, 2018 at 2:51 pm

Daniel ShiftMan 😉

Simon Keisala · November 24, 2018 at 10:24 pm

Not sure if this solution is any easier:
https://editor.p5js.org/miiza/sketches/By6wTfPA7

The array of the snake adds a new head in the front of an array and removes the last element if the snake's body is longer than "len" — the length of the snake

Known bug:
If the player wins (fills all the cells) the game will freeze due to a do — while never finishing

Played around a little bit more with it and changed it from a classic snake to a more dynamic snake:
https://editor.p5js.org/miiza/sketches/H1jAb8P0m

Ali Salman · December 21, 2018 at 10:18 am

You teach so clearly.Could you upload a java course on any teaching website?Would be really helpfull to so many people.

ArnoldsK · December 23, 2018 at 4:37 pm

Talking to past Daniel: use `get head() {}` instead of copying the last body element code.

Marcus Parsons · December 27, 2018 at 3:14 am

I love making prototypes and one handy (yet simple) prototype I made up is the end() function:

Array.prototype.end = Array.prototype.end || function () { return this[this.length – 1]; }

And then you can call it with an array, let's say "this.body" in Dan's video, calling "this.body.end().x" will give you back the last element's x, which is the end of the array, instead of having to type "this.body[this.body.length -1].x" It is a little more handy than having to call the array multiple times in a statement. Saves some elbow grease lol

FirePhoenix555 · December 28, 2018 at 9:33 pm

11:15 how do you spell resolution

MrMeow Beats · January 3, 2019 at 8:43 pm

you should also make the snake not able to go backwards (for example if you're going right you should only be able to go up or down, not left.)

SAMUEL GAMING · January 5, 2019 at 5:50 pm

Dan: "snake.eat(food)"
me: lmao

drewski west · January 9, 2019 at 11:49 pm

so I'm using VSC on windows 7 and i have a ton of extensions… more importantly the p5canvas and everything with javascript so i have no idea why the output is giving me error
"Line X, col X: "let" is available in ES6 (use 'esversion: 6') or Mozilla JS extensions (use moz).
does this mean use firefox browser instead of chrome when testing my .html file that has the snake.js file script coded into it or what the hell is going on??
i have no idea what moz or es6 extension is because even after installing Es6 on VSC it.. still.. has.. this.. error

Geoffrey Casper · January 11, 2019 at 5:01 am

https://editor.p5js.org/Geo25rey/sketches/B1h_ZorGV

OneMadGypsy · January 11, 2019 at 12:12 pm

What's your beef with switch/case? All those spaghetti conditions are redundant and result in long lines.

However, there is another way you could have done it that is even better.

Make an array with 4 indexes, containing the appropriate vectors for LEFT, UP, RIGHT, DOWN … in that order. Then just pass dirArray[keyCode-37] to your update function.

The array can be a constant so you aren't creating those vectors every frame. Also the keyPress conditions are completely eliminated.

If 37 is too ambiguous for you, make another constant ARROW_KEYS_OFFSET = LEFT_ARROW; /*37*/ and do dirArray[keyCode -ARROW_KEYS_OFFSET]

Abdul Basith Mohammed · January 26, 2019 at 8:30 am

could yo send a pic of everything ????? pleeease

kristianboy 44 · February 3, 2019 at 7:01 am

i made this strange thing thank to you https://editor.p5js.org/kristianboy04/full/jlFOpB2Mc

Zak · February 9, 2019 at 9:07 pm

a bit late to the party but I have a question. I want to use this code for a game, but need to change a few things. I've changed most of them but I need help on one thing. Upon pressing each arrow key, I want it to only move once, not continuously and when the key is held, it moves continuously until released

Kevin Cleppe · March 1, 2019 at 6:46 am

I tried copying and pasting the code into my p5.js editor and got error: Uncaught ReferenceError: Snake is not defined (sketch: line 12).

The code works fine in the codingtrain editor, any ideas why I might be getting the error when I copy and paste it?

ComScience Simplified · March 14, 2019 at 7:28 am

1 question, why was there a gap between the body parts of the snake the last time and why does the body look like a single entity this time around? Can anyone please explain?

viral varuj · March 19, 2019 at 3:41 am

what does } and { mean

Theo Ainley · March 22, 2019 at 2:00 pm

Can anyone explain why there is sfx automatically added to the game?? I can't find where the code is to remove it

Küper Men · April 2, 2019 at 1:52 pm

I don't want to know more about p5.js, I want to know more about how you do those crazy sound effects 😀

Luis Pato · April 12, 2019 at 7:11 pm

i spent the video waiting for the moment you would start using redux!!! 😛

Melzarts · April 14, 2019 at 12:13 pm

I'm 4:20 into the video but keep getting the error "Cannot find a class or type named “let” "

Tier1.5 · April 24, 2019 at 7:00 am

Coding Challenge: Make an Etch-A-Sketch Make sure to include a "Shake" Function to lighten all drawn material but not delete it this will allow for Shading.

It would allow users to make legit art and probably stick with 1 pixel scale 🙂

shubhankur kumar · May 13, 2019 at 1:27 am

28:03 – Coincidence!!! I think not!!!!

Doing Something Different · June 3, 2019 at 9:01 am

you could have added some resistance (if the last key pressed was right, we can't press left, only up or down and so on)

Sir Isaac Justin · July 6, 2019 at 5:58 pm

28:08 the prophet was right(BTW Tony died at the end)

Yuplicon · July 11, 2019 at 11:52 pm

12:16

SHAHNAWAZ ALI · July 19, 2019 at 8:13 am

Please code doom RPG

William Bille Meyling · July 21, 2019 at 1:57 pm

Great video! I made an A* based snake AI: https://editor.p5js.org/WilliamP5/full/MJ4bcGoKr 🙂

Un BelExité :-D · July 28, 2019 at 6:04 am

Man, is a switch that terrible ?? C'on !
That's the last time I show you, you brat !
switch(key){
case LEFT_ARROW:
blablabla….
break;
case RIGHT_ARROW:
blablabla….
break;
case UP_ARROW:
blablabla….
break;
case DOWN_ARROW:
blablabla….
break;
default:
}

Brandy Anderson · July 30, 2019 at 1:40 pm

Just started coding and found your vids! Can you tell me what the cloudflare.com in the HTML are for? I tried it without them and it wouldn't work, so what vital function do they server how would I make this without sourcing Cloudflare?

Scud McFox · October 2, 2019 at 11:27 am

try to play it blindfolded 😉

Arniox · October 17, 2019 at 4:00 am

Your coding practises are so bloody bad

Harald Ankarcrona · October 24, 2019 at 2:29 pm

i live the channel but i really don like how this tutorial is basically useless outside of p5

TC TrainConstruct · October 27, 2019 at 11:55 am

I created Snake in Processing (the external joystick feature only works w/ my joystick)
https://pastebin.com/d7CJ0KH4

Elay Maharramli · October 31, 2019 at 7:00 pm

i dont know javascript language 🙁 but I know python language 🙂

phuong ly · November 1, 2019 at 11:47 am

hey guys, this is mine code for the Snake game : https://editor.p5js.org/thien/full/AiI8LqpG-

Digital Jihad911 · November 6, 2019 at 12:47 am

"aw i forgot how to do this already" 8:04 i died

Just Smile · November 28, 2019 at 2:45 pm

I’ve currently been learning JS!

Hamza Arslan · December 8, 2019 at 9:49 pm

I love your videos !

Smalizius1 · December 12, 2019 at 6:32 pm

I dont get the black dot after tipe in fill(0); like in 7:00
Can someone help me,why nothing is happening?

Leave a Reply

Your email address will not be published. Required fields are marked *