// A Pong Game. class PongGame { // The singlton static PongGame instance; // The bat field Bat bat; // The ball field Ball ball; // The current wall that the ball is bouncing from. field int wall; // True when the game is over field boolean exit; // The current score. field int score; // The last wall that the ball bounced from. field int lastWall; // The current width of the bat field int batWidth; // Constructs a new Pong Game. constructor PongGame new() { do Screen.clearScreen(); let batWidth = 50; let bat = Bat.new(230, 229, batWidth, 7); let ball = Ball.new(253, 222, 0, 511, 0, 229); do ball.setDestination(400,0); do Screen.drawRectangle(0, 238, 511, 240); do Output.moveCursor(22,0); do Output.printString("SCORE: 0"); return this; } // Deallocates the object's memory. method void dispose() { do bat.dispose(); do Memory.deAlloc(this); return; } // Returns the single instance function PongGame getInstance() { if (instance = null) { let instance = PongGame.new(); } return instance; } // Starts the game. Handles inputs from the user that controls // the bat's movement direction. method void run() { var char key; while (~exit) { // waits for a key to be pressed. while ((key = 0) & (~exit)) { let key = Keyboard.keyPressed(); do bat.move(); do moveBall(); } if (key = 130) { do bat.setDirection(1); } else { if (key = 132) { do bat.setDirection(2); } else { if (key = 140) { let exit = true; } } } // waits for the key to be released. while ((~(key = 0)) & (~exit)) { let key = Keyboard.keyPressed(); do bat.move(); do moveBall(); } } if (exit) { do Output.moveCursor(10,27); do Output.printString("GAME OVER"); } return; } method void moveBall() { var int bouncingDirection, batLeft, batRight, ballLeft, ballRight; let wall = ball.move(); if ((wall > 0) & (~(wall = lastWall))) { let lastWall = wall; let bouncingDirection = 0; let batLeft = bat.getLeft(); let batRight = bat.getRight(); let ballLeft = ball.getLeft(); let ballRight = ball.getRight(); if (wall = 4) { let exit = (batLeft > ballRight) | (batRight < ballLeft); if (~exit) { if (ballRight < (batLeft + 10)) { let bouncingDirection = -1; } else { if (ballLeft > (batRight - 10)) { let bouncingDirection = 1; } } let batWidth = batWidth - 2; do bat.setWidth(batWidth); let score = score + 1; do Output.moveCursor(22,7); do Output.printInt(score); } } do ball.bounce(bouncingDirection); } return; } }