Ucigame - Gallery - PongWithScenes

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

Your browser cannot show Java applets. PongWithScenes works just like the Ucigame version of Pong, except that it also has an instructions screen shown initially. Press any keyboard key to proceed to the Pong game, which is a simple version of the traditional video game. There is only one paddle, and no scoring.

PongWithScenes.java
// This version of Pong is implemented with two scenes:
// "Instructions" and "PlayGame"
import ucigame.*;

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

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

        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);

        startScene("Instructions");
    }

    public void startInstructions()
    {
        canvas.background(0, 0, 255);
        String[] fontlist = arrayOfAvailableFonts();
        println("fontlist[3]: " + fontlist[3]);   // arbitrarily choose fourth font
        canvas.font(fontlist[3], BOLD, 16);
    }

    public void drawInstructions()
    {
        canvas.clear();
        canvas.putText("Avoid missing ball for high score", 5, 100);
    }

    // Press any key to start game.
    public void onKeyPressInstructions()
    {
        startScene("PlayGame");
    }

    public void startPlayGame()
    {
        Image bkg = getImage("images/background.png");
        canvas.background(bkg);
    }

    public void drawPlayGame()
    {
        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 onKeyPressPlayGame()
    {
        // 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);
    }
}