de.uni_paderborn.robots.data
Class Arena

java.lang.Object
  |
  +--java.lang.Thread
        |
        +--de.uni_paderborn.robots.data.Arena
All Implemented Interfaces:
java.lang.Runnable

public class Arena
extends java.lang.Thread

The arena thread.


Inner Class Summary
private  class Arena.ExchangeOkThread
          This thread ask a robot if the exchange proposal is ok.
private  class Arena.ExchangeProposalThread
          This thread ask a robot for his exchange proposal.
private  class Arena.GetCommandThread
          This thread ask a robot for his next command.
private  class Arena.RobotTimer
          This class is the robot timer thread which controls the robot time.
 
Field Summary
private  ArenaFrame arenaFrame
          link to gui
private  Robot[] arenaRobotData
          contains infos for all playing robots
private  boolean debug
          true, if debugging is turned on
private  java.lang.String debugMessage
          used for messageoutput in debugmode
private  int delay
          delay in ms
private  java.lang.String disqMessage
          used for gui disqualification messages
private  java.lang.String endGameMessage
          used for gui showRanking messages
private  Robot[][] exchangePairs
          contains exchange pairs for card exchange as RobotArray with two Elements
private  boolean exitEntered
          true if a robot enters exitfield
private  Fields fields
          reference to Fields object
private  boolean gameAborted
          true, if game was aborted
private  boolean gameActive
          true, if game is active (not paused)
private  boolean gameRunning
          true, if game is running (between start/stop)
private  java.lang.String lastException
          used to remember last exception
private  int noOfExchangePairs
          number of computed exchaingePairs every round
private  int punishmentAmount
          how much energy is decreased if robot runs against an item
private  int rechargeAmount
          how much energy a well reloads per turn
private  java.util.Iterator robotFieldIterator
          iterator for robotFields
private  int robotIdCounter
          number of robots in the game
private  java.util.Iterator robotIterator
          iterator for robots
private  Robot robotOnTheRun
          actual robot
private  boolean robotReady
          true, if robot has answered
private  boolean robotThrewException
          true, if robot has thrown exception
private  boolean robotTimeElapsed
          true, if robot time is elapsed
private  boolean[] robotTypes
          registered robot types
private  boolean step
          true, if next step is to be performed
private  java.io.StringWriter stringWriter
          used for exception description
private  int turnNo
          Number of actual turn
private  Robot[] winnerList
          stores list of not disqualified robots, sorted regarding their points
 
Fields inherited from class java.lang.Thread
contextClassLoader, daemon, eetop, group, inheritableThreadLocals, inheritedAccessControlContext, MAX_PRIORITY, MIN_PRIORITY, name, NORM_PRIORITY, priority, single_step, stillborn, stopThreadPermission, target, threadInitNumber, threadLocals, threadQ
 
Constructor Summary
Arena(Fields fields)
          constructor, creates a new arena from the given Fields object.
Arena(java.io.File file)
          constructor, creates new arena by loading one arena from the specified file.
Arena(int width, int height)
          constructor, creates empty arena with specified width and height.
 
Method Summary
 void abortGame()
          Aborts the arena thread instantly!!!
 Robot addRobot(RobotFunctions toAdd, java.lang.String name)
          Adds a robot to the game.
private  int[] calculateWinner()
          Calculates the winner of the game when finished.
private  void checkWaitDebug()
          Waits if debug mode is active and step button is not pressed yet!
private  void checkWaitPause()
          Waits if pause mode is active.
private  FieldData computeFieldData(Field dummy)
          Converts group10 Field and ItemData to RobotArenaInterface datastructures.
 void continueGame()
          Continues the game.
private  Card convertCard(CardData card, Robot robot)
          Converts CardData Object into Card Object, if Robot owns Card.
private  RobotData createRobotData(Robot nextInternBot)
          Creates a new RobotData object which contains all necessary information for a robot thread to calculate the next command.
private  void exchangeManagement()
          Performs the card exchange.
private  boolean executeCommand(AbstractRobotAction action, Robot robot)
          Excecutes robot command.
private  void finalTurn()
          Runs a further turn if a robot entered the exit; necessary for the proxy object of group 14.
 int getActualTurnNo()
          returns the turn No
 ArenaFrame getArenaFrame()
          Gets ArenaCanvas for this arena.
 int getDelay()
          Returns the delay.
private  boolean getExchangeOk(Robot robot, CardData hisCard, CardData otherCard)
          This method asks the robot if he agrees to the exchange
private  CardData getExchangeProposal(Robot robot)
          This method asks the robot for his exchange proposal
 Fields getFields()
          Returns the internal Fields object (used by ArenaCanvas objects)
private  Field getFirstFreeSurroundingField(Field field)
          Checks the fields surrounding field and returns the first empty field
 int getPunishmentAmount()
          Gets the punishment amount.
 int getRechargeAmount()
          Gets the recharge amount.
private  void initGame()
          Initializes game.
private  void isaRobotActive()
          Checks if at least one robot is active (not disqualified and has energy).
 boolean isDebuggingOn()
          Returns if debug option is on or not.
 boolean isGameActive()
          Returns if game is active or not.
 boolean isGameRunning()
          Returns if game is running or not.
 void loadArena(java.io.File file)
          Loads an arena from a local file into this class.
private  void makeExchangeList()
          Computes all exchangePairs.
private  Robot[] mixRobots()
          Creates new random list of robots.
 void nextStep()
          Executes the next game step, if debugging is turned on.
 int numRobotFields()
          Returns number of robot fields in the arena.
 int numRobots()
          Returns number of robots in the arena.
private  void oneTurn()
          Performs one round of the game: All robot-threads are asked for their next command which is executed immediately if valid.
 void pauseGame()
          Pauses the game.
 boolean removeRobot(Robot toRemove, boolean replaceByRobotField)
          Removes a robot from the game.
private  void removeStartFields()
          Replaces all RobotFields with empty fields.
 void robotDisqualified()
          Signal that robot is disqualified
private  void robotHasThrownException()
          Informs arena thread that robot has thrown an exception.
private  void robotIsReady()
          Informs arena thread that robot is ready.
 void run()
          This method controls most parts of the game.
 void saveArena(java.io.File file)
          Saves an arena to a local file.
 void setArenaFrame(ArenaFrame arenaFrame)
          Sets ArenaCanvas for this arena.
 void setDebugging(boolean debug)
          Set the debug option on/off.
 void setDelay(int delay)
          Sets the delay.
private  void setLastException(java.lang.Exception e)
          This method sets the last Exception.
 void setPunishmentAmount(int punishmentAmount)
          Sets the punishment amount.
 void setRechargeAmount(int rechargeAmount)
          Sets the recharge amount.
private  void setRobotTimerIsElapsed()
          Informs arena thread that robot timer elapsed.
private  void showRanking()
          Calculates winner and calls Arenaframe method showRanking().
 void startGame()
          Starts the game.
 void stopGame()
          Stops the game.
private  CardData toCardData(Card card)
          Converts Card Object into CardData Object
private  void waitForRobot()
          Waits until robot has answered resp. robot time is elapsed.
 
Methods inherited from class java.lang.Thread
, activeCount, checkAccess, countStackFrames, currentThread, destroy, dumpStack, enumerate, exit, getContextClassLoader, getName, getPriority, getThreadGroup, init, interrupt, interrupt0, interrupted, isAlive, isDaemon, isInterrupted, isInterrupted, join, join, join, nextThreadNum, registerNatives, resume, resume0, setContextClassLoader, setDaemon, setName, setPriority, setPriority0, sleep, sleep, start, stop, stop, stop0, suspend, suspend0, toString, yield
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

fields

private Fields fields
reference to Fields object

gameRunning

private boolean gameRunning
true, if game is running (between start/stop)

gameActive

private boolean gameActive
true, if game is active (not paused)

gameAborted

private boolean gameAborted
true, if game was aborted

exitEntered

private boolean exitEntered
true if a robot enters exitfield

debug

private boolean debug
true, if debugging is turned on

step

private boolean step
true, if next step is to be performed

robotIdCounter

private int robotIdCounter
number of robots in the game

robotFieldIterator

private java.util.Iterator robotFieldIterator
iterator for robotFields

robotIterator

private java.util.Iterator robotIterator
iterator for robots

arenaFrame

private ArenaFrame arenaFrame
link to gui

delay

private int delay
delay in ms

rechargeAmount

private int rechargeAmount
how much energy a well reloads per turn

punishmentAmount

private int punishmentAmount
how much energy is decreased if robot runs against an item

turnNo

private int turnNo
Number of actual turn

noOfExchangePairs

private int noOfExchangePairs
number of computed exchaingePairs every round

robotTypes

private boolean[] robotTypes
registered robot types

arenaRobotData

private Robot[] arenaRobotData
contains infos for all playing robots

winnerList

private Robot[] winnerList
stores list of not disqualified robots, sorted regarding their points

exchangePairs

private Robot[][] exchangePairs
contains exchange pairs for card exchange as RobotArray with two Elements

robotReady

private boolean robotReady
true, if robot has answered

robotTimeElapsed

private boolean robotTimeElapsed
true, if robot time is elapsed

robotThrewException

private boolean robotThrewException
true, if robot has thrown exception

disqMessage

private java.lang.String disqMessage
used for gui disqualification messages

endGameMessage

private java.lang.String endGameMessage
used for gui showRanking messages

debugMessage

private java.lang.String debugMessage
used for messageoutput in debugmode

stringWriter

private java.io.StringWriter stringWriter
used for exception description

lastException

private java.lang.String lastException
used to remember last exception

robotOnTheRun

private Robot robotOnTheRun
actual robot
Constructor Detail

Arena

public Arena(int width,
             int height)
constructor, creates empty arena with specified width and height.
Parameters:
width - width of arena
height - height of arena

Arena

public Arena(Fields fields)
constructor, creates a new arena from the given Fields object.
Parameters:
fields - the Fields object

Arena

public Arena(java.io.File file)
      throws java.io.IOException,
             java.lang.ClassCastException,
             java.lang.ClassNotFoundException
constructor, creates new arena by loading one arena from the specified file.
Parameters:
filename - name of file containing arena template
Throws:
java.io.IOException - if file cannot be read
java.lang.ClassCastException - if class cannot be type-casted
java.lang.ClassNotFoundException - if necessary class cannot be found
Method Detail

loadArena

public void loadArena(java.io.File file)
               throws java.io.IOException,
                      java.lang.ClassCastException,
                      java.lang.ClassNotFoundException
Loads an arena from a local file into this class. This operation is undoable! If you want to ensure that to return to the old arena, use the constructor Arena(File) instead!
Parameters:
file - a local file
Throws:
java.io.IOException - if file cannot be read
java.lang.ClassCastException - if class cannot be type-casted
java.lang.ClassNotFoundException - if necessary class cannot be found

saveArena

public void saveArena(java.io.File file)
               throws java.io.IOException
Saves an arena to a local file.
Parameters:
file - a local file
Throws:
java.io.IOException - if file cannot be written

oneTurn

private void oneTurn()
Performs one round of the game: All robot-threads are asked for their next command which is executed immediately if valid.

finalTurn

private void finalTurn()
Runs a further turn if a robot entered the exit; necessary for the proxy object of group 14.

exchangeManagement

private void exchangeManagement()
Performs the card exchange.

getExchangeProposal

private CardData getExchangeProposal(Robot robot)
This method asks the robot for his exchange proposal
Parameters:
robot - the robot to ask
Returns:
the card the robot wants to change

getExchangeOk

private boolean getExchangeOk(Robot robot,
                              CardData hisCard,
                              CardData otherCard)
This method asks the robot if he agrees to the exchange
Parameters:
robot - the robot to ask
hisCard - the card he would give away
otherCard - the card he would become from the other robot
Returns:
true if robot wants to change cards

run

public void run()
This method controls most parts of the game.
Overrides:
run in class java.lang.Thread

removeStartFields

private void removeStartFields()
Replaces all RobotFields with empty fields.

checkWaitPause

private void checkWaitPause()
Waits if pause mode is active.

checkWaitDebug

private void checkWaitDebug()
Waits if debug mode is active and step button is not pressed yet!

waitForRobot

private void waitForRobot()
Waits until robot has answered resp. robot time is elapsed.

mixRobots

private Robot[] mixRobots()
Creates new random list of robots.
Returns:
array with all robots in new order

executeCommand

private boolean executeCommand(AbstractRobotAction action,
                               Robot robot)
Excecutes robot command.
Parameters:
action - a AbstractAction object returned by robot thread
robot - the current robot
Returns:
true, if command could be executed successfully, false, if not

getFirstFreeSurroundingField

private Field getFirstFreeSurroundingField(Field field)
Checks the fields surrounding field and returns the first empty field
Parameters:
field - which has to checked
Returns:
first found empty field, null if all fields are filled

convertCard

private Card convertCard(CardData card,
                         Robot robot)
Converts CardData Object into Card Object, if Robot owns Card.
Parameters:
card - CardData Object to be converted
robot - Robot whose cards have to be compared with card
Returns:
the converted Card Object

toCardData

private CardData toCardData(Card card)
Converts Card Object into CardData Object
Parameters:
card - Card Object to be converted
Returns:
the converted CardData Object

createRobotData

private RobotData createRobotData(Robot nextInternBot)
Creates a new RobotData object which contains all necessary information for a robot thread to calculate the next command.
Parameters:
nextInternBot - robot for which RobotData should be created
Returns:
RobotData DataContainer defiened in RobotArenaInterface

computeFieldData

private FieldData computeFieldData(Field dummy)
Converts group10 Field and ItemData to RobotArenaInterface datastructures.
Parameters:
dummy - field to convert, including all referented objects
Returns:
a field RobotArenaInterface compatible

makeExchangeList

private void makeExchangeList()
Computes all exchangePairs.

initGame

private void initGame()
Initializes game. Sets all robots energy to max-energy. Puts a set of 52 cards into the arena.

isaRobotActive

private void isaRobotActive()
Checks if at least one robot is active (not disqualified and has energy). Stops game if no robot is active.

showRanking

private void showRanking()
Calculates winner and calls Arenaframe method showRanking().

calculateWinner

private int[] calculateWinner()
Calculates the winner of the game when finished. Brings arenaRobotData in correct order

startGame

public void startGame()
Starts the game.

stopGame

public void stopGame()
Stops the game.

abortGame

public void abortGame()
Aborts the arena thread instantly!!!

pauseGame

public void pauseGame()
Pauses the game.

continueGame

public void continueGame()
Continues the game.

robotDisqualified

public void robotDisqualified()
Signal that robot is disqualified

removeRobot

public boolean removeRobot(Robot toRemove,
                           boolean replaceByRobotField)
Removes a robot from the game.
Parameters:
toRemove - reference to the robot, which should be removed
replaceByRobotField - true, if robot field should be placed instead, otherwise the field stays empty
Returns:
true, if robot could be removed, false if not

addRobot

public Robot addRobot(RobotFunctions toAdd,
                      java.lang.String name)
Adds a robot to the game. It is ensured that the arena has at least one empty robot field.
Parameters:
toAdd - reference to the robot which should be added
name - name of the new robot
Returns:
true, if robot could be placed, false if not

setDebugging

public void setDebugging(boolean debug)
Set the debug option on/off.
Parameters:
debug - true, if debugging should be turned on

nextStep

public void nextStep()
Executes the next game step, if debugging is turned on.

isDebuggingOn

public boolean isDebuggingOn()
Returns if debug option is on or not.
Returns:
true, if debugging is on, false, if not

isGameRunning

public boolean isGameRunning()
Returns if game is running or not.
Returns:
true, if game is running, false, if not

isGameActive

public boolean isGameActive()
Returns if game is active or not.
Returns:
true, if game is running, false, if not

numRobots

public int numRobots()
Returns number of robots in the arena.
Returns:
number of robots in the arena

numRobotFields

public int numRobotFields()
Returns number of robot fields in the arena.
Returns:
number of robot fields in the arena

getFields

public Fields getFields()
Returns the internal Fields object (used by ArenaCanvas objects)

setDelay

public void setDelay(int delay)
Sets the delay.
Parameters:
delay - new delay

getDelay

public int getDelay()
Returns the delay.
Returns:
the actual delay

setArenaFrame

public void setArenaFrame(ArenaFrame arenaFrame)
Sets ArenaCanvas for this arena.
Parameters:
ArenaCanvas - ArenaCanvas for this arena

getArenaFrame

public ArenaFrame getArenaFrame()
Gets ArenaCanvas for this arena.
Returns:
ArenaCanvas for this arena

setRechargeAmount

public void setRechargeAmount(int rechargeAmount)
Sets the recharge amount.
Parameters:
rechargeAmount - the value of one well usage

getRechargeAmount

public int getRechargeAmount()
Gets the recharge amount.
Returns:
the value of one well usage

setPunishmentAmount

public void setPunishmentAmount(int punishmentAmount)
Sets the punishment amount.
Parameters:
the - value energy is decreased by if robots runs against an item

getPunishmentAmount

public int getPunishmentAmount()
Gets the punishment amount.
Returns:
the value energy is decreased by if robots runs against an item

getActualTurnNo

public int getActualTurnNo()
returns the turn No
Returns:
the actual turn No

robotIsReady

private void robotIsReady()
Informs arena thread that robot is ready.

setRobotTimerIsElapsed

private void setRobotTimerIsElapsed()
Informs arena thread that robot timer elapsed.

robotHasThrownException

private void robotHasThrownException()
Informs arena thread that robot has thrown an exception.

setLastException

private void setLastException(java.lang.Exception e)
This method sets the last Exception.
Parameters:
e - last exception occured