ICM Assignment 2
classical snake game
This week’s ICM we learn rule-based animations. I really think p5 is great for creating games. Last week I created a click game. It is sort of animated so I want to create a game most people played — snake game.
snake.js
I realized that I can not code this game in one file. Creating a separate class snake that controls the action of the snake is very helpful. The snake class first needs a constructor to initialize a snake when called. Then each time player pressed the keyboard I need to update() and show() the snake. When a snake consumes food, it will eat() and expand(). Setters for set horizontal speed and set vertical speed. However, I realized that changing speed on only one direction will have a bug since the snake will always move in one direction. I will change it to move on an (x,y) coordinate instead.
setMoveDir(x,y){this.xSpeed = x;this.ySpeed = y;}
Now my snake can move across the screen by pressing the keyboard’s arrow key. I used p5 build in functionkeyPressed() to achieve it.
I will randomly generate a square on my canvas. Whenever the snake’s head hits the food, I will regenerate the food. I use dist() function to check if the snake’s head hits the food.
let distance = dist(this.body[0].x,this.body[0].y,food.x,food.y);
Sketch.js
In this file, I only need to call functions in the snake and check if the game ends. I had some problem display game end text on canvas but I don’t know what I did wrong I see nothing. Instead, I show the text in the console. Just learn some simple logic and loop I am able to code a snake game. It’s very fun.
Things to Improve
- make the end game text working
- Somehow I have to start the snake at 0,0 other positions will not show the snake.
- add high score feature and display scores
- when a snake moved to the edge it will not end game instead it appears on the other end.
- The restart button when the game ends
- improve the snake’s looking and food looking
Reference
Special Thanks to Daniel Shiffman for his snake game video link.