soc.game
Class SOCGame

java.lang.Object
  extended bysoc.game.SOCGame
All Implemented Interfaces:
java.lang.Cloneable, java.io.Serializable

public class SOCGame
extends java.lang.Object
implements java.io.Serializable, java.lang.Cloneable

A class for holding and manipulating game data. Most methods are not implicitly thread-safe; call takeMonitor() and releaseMonitor() around them.

The model in this client/server game is: The SOCGame at server contains the game's complete state information, and game logic advances there. Each client's local SOCGame contains only partial state (for instance, other players' resources or devel cards may be of unknown type); and the server directly updates clients' game state by sending messages such as SOCGameState and SOCSetPlayedDevCard.

For the board coordinate system and terms (hex, node, edge), see the SOCBoard class javadoc.

putPiece(SOCPlayingPiece) and other game-action methods update gameState.

Author:
Robert S. Thomas
See Also:
Serialized Form

Field Summary
private  boolean active
          true if this game is ACTIVE
(package private)  boolean allOriginalPlayers
          used to track if there were any player subs
private  SOCBoard board
          the game board
private  int boardResetVoteRequester
          If a board reset vote is active, player number who requested the vote.
private  int[] boardResetVotes
          If a board reset vote is active, votes are recorded here.
private  int boardResetVotesWaiting
          If a board reset vote is active, we're waiting to receive this many more votes.
static SOCResourceSet CARD_SET
          the set of resources a player needs to buy a development card
static SOCResourceSet CITY_SET
          the set of resources a player needs to build a city
 int clientVersionHighest
          For use at server; lowest and highest version of connected clients.
 int clientVersionLowest
          For use at server; lowest and highest version of connected clients.
private  int currentDice
          the current dice result
private  int currentPlayerNumber
          the number of the current player
private  int[] devCardDeck
          the development card deck
static SOCResourceSet EMPTY_RESOURCES
          the set of resources a player needs to build a settlement
(package private)  long expiration
          expiration time for this game in milliseconds
private  int firstPlayerNumber
          the first player to place a settlement
private  boolean forcingEndTurn
          If true, this turn is being ended.
private  int gameState
          the current game state
 boolean hasOldClients
          For use at server; are there clients connected which aren't at the latest version?
(package private)  boolean inUse
          monitor for synchronization
private  boolean isFromBoardReset
          true if the game came from a board reset
 boolean isLocal
          true if the game's network is local for practice.
private  int lastPlayerNumber
          the last player to place the first settlement
static boolean LOCKED
          seatLock states
static int MAXPLAYERS
          maximum number of players in a game
static int MINPLAYERS
          minimum number of players in a game (was assumed ==MAXPLAYERS in standard 1.0.6).
private  java.lang.String name
          the name of the game
static int NEW
          Game states.
private  int numDevCards
          the number of development cards left
static int OCCUPIED
          seat states
private  int oldGameState
          the old game state
private  int oldPlayerWithLargestArmy
           
(package private)  java.util.Stack oldPlayerWithLongestRoad
          used to restore the LR player
static int OVER
          The game is over.
static int PLACING_CITY
           
static int PLACING_FREE_ROAD1
           
static int PLACING_FREE_ROAD2
           
static int PLACING_ROAD
           
static int PLACING_ROBBER
           
static int PLACING_SETTLEMENT
           
private  boolean placingRobberForKnightCard
          If true, and if state is PLACING_ROBBER, the robber is being moved because a knight card has just been played.
static int PLAY
          Start of a normal turn.
static int PLAY1
          Done rolling (or moving robber on 7).
private  SOCPlayer[] players
          the players; never contains a null element, use isSeatVacant(int) to see if a position is occupied.
private  int playerWithLargestArmy
          the player with the largest army, or -1 if none
private  int playerWithLongestRoad
          the player with the longest road, or -1 if none
private  int playerWithWin
          the player declared winner, if gamestate == OVER; otherwise -1
private  java.util.Random rand
          used to generate random numbers
static int READY
          Ready to start playing.
static int RESET_OLD
          This game is an obsolete old copy of a new (reset) game with the same name.
static SOCResourceSet ROAD_SET
          the set of resources a player needs to build a road
private  boolean[] seatLocks
          the states if the locks for the player's seats
private  int[] seats
          the states for the player's seats
static int SETOPTIONS_EXCL
           
static int SETOPTIONS_INCL
           
static SOCResourceSet SETTLEMENT_SET
          the set of resources a player needs to build a settlement
static int START1A
          Players place first settlement.
static int START1B
          Players place first road.
static int START2A
          Players place second settlement.
static int START2B
          Players place second road.
(package private)  java.util.Date startTime
          when this game was created
static boolean UNLOCKED
          seatLock states
static int VACANT
          seat states
static int VOTE_NO
           
static int VOTE_NONE
          boardResetVotes per-player states: no vote sent; yes; no.
static int VOTE_YES
           
static int VP_WINNER
          Number of victory points (10) needed to win.
static int WAITING_FOR_CHOICE
           
static int WAITING_FOR_DISCARDS
           
static int WAITING_FOR_DISCOVERY
           
static int WAITING_FOR_MONOPOLY
           
 
Constructor Summary
SOCGame(java.lang.String n)
          create a new game
SOCGame(java.lang.String n, boolean a)
          create a new game that can be INACTIVE
 
Method Summary
 void addPlayer(java.lang.String name, int pn)
          add a new player
protected  void advanceTurn()
          advance the turn to the next player
protected  void advanceTurnBackwards()
          advance the turn to the previous player, used during initial placement
private  void advanceTurnStateAfterPutPiece()
          After placing a piece on the board, update the state of the game, and possibly current player, for play to continue.
 boolean allOriginalPlayers()
           
 void buyCity(int pn)
          a player is buying a city
 int buyDevCard()
          the current player is buying a dev card
 void buyRoad(int pn)
          a player is buying a road
 void buySettlement(int pn)
          a player is buying a settlement
 void cancelBuildCity(int pn)
          a player is UNbuying a city; return resources, set gameState PLAY1
 void cancelBuildRoad(int pn)
          a player is UNbuying a road; return resources, set gameState PLAY1
 void cancelBuildSettlement(int pn)
          a player is UNbuying a settlement; return resources, set gameState PLAY1
 boolean canChoosePlayer(int pn)
           
 boolean canDiscard(int pn, SOCResourceSet rs)
           
 boolean canDoDiscoveryAction(SOCResourceSet pick)
           
 boolean canDoMonopolyAction()
           
 boolean canEndTurn(int pn)
          Can this player end the current turn?
 boolean canMakeBankTrade(SOCResourceSet give, SOCResourceSet get)
           
 boolean canMakeTrade(int offering, int accepting)
           
 boolean canMoveRobber(int pn, int co)
           
 boolean canPlayDiscovery(int pn)
          return true if the player can play a Discovery card
 boolean canPlayKnight(int pn)
           
 boolean canPlayMonopoly(int pn)
          return true if the player can play a Monopoly card
 boolean canPlayRoadBuilding(int pn)
          Can the current player play a Road Building card?
 boolean canRollDice(int pn)
           
 void checkForWinner()
          check current player's vp total to see if the game is over.
 boolean couldBuildCity(int pn)
           
 boolean couldBuildRoad(int pn)
           
 boolean couldBuildSettlement(int pn)
           
 boolean couldBuyDevCard(int pn)
           
 void destroyGame()
          set vars to null so gc can clean up
 void discard(int pn, SOCResourceSet rs)
          A player is discarding resources.
static void discardPickRandom(SOCResourceSet fromHand, int numDiscards, SOCResourceSet discards, java.util.Random rand)
          Choose discards at random; does not actually discard anything.
 void doDiscoveryAction(SOCResourceSet pick)
          perform the Discovery card action
 void doMonopolyAction(int pick)
          perform the Monopoly card action
 void endTurn()
          end the turn for the current player, and check for winner.
 SOCForceEndTurnResult forceEndTurn()
          In an active game, force current turn to be able to be ended.
private  SOCForceEndTurnResult forceEndTurnChkDiscards(int pn)
          Randomly discard from this player's hand, by calling discard(int, SOCResourceSet).
private  SOCForceEndTurnResult forceEndTurnStartState(boolean advTurnForward)
          Special forceEndTurn() treatment for start-game states.
 java.lang.String gameOverMessageToPlayer(SOCPlayer pl)
          If game is over, formulate a message to tell a player.
 SOCBoard getBoard()
           
 int getCurrentDice()
           
 int getCurrentPlayerNumber()
           
 long getExpiration()
           
 int getFirstPlayer()
           
 int getGameState()
          Current game state.
 java.lang.String getName()
           
 int getNumDevCards()
           
 SOCPlayer getPlayer(int pn)
           
 SOCPlayer getPlayer(java.lang.String nn)
           
 SOCPlayer[] getPlayers()
           
 java.util.Vector getPlayersOnHex(int hex)
           
 SOCPlayer getPlayerWithLargestArmy()
           
 SOCPlayer getPlayerWithLongestRoad()
           
 SOCPlayer getPlayerWithWin()
          Find the player who was declared winner at end of game.
 java.util.Vector getPossibleVictims()
           
 int getResetOldGameState()
          If the game board was reset, get the old game state.
 int getResetPlayerVote(int pn)
          Get this player's vote on a board reset request.
 boolean getResetVoteActive()
           
 int getResetVoteRequester()
          If a board reset vote is active, player number who requested the vote.
 boolean getResetVoteResult()
          If a board-reset vote is complete, give its result.
 SOCResourceSet getResourcesGainedFromRoll(SOCPlayer player, int roll)
          figure out what resources a player would get on a given roll
 java.util.Date getStartTime()
           
 boolean isBoardReset()
           
 boolean isForcingEndTurn()
          If true, this turn is being ended.
 boolean isSeatLocked(int pn)
           
 boolean isSeatVacant(int pn)
           
 void lockSeat(int pn)
          locks a seat, so no one can take it
 void makeBankTrade(SOCResourceSet give, SOCResourceSet get)
          perform a bank trade
 void makeTrade(int offering, int accepting)
          perform a trade between two players the trade performed is described in the offering player's current offer
 SOCMoveRobberResult moveRobber(int pn, int co)
          move the robber.
 void playDiscovery()
          the current player plays a Discovery card
 SOCResourceSet playerDiscardRandom(int pn)
          Force this non-current player to discard randomly.
 void playKnight()
          the current player plays a Knight card
 void playMonopoly()
          the current player plays a monopoly card
 void playRoadBuilding()
          The current player plays a Road Building card.
 void putPiece(SOCPlayingPiece pp)
          Put this piece on the board and update all related game state.
 void putTempPiece(SOCPlayingPiece pp)
          a temporary piece has been put on the board
 void releaseMonitor()
          release the monitor for this game
 void removePlayer(java.lang.String name)
          remove a player
 SOCGame resetAsCopy()
          Create a new game with same players and name, new board; like calling constructor otherwise.
 void resetVoteBegin(int reqPN)
          Begin a board-reset vote.
 void resetVoteClear()
          At end of turn, clear flags for board reset voting: requester, players' setAskedBoardReset.
 boolean resetVoteRegister(int pn, boolean votingYes)
          Register this player's vote in a board reset request.
 void restoreLargestArmyState()
          restore the state of who had largest army
 IntPair rollDice()
          roll the dice
 void saveLargestArmyState()
          save the state of who has largest army
protected  void setBoard(SOCBoard gb)
          set the game board
 void setCurrentDice(int dr)
          set the current dice result
 void setCurrentPlayerNumber(int pn)
          Set the number of the current player, and check for winner.
 void setExpiration(long ex)
          set the expiration time
 void setFirstPlayer(int pn)
          sets who the first player is
 void setGameState(int gs)
          set the current game state.
 void setNumDevCards(int nd)
          set the number of dev cards in the deck
protected  void setPlayer(int pn, SOCPlayer pl)
          set the data for a player
 void setPlayerWithLargestArmy(SOCPlayer pl)
          set the player with the largest army
 void setPlayerWithLongestRoad(SOCPlayer pl)
          set the player with the longest road
 void startGame()
          do the things involved in starting a game: shuffle the tiles and cards, make a board, choose first player.
 int stealFromPlayer(int pn)
          the current player has choosen a victim to rob.
 void takeMonitor()
          take the monitor for this game
 void undoPutInitSettlement(SOCPlayingPiece pp)
          undo the putting of an initial settlement.
protected  void undoPutPieceCommon(SOCPlayingPiece pp)
          undo the putting of a temporary or initial piece
 void undoPutTempPiece(SOCPlayingPiece pp)
          undo the putting of a temporary piece
 void unlockSeat(int pn)
          unlocks a seat
 void updateLargestArmy()
          update which player has the largest army larger than 2
 void updateLongestRoad(int pn)
          update which player has longest road longer than 4 this version only calculates the longest road for the player who is affected by the most recently placed piece
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

NEW

public static final int NEW
Game states. NEW is a brand-new game, not yet ready to start playing. Players are choosing where to sit, or have all sat but no one has yet clicked the "start game" button. Next state from NEW is READY if robots, or START1A if only humans are playing.

General assumptions for states and their numeric values:

The code reacts to (switches based on) game state in several places. The main places to check, if you add a game state:

        SOCBoardPanel.updateMode()
        SOCBuildingPanel.updateButtonStatus()
        SOCPlayerInterface.updateAtGameState()
        putPiece(SOCPlayingPiece)
        SOCRobotBrain.run()
        SOCServer.sendGameState(SOCGame)
 
Other places to check, if you add a game state:
        SOCBoardPanel.BoardPopupMenu.showBuild, showCancelBuild
        SOCBoardPanel.drawBoard
        SOCHandPanel.addPlayer, began, removePlayer, updateAtTurn, updateValue
        SOCGame.addPlayer
        SOCServer.handleSTARTGAME, leaveGame, sitDown, handleCANCELBUILDREQUEST, handlePUTPIECE
        SOCPlayerClient.handleCANCELBUILDREQUEST, SOCDisplaylessPlayerClient.handleCANCELBUILDREQUEST
 

See Also:
Constant Field Values

READY

public static final int READY
Ready to start playing. All humans have chosen a seat. Wait for requested robots to sit down. Once robots have joined the game (this happens in other threads, possibly in other processes), gameState will become START1A.

See Also:
Constant Field Values

SETOPTIONS_EXCL

public static final int SETOPTIONS_EXCL
See Also:
Constant Field Values

SETOPTIONS_INCL

public static final int SETOPTIONS_INCL
See Also:
Constant Field Values

START1A

public static final int START1A
Players place first settlement. Proceed in order for each player; next state is START1B to place each player's 1st road.

See Also:
Constant Field Values

START1B

public static final int START1B
Players place first road. Next state is START1A to place next player's 1st settlement, or if all have placed settlements, START2A to place 2nd settlement.

See Also:
Constant Field Values

START2A

public static final int START2A
Players place second settlement. Proceed in reverse order for each player; next state is START2B to place 2nd road.

See Also:
Constant Field Values

START2B

public static final int START2B
Players place second road. Next state is START2A to place previous player's 2nd settlement (player changes in reverse order), or if all have placed settlements, PLAY to begin first player's turn.

See Also:
Constant Field Values

PLAY

public static final int PLAY
Start of a normal turn. Time to roll or play a card. Next state depends on card or roll, but usually is PLAY1.

See Also:
Constant Field Values

PLAY1

public static final int PLAY1
Done rolling (or moving robber on 7). Time for other turn actions, such as building or buying or trading, or playing a card if not already done. Next state depends on what's done, but usually is the next player's PLAY.

See Also:
Constant Field Values

PLACING_ROAD

public static final int PLACING_ROAD
See Also:
Constant Field Values

PLACING_SETTLEMENT

public static final int PLACING_SETTLEMENT
See Also:
Constant Field Values

PLACING_CITY

public static final int PLACING_CITY
See Also:
Constant Field Values

PLACING_ROBBER

public static final int PLACING_ROBBER
See Also:
Constant Field Values

PLACING_FREE_ROAD1

public static final int PLACING_FREE_ROAD1
See Also:
Constant Field Values

PLACING_FREE_ROAD2

public static final int PLACING_FREE_ROAD2
See Also:
Constant Field Values

WAITING_FOR_DISCARDS

public static final int WAITING_FOR_DISCARDS
See Also:
Constant Field Values

WAITING_FOR_CHOICE

public static final int WAITING_FOR_CHOICE
See Also:
Constant Field Values

WAITING_FOR_DISCOVERY

public static final int WAITING_FOR_DISCOVERY
See Also:
Constant Field Values

WAITING_FOR_MONOPOLY

public static final int WAITING_FOR_MONOPOLY
See Also:
Constant Field Values

OVER

public static final int OVER
The game is over. A player has accumulated 10 (VP_WINNER) victory points.

See Also:
Constant Field Values

RESET_OLD

public static final int RESET_OLD
This game is an obsolete old copy of a new (reset) game with the same name. To assist logic, numeric constant value is greater than OVER.

See Also:
resetAsCopy(), getResetOldGameState(), Constant Field Values

VACANT

public static final int VACANT
seat states

See Also:
Constant Field Values

OCCUPIED

public static final int OCCUPIED
seat states

See Also:
Constant Field Values

LOCKED

public static final boolean LOCKED
seatLock states

See Also:
Constant Field Values

UNLOCKED

public static final boolean UNLOCKED
seatLock states

See Also:
Constant Field Values

VOTE_NONE

public static final int VOTE_NONE
boardResetVotes per-player states: no vote sent; yes; no.

See Also:
Constant Field Values

VOTE_YES

public static final int VOTE_YES
See Also:
Constant Field Values

VOTE_NO

public static final int VOTE_NO
See Also:
Constant Field Values

MAXPLAYERS

public static final int MAXPLAYERS
maximum number of players in a game

See Also:
Constant Field Values

MINPLAYERS

public static final int MINPLAYERS
minimum number of players in a game (was assumed ==MAXPLAYERS in standard 1.0.6). Use isSeatVacant(i) to determine if a player is present; players[i] will be non-null although no player is there.

See Also:
Constant Field Values

VP_WINNER

public static final int VP_WINNER
Number of victory points (10) needed to win. Set to constant for searching if in future, decide to make a per-game choice.

See Also:
Constant Field Values

EMPTY_RESOURCES

public static final SOCResourceSet EMPTY_RESOURCES
the set of resources a player needs to build a settlement


SETTLEMENT_SET

public static final SOCResourceSet SETTLEMENT_SET
the set of resources a player needs to build a settlement


ROAD_SET

public static final SOCResourceSet ROAD_SET
the set of resources a player needs to build a road


CITY_SET

public static final SOCResourceSet CITY_SET
the set of resources a player needs to build a city


CARD_SET

public static final SOCResourceSet CARD_SET
the set of resources a player needs to buy a development card


inUse

boolean inUse
monitor for synchronization


name

private java.lang.String name
the name of the game


active

private boolean active
true if this game is ACTIVE


isLocal

public boolean isLocal
true if the game's network is local for practice. Used by client to route messages to appropriate connection.


hasOldClients

public boolean hasOldClients
For use at server; are there clients connected which aren't at the latest version?


clientVersionLowest

public int clientVersionLowest
For use at server; lowest and highest version of connected clients.


clientVersionHighest

public int clientVersionHighest
For use at server; lowest and highest version of connected clients.


isFromBoardReset

private boolean isFromBoardReset
true if the game came from a board reset


boardResetVoteRequester

private int boardResetVoteRequester
If a board reset vote is active, player number who requested the vote. All human players must vote unanimously, or board reset is rejected. -1 if no vote is active. Synchronize on boardResetVotes before reading or writing.


boardResetVotes

private int[] boardResetVotes
If a board reset vote is active, votes are recorded here. Values: VOTE_NONE, VOTE_YES, VOTE_NO. Indexed 0 to SOCGame.MAXPLAYERS-1. Synchronize on this object before reading or writing.


boardResetVotesWaiting

private int boardResetVotesWaiting
If a board reset vote is active, we're waiting to receive this many more votes. All human players vote, except the vote requester. Robots do not vote. Synchronize on boardResetVotes before reading or writing. When the vote is complete, this is 0. Undefined before the first vote; this field is not reset each turn. Set in resetVoteBegin, resetVoteRegister.


board

private SOCBoard board
the game board


players

private SOCPlayer[] players
the players; never contains a null element, use isSeatVacant(int) to see if a position is occupied.


seats

private int[] seats
the states for the player's seats


seatLocks

private boolean[] seatLocks
the states if the locks for the player's seats


currentPlayerNumber

private int currentPlayerNumber
the number of the current player


firstPlayerNumber

private int firstPlayerNumber
the first player to place a settlement


lastPlayerNumber

private int lastPlayerNumber
the last player to place the first settlement


currentDice

private int currentDice
the current dice result


gameState

private int gameState
the current game state


oldGameState

private int oldGameState
the old game state


placingRobberForKnightCard

private boolean placingRobberForKnightCard
If true, and if state is PLACING_ROBBER, the robber is being moved because a knight card has just been played. This, if forceEndTurn() is called, the knight card should be returned to the player's hand.


forcingEndTurn

private boolean forcingEndTurn
If true, this turn is being ended. Controller of game should call endTurn() whenever possible. Usually set when we have called forceEndTurn(), and forced the current player to discard randomly, and are waiting for other players to discard in gamestate WAITING_FOR_DISCARDS. Once all players have discarded, the turn should be ended.

See Also:
forceEndTurn()

playerWithLargestArmy

private int playerWithLargestArmy
the player with the largest army, or -1 if none


oldPlayerWithLargestArmy

private int oldPlayerWithLargestArmy

playerWithLongestRoad

private int playerWithLongestRoad
the player with the longest road, or -1 if none


playerWithWin

private int playerWithWin
the player declared winner, if gamestate == OVER; otherwise -1


numDevCards

private int numDevCards
the number of development cards left


devCardDeck

private int[] devCardDeck
the development card deck


rand

private java.util.Random rand
used to generate random numbers


allOriginalPlayers

boolean allOriginalPlayers
used to track if there were any player subs


oldPlayerWithLongestRoad

java.util.Stack oldPlayerWithLongestRoad
used to restore the LR player


startTime

java.util.Date startTime
when this game was created


expiration

long expiration
expiration time for this game in milliseconds

Constructor Detail

SOCGame

public SOCGame(java.lang.String n)
create a new game

Parameters:
n - the name of the game

SOCGame

public SOCGame(java.lang.String n,
               boolean a)
create a new game that can be INACTIVE

Parameters:
n - the name of the game
a - true if this is an active game, false for inactive
Method Detail

takeMonitor

public void takeMonitor()
take the monitor for this game


releaseMonitor

public void releaseMonitor()
release the monitor for this game


allOriginalPlayers

public boolean allOriginalPlayers()
Returns:
allOriginalPlayers

getStartTime

public java.util.Date getStartTime()
Returns:
the start time for this game, or null if inactive

getExpiration

public long getExpiration()
Returns:
the expiration time in milliseconds, same epoch as Date.getTime()

setExpiration

public void setExpiration(long ex)
set the expiration time

Parameters:
ex - the expiration time in milliseconds, same epoch as Date.getTime()

addPlayer

public void addPlayer(java.lang.String name,
                      int pn)
add a new player

Parameters:
name - the player's name
pn - the player's number

removePlayer

public void removePlayer(java.lang.String name)
remove a player

Parameters:
name - the player's name

isSeatVacant

public boolean isSeatVacant(int pn)
Parameters:
pn - the number of the seat
Returns:
true if the seat is VACANT

lockSeat

public void lockSeat(int pn)
locks a seat, so no one can take it

Parameters:
pn - the number of the seat

unlockSeat

public void unlockSeat(int pn)
unlocks a seat

Parameters:
pn - the number of the seat

isSeatLocked

public boolean isSeatLocked(int pn)
Parameters:
pn - the number of the seat
Returns:
true if this seat is locked

getPlayer

public SOCPlayer getPlayer(int pn)
Parameters:
pn - the player number, in range 0 to MAXPLAYERS-1
Returns:
the player object for a player id; never null if pn is in range

getPlayer

public SOCPlayer getPlayer(java.lang.String nn)
Parameters:
nn - the nickname
Returns:
the player object for a player nickname if there is no match, return null

getName

public java.lang.String getName()
Returns:
the name of the game

isBoardReset

public boolean isBoardReset()
Returns:
whether this game was created by board reset of an earlier game

getBoard

public SOCBoard getBoard()
Returns:
the game board

setBoard

protected void setBoard(SOCBoard gb)
set the game board

Parameters:
gb - the game board

getPlayers

public SOCPlayer[] getPlayers()
Returns:
the list of players

setPlayer

protected void setPlayer(int pn,
                         SOCPlayer pl)
set the data for a player

Parameters:
pn - the number of the player
pl - the player data

getCurrentPlayerNumber

public int getCurrentPlayerNumber()
Returns:
the number of the current player

setCurrentPlayerNumber

public void setCurrentPlayerNumber(int pn)
Set the number of the current player, and check for winner. Called only at client - server instead calls endTurn() or advanceTurn(). Check for gamestate OVER after calling setCurrentPlayerNumber. This is needed because a player can win only during their own turn; if they reach winning points (VP_WINNER or more) during another player's turn, they must wait.

Parameters:
pn - the player number
See Also:
endTurn(), checkForWinner()

getCurrentDice

public int getCurrentDice()
Returns:
the current dice result

setCurrentDice

public void setCurrentDice(int dr)
set the current dice result

Parameters:
dr - the dice result

getGameState

public int getGameState()
Current game state. For general information about what states are expected when, please see the javadoc for NEW.

Returns:
the current game state

setGameState

public void setGameState(int gs)
set the current game state. If the new state is OVER, and no playerWithWin yet determined, call checkForWinner. For general information about what states are expected when, please see the javadoc for NEW.

Parameters:
gs - the game state
See Also:
checkForWinner()

getResetOldGameState

public int getResetOldGameState()
                         throws java.lang.IllegalStateException
If the game board was reset, get the old game state.

Returns:
the old game state
Throws:
java.lang.IllegalStateException - Game state must be RESET_OLD when called; during normal game play, oldGameState is private.

isForcingEndTurn

public boolean isForcingEndTurn()
If true, this turn is being ended. Controller of game should call endTurn() whenever possible. Usually set if we have called forceEndTurn(), and forced the current player to discard randomly, and are waiting for other players to discard in gamestate WAITING_FOR_DISCARDS. Once all players have discarded, the turn should be ended.

See Also:
forceEndTurn()

getNumDevCards

public int getNumDevCards()
Returns:
the number of dev cards in the deck

setNumDevCards

public void setNumDevCards(int nd)
set the number of dev cards in the deck

Parameters:
nd - the number of dev cards in the deck

getPlayerWithLargestArmy

public SOCPlayer getPlayerWithLargestArmy()
Returns:
the player with the largest army

setPlayerWithLargestArmy

public void setPlayerWithLargestArmy(SOCPlayer pl)
set the player with the largest army

Parameters:
pl - the player

getPlayerWithLongestRoad

public SOCPlayer getPlayerWithLongestRoad()
Returns:
the player with the longest road

setPlayerWithLongestRoad

public void setPlayerWithLongestRoad(SOCPlayer pl)
set the player with the longest road

Parameters:
pl - the player

getPlayerWithWin

public SOCPlayer getPlayerWithWin()
Find the player who was declared winner at end of game. This is determined in checkForWinner(); there is no corresponding setter.

Returns:
the winning player, or null if none, or if game is not yet over.

gameOverMessageToPlayer

public java.lang.String gameOverMessageToPlayer(SOCPlayer pl)
                                         throws java.lang.IllegalStateException
If game is over, formulate a message to tell a player.

Parameters:
pl - Player to tell (may be the winner)
Returns:
A message of one of these forms: "The game is over; you are the winner!" "The game is over; won." "The game is over; no one won."
Throws:
java.lang.IllegalStateException - If the game state is not OVER

advanceTurnBackwards

protected void advanceTurnBackwards()
advance the turn to the previous player, used during initial placement


advanceTurn

protected void advanceTurn()
advance the turn to the next player


putPiece

public void putPiece(SOCPlayingPiece pp)
Put this piece on the board and update all related game state. If the piece is a city, putPiece removes the settlement there.

Parameters:
pp - the piece to put on the board

advanceTurnStateAfterPutPiece

private void advanceTurnStateAfterPutPiece()
After placing a piece on the board, update the state of the game, and possibly current player, for play to continue.

Also used in forceEndTurn() to continue the game after a cancelled piece placement in START1A..START2B . If the current player number changes here, isForcingEndTurn() is cleared.


putTempPiece

public void putTempPiece(SOCPlayingPiece pp)
a temporary piece has been put on the board

Parameters:
pp - the piece to put on the board

undoPutPieceCommon

protected void undoPutPieceCommon(SOCPlayingPiece pp)
undo the putting of a temporary or initial piece

Parameters:
pp - the piece to put on the board

undoPutTempPiece

public void undoPutTempPiece(SOCPlayingPiece pp)
undo the putting of a temporary piece

Parameters:
pp - the piece to put on the board
See Also:
undoPutInitSettlement(SOCPlayingPiece)

undoPutInitSettlement

public void undoPutInitSettlement(SOCPlayingPiece pp)
undo the putting of an initial settlement. If state is STATE2B, resources will be returned. Player is unchanged; state will become STATE1A or STATE2A.

Parameters:
pp - the piece to remove from the board

startGame

public void startGame()
do the things involved in starting a game: shuffle the tiles and cards, make a board, choose first player. gameState becomes START1A.


setFirstPlayer

public void setFirstPlayer(int pn)
sets who the first player is

Parameters:
pn - the seat number of the first player

getFirstPlayer

public int getFirstPlayer()
Returns:
the seat number of the first player

canEndTurn

public boolean canEndTurn(int pn)
Can this player end the current turn?

In some states, the current player can't end their turn yet (such as needing to move the robber, or choose resources for a year-of-plenty card, or discard if a 7 is rolled).

Parameters:
pn - player number of the player who wants to end the turn
Returns:
true if ok for this player to end the turn (They are current player, game state is PLAY1)
See Also:
endTurn(), forceEndTurn()

endTurn

public void endTurn()
end the turn for the current player, and check for winner. Check for gamestate OVER after calling endTurn. endTurn() is called only at server - client instead calls setCurrentPlayerNumber. The winner check is needed because a player can win only during their own turn; if they reach winning points (VP_WINNER or more) during another player's turn, they must wait.

See Also:
setCurrentPlayerNumber(int), checkForWinner(), forceEndTurn(), isForcingEndTurn()

forceEndTurn

public SOCForceEndTurnResult forceEndTurn()
                                   throws java.lang.IllegalStateException
In an active game, force current turn to be able to be ended. Takes whatever action needed to force current player to end their turn, and if possible, sets state to PLAY1, but does not call endTurn(). May be used if player loses connection, or robot does not respond.

TODO finish this javadoc...

Since only the server calls endTurn(), this method does not do so.

After calling forceEndTurn, usually the gameState will be PLAY1, and the caller should call endTurn(). The isForcingEndTurn() flag is also set. Exceptions (caller should not call endTurn) are these return types:

Returns:
Type of action performed, one of these values:
Throws:
java.lang.IllegalStateException - if game is not active (gamestate < START1A or >= OVER)
See Also:
canEndTurn(int), endTurn()

forceEndTurnStartState

private SOCForceEndTurnResult forceEndTurnStartState(boolean advTurnForward)
Special forceEndTurn() treatment for start-game states. See forceEndTurn() for description.

Parameters:
advTurnForward - Should the next player be normal (placing first settlement), or backwards (placing second settlement)?
Returns:
A forceEndTurn result of type SOCForceEndTurnResult.FORCE_ENDTURN_SKIP_START_ADV, SOCForceEndTurnResult.FORCE_ENDTURN_SKIP_START_ADVBACK, or SOCForceEndTurnResult.FORCE_ENDTURN_SKIP_START_TURN.

forceEndTurnChkDiscards

private SOCForceEndTurnResult forceEndTurnChkDiscards(int pn)
Randomly discard from this player's hand, by calling discard(int, SOCResourceSet). Then look at other players' hand size. If no one else must discard, ready to end turn, set state PLAY1. Otherwise, must wait for them; if so, set game state to WAITING_FOR_DISCARDS. When called, assumes isForcingEndTurn() flag is already set.

Parameters:
pn - Player number to force to randomly discard
Returns:
The force result, including any discarded resources. Type will be SOCForceEndTurnResult.FORCE_ENDTURN_RSRC_DISCARD or SOCForceEndTurnResult.FORCE_ENDTURN_RSRC_DISCARD_WAIT.

discardPickRandom

public static void discardPickRandom(SOCResourceSet fromHand,
                                     int numDiscards,
                                     SOCResourceSet discards,
                                     java.util.Random rand)
Choose discards at random; does not actually discard anything.

Parameters:
fromHand - Discard from this set
numDiscards - This many must be discarded
discards - Add discards to this set (typically new,empty, when called)
rand - Source of random

playerDiscardRandom

public SOCResourceSet playerDiscardRandom(int pn)
                                   throws java.lang.IllegalStateException
Force this non-current player to discard randomly. Used at server when a player must discard and they lose connection while the game is waiting for them.

On return, gameState will be:

Parameters:
pn - Player number to discard; player must must need to discard, must not be current player (use forceEndTurn() for that)
Returns:
Set of resource cards which were discarded
Throws:
java.lang.IllegalStateException - If the gameState isn't WAITING_FOR_DISCARDS, or if pn's SOCPlayer.getNeedToDiscard() is false, or if pn == currentPlayer.

canRollDice

public boolean canRollDice(int pn)
Parameters:
pn - player number of the player who wants to roll
Returns:
true if it's ok for this player to roll the dice

rollDice

public IntPair rollDice()
roll the dice


getResourcesGainedFromRoll

public SOCResourceSet getResourcesGainedFromRoll(SOCPlayer player,
                                                 int roll)
figure out what resources a player would get on a given roll

Parameters:
player - the player
roll - the roll
Returns:
the resource set

canDiscard

public boolean canDiscard(int pn,
                          SOCResourceSet rs)
Parameters:
pn - the number of the player that is discarding
rs - the resources that the player is discarding
Returns:
true if the player can discard these resources

discard

public void discard(int pn,
                    SOCResourceSet rs)
A player is discarding resources. Discard, check if other players must still discard, and set gameState to WAITING_FOR_DISCARDS or PLACING_ROBBER accordingly.

Special case: If isForcingEndTurn(), and no one else needs to discard, gameState becomes PLAY1 but the caller must call endTurn() as soon as possible.

Parameters:
pn - the number of the player
rs - the resources that are being discarded

canMoveRobber

public boolean canMoveRobber(int pn,
                             int co)
Parameters:
pn - the number of the player that is moving the robber
co - the coordinates
Returns:
true if the player can move the robber to the coordinates

moveRobber

public SOCMoveRobberResult moveRobber(int pn,
                                      int co)
move the robber. If no victims (players to possibly steal from): State becomes oldGameState. If just one victim: call stealFromPlayer, State becomes oldGameState. If multiple possible victims: Player must choose a victim; State becomes WAITING_FOR_CHOICE.

Parameters:
pn - the number of the player that is moving the robber
co - the coordinates
Returns:
returns a result that says if a resource was stolen, or if the player needs to make a choice. It also returns what was stolen and who was the victim.

canChoosePlayer

public boolean canChoosePlayer(int pn)
Parameters:
pn - the number of the player to rob
Returns:
true if the current player can choose a player to rob

getPlayersOnHex

public java.util.Vector getPlayersOnHex(int hex)
Parameters:
hex - the coordinates of the hex
Returns:
a list of players touching a hex

getPossibleVictims

public java.util.Vector getPossibleVictims()
Returns:
a list of possible players to rob

stealFromPlayer

public int stealFromPlayer(int pn)
the current player has choosen a victim to rob. perform the robbery. Set gameState back to oldGameState.

Parameters:
pn - the number of the player being robbed
Returns:
the type of resource that was stolen, as in SOCResourceConstants

canMakeTrade

public boolean canMakeTrade(int offering,
                            int accepting)
Parameters:
offering - the number of the player making the offer
accepting - the number of the player accepting the offer
Returns:
true if the two players can make the trade described in the offering players current offer

makeTrade

public void makeTrade(int offering,
                      int accepting)
perform a trade between two players the trade performed is described in the offering player's current offer

Parameters:
offering - the number of the player making the offer
accepting - the number of the player accepting the offer

canMakeBankTrade

public boolean canMakeBankTrade(SOCResourceSet give,
                                SOCResourceSet get)
Parameters:
give - what the player will give to the bank
get - what the player wants from the bank
Returns:
true if the current player can make a particular bank/port trade

makeBankTrade

public void makeBankTrade(SOCResourceSet give,
                          SOCResourceSet get)
perform a bank trade

Parameters:
give - the number of the player making the offer
get - the number of the player accepting the offer

couldBuildRoad

public boolean couldBuildRoad(int pn)
Parameters:
pn - the number of the player
Returns:
true if the player has the resources, pieces, and room to build a road

couldBuildSettlement

public boolean couldBuildSettlement(int pn)
Parameters:
pn - the number of the player
Returns:
true if the player has the resources, pieces, and room to build a settlement

couldBuildCity

public boolean couldBuildCity(int pn)
Parameters:
pn - the number of the player
Returns:
true if the player has the resources, pieces, and room to build a city

couldBuyDevCard

public boolean couldBuyDevCard(int pn)
Parameters:
pn - the number of the player
Returns:
true if the player has the resources to buy a dev card, and if there are dev cards left to buy

buyRoad

public void buyRoad(int pn)
a player is buying a road

Parameters:
pn - the number of the player

buySettlement

public void buySettlement(int pn)
a player is buying a settlement

Parameters:
pn - the number of the player

buyCity

public void buyCity(int pn)
a player is buying a city

Parameters:
pn - the number of the player

cancelBuildRoad

public void cancelBuildRoad(int pn)
a player is UNbuying a road; return resources, set gameState PLAY1

Parameters:
pn - the number of the player

cancelBuildSettlement

public void cancelBuildSettlement(int pn)
a player is UNbuying a settlement; return resources, set gameState PLAY1

Parameters:
pn - the number of the player

cancelBuildCity

public void cancelBuildCity(int pn)
a player is UNbuying a city; return resources, set gameState PLAY1

Parameters:
pn - the number of the player

buyDevCard

public int buyDevCard()
the current player is buying a dev card

Returns:
the card that was drawn

canPlayKnight

public boolean canPlayKnight(int pn)
Parameters:
pn - the number of the player
Returns:
true if the player can play a knight card

canPlayRoadBuilding

public boolean canPlayRoadBuilding(int pn)
Can the current player play a Road Building card?

This card directs the player to place 2 roads. Checks of game rules online show they "MAY" or "CAN", not "MUST", place 2. If they have 2 or more roads, place 2. If they have just 1 road, place 1. If they have 0 roads, cannot play the card.

Parameters:
pn - the number of the player
Returns:
true if the player can play a Road Building card.

canPlayDiscovery

public boolean canPlayDiscovery(int pn)
return true if the player can play a Discovery card

Parameters:
pn - the number of the player

canPlayMonopoly

public boolean canPlayMonopoly(int pn)
return true if the player can play a Monopoly card

Parameters:
pn - the number of the player

playKnight

public void playKnight()
the current player plays a Knight card


playRoadBuilding

public void playRoadBuilding()
The current player plays a Road Building card. This card directs the player to place 2 roads. Checks of game rules online show "MAY" or "CAN", not "MUST" place 2. If they have 2 or more roads, may place 2; gameState becomes PLACING_FREE_ROAD1. If they have just 1 road, may place that; gameState becomes PLACING_FREE_ROAD2. If they have 0 roads, cannot play the card. Assumes canPlayRoadBuilding(int) has already been called, and move is valid.


playDiscovery

public void playDiscovery()
the current player plays a Discovery card


playMonopoly

public void playMonopoly()
the current player plays a monopoly card


canDoDiscoveryAction

public boolean canDoDiscoveryAction(SOCResourceSet pick)
Parameters:
pick - the resources that the player wants
Returns:
true if the current player can do the discovery card action and the pick contains exactly 2 resources

canDoMonopolyAction

public boolean canDoMonopolyAction()
Returns:
true if the current player can do the Monopoly card action

doDiscoveryAction

public void doDiscoveryAction(SOCResourceSet pick)
perform the Discovery card action

Parameters:
pick - what the player picked

doMonopolyAction

public void doMonopolyAction(int pick)
perform the Monopoly card action

Parameters:
pick - the type of resource to monopolize

updateLargestArmy

public void updateLargestArmy()
update which player has the largest army larger than 2


saveLargestArmyState

public void saveLargestArmyState()
save the state of who has largest army


restoreLargestArmyState

public void restoreLargestArmyState()
restore the state of who had largest army


updateLongestRoad

public void updateLongestRoad(int pn)
update which player has longest road longer than 4 this version only calculates the longest road for the player who is affected by the most recently placed piece

Parameters:
pn - the number of the player who is affected

checkForWinner

public void checkForWinner()
check current player's vp total to see if the game is over. Set game state to OVER, set player with win.

Per rules FAQ, a player can win only during their own turn. If a player reaches winning points (VP_WINNER or more) but it's not their turn, there is not yet a winner. This could happen if, for example, the longest road is broken by a new settlement, and the next-longest road is not the current player's road.

See Also:
getGameState(), getPlayerWithWin()

destroyGame

public void destroyGame()
set vars to null so gc can clean up


resetAsCopy

public SOCGame resetAsCopy()
Create a new game with same players and name, new board; like calling constructor otherwise. State of current game can be any state. State of copy is NEW. Deep copy: Player names, faceIDs, and robot-flag are copied from old game, but all other fields set as new Player and Board objects. Robot players are NOT carried over, and must be asked to re-join. (This simplifies the robot client.)

Old game's state becomes RESET_OLD. Old game's previous state is saved to getResetOldGameState(). Please call destroyGame() on old game when done examining its state.

Assumes that if the game had more than one human player, they've already voted interactively to reset the board.

See Also:
resetVoteBegin(int)

resetVoteBegin

public void resetVoteBegin(int reqPN)
                    throws java.lang.IllegalArgumentException,
                           java.lang.IllegalStateException
Begin a board-reset vote.

Parameters:
reqPN - Player number requesting the vote
Throws:
java.lang.IllegalArgumentException - If this player number has already requested a reset this turn
java.lang.IllegalStateException - If there is alread a vote in progress
See Also:
getResetVoteRequester(), resetVoteRegister(int, boolean), getResetVoteResult()

getResetVoteRequester

public int getResetVoteRequester()
If a board reset vote is active, player number who requested the vote. All human players must vote unanimously, or board reset is rejected. -1 if no vote is active. After the vote completes, this is set to -1 if the vote was rejected, but retains the requester number if the vote succeeded and the board will soon be reset.

Returns:
player number who requested the vote.
See Also:
resetVoteBegin(int)

getResetVoteActive

public boolean getResetVoteActive()
Returns:
if a board-reset vote is active (waiting for votes).

resetVoteRegister

public boolean resetVoteRegister(int pn,
                                 boolean votingYes)
                          throws java.lang.IllegalArgumentException,
                                 java.lang.IllegalStateException
Register this player's vote in a board reset request.

Parameters:
pn - Player number
votingYes - Are they voting yes, or no?
Returns:
True if voting is now complete, false if still waiting for other votes
Throws:
java.lang.IllegalArgumentException - If pn already voted, or can't vote (vacant or robot).
java.lang.IllegalStateException - If voting is not currently active.
See Also:
getResetPlayerVote(int)

getResetPlayerVote

public int getResetPlayerVote(int pn)
Get this player's vote on a board reset request.

Parameters:
pn - Player number
Returns:
Vote value for player: VOTE_YES, VOTE_NO, or if player hasn't yet voted, VOTE_NONE.
See Also:
resetVoteRegister(int, boolean), getResetVoteResult()

resetVoteClear

public void resetVoteClear()
At end of turn, clear flags for board reset voting: requester, players' setAskedBoardReset. This is outside of endTurn() because endTurn is called only at the server, not at clients. Do not call this to cancel a vote, because it would allow players to ask for a reset more than once per turn.


getResetVoteResult

public boolean getResetVoteResult()
                           throws java.lang.IllegalStateException
If a board-reset vote is complete, give its result. All human players must vote unanimously, or board reset is rejected.

Returns:
True if accepted, false if rejected.
Throws:
java.lang.IllegalStateException - if voting is still active. See getResetVoteActive().
See Also:
getResetPlayerVote(int)