Programming with Passion

Make the best out of everything.

Wednesday 27 November 2019

Snake Game using javascript (P5.js)

Snake Game using javascript (P5.js)



Follow me at Instagram here.
Subscribe to my youtube channel here.

Just learnt something new called P5.js and tried this classic snake game, back in the days I tried it in C++ also, click here to check that one out.

With P5 it looks better. For any suggestion comment below.




Snake Game Code below you can try it out in the online p5 editor.


function setup() {
  createCanvas(600, 400);
  stroke(100);
  s = new Snake();
  s.foodCrd();
  
}

function draw() {
  background(0);
  fill(0);
  rect(0,0,400,400);
  fill(255);
  textSize(20);
  text("P5 Snake", 420, 30);
  textSize(15);
  text("Use arrows to control", 420, 50);
  
  text("Score - ", 420, 70);
  text((s.length)*4, 490, 70);
  s.draw();
  s.dead();
  s.check();
  s.move();
  s.food();
  
  frameRate(10);
  
  
}

function Snake(){
 this.x = 200;
  this.y = 200;
  this.tailx = [];
  this.taily = [];
  this.length = 0;
  this.xspeed = 1;
  this.yspeed = 0;
  this.move = function(){
    
    for(i = this.length-1; i > 0; i--)
    {
       this.tailx[i] = this.tailx[i-1];  
       this.taily[i] = this.taily[i-1];   
    }
    this.tailx[0] = this.x;
    this.taily[0] = this.y;
    
      this.x += this.xspeed*10;
      this.y += this.yspeed*10;
      if(this.x > 390)
        this.x = 0;
      else if(this.x < 0)
        this.x = 390;
      if(this.y < 0)
        this.y = 390;
      else if(this.y > 390)
        this.y = 0;
    
  }
  
  
  this.draw = function(){
    rect(this.x,this.y,12,12);
    
    for(i=0; i < this.length; i++)
      rect(this.tailx[i], this.taily[i], 12, 12);
    
    
  }
  
  this.change = function(x,y){
    this.xspeed = x;
    this.yspeed = y;
  }
  
  this.food = function(){
    fill(150,0,0);
    rect(this.r,this.p,12,12);
    fill(255);
  }
  
  this.foodCrd = function(){
    this.r = int(random(0,400)/10)*10;
    this.p = int(random(0,400)/10)*10; 
    
  }
  
  this.check = function(){
     if(this.x == this.r && this.y == this.p)
     {
       this.foodCrd(); 
       this.length+=1;
     }
       
  }
  
  this.dead = function(){
     for(i=0; i<this.length; i++)
       if(this.x == this.tailx[i] && this.y == this.taily[i])
       {
          this.length = 0;
           this.tailx = [];
         this.taily = [];
           
       }
  }
}

function keyPressed(){
   
    if(keyCode === UP_ARROW)
      s.change(0,-1);
    else if(keyCode === DOWN_ARROW)
      s.change(0,1);
    else if(keyCode === LEFT_ARROW)
      s.change(-1,0);
    else if(keyCode === RIGHT_ARROW)
      s.change(1,0); 
  }


I hope you like it. 
Follow me at Instagram here.
Subscribe to my youtube channel here.

No comments:

Post a Comment