Code
float px;
float py;
float vx;
float vy;
float mx0;
float mx1;
float my0;
float my1;
int nLives;
void setup(){
size(300,300);
nLives = 5;
reset();
}
void draw(){
if (nLives > 0){
background(0,0,48);
updatePuckMovement();
drawLives();
drawPuck();
} else {
background(255,0,0);
}
updatePaddle();
}
void updatePaddle(){
mx0 = 10;
mx1 = 20;
float my = max(25, min(height-25, mouseY));
my0 = my - 25;
my1 = my + 25;
fill(255,255,255, 127);
rect(mx0,my0, mx1-mx0,my1-my0);
}
void drawPuck(){
fill(255);
stroke(255);
ellipse (px,py,10,10);
}
void drawLives(){
fill(255,255,255,64);
stroke(255,255,255,64);
for (int i=0; i<nLives; i++){
ellipse (10 + i*10,10,7,7);
}
}
void updatePuckMovement(){
px += vx;
py += vy;
if (px >= width){
vx = -vx;
}
if ((py >= height) || (py <= 0)){
vy = -vy;
}
// reflect if puck hits paddle
if ((px >= mx0) && (px <= mx1) &&
(py >= my0) && (py <= my1)){
vx = -vx;
}
// update life count
if (px < 0){
nLives--;
reset();
}
}
void mousePressed(){
reset();
}
void reset(){
px = width/2;
py = height/2;
/*
// a simple way to generate a random velocity is as follows:
vx = random(-4,4);
vy = random(-4,4);
*/
// This way of generating a random velocity is more sophisticated.
// It guarantees a known speed, while choosing a random orientation.
float angle = random(0, TWO_PI);
float speed = 4.0;
vx = speed * cos(angle);
vy = speed * sin(angle);
}
0405 - Pong IV: Towards a simple game
Statement:
hide statement