// KeyEventWorld.java import java.util.Random; // ------------------------------------------------------------------------------ // represent the world of a Blob class KeyEventWorld extends World { Blob blob; KeyEventWorld(Blob blob) { this.blob = blob; } // what happens when the player presses a key World onKeyEvent(String ke) { // return the new world with the moved blob return new KeyEventWorld(this.blob.moveBlob(ke)); } // draw this world public boolean draw() { return this.blob.draw(this); } } /* ; ; ; ; ;;;;; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;;; ; ;; ; ;;;; ; ; ; ;; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;; ; ; ;;;;; ; ;;; ; ;; ; ; ; */ // to represent a blob on the canvas class Blob { Posn center; int radius; Blob(Posn center, int radius) { this.center = center; this.radius = radius; } // draw this blob in the given World boolean draw(World w) { return w.drawDisk(this.center, this.radius, new Red()); } // move this blob 20 pixels in the direction given by the ke Blob moveBlob(String ke){ if (ke.equals("right")) return new Blob(new Posn(this.center.x + 20, this.center.y), this.radius); else if (ke.equals("left")) return new Blob(new Posn(this.center.x - 20, this.center.y), this.radius); else if (ke.equals("up")) return new Blob(new Posn(this.center.x, this.center.y - 20), this.radius); else if (ke.equals("down")) return new Blob(new Posn(this.center.x, this.center.y + 20), this.radius); else return this; } // determine whether this blob is the same as than given blob boolean same(Blob b){ return this.center.x == b.center.x && this.center.y == b.center.y && this.radius == b.radius; } // run the tests and start the world public static void main(String[] argv){ // Tests for the Blob class: Blob b1 = new Blob(new Posn(100, 100), 50); Blob b2 = b1.moveBlob("left"); // construct an instance of a KeyEventWorld KeyEventWorld w = new KeyEventWorld(new Blob(new Posn(100, 200), 20)); System.out.println( "test moveBlob " + "\n" + (b1.moveBlob("left").same(new Blob(new Posn(80, 100), 50))) + "\n" + (b1.moveBlob("right").same(new Blob(new Posn(120, 100), 50))) + "\n" + (b1.moveBlob("up").same(new Blob(new Posn(100, 80), 50))) + "\n" + "test moveDown " + "\n" + (b1.moveBlob("down").same(new Blob(new Posn(100, 120), 50))) + "\n" ); // start the world, start the key event monitoring only boolean testWorld = w.start(200,400) && w.theWorld.bigBang(0.0, w, true, false); } }