Snake Game with p5js
August 03, 2020
Snake Game with p5js
6th week of blogging
Hai,Everyone 👋 ,
I have done Snake game as my 1st python microproject during the 1st semester of college, so I challenged myself how much did you grow after 3 years, by making the same game in p5js and Angular.
So I thought how about some OOP in case of the snake.
class Snake{
x: number = 0;
y: number = 0;
xspeed: number = 1;
yspeed: number = 0;
pix: number;
s: any;
size: number;
total: number = 0;
tail: number[] = [];
constructor(pix: number,size: number){
this.pix = pix;
this.size = size;
}
update = (currPos) => {
if(this.total === this.tail.length){
for(let i=0; i < this.total-1;i++){
this.tail[i] = this.tail[i+1];
}
}
this.tail[this.total - 1] = currPos;
this.x = this.x + this.xspeed * this.pix;
this.y = this.y + this.yspeed * this.pix;
}
constrain = (x,y) => {
this.x = x;
this.y = y;
}
dir = (x,y) => {
this.xspeed = x;
this.yspeed = y;
}
eat = (d) => {
if(d < 1){
this.total+=1;
return true;
}else{
return false;
}
}
death = () => {
this.total =0;
this.tail = [];
}
}
export { Snake };
First, start by dividing the Canvas into rows and columns, I called this Pix, it will act as the size of the snake too.
so the size and pix are initialized,
the snake has different functions:
Update
This function takes care of the snake position, in the canvas. It stores the tail of the snake in an array, and whenever a snake eats a fruit it updates array with currentPos of snake and shifts all positions to the right so the snake is shown as moving.
Constrains
It constrains the snakes x,y so that I won’t go out of the canvas.
Direction
This specifies the direction in which the snake moves, it’s done by setting the xspeed and yspeed.
Eat
To know that snake has eaten the fruit, which can be calculated by finding distance between snakehead the fruit.
Death
Which is triggered when a snake dies and takes care of the reinitialization of the snake for the new game.
then we export the snake to use in Componets.ts in Angular, We import as import { Snake } from “./snake”;
When the game starts a new snake is initialized and a new location for the fruit is picked by a random function.
Draw function draws the snake at every instant. when Keys are pressed the snake directions are changed by setting the xspeed and yspeed
constructor() {
this.getScreenSize();
}
@HostListener('window:resize', ['$event'])
getScreenSize(event?) {
this.screenHeight = window.innerHeight;
this.screenWidth = window.innerWidth;
console.log(this.screenHeight, this.screenWidth);
}
getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
scoreUpdate(score){
this.score = score;
console.log(this.score);
}
gameOver(game_over){
this.game_over = game_over;
if(this.game_over){
setTimeout(() => {
console.log("restart");
this.game_over = false;
}, 1000);
}
console.log(this.game_over);
}
ngOnInit() {
const sketch = (s) => {
let size = 500;
let pix = 20;
let col,row;
let snake;
let x,y;
let food;
s.preload = () => {
}
s.setup = () => {
s.createCanvas(size, size).parent('sketch-holder');
s.frameRate(10);
col = Math.floor(size / pix);
row = Math.floor(size / pix);
console.log(col,row);
snake = new Snake(pix,size);
pickLoc();
}
const pickLoc = () => {
food = s.createVector(this.getRandomInt(row),this.getRandomInt(col));
food.mult(pix);
}
const death = () => {
for(let i=0;i < snake.tail.length;i++){
let pos = snake.tail[i];
let d = s.dist(snake.x,snake.y,pos.x,pos.y);
if(d < 1){
console.log("death");
snake.death();
this.gameOver(true);
}
}
}
s.draw = () =>{
this.scoreUpdate(snake.tail.length);
s.background(51);
death();
if(!this.game_over){
snake.update(s.createVector(snake.x,snake.y));
x = s.constrain(snake.x, 0, size - pix);
y = s.constrain(snake.y, 0, size - pix);
snake.constrain(x,y);
s.fill(255);
for(let i=0;i < snake.total;i++){
s.rect(snake.tail[i].x,snake.tail[i].y,pix,pix);
}
s.rect(snake.x,snake.y,pix,pix);
let d = s.dist(snake.x,snake.y,food.x,food.y);
if(snake.eat(d)){
pickLoc();
}
s.fill(255,0,100);
s.noStroke()
s.rect(food.x,food.y,pix,pix);
}
}
s.keyPressed = () =>{
if(s.keyCode === s.UP_ARROW){
snake.dir(0,-1);
} else if(s.keyCode === s.DOWN_ARROW){
snake.dir(0,1);
}else if(s.keyCode === s.RIGHT_ARROW){
snake.dir(1,0);
}else if(s.keyCode === s.LEFT_ARROW){
snake.dir(-1,0);
}
}
}
this.canvas = new p5(sketch);
}
But the results were that I was Equally disappointed. Snake Game