21-class-examples

21-class-examples - **/ private GObject...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Landmines.java import java.awt.event.MouseEvent ; import acm.graphics.GImage ; import acm.graphics.GObject ; import acm.graphics.GOval ; import acm.program.GraphicsProgram ; public class Landmines extends GraphicsProgram { /** width of a landmine */ private static final int SIZE = 30 ; private static final int PLAYER_Y = 30 ; private static final int SPEED = 1 ; private static final int PAUSE_TIME = 10 ; /** Instance Variables */ private GImage player ; private int vx = SPEED ; private int vy = 0 ; public void run() { addPlayer() ; addMouseListeners() ; animatePlayer() ; } /** creates and adds the player's image to the screen. */ private void addPlayer() { player = new GImage( "o.jpg" , 0, PLAYER_Y ) ; add( player ) ; } /** main loop of the game. Animates the player moving across the screen, checking for collisions with landmines along the way. */ private void animatePlayer() { while ( true ) { player .move( vx , vy ) ; pause( PAUSE_TIME ) ; if (getCollidingObject() != null ) { lose() ; break ; } } } /** Checks the bottom two corners of the player. If an object exists at the bottom left corner of the player, * it returns that object. If not, it checks the bottom right corner. And if there's no object at either corner, * it will return null.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: **/ private GObject getCollidingObject() { double left = player .getX() ; double right = player .getX() + player .getWidth() ; double bottom = player .getY() + player .getHeight() + 1 ; GObject obj = getElementAt(left, bottom) ; Page 1 Landmines.java if (obj != null ) { return obj ; } obj = getElementAt(right, bottom) ; return obj ; } /** changes the image of the player to the losing image. */ private void lose() { player .setImage( "olose.jpg" ) ; } /** Called whenever the mouse moves. Adds a new landmine to the screen at the mouse's location. */ public void mouseMoved(MouseEvent e) { add( new GOval(e.getX() - SIZE /2, e.getY() - SIZE /2, SIZE , SIZE )) ; } /** Called whenever the mouse is pressed. Changes the player's direction so that he's moving downward. */ public void mousePressed(MouseEvent e) { vx = 0 ; vy = SPEED ; } } Page 2...
View Full Document

Page1 / 2

21-class-examples - **/ private GObject...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online