Code

float px = width/2;
float py = height/2;
float vx = 0;
float vy = 0;

void setup (){
  size (300, 300);
  reset ();
}

void draw (){
  background (0);
  px = px + vx;
  py = py + vy;
  ellipse (px, py, 20, 20);
  
}

void mousePressed (){
  reset ();
}

void reset () {
  px = width/2;
  py = height/2;
  vx = random (-4, 4);
  vy = random (-4, 4);
}

0402 - Pong I: Towards a simple game

Statement:Over the next several exercises we will gradually construct a one-player version of Pong, a classic arcade game first released in November 1972. The placebo student will have working examples from which you can study the intended behavior.

In a 300x300 pixel canvas, create a program which uses two global float variables, px and py, to represent the position of a small puck on the screen. Create another two global variables, vx and vy, to represent the velocity of this puck. You will now have four variables representing the state of the puck.

Create a method called reset() which restores the position variables to the center of the screen, and which assigns the velocity variables to pair of small random numbers between -4 and 4. Call the reset() function when the program first starts, and whenever the user clicks the mouse.

On each frame of animation (i.e. on each repeat of the draw() loop), clobber the position variables by adding in the velocity. In other words, you will reassigning each position variable to be the sum of whatever it just was, plus its corresponding velocity variable: px = px + vx.

Draw the puck by rendering a small circle at location (px,py). You will notice that it travels off the canvas and doesn't return; we'll fix that in the next exercise.

hide statement