import uwcse.graphics.*; import java.awt.Color; import java.util.*; import java.awt.Point; import javax.swing.JOptionPane; /** * A CaterpillarDisplay displays a Caterpillar that moves constantly * in a graphics window. The user can change the direction of motion * of the caterpillar via the keyboard
* 'i' is north
* 'j' is west
* 'k' is east
* 'm' is south
*/ public class CaterpillarDisplay extends GWindowEventAdapter implements CaterpillarConstants { // Game window private GWindow window; // The caterpillar private Caterpillar cp; // Direction of motion given by the player private int dirFromKeyboard; // Do we have a keyboard event private boolean isKeyboardEventNew = false; /** * Construct a CaterpillarDisplay */ public CaterpillarDisplay() { // Graphics window window = new GWindow("Caterpillar game",WINDOW_WIDTH,WINDOW_HEIGHT); window.setExitOnClose(); // Send all events to this CaterpillarDisplay window.addEventHandler(this); // Initialize the display initializeGame(); } /** * Initialize the display */ private void initializeGame() { // No keyboard event yet isKeyboardEventNew = false; // Background Rectangle background = new Rectangle(0,0,window.getWindowWidth(),window.getWindowHeight(), Color.green,true); window.add(background); // Create the caterpillar cp = new Caterpillar(window); // start timer events window.startTimerEvents(ANIMATION_PERIOD); } /** * Move the caterpillar within the graphics window every time the timer * fires an event */ public void timerExpired(GWindowEvent we) { // Did we get a new direction from the user? if (isKeyboardEventNew) { isKeyboardEventNew = false; cp.move(dirFromKeyboard); } else cp.move(); } /** * Move the caterpillar according to the selection of the user * i: NORTH, j: WEST, k: EAST, m: SOUTH */ public void keyPressed(GWindowEvent e) { switch(Character.toLowerCase(e.getKey())) { case 'i': dirFromKeyboard = NORTH; break; case 'j': dirFromKeyboard = WEST; break; case 'k': dirFromKeyboard = EAST; break; case 'm': dirFromKeyboard = SOUTH; break; default: return; } // new keyboard event isKeyboardEventNew = true; } /** * If you are not using BlueJ */ public static void main(String[] args) { CaterpillarDisplay g = new CaterpillarDisplay(); } }