Ucigame - Gallery - Pong

Home | Getting Started | Reference | Introduction to Java | Gallery

Your browser cannot show Java applets. Pong is a simple version of the traditional video game. There is only one paddle, and no scoring.

Pong.java
import ucigame.*;

public class Pong extends Ucigame
{
    Sprite ball;
    Sprite paddle;

    public void setup()
    {
        window.size(250, 250);
        window.title("Pong");
        framerate(30);

        Image bkg = getImage("images/background.png");
        canvas.background(bkg);

        ball = makeSprite(getImage("images/ball.gif", 255, 255, 255));
        paddle = makeSprite(getImage("images/paddle.png"));

        ball.position(canvas.width()/2 - ball.width()/2,
                      canvas.height()/2 - ball.height()/2);
        ball.motion(6, 3);
        paddle.position(canvas.width() - paddle.width() - 10,
                       (canvas.height() - paddle.height()) / 2);
    }

    public void draw()
    {
        canvas.clear();

        ball.move();
        ball.bounceIfCollidesWith(paddle);
        ball.bounceIfCollidesWith(TOPEDGE, BOTTOMEDGE, LEFTEDGE, RIGHTEDGE);
        paddle.stopIfCollidesWith(TOPEDGE, BOTTOMEDGE, LEFTEDGE, RIGHTEDGE);

        paddle.draw();
        ball.draw();
    }

    public void onKeyPress()
    {
        // Arrow keys and WASD keys move the paddle
        if (keyboard.isDown(keyboard.UP, keyboard.W))
            paddle.nextY(paddle.y() - 2);
        if (keyboard.isDown(keyboard.DOWN, keyboard.S))
            paddle.nextY(paddle.y() + 2);
        if (keyboard.isDown(keyboard.LEFT, keyboard.A))
            paddle.nextX(paddle.x() - 2);
        if (keyboard.isDown(keyboard.RIGHT, keyboard.D))
            paddle.nextX(paddle.x() + 2);
    }
}