Friday, August 14, 2020

Ping Pong game

Ping Pong Game 







Codes:

//create the ball, playerPaddle and computerPaddle as sprite objects


var ball = createSprite(200,200);

ball.setAnimation("ball");
ball.scale = 0.060;


var playerPaddle = createSprite(370,200);
playerPaddle.setAnimation("player_paddle");
playerPaddle.scale = 0.3;


var computerPaddle = createSprite(30,200 );
computerPaddle.setAnimation("comp_paddle");
computerPaddle.scale = 0.3;



//Scores       r


var ps = 0;

var cs = 0;



//Game State


var gameState = "start";
 


function draw() {
  

//color the screen
 background 

background("yellow");
  
  
if(gameState=="play"){  

//make the player paddle move with the mouse's y position
  

playerPaddle.y = World.mouseY;
  
  

//AI for the computer paddle
 

computerPaddle.y = ball.y;

}
 
//Displaying Scores 
 
  
textSize(30);
  
fill("black")
  
text(ps,210,25);

text(cs,175,25)
  
  

//drawing line at the centre
  

for (var i = 0; i < 400; i=i+20) {
   
line(200,i,200,i+10);
  }
  
textSize(14);
 

if(gameState == "start"){
 
text( " Press space to serve ", 150,180);

  }
  
 

//create edge boundaries
 

createEdgeSprites();


//make the ball bounce with the top and the bottom edges
    

ball.bounceOff(topEdge);
 
ball.bounceOff(bottomEdge);


if(ball.isTouching(playerPaddle)||ball.isTouching(computerPaddle)){
  
ball.bounceOff(playerPaddle);
ball.bounceOff(computerPaddle)
playSound("sound://category_bell/vibrant_game_bell_twinkle_positive_touch_1.mp3");

}

  

//serve the ball when space is pressed
  

if (keyDown("space") && gameState == "start") {
    
serve();

playSound("sound://category_bell/vibrant_game_bell_twinkle_positive_touch_1.mp3");
    
gameState ="play";
  
}
  
 
  

//reset the ball to the centre if it crosses the screen
  

if(ball.x > 400 || ball.x <0) {
   

if(ball.x > 400){
   

cs = cs+1

playSound("sound://category_digital/fail.mp3")
   
}
   

   
if(ball.x<0){
  
   
ps = ps+1;
   

}
   

reset();
  

}
  
  

//GameOver
  

if((cs == 5)||(ps==5)){
  
 
 
textSize(20)
    
text("GameOver",150,150)
    
    
textSize(14)
    
text("Press R to restart",210,210);



gameState = "over";
  

}

if((cs==4||ps==4)&&((ball.x>395)||(ball.x<5))){
  
  playSound("sound://category_female_voiceover/game_over_female.mp3");
}
  

//Reset
  

if(keyDown("R")&&(gameState=="over")){
   
 
gameState = "start";
    
cs = 0;
    
ps = 0;
  

}
  
  

drawSprites();


}



//Serving the Ball


function serve() {
  
ball.velocityX = 6;
  
ball.velocityY = 8;

}



//Reset the Game


function reset() {
  
ball.x = 200;
  
ball.y = 200;
  
ball.velocityX = 0;
  
ball.velocityY = 0;
  
gameState = "start"
}


Watch Video:

Part I


Part II


Part III


Part IV






 

Previous Post
First

post written by:

0 Comments: