import java.util.Random; import edu.neu.world.*; /** * A class to represent a dice player in a universe * After being connected, on receiving message "roll" * the user hits a space bar to roll again. * * @author Viera K. Proulx * @since 9 April 2010 */ @WorldSettings(height=200,width=100,tick=5,title="MyWorld") public class Dice extends edu.neu.universe.World{ /** silly toggle to flip color on every tick */ boolean even = true; /** are we ready to roll again? */ boolean ready = false; /** the current roll of the die to display and send to universe */ int current = 0; /** * The required public default constructor */ public Dice(){} /** * Connect to the server when the world starts */ public void onInit(){ this.connect("192.168.1.2", 7070, "Dice client"); } /** * On connection tell the universe you are ready to play */ public void onConnect(){ sendMessage(randomRoll()); } /** * Print a message indicating we have been disconnected */ public void onDisconnect(){ System.out.println("We have been disconnected."); } /** * Allow the user to roll again * when told to do so * Disconnect if told to stop * Ignore any other messages * @param s the message received */ public void onReceive(String s){ if (s.equals("roll")){ this.ready = true; } else if(s.equals("deuce")){ this.current = 1000; } else if (s.equals("stop")){ disconnect(); } } /** * Hit the space bar to roll again * and disable roll until the next message comes * from the universe */ public void onKeyEvent(IWorld.Key ke, int mode){ if (ke.equals(IWorld.Key.SPACE) && this.ready && mode == KEY_PRESSED){ this.current = randomRoll(); sendMessage("" + this.current); this.ready = false; } } /** * Change the color of the dot on each tick */ public void onTick(){ this.even = !this.even; } /** * Fill a red rectangle 50 by 100 in the top left corner * on the world canvas, * Display the last number rolled, (or 1000 if deuce) * Show a flashing dot - changing the color on each tick * @param c the world canvas */ public void onDraw(edu.neu.world.desktop.Canvas c){ c.fillRect(0, 0, 50, 100, edu.neu.world.Color.RED); c.drawString("" + this.current, 20, 20, 12); if (this.even) c.fillCircle(25, 50, 5, edu.neu.world.Color.BLUE); else c.fillCircle(25, 50, 5, edu.neu.world.Color.YELLOW); } /** * A helper method to generate a random number * in the range 0 to n */ int randomRoll(){ return new Random().nextInt(6) + 1; } }