// KeyEventWorld.java import draw.Posn; import draw.World; import draw.Color; import draw.Red; import draw.White; import draw.Green; import draw.Blue; 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 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; } } /* ; ; ; ; ;;;;;; ; ; ; ; ; ; ; ; ; ; ; ;;; ; ;; ;; ; ;; ; ;;; ;;; ; ;;;;; ; ; ; ; ;; ;; ; ;; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;; ; ; ; ;;;; ; ; ; ; ; ; ;;;;;; ;; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;; ; ; ; ; ; ;;;;;;; ; ;;;;; ; ; ; ; ;; ; ;;;; ;;; ; ; ; ; ; ; */ class Examples { Examples() {} // Tests for the Blob class: Blob b1 = new Blob(new Posn(100, 100), 50); Blob b2 = this.b1.moveBlob("left"); boolean testMoveLeft = this.b1.moveBlob("left").same(new Blob(new Posn(80, 100), 50)); boolean testMoveRight = this.b1.moveBlob("right").same(new Blob(new Posn(120, 100), 50)); boolean testMoveUp = this.b1.moveBlob("up").same(new Blob(new Posn(100, 80), 50)); boolean testMoveDown = this.b1.moveBlob("down").same(new Blob(new Posn(100, 120), 50)); // construct an instance of a KeyEventWorld KeyEventWorld w = new KeyEventWorld(new Blob(new Posn(100, 200), 20)); // start the world, start the timer boolean testWorld = this.w.start(200,400) && this.w.bigBang(0.3); }