Coding a Game with OOP

I decided to create a (really) simple game using what we learned in Object Oriented Programing. This game’s logic basically entails using the space bar to move the ellipse in order to avoid the barriers or the lines. Yes, I made a very rudimentary version of Flappy Bird. It was… an experience. I learned how to create new objects using the function “new”,  calling functions from classes, and my favorite part – checking for collisions.

Prepare to be amazed:

Code:

int state = 0; 
int score=0;
bird b = new bird();
pillar[] p = new pillar[3];


void setup(){
 size(500,700);
 int i; 
 for (i = 0; i < 3; i++){
   p[i]=new pillar(i);
 };
}

void draw(){
  background(0);
  if (state==0){
    // intro state
    text("Click to Play",155,240);
    b.move(p);
  }
  
  else if (state==1){
    // start state 
    b.move(p);
    b.drag();
    b.checkCollisions();
    rect(20,20,100,50);
    fill(255);
    text(score,30,58);
  }
  
  else {
    // end state 
    rect(150,100,200,50);
    rect(150,200,200,50);
    fill(255);
    text("game over",170,140);
    text("score",180,240);
    text(score,280,240);
  }
  
  b.drawBird();
  
  for(int i = 0;i<3;i++){
    p[i].drawPillar();
    p[i].checkPosition();
  }
  
  stroke(255);
  textSize(32);
}
void mousePressed(){
  state = 1;
}

void keyPressed(){
  b.jump();
}

Class:

class bird {
  float xPos, yPos, ySpeed;
  bird(){
    xPos = 250;
    yPos = 400;
  }
  
  void drawBird(){
    stroke(255);
    noFill();
    strokeWeight(2);
    ellipse(xPos, yPos, 20, 20);
  }
  
  void jump(){
    ySpeed=-10;
  }
  
  void drag(){
    ySpeed+=0.5;
  }
  
  void move(pillar[] pillarArray){
    yPos+=ySpeed;
    for (int i = 0; i < 3; i++){
      pillarArray[i].xPos-=3; 
    }
  }
  
  void checkCollisions(){
    if(yPos>800){
      state = 2;
    }
    
    for (int i = 0; i < 3; i++){
      if((xPos< p[i].xPos+10&&xPos>p[i].xPos-10)&&(yPos<p[i].opening-100||yPos>p[i].opening+100)){
        state = 2;
      }
    }
  }
}
    

class pillar {
  float xPos, opening;
  boolean cashed = false;
  pillar(int i){
    xPos = 100+(i*200);
    opening = random(600)+100;
  }
  void drawPillar(){
    line(xPos,0,xPos,opening-100); 
    line(xPos,opening+100,xPos,800);
  }
  void checkPosition(){
    if(xPos<0){
      xPos+=(200*3);
      opening = random(600)+100;
      cashed=false;
    } 
    if(xPos<250&&cashed==false){
      cashed=true;
      score++;
    }
  }
  void reset(){
    state = 0;
    score=0;
    b.yPos=400;
    for(int i = 0;i<3;i++){
      p[i].xPos+=550;
      p[i].cashed = false;
    }
  }
}

 

 

 

Leave a Reply