Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Liz Rossman
- //Ma
- //Code
- ///Code Sketch 9: Fix Pong!
- //Pong is broken :( we must fix him/her/they!
- Ball ball;
- Paddle p1;
- Paddle p2;
- int p1Score = 0;
- int p2Score = 0;
- void setup() {
- size(1000, 700);
- background(255);
- noStroke();
- ball = new Ball();
- p1 = new Paddle(1);
- p2 = new Paddle(2);
- fill(255);
- rectMode(CENTER);
- textSize(80);
- }
- void draw() {
- background(5);
- p1.update();
- p1.display();
- p2.update();
- p2.display();
- ball.update();
- ball.display();
- text(p1Score, width/2-120, 100);
- text(p2Score, width/2+50, 100);
- rect(width/2, height/2, 20, height);
- }
- class Paddle {
- int player;
- int pWidth = 20;
- int pHeight = 100;
- float x;
- float y;
- Paddle(int pNum) {
- player = pNum; //setting the which player value from the constructor value
- if (player == 1) {
- x = 30; //set player 1 to left side of the screen
- } else if (player == 2) {
- x = width-30; //set player 2 to right side of the screen
- }
- y = height/2;
- }
- ///PADDLE CONTROL
- void update() {
- if (player == 1) {
- if (keyPressed) {
- if (key == CODED) {
- if (keyCode == UP && y > 60) {
- y-=10;
- } else if (keyCode == DOWN && y < 640) {
- y+=10;
- }
- }
- }
- } else if (player == 2) {
- if (keyPressed) {
- if (key == CODED) {
- if (keyCode == UP && y > 60) {
- y-=10;
- } else if (keyCode == DOWN && y < 640) {
- y+=10;
- }
- }
- }
- }
- if (ball.posX > x - pWidth/2 && ball.posX < x + pWidth/2) {
- if (ball.posY > y - pHeight/2 && ball.posY < y + pHeight/2) {
- ball.contact();
- }
- }
- }
- void display() {
- rect(x, y, pWidth, pHeight);
- }
- }
- class Ball {
- float posX;
- float posY;
- float velX;
- float velY;
- float size;
- Ball() {
- posX = width/2;
- posY = height/2;
- if (int(random(2)) == 0) {
- velX = 4;
- } else {
- velX = -4;
- }
- velY = random(-4, 4);
- }
- void update() {
- ///INCREASES PLAYER SCORES
- if (posX < 0) { //if the ball goes off the left side of the screen
- p2Score++; //increase player 1 score
- posX = width/2;
- posY = height/2;
- velX = -9;
- velY = random(-5, 5);
- fill(255, 0, 0); //MODIFICATION: if player wins background color changes
- } else if (posX > width) {
- p1Score++; //increase player 2 score
- posX = width/2;
- posY = height/2;
- velX = 9;
- velY = random(-5, 5);
- fill(0, 0, 255);
- }
- ///BALL BOUNCE
- if (posY > height - size/2) { //bounce off the bottom
- posY = height - size/2;
- velY = -velY;
- } else if (posY < 0 + size/2) { //bounce off the top
- posY = 0 + size/2;
- velY = -velY;
- }
- posX += velX;
- posY += velY;
- }
- void display() {
- ellipse(posX, posY, 30, 30);
- }
- void contact() { //call this function when the ball contacts the paddle
- posX = posX - velX; //step the ball back one frame
- velX = -velX;
- velY = random(-5, 5);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement