From: <ev...@us...> - 2010-07-04 20:44:36
|
Revision: 1331 http://rails.svn.sourceforge.net/rails/?rev=1331&view=rev Author: evos Date: 2010-07-04 20:44:29 +0000 (Sun, 04 Jul 2010) Log Message: ----------- Fixed price token order changes at end of SR Modified Paths: -------------- trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/GameManagerI.java trunk/18xx/rails/game/StockRound.java Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-07-04 15:17:14 UTC (rev 1330) +++ trunk/18xx/rails/game/GameManager.java 2010-07-04 20:44:29 UTC (rev 1331) @@ -1,10 +1,22 @@ /* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/GameManager.java,v 1.107 2010/06/17 21:35:54 evos Exp $ */ package rails.game; -import java.io.*; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.io.PrintWriter; import java.lang.reflect.Constructor; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; import org.apache.log4j.Logger; import org.apache.log4j.NDC; @@ -12,15 +24,28 @@ import rails.algorithms.RevenueManager; import rails.common.GuiDef; import rails.common.GuiHints; -import rails.game.action.*; -import rails.game.correct.*; -import rails.game.move.*; +import rails.game.action.GameAction; +import rails.game.action.NullAction; +import rails.game.action.PossibleAction; +import rails.game.action.PossibleActions; +import rails.game.action.RepayLoans; +import rails.game.correct.CorrectionAction; +import rails.game.correct.CorrectionManagerI; +import rails.game.correct.CorrectionType; +import rails.game.move.AddToList; +import rails.game.move.CashMove; +import rails.game.move.MoveStack; +import rails.game.move.Moveable; import rails.game.special.SpecialPropertyI; import rails.game.special.SpecialTokenLay; import rails.game.state.BooleanState; import rails.game.state.IntegerState; import rails.game.state.State; -import rails.util.*; +import rails.util.BuildInfo; +import rails.util.Config; +import rails.util.LocalText; +import rails.util.Tag; +import rails.util.Util; /** * This class manages the playing rounds by supervising all implementations of @@ -34,11 +59,11 @@ * action package. */ public static final long saveFileVersionID = - saveFileHeaderVersionID * PossibleAction.serialVersionUID; + saveFileHeaderVersionID * PossibleAction.serialVersionUID; protected Class<? extends StockRound> stockRoundClass = StockRound.class; protected Class<? extends OperatingRound> operatingRoundClass = - OperatingRound.class; + OperatingRound.class; // Variable UI Class names protected String gameUIManagerClassName = GuiDef.getDefaultClassName(GuiDef.ClassName.GAME_UI_MANAGER); @@ -75,7 +100,7 @@ new HashMap<String, Portfolio> (); protected IntegerState playerCertificateLimit - = new IntegerState ("PlayerCertificateLimit", 0); + = new IntegerState ("PlayerCertificateLimit", 0); protected int currentNumberOfOperatingRounds = 1; protected boolean skipFirstStockRound = false; protected boolean showCompositeORNumber = true; @@ -85,10 +110,10 @@ protected boolean gameEndsAfterSetOfORs = true; protected EnumMap<GameDef.Parm, Object> gameParameters - = new EnumMap<GameDef.Parm, Object>(GameDef.Parm.class); + = new EnumMap<GameDef.Parm, Object>(GameDef.Parm.class); -// protected EnumSet<CorrectionType> activeCorrections -// = EnumSet.noneOf(CorrectionType.class); + // protected EnumSet<CorrectionType> activeCorrections + // = EnumSet.noneOf(CorrectionType.class); /** * Current round should not be set here but from within the Round classes. @@ -103,9 +128,9 @@ protected IntegerState srNumber = new IntegerState ("SRNumber"); protected IntegerState absoluteORNumber = - new IntegerState("AbsoluteORNUmber"); + new IntegerState("AbsoluteORNUmber"); protected IntegerState relativeORNumber = - new IntegerState("RelativeORNumber"); + new IntegerState("RelativeORNumber"); protected int numOfORs; protected BooleanState gameOver = new BooleanState("GameOver" ,false); @@ -142,7 +167,7 @@ * For now, the key is a fixed string, but that may change in the future. */ protected static Map<String, GameManagerI> gameManagerMap - = new HashMap<String, GameManagerI>(); + = new HashMap<String, GameManagerI>(); /** * The temporary fixed key to the currently single GameManager instance @@ -188,10 +213,10 @@ /** A List of available game options */ protected List<GameOption> availableGameOptions = - new ArrayList<GameOption>(); + new ArrayList<GameOption>(); protected static Logger log = - Logger.getLogger(GameManager.class.getPackage().getName()); + Logger.getLogger(GameManager.class.getPackage().getName()); public GameManager() { gmName = GM_NAME; @@ -209,7 +234,7 @@ Tag gameTag = tag.getChild("Game"); if (gameTag == null) throw new ConfigurationException( - "No Game tag specified in GameManager tag"); + "No Game tag specified in GameManager tag"); gameName = gameTag.getAttributeAsString("name"); if (gameName == null) throw new ConfigurationException("No name specified in Game tag"); @@ -261,19 +286,19 @@ // StockRound class and other properties - Tag srTag = gameParmTag.getChild("StockRound"); + Tag srTag = gameParmTag.getChild("StockRound"); if (srTag != null) { String srClassName = - srTag.getAttributeAsString("class", "rails.game.StockRound"); + srTag.getAttributeAsString("class", "rails.game.StockRound"); try { stockRoundClass = - Class.forName(srClassName).asSubclass(StockRound.class); + Class.forName(srClassName).asSubclass(StockRound.class); } catch (ClassNotFoundException e) { throw new ConfigurationException("Cannot find class " - + srClassName, e); + + srClassName, e); } String stockRoundSequenceRuleString = - srTag.getAttributeAsString("sequence"); + srTag.getAttributeAsString("sequence"); if (Util.hasValue(stockRoundSequenceRuleString)) { if (stockRoundSequenceRuleString.equalsIgnoreCase("SellBuySell")) { setGameParameter(GameDef.Parm.STOCK_ROUND_SEQUENCE, @@ -288,8 +313,8 @@ } skipFirstStockRound = - srTag.getAttributeAsBoolean("skipFirst", - skipFirstStockRound); + srTag.getAttributeAsBoolean("skipFirst", + skipFirstStockRound); for (String ruleTagName : srTag.getChildren().keySet()) { if (ruleTagName.equals("NoSaleInFirstSR")) { @@ -301,21 +326,21 @@ } } - } + } // OperatingRound class Tag orTag = gameParmTag.getChild("OperatingRound"); if (orTag != null) { String orClassName = - orTag.getAttributeAsString("class", - "rails.game.OperatingRound"); + orTag.getAttributeAsString("class", + "rails.game.OperatingRound"); try { operatingRoundClass = - Class.forName(orClassName).asSubclass( - OperatingRound.class); + Class.forName(orClassName).asSubclass( + OperatingRound.class); } catch (ClassNotFoundException e) { throw new ConfigurationException("Cannot find class " - + orClassName, e); + + orClassName, e); } } @@ -354,8 +379,8 @@ Tag bankBreaksTag = endOfGameTag.getChild("BankBreaks"); if (bankBreaksTag != null) { gameEndsWhenBankHasLessOrEqual = - bankBreaksTag.getAttributeAsInteger("limit", - gameEndsWhenBankHasLessOrEqual); + bankBreaksTag.getAttributeAsInteger("limit", + gameEndsWhenBankHasLessOrEqual); String attr = bankBreaksTag.getAttributeAsString("finish"); if (attr.equalsIgnoreCase("SetOfORs")) { gameEndsAfterSetOfORs = true; @@ -372,7 +397,7 @@ Tag gameUIMgrTag = guiClassesTag.getChild("GameUIManager"); if (gameUIMgrTag != null) { gameUIManagerClassName = - gameUIMgrTag.getAttributeAsString("class", gameUIManagerClassName); + gameUIMgrTag.getAttributeAsString("class", gameUIManagerClassName); // Check instantiatability (not sure if this belongs here) canClassBeInstantiated (gameUIManagerClassName); } @@ -381,7 +406,7 @@ Tag orMgrTag = guiClassesTag.getChild("ORUIManager"); if (orMgrTag != null) { orUIManagerClassName = - orMgrTag.getAttributeAsString("class", orUIManagerClassName); + orMgrTag.getAttributeAsString("class", orUIManagerClassName); // Check instantiatability (not sure if this belongs here) canClassBeInstantiated (orUIManagerClassName); } @@ -390,7 +415,7 @@ Tag gameStatusTag = guiClassesTag.getChild("GameStatus"); if (gameStatusTag != null) { gameStatusClassName = - gameStatusTag.getAttributeAsString("class", gameStatusClassName); + gameStatusTag.getAttributeAsString("class", gameStatusClassName); // Check instantiatability (not sure if this belongs here) canClassBeInstantiated (gameStatusClassName); } @@ -399,8 +424,8 @@ Tag statusWindowTag = guiClassesTag.getChild("StatusWindow"); if (statusWindowTag != null) { statusWindowClassName = - statusWindowTag.getAttributeAsString("class", - statusWindowClassName); + statusWindowTag.getAttributeAsString("class", + statusWindowClassName); // Check instantiatability (not sure if this belongs here) canClassBeInstantiated (statusWindowClassName); } @@ -431,7 +456,7 @@ Class.forName(className); } catch (ClassNotFoundException e) { throw new ConfigurationException("Cannot find class " - + className, e); + + className, e); } } @@ -497,7 +522,7 @@ if (company.getMaxNumberOfLoans() != 0) guiParameters.put(GuiDef.Parm.HAS_ANY_COMPANY_LOANS, true); } -loop: for (PrivateCompanyI company : companyManager.getAllPrivateCompanies()) { + loop: for (PrivateCompanyI company : companyManager.getAllPrivateCompanies()) { for (SpecialPropertyI sp : company.getSpecialProperties()) { if (sp instanceof SpecialTokenLay && ((SpecialTokenLay)sp).getToken() instanceof BonusToken) { @@ -513,7 +538,7 @@ guiParameters.put(GuiDef.Parm.NO_MAP_MODE, true); guiParameters.put(GuiDef.Parm.ROUTE_HIGHLIGHT, false); guiParameters.put(GuiDef.Parm.REVENUE_SUGGEST, false); - } else { + } else { if (getGameOption("RouteAwareness").equalsIgnoreCase("Highlight")) { guiParameters.put(GuiDef.Parm.ROUTE_HIGHLIGHT, true); } @@ -561,7 +586,7 @@ startOperatingRound(false); } else if (skipFirstStockRound) { PhaseI currentPhase = - phaseManager.getCurrentPhase(); + phaseManager.getCurrentPhase(); numOfORs = currentPhase.getNumberOfOperatingRounds(); log.info("Phase=" + currentPhase.getName() + " ORs=" + numOfORs); @@ -612,7 +637,7 @@ } catch (Exception e) { log.fatal("Cannot find class " + startRoundClassName, e); - System.exit(1); + System.exit(1); } StartRound startRound = createRound (startRoundClass); startRound.start (); @@ -640,7 +665,7 @@ round = cons.newInstance(this); } catch (Exception e) { log.fatal("Cannot instantiate class " - + roundClass.getName(), e); + + roundClass.getName(), e); System.exit(1); } setRound (round); @@ -648,7 +673,7 @@ } protected <T extends RoundI, U extends RoundI> - T createRound (Class<T> roundClass, U parentRound) { + T createRound (Class<T> roundClass, U parentRound) { if (parentRound == null) { return createRound (roundClass); @@ -660,7 +685,7 @@ round = cons.newInstance(this, parentRound); } catch (Exception e) { log.fatal("Cannot instantiate class " - + roundClass.getName(), e); + + roundClass.getName(), e); System.exit(1); } setRound (round); @@ -710,7 +735,7 @@ interruptedRound = getCurrentRound(); createRound (ShareSellingRound.class, interruptedRound) - .start(player, cashToRaise, unsellableCompany); + .start(player, cashToRaise, unsellableCompany); } /* (non-Javadoc) @@ -799,7 +824,7 @@ if (result && !(action instanceof GameAction) && action.hasActed()) { new AddToList<PossibleAction>(executedActions, action, - "ExecutedActions"); + "ExecutedActions"); } } @@ -834,7 +859,7 @@ // logging of game actions activated for (PossibleAction pa : possibleActions.getList()) { log.debug(((Player) currentPlayer.getObject()).getName() + " may: " - + pa.toString()); + + pa.toString()); } return result; @@ -865,9 +890,9 @@ private boolean processCorrectionActions(PossibleAction a){ - boolean result = false; + boolean result = false; - if (a instanceof CorrectionAction) { + if (a instanceof CorrectionAction) { CorrectionAction ca= (CorrectionAction)a; CorrectionType ct = ca.getCorrectionType(); CorrectionManagerI cm = getCorrectionManager(ct); @@ -899,8 +924,8 @@ log.debug("Action ("+action.getPlayerName()+"): " + action); if (!processCorrectionActions(action) && !getCurrentRound().process(action)) { String msg = "Player "+action.getPlayerName()+"\'s action \"" - +action.toString()+"\"\n in "+getCurrentRound().getRoundName() - +" is considered invalid by the game engine"; + +action.toString()+"\"\n in "+getCurrentRound().getRoundName() + +" is considered invalid by the game engine"; log.error(msg); DisplayBuffer.add(msg); if (moveStack.isOpen()) moveStack.finish(); @@ -918,14 +943,14 @@ throw new Exception("Reload failure", e); } new AddToList<PossibleAction>(executedActions, action, - "ExecutedActions"); + "ExecutedActions"); if (moveStack.isOpen()) moveStack.finish(); - + log.debug("Turn: "+getCurrentPlayer().getName()); } -// DisplayBuffer.clear(); -// previous line removed to allow display of nextPlayerMessages + // DisplayBuffer.clear(); + // previous line removed to allow display of nextPlayerMessages guiHints.clearVisibilityHints(); return true; @@ -938,8 +963,8 @@ try { ObjectOutputStream oos = - new ObjectOutputStream(new FileOutputStream(new File( - filepath))); + new ObjectOutputStream(new FileOutputStream(new File( + filepath))); oos.writeObject(Game.version+" "+BuildInfo.buildDate); oos.writeObject(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); oos.writeObject(saveFileVersionID); @@ -973,8 +998,8 @@ for (MapHex hex:hexRow) if (hex != null) { pw.println(hex.getName() + "," + hex.getCurrentTile().getExternalId() + "," - + hex.getCurrentTileRotation() + "," - + hex.getOrientationName(hex.getCurrentTileRotation()) + + hex.getCurrentTileRotation() + "," + + hex.getOrientationName(hex.getCurrentTileRotation()) ) ; } @@ -1019,8 +1044,8 @@ public void registerBankruptcy() { endedByBankruptcy.set(true); String message = - LocalText.getText("PlayerIsBankrupt", - getCurrentPlayer().getName()); + LocalText.getText("PlayerIsBankrupt", + getCurrentPlayer().getName()); ReportBuffer.add(message); DisplayBuffer.add(message); if (gameEndsWithBankruptcy) { @@ -1044,7 +1069,7 @@ newPresident = null; maxShare = 0; for (int index=getCurrentPlayerIndex()+1; - index<getCurrentPlayerIndex()+numberOfPlayers; index++) { + index<getCurrentPlayerIndex()+numberOfPlayers; index++) { player = getPlayerByIndex(index%numberOfPlayers); share = player.getPortfolio().getShare(company); if (share >= company.getPresidentsShare().getShare() @@ -1068,7 +1093,7 @@ // Finish the share selling round if (getCurrentRound() instanceof ShareSellingRound) { - finishShareSellingRound(); + finishShareSellingRound(); } } } @@ -1142,7 +1167,7 @@ int i = 0; for (Player p : rankedPlayers) { b.add((++i) + ". " + Bank.format(p.getWorth()) + " " - + p.getName()); + + p.getName()); } return b; @@ -1167,8 +1192,8 @@ */ public void setCurrentPlayerIndex(int currentPlayerIndex) { currentPlayerIndex = currentPlayerIndex % numberOfPlayers; -// currentPlayer.set(players.get(currentPlayerIndex)); -// changed to activate nextPlayerMessages + // currentPlayer.set(players.get(currentPlayerIndex)); + // changed to activate nextPlayerMessages setCurrentPlayer(players.get(currentPlayerIndex)); } @@ -1192,7 +1217,7 @@ */ public void setPriorityPlayer() { int priorityPlayerIndex = - (getCurrentPlayer().getIndex() + 1) % numberOfPlayers; + (getCurrentPlayer().getIndex() + 1) % numberOfPlayers; setPriorityPlayer(players.get(priorityPlayerIndex)); } @@ -1203,7 +1228,7 @@ public void setPriorityPlayer(Player player) { priorityPlayer.set(player); log.debug("Priority player set to " + player.getIndex() + " " - + player.getName()); + + player.getName()); } /* (non-Javadoc) @@ -1280,7 +1305,7 @@ public void setNextPlayer() { int currentPlayerIndex = getCurrentPlayerIndex(); do { - currentPlayerIndex = ++currentPlayerIndex % numberOfPlayers; + currentPlayerIndex = ++currentPlayerIndex % numberOfPlayers; } while (players.get(currentPlayerIndex).isBankrupt()); setCurrentPlayerIndex(currentPlayerIndex); } @@ -1546,9 +1571,42 @@ cm=ct.newCorrectionManager(this); correctionManagers.put(ct, cm); log.debug("Added CorrectionManager for " + ct); -} + } return cm; } + /** Return a list of companies in operation order. + * <p>Note that, unlike Round.setOperatingCompanies(), this method does <b>not</b> check + * if the companies are actualy allowed to operate. One purpose is to check for upping the + * share price at the end of an SR un sucn a way, that the token order gets preserved. + * @return + */ + public List<PublicCompanyI> getCompaniesInRunningOrder () { + + Map<Integer, PublicCompanyI> operatingCompanies = + new TreeMap<Integer, PublicCompanyI>(); + StockSpaceI space; + int key; + int minorNo = 0; + for (PublicCompanyI company : companyManager.getAllPublicCompanies()) { + + // Key must put companies in reverse operating order, because sort + // is ascending. + if (company.hasStockPrice() && company.hasStarted()) { + space = company.getCurrentSpace(); + key = + 1000000 * (999 - space.getPrice()) + 10000 + * (99 - space.getColumn()) + 100 + * space.getRow() + + space.getStackPosition(company); + } else { + key = ++minorNo; + } + operatingCompanies.put(new Integer(key), company); + } + + return new ArrayList<PublicCompanyI>(operatingCompanies.values()); + } + } Modified: trunk/18xx/rails/game/GameManagerI.java =================================================================== --- trunk/18xx/rails/game/GameManagerI.java 2010-07-04 15:17:14 UTC (rev 1330) +++ trunk/18xx/rails/game/GameManagerI.java 2010-07-04 20:44:29 UTC (rev 1331) @@ -1,202 +1,204 @@ -package rails.game; - -import java.util.List; -import java.util.Map; - -import rails.algorithms.RevenueManager; -import rails.common.GuiDef; -import rails.common.GuiHints; -import rails.game.action.PossibleAction; -import rails.game.correct.CorrectionManagerI; -import rails.game.correct.CorrectionType; -import rails.game.model.ModelObject; -import rails.game.move.MoveStack; -import rails.game.move.MoveableHolder; -import rails.game.special.SpecialPropertyI; - -public interface GameManagerI extends MoveableHolder, ConfigurableComponentI { - - /** - * @see rails.game.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) - */ - public abstract void init(String gameName, PlayerManager playerManager, - CompanyManagerI companyManager, PhaseManager phaseManager, - TrainManager trainManager, StockMarketI stockMarket, - MapManager mapManager, TileManager tileManager, - RevenueManager revenueManager, Bank bank); - public abstract void startGame(Map<String, String> gameOptions); - - public abstract CompanyManagerI getCompanyManager(); - - /** - * Should be called by each Round when it finishes. - * - * @param round The object that represents the finishing round. - */ - public abstract void nextRound(RoundI round); - - public String getORId (); - public abstract String getCompositeORNumber(); - public int getRelativeORNumber(); - - public abstract int getSRNumber(); - - public abstract void startShareSellingRound(Player sellingPlayer, - int cashToRaise, PublicCompanyI unsellableCompany); - - public abstract void startTreasuryShareTradingRound(); - - /** - * The central server-side method that takes a client-side initiated action - * and processes it. - * - * @param action A PossibleAction subclass object sent by the client. - * @return TRUE is the action was valid. - */ - public abstract boolean process(PossibleAction action); - - public abstract boolean processOnReload(List<PossibleAction> actions) - throws Exception; - - public abstract void finishShareSellingRound(); - - public abstract void finishTreasuryShareRound(); - - public abstract void registerBankruptcy(); - - public abstract void registerBrokenBank(); - - /** - * To be called by the UI to check if the rails.game is over. - * - * @return - */ - public abstract boolean isGameOver(); - - public void setGameOverReportedUI(boolean b); - - public boolean getGameOverReportedUI(); - - /** - * Create a HTML-formatted rails.game status report. - * - * @return - */ - public abstract List<String> getGameReport(); - - /** - * Should be called whenever a Phase changes. The effect on the number of - * ORs is delayed until a StockRound finishes. - * - */ - public abstract RoundI getCurrentRound(); - - /** - * @return Returns the currentPlayerIndex. - */ - public abstract int getCurrentPlayerIndex(); - - /** - * @param currentPlayerIndex The currentPlayerIndex to set. - */ - public abstract void setCurrentPlayerIndex(int currentPlayerIndex); - - public abstract void setCurrentPlayer(Player player); - - /** - * Set priority deal to the player after the current player. - * - */ - public abstract void setPriorityPlayer(); - - public abstract void setPriorityPlayer(Player player); - - /** - * @return Returns the priorityPlayer. - */ - public abstract Player getPriorityPlayer(); - - /** - * @return Returns the currentPlayer. - */ - public abstract Player getCurrentPlayer(); - - /** - * @return Returns the players. - */ - public abstract List<Player> getPlayers(); - - public abstract int getNumberOfPlayers(); - - public abstract List<String> getPlayerNames(); - - public abstract List<PublicCompanyI> getAllPublicCompanies(); - - public abstract List<PrivateCompanyI> getAllPrivateCompanies(); - - /** - * Return a player by its index in the list, modulo the number of players. - * - * @param index The player index. - * @return A player object. - */ - public abstract Player getPlayerByIndex(int index); - - public abstract void setNextPlayer(); - - public void addPortfolio (Portfolio portfolio); - public Portfolio getPortfolioByName (String name); - - /** - * @return the StartPacket - */ - public abstract StartPacket getStartPacket(); - - /** - * @return Current phase - */ - public abstract PhaseI getCurrentPhase(); - - public abstract PhaseManager getPhaseManager(); - public void initialiseNewPhase(PhaseI phase); - - public abstract TrainManager getTrainManager (); - public PlayerManager getPlayerManager(); - public TileManager getTileManager(); - public StockMarketI getStockMarket(); - public MapManager getMapManager(); - public RevenueManager getRevenueManager(); - public Bank getBank (); - - public String getGameName (); - public String getGameOption (String key); - - public int getPlayerCertificateLimit(Player player); - public void setPlayerCertificateLimit(int newLimit); - public ModelObject getPlayerCertificateLimitModel (); - - public abstract String getHelp(); - - public abstract boolean canAnyCompanyHoldShares(); - - public abstract String getClassName(GuiDef.ClassName key); - - public abstract Object getGuiParameter(GuiDef.Parm key); - public Object getGameParameter (GameDef.Parm key); - public void setGameParameter (GameDef.Parm key, Object value); - - public RoundI getInterruptedRound(); - - public List<SpecialPropertyI> getCommonSpecialProperties (); - public <T extends SpecialPropertyI> List<T> getSpecialProperties( - Class<T> clazz, boolean includeExercised); - - public String getGMKey (); - public MoveStack getMoveStack (); - public DisplayBuffer getDisplayBuffer(); - public void addToNextPlayerMessages(String s, boolean undoable); - public ReportBuffer getReportBuffer(); - public GuiHints getUIHints(); - - public CorrectionManagerI getCorrectionManager(CorrectionType ct); +package rails.game; + +import java.util.List; +import java.util.Map; + +import rails.algorithms.RevenueManager; +import rails.common.GuiDef; +import rails.common.GuiHints; +import rails.game.action.PossibleAction; +import rails.game.correct.CorrectionManagerI; +import rails.game.correct.CorrectionType; +import rails.game.model.ModelObject; +import rails.game.move.MoveStack; +import rails.game.move.MoveableHolder; +import rails.game.special.SpecialPropertyI; + +public interface GameManagerI extends MoveableHolder, ConfigurableComponentI { + + /** + * @see rails.game.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) + */ + public abstract void init(String gameName, PlayerManager playerManager, + CompanyManagerI companyManager, PhaseManager phaseManager, + TrainManager trainManager, StockMarketI stockMarket, + MapManager mapManager, TileManager tileManager, + RevenueManager revenueManager, Bank bank); + public abstract void startGame(Map<String, String> gameOptions); + + public abstract CompanyManagerI getCompanyManager(); + + /** + * Should be called by each Round when it finishes. + * + * @param round The object that represents the finishing round. + */ + public abstract void nextRound(RoundI round); + + public String getORId (); + public abstract String getCompositeORNumber(); + public int getRelativeORNumber(); + + public abstract int getSRNumber(); + + public abstract void startShareSellingRound(Player sellingPlayer, + int cashToRaise, PublicCompanyI unsellableCompany); + + public abstract void startTreasuryShareTradingRound(); + + /** + * The central server-side method that takes a client-side initiated action + * and processes it. + * + * @param action A PossibleAction subclass object sent by the client. + * @return TRUE is the action was valid. + */ + public abstract boolean process(PossibleAction action); + + public abstract boolean processOnReload(List<PossibleAction> actions) + throws Exception; + + public abstract void finishShareSellingRound(); + + public abstract void finishTreasuryShareRound(); + + public abstract void registerBankruptcy(); + + public abstract void registerBrokenBank(); + + /** + * To be called by the UI to check if the rails.game is over. + * + * @return + */ + public abstract boolean isGameOver(); + + public void setGameOverReportedUI(boolean b); + + public boolean getGameOverReportedUI(); + + /** + * Create a HTML-formatted rails.game status report. + * + * @return + */ + public abstract List<String> getGameReport(); + + /** + * Should be called whenever a Phase changes. The effect on the number of + * ORs is delayed until a StockRound finishes. + * + */ + public abstract RoundI getCurrentRound(); + + /** + * @return Returns the currentPlayerIndex. + */ + public abstract int getCurrentPlayerIndex(); + + /** + * @param currentPlayerIndex The currentPlayerIndex to set. + */ + public abstract void setCurrentPlayerIndex(int currentPlayerIndex); + + public abstract void setCurrentPlayer(Player player); + + /** + * Set priority deal to the player after the current player. + * + */ + public abstract void setPriorityPlayer(); + + public abstract void setPriorityPlayer(Player player); + + /** + * @return Returns the priorityPlayer. + */ + public abstract Player getPriorityPlayer(); + + /** + * @return Returns the currentPlayer. + */ + public abstract Player getCurrentPlayer(); + + /** + * @return Returns the players. + */ + public abstract List<Player> getPlayers(); + + public abstract int getNumberOfPlayers(); + + public abstract List<String> getPlayerNames(); + + public abstract List<PublicCompanyI> getAllPublicCompanies(); + + public abstract List<PrivateCompanyI> getAllPrivateCompanies(); + + /** + * Return a player by its index in the list, modulo the number of players. + * + * @param index The player index. + * @return A player object. + */ + public abstract Player getPlayerByIndex(int index); + + public abstract void setNextPlayer(); + + public void addPortfolio (Portfolio portfolio); + public Portfolio getPortfolioByName (String name); + + /** + * @return the StartPacket + */ + public abstract StartPacket getStartPacket(); + + /** + * @return Current phase + */ + public abstract PhaseI getCurrentPhase(); + + public abstract PhaseManager getPhaseManager(); + public void initialiseNewPhase(PhaseI phase); + + public abstract TrainManager getTrainManager (); + public PlayerManager getPlayerManager(); + public TileManager getTileManager(); + public StockMarketI getStockMarket(); + public MapManager getMapManager(); + public RevenueManager getRevenueManager(); + public Bank getBank (); + + public String getGameName (); + public String getGameOption (String key); + + public int getPlayerCertificateLimit(Player player); + public void setPlayerCertificateLimit(int newLimit); + public ModelObject getPlayerCertificateLimitModel (); + + public abstract String getHelp(); + + public abstract boolean canAnyCompanyHoldShares(); + + public abstract String getClassName(GuiDef.ClassName key); + + public abstract Object getGuiParameter(GuiDef.Parm key); + public Object getGameParameter (GameDef.Parm key); + public void setGameParameter (GameDef.Parm key, Object value); + + public RoundI getInterruptedRound(); + + public List<SpecialPropertyI> getCommonSpecialProperties (); + public <T extends SpecialPropertyI> List<T> getSpecialProperties( + Class<T> clazz, boolean includeExercised); + + public String getGMKey (); + public MoveStack getMoveStack (); + public DisplayBuffer getDisplayBuffer(); + public void addToNextPlayerMessages(String s, boolean undoable); + public ReportBuffer getReportBuffer(); + public GuiHints getUIHints(); + + public CorrectionManagerI getCorrectionManager(CorrectionType ct); + public List<PublicCompanyI> getCompaniesInRunningOrder (); + } \ No newline at end of file Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2010-07-04 15:17:14 UTC (rev 1330) +++ trunk/18xx/rails/game/StockRound.java 2010-07-04 20:44:29 UTC (rev 1331) @@ -1,12 +1,29 @@ package rails.game; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import rails.common.GuiDef; -import rails.game.action.*; -import rails.game.move.*; -import rails.game.special.*; -import rails.game.state.*; +import rails.game.action.BuyCertificate; +import rails.game.action.NullAction; +import rails.game.action.PossibleAction; +import rails.game.action.RequestTurn; +import rails.game.action.SellShares; +import rails.game.action.StartCompany; +import rails.game.action.UseSpecialProperty; +import rails.game.move.AddToList; +import rails.game.move.CashMove; +import rails.game.move.DoubleMapChange; +import rails.game.special.ExchangeForShare; +import rails.game.special.SpecialProperty; +import rails.game.special.SpecialPropertyI; +import rails.game.state.BooleanState; +import rails.game.state.IntegerState; +import rails.game.state.State; import rails.util.LocalText; /** @@ -23,22 +40,22 @@ protected Player startingPlayer; protected State companyBoughtThisTurnWrapper = - new State("CompanyBoughtThisTurn", PublicCompany.class); + new State("CompanyBoughtThisTurn", PublicCompany.class); protected BooleanState hasSoldThisTurnBeforeBuying = - new BooleanState("HoldSoldBeforeBuyingThisTurn", false); + new BooleanState("HoldSoldBeforeBuyingThisTurn", false); protected BooleanState hasActed = new BooleanState("HasActed", false); // Is protected IntegerState numPasses = new IntegerState("StockRoundPasses"); protected Map<String, StockSpaceI> sellPrices = - new HashMap<String, StockSpaceI>(); + new HashMap<String, StockSpaceI>(); /* Transient data needed for rule enforcing */ /** HashMap per player containing a HashMap per company */ protected HashMap<Player, HashMap<PublicCompanyI, Object>> playersThatSoldThisRound = - new HashMap<Player, HashMap<PublicCompanyI, Object>>(); + new HashMap<Player, HashMap<PublicCompanyI, Object>>(); /* Rule constants */ static protected final int SELL_BUY_SELL = 0; @@ -74,7 +91,7 @@ public void start() { ReportBuffer.add(LocalText.getText("StartStockRound", - getStockRoundNumber())); + getStockRoundNumber())); setCurrentPlayerIndex(gameManager.getPriorityPlayer().getIndex()); startingPlayer = getCurrentPlayer(); // For the Report @@ -157,17 +174,17 @@ /* Get the next available IPO certificates */ // Never buy more than one from the IPO PublicCompanyI companyBoughtThisTurn = - (PublicCompanyI) companyBoughtThisTurnWrapper.getObject(); + (PublicCompanyI) companyBoughtThisTurnWrapper.getObject(); if (companyBoughtThisTurn == null) { from = ipo; Map<String, List<PublicCertificateI>> map = - from.getCertsPerCompanyMap(); + from.getCertsPerCompanyMap(); int shares; for (String compName : map.keySet()) { certs = map.get(compName); if (certs == null || certs.isEmpty()) continue; - + /* Only the top certificate is buyable from the IPO */ int lowestIndex = 99; cert = null; @@ -179,7 +196,7 @@ cert = c; } } - + comp = cert.getCompany(); unitsForPrice = comp.getShareUnitsForSharePrice(); if (isSaleRecorded(currentPlayer, comp)) continue; @@ -223,7 +240,7 @@ /* Get the unique Pool certificates and check which ones can be bought */ from = pool; Map<String, List<PublicCertificateI>> map = - from.getCertsPerCompanyMap(); + from.getCertsPerCompanyMap(); /* Allow for multiple share unit certificates (e.g. 1835) */ PublicCertificateI[] uniqueCerts; int[] numberOfCerts; @@ -241,7 +258,7 @@ price = stockSpace.getPrice() / unitsForPrice; shareUnit = comp.getShareUnit(); maxNumberOfSharesToBuy - = maxAllowedNumberOfSharesToBuy(currentPlayer, comp, shareUnit); + = maxAllowedNumberOfSharesToBuy(currentPlayer, comp, shareUnit); /* Checks if the player can buy any shares of this company */ if (maxNumberOfSharesToBuy < 1) continue; @@ -279,7 +296,7 @@ /* Would the player exceed the total certificate limit? */ if (!stockSpace.isNoCertLimit() - && !mayPlayerBuyCertificate(currentPlayer, comp, number)) + && !mayPlayerBuyCertificate(currentPlayer, comp, number)) continue; } @@ -301,8 +318,8 @@ for (PublicCompanyI company : companyManager.getAllPublicCompanies()) { certs = - company.getPortfolio().getCertificatesPerCompany( - company.getName()); + company.getPortfolio().getCertificatesPerCompany( + company.getName()); if (certs == null || certs.isEmpty()) continue; cert = certs.get(0); if (isSaleRecorded(currentPlayer, company)) continue; @@ -311,7 +328,7 @@ certs.get(0).getShare()) < 1) continue; stockSpace = company.getCurrentSpace(); if (!stockSpace.isNoCertLimit() - && !mayPlayerBuyCertificate(currentPlayer, company, 1)) continue; + && !mayPlayerBuyCertificate(currentPlayer, company, 1)) continue; if (company.getMarketPrice() <= playerCash) { possibleActions.add(new BuyCertificate(cert, company.getPortfolio(), company.getMarketPrice())); @@ -347,16 +364,16 @@ // In some games, can't sell shares if not operated if (company.mustHaveOperatedToTradeShares() - && !company.hasOperated()) continue; + && !company.hasOperated()) continue; share = maxShareToSell = playerPortfolio.getShare(company); if (maxShareToSell == 0) continue; /* May not sell more than the Pool can accept */ maxShareToSell = - Math.min(maxShareToSell, - getGameParameterAsInt(GameDef.Parm.POOL_SHARE_LIMIT) - - pool.getShare(company)); + Math.min(maxShareToSell, + getGameParameterAsInt(GameDef.Parm.POOL_SHARE_LIMIT) + - pool.getShare(company)); if (maxShareToSell == 0) continue; /* @@ -365,7 +382,7 @@ */ if (company.getPresident() == currentPlayer) { int presidentShare = - company.getCertificates().get(0).getShare(); + company.getCertificates().get(0).getShare(); if (maxShareToSell > share - presidentShare) { dumpAllowed = false; int playerShare; @@ -416,14 +433,14 @@ number = shareCountPerUnit[i]; if (number == 0) continue; number = - Math.min(number, maxShareToSell - / (i * company.getShareUnit())); + Math.min(number, maxShareToSell + / (i * company.getShareUnit())); /* In some games (1856), a just bought share may not be sold */ // This code ignores the possibility of different share units if ((Boolean)gameManager.getGameParameter(GameDef.Parm.NO_SALE_OF_JUST_BOUGHT_CERT) - && company.equals(companyBoughtThisTurnWrapper.getObject())) { - number--; + && company.equals(companyBoughtThisTurnWrapper.getObject())) { + number--; } if (number <= 0) continue; @@ -436,8 +453,8 @@ protected void setSpecialActions() { List<SpecialProperty> sps = - currentPlayer.getPortfolio().getSpecialProperties( - SpecialProperty.class, false); + currentPlayer.getPortfolio().getSpecialProperties( + SpecialProperty.class, false); for (SpecialPropertyI sp : sps) { if (sp.isUsableDuringSR()) { possibleActions.add(new UseSpecialProperty(sp)); @@ -464,7 +481,7 @@ break; case NullAction.AUTOPASS: result = done(playerName, true); - break; + break; } } else if (action instanceof StartCompany) { @@ -554,7 +571,7 @@ // The company may not have started yet. if (company.hasStarted()) { errMsg = - LocalText.getText("CompanyAlreadyStarted", companyName); + LocalText.getText("CompanyAlreadyStarted", companyName); break; } @@ -581,8 +598,8 @@ // Else the given price must be a valid start price if ((startSpace = stockMarket.getStartSpace(price)) == null) { errMsg = LocalText.getText("InvalidStartPrice", - Bank.format(price), - company.getName() ); + Bank.format(price), + company.getName() ); break; } } @@ -695,9 +712,9 @@ // The player may not have sold the company this round. if (isSaleRecorded(currentPlayer, company)) { errMsg = - LocalText.getText("AlreadySoldThisTurn", - currentPlayer.getName(), - companyName ); + LocalText.getText("AlreadySoldThisTurn", + currentPlayer.getName(), + companyName ); break; } @@ -709,9 +726,9 @@ // The player may not have bought this turn, unless the company // bought before and now is in the brown area. PublicCompanyI companyBoughtThisTurn = - (PublicCompanyI) companyBoughtThisTurnWrapper.getObject(); + (PublicCompanyI) companyBoughtThisTurnWrapper.getObject(); if (companyBoughtThisTurn != null - && (companyBoughtThisTurn != company || !company.getCurrentSpace().isNoBuyLimit())) { + && (companyBoughtThisTurn != company || !company.getCurrentSpace().isNoBuyLimit())) { errMsg = LocalText.getText("AlreadyBought", playerName); break; } @@ -719,9 +736,9 @@ // Check if that many shares are available if (shares > from.getShare(company)) { errMsg = - LocalText.getText("NotAvailable", - companyName, - from.getName() ); + LocalText.getText("NotAvailable", + companyName, + from.getName() ); break; } @@ -742,20 +759,20 @@ // Check if player would not exceed the certificate limit. // (shortcut: assume 1 cert == 1 certificate) if (!currentSpace.isNoCertLimit() - && !mayPlayerBuyCertificate(currentPlayer, company, number)) { + && !mayPlayerBuyCertificate(currentPlayer, company, number)) { errMsg = - currentPlayer.getName() - + LocalText.getText("WouldExceedCertLimit", - String.valueOf(gameManager.getPlayerCertificateLimit(currentPlayer))); + currentPlayer.getName() + + LocalText.getText("WouldExceedCertLimit", + String.valueOf(gameManager.getPlayerCertificateLimit(currentPlayer))); break; } // Check if player would exceed the per-company share limit if (!currentSpace.isNoHoldLimit() - && !checkAgainstHoldLimit(currentPlayer, company, shares)) { - errMsg = LocalText.getText("WouldExceedHoldLimit", - currentPlayer.getName(), - GameDef.Parm.PLAYER_SHARE_LIMIT.defaultValueAsInt()); + && !checkAgainstHoldLimit(currentPlayer, company, shares)) { + errMsg = LocalText.getText("WouldExceedHoldLimit", + currentPlayer.getName(), + GameDef.Parm.PLAYER_SHARE_LIMIT.defaultValueAsInt()); break; } @@ -811,7 +828,7 @@ cert2 = from.findCertificate(company, cert.getShares(), false); if (cert2 == null) { log.error("Cannot find " + companyName + " " + shareUnit - + "% share in " + from.getName()); + + "% share in " + from.getName()); } cert2.moveTo(currentPlayer.getPortfolio()); } @@ -845,13 +862,13 @@ PublicCompanyI company) { } - + /** Allow different price setting in subclasses (i.e. 1835 Nationalisation) */ protected int getBuyPrice (BuyCertificate action, StockSpaceI currentSpace) { return currentSpace.getPrice(); } - /** + /** * Who receives the cash when a certificate is bought. * With incremental capitalization, this can be the company treasure. * This method must be called <i>before</i> transferring the certificate. @@ -864,8 +881,8 @@ PublicCompanyI comp; CashHolder recipient; if ((comp = (cert).getCompany()).hasFloated() - && oldHolder == ipo - && comp.getCapitalisation() == PublicCompanyI.CAPITALISE_INCREMENTAL) { + && oldHolder == ipo + && comp.getCapitalisation() == PublicCompanyI.CAPITALISE_INCREMENTAL) { recipient = comp; } else { recipient = oldHolder.getOwner(); @@ -873,7 +890,7 @@ return recipient; } - /** Make the certificates of one company available for buying + /** Make the certificates of one company available for buying * by putting these in the IPO. * @param company The company to be released. */ @@ -893,8 +910,8 @@ protected boolean isSaleRecorded(Player player, PublicCompanyI company) { return playersThatSoldThisRound.containsKey(currentPlayer) - && playersThatSoldThisRound.get(currentPlayer).containsKey( - company); + && playersThatSoldThisRound.get(currentPlayer).containsKey( + company); } public boolean sellShares(SellShares action) @@ -906,11 +923,11 @@ String errMsg = null; String companyName = action.getCompanyName(); PublicCompanyI company = - companyManager.getPublicCompany(action.getCompanyName()); + companyManager.getPublicCompany(action.getCompanyName()); PublicCertificateI cert = null; PublicCertificateI presCert = null; List<PublicCertificateI> certsToSell = - new ArrayList<PublicCertificateI>(); + new ArrayList<PublicCertificateI>(); Player dumpedPlayer = null; int presSharesToSell = 0; int numberToSell = action.getNumberSold(); @@ -957,7 +974,7 @@ // Find the certificates to sell Iterator<PublicCertificateI> it = - portfolio.getCertificatesPerCompany(companyName).iterator(); + portfolio.getCertificatesPerCompany(companyName).iterator(); while (numberToSell > 0 && it.hasNext()) { cert = it.next(); if (cert.isPresidentShare()) { @@ -1062,7 +1079,7 @@ // First swap the certificates Portfolio dumpedPortfolio = dumpedPlayer.getPortfolio(); List<PublicCertificateI> swapped = - portfolio.swapPresidentCertificate(company, dumpedPortfolio); + portfolio.swapPresidentCertificate(company, dumpedPortfolio); for (int i = 0; i < presSharesToSell; i++) { certsToSell.add(swapped.get(i)); } @@ -1106,7 +1123,7 @@ } protected void adjustSharePrice (PublicCompanyI company, int numberSold, boolean soldBefore) { - + if (company.canSharePriceVary()) { stockMarket.sell(company, numberSold); } @@ -1132,7 +1149,7 @@ public boolean executeExchangeForShare (ExchangeForShare sp) { PublicCompanyI publicCompany = - companyManager.getPublicCompany(sp.getPublicCompanyName()); + companyManager.getPublicCompany(sp.getPublicCompanyName()); CompanyI privateCompany = sp.getOriginalCompany(); Portfolio portfolio = privateCompany.getPortfolio(); Player player = null; @@ -1145,8 +1162,8 @@ /* Check if the private is owned by a player */ if (!(portfolio.getOwner() instanceof Player)) { errMsg = - LocalText.getText("PrivateIsNotOwnedByAPlayer", - privateCompany.getName()); + LocalText.getText("PrivateIsNotOwnedByAPlayer", + privateCompany.getName()); break; } @@ -1155,16 +1172,16 @@ /* Check if a share is available */ if (!ipoHasShare && !poolHasShare) { errMsg = - LocalText.getText("NoSharesAvailable", - publicCompany.getName()); + LocalText.getText("NoSharesAvailable", + publicCompany.getName()); break; } /* Check if the player has room for a share of this company */ if (!checkAgainstHoldLimit(player, publicCompany, 1)) { // TODO: Not nice to use '1' here, should be percentage. errMsg = - LocalText.getText("WouldExceedHoldLimit", - String.valueOf(getGameParameterAsInt(GameDef.Parm.PLAYER_SHARE_LIMIT))); + LocalText.getText("WouldExceedHoldLimit", + String.valueOf(getGameParameterAsInt(GameDef.Parm.PLAYER_SHARE_LIMIT))); break; } break; @@ -1172,33 +1189,33 @@ if (errMsg != null) { DisplayBuffer.add(LocalText.getText( "CannotSwapPrivateForCertificate", - player.getName(), - privateCompany.getName(), - sp.getShare(), - publicCompany.getName(), - errMsg )); + player.getName(), + privateCompany.getName(), + sp.getShare(), + publicCompany.getName(), + errMsg )); return false; } moveStack.start(true); Certificate cert = - ipoHasShare ? ipo.findCertificate(publicCompany, - false) : pool.findCertificate(publicCompany, - false); - cert.moveTo(player.getPortfolio()); - ReportBuffer.add(LocalText.getText("SwapsPrivateForCertificate", - player.getName(), - privateCompany.getName(), - sp.getShare(), - publicCompany.getName())); - sp.setExercised(); - privateCompany.setClosed(); + ipoHasShare ? ipo.findCertificate(publicCompany, + false) : pool.findCertificate(publicCompany, + false); + cert.moveTo(player.getPortfolio()); + ReportBuffer.add(LocalText.getText("SwapsPrivateForCertificate", + player.getName(), + privateCompany.getName(), + sp.getShare(), + publicCompany.getName())); + sp.setExercised(); + privateCompany.setClosed(); - // Check if the company has floated - if (!publicCompany.hasFloated()) checkFlotation(publicCompany); + // Check if the company has floated + if (!publicCompany.hasFloated()) checkFlotation(publicCompany); - return true; + return true; } /** @@ -1237,31 +1254,6 @@ if (numPasses.intValue() >= getNumberOfActivePlayers()) { - ReportBuffer.add(LocalText.getText("END_SR", - String.valueOf(getStockRoundNumber()))); - - /* Check if any companies are sold out. */ - for (PublicCompanyI company : companyManager.getAllPublicCompanies()) { - if (company.hasStockPrice() && company.isSoldOut()) { - StockSpaceI oldSpace = company.getCurrentSpace(); - stockMarket.soldOut(company); - StockSpaceI newSpace = company.getCurrentSpace(); - if (newSpace != oldSpace) { - ReportBuffer.add(LocalText.getText("SoldOut", - company.getName(), - Bank.format(oldSpace.getPrice()), - oldSpace.getName(), - Bank.format(newSpace.getPrice()), - newSpace.getName())); - } else { - ReportBuffer.add(LocalText.getText("SoldOutNoRaise", - company.getName(), - Bank.format(newSpace.getPrice()), - newSpace.getName())); - } - } - } - finishRound(); } else { @@ -1272,6 +1264,37 @@ return true; } + @Override + protected void finishRound () { + + ReportBuffer.add(LocalText.getText("END_SR", + String.valueOf(getStockRoundNumber()))); + + /* Check if any companies are sold out. */ + for (PublicCompanyI company : gameManager.getCompaniesInRunningOrder()) { + if (company.hasStockPrice() && company.isSoldOut()) { + StockSpaceI oldSpace = company.getCurrentSpace(); + stockMarket.soldOut(company); + StockSpaceI newSpace = company.getCurrentSpace(); + if (newSpace != oldSpace) { + ReportBuffer.add(LocalText.getText("SoldOut", + company.getName(), + Bank.format(oldSpace.getPrice()), + oldSpace.getName(), + Bank.format(newSpace.getPrice()), + newSpace.getName())); + } else { + ReportBuffer.add(LocalText.getText("SoldOutNoRaise", + company.getName(), + Bank.format(newSpace.getPrice()), + newSpace.getName())); + } + } + } + + super.finishRound(); + } + protected boolean requestTurn (RequestTurn action) { Player requestingPlayer = playerManager.getPlayerByName(action.getRequestingPlayerName()); @@ -1331,6 +1354,7 @@ gameManager.setPriorityPlayer(); } + @Override public void setCurrentPlayer(Player player) { super.setCurrentPlayer(player); currentPlayer = player; @@ -1356,8 +1380,8 @@ if (getStockRoundNumber() == 1 && noSaleInFirstSR()) return false; if (companyBoughtThisTurnWrapper.getObject() != null - && (sequenceRule == SELL_BUY_OR_BUY_SELL - && hasSoldThisTurnBeforeBuying.booleanValue() || sequenceRule == SELL_BUY)) + ... [truncated message content] |
From: <ev...@us...> - 2010-07-04 20:51:40
|
Revision: 1332 http://rails.svn.sourceforge.net/rails/?rev=1332&view=rev Author: evos Date: 2010-07-04 20:51:33 +0000 (Sun, 04 Jul 2010) Log Message: ----------- Fixed import expansion Modified Paths: -------------- trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/StockRound.java Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-07-04 20:44:29 UTC (rev 1331) +++ trunk/18xx/rails/game/GameManager.java 2010-07-04 20:51:33 UTC (rev 1332) @@ -1,22 +1,10 @@ /* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/GameManager.java,v 1.107 2010/06/17 21:35:54 evos Exp $ */ package rails.game; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.io.PrintWriter; +import java.io.*; import java.lang.reflect.Constructor; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.EnumMap; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; +import java.util.*; import org.apache.log4j.Logger; import org.apache.log4j.NDC; @@ -24,28 +12,13 @@ import rails.algorithms.RevenueManager; import rails.common.GuiDef; import rails.common.GuiHints; -import rails.game.action.GameAction; -import rails.game.action.NullAction; -import rails.game.action.PossibleAction; -import rails.game.action.PossibleActions; -import rails.game.action.RepayLoans; -import rails.game.correct.CorrectionAction; -import rails.game.correct.CorrectionManagerI; -import rails.game.correct.CorrectionType; -import rails.game.move.AddToList; -import rails.game.move.CashMove; -import rails.game.move.MoveStack; -import rails.game.move.Moveable; +import rails.game.action.*; +import rails.game.correct.*; +import rails.game.move.*; import rails.game.special.SpecialPropertyI; import rails.game.special.SpecialTokenLay; -import rails.game.state.BooleanState; -import rails.game.state.IntegerState; -import rails.game.state.State; -import rails.util.BuildInfo; -import rails.util.Config; -import rails.util.LocalText; -import rails.util.Tag; -import rails.util.Util; +import rails.game.state.*; +import rails.util.*; /** * This class manages the playing rounds by supervising all implementations of Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2010-07-04 20:44:29 UTC (rev 1331) +++ trunk/18xx/rails/game/StockRound.java 2010-07-04 20:51:33 UTC (rev 1332) @@ -1,29 +1,12 @@ package rails.game; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; import rails.common.GuiDef; -import rails.game.action.BuyCertificate; -import rails.game.action.NullAction; -import rails.game.action.PossibleAction; -import rails.game.action.RequestTurn; -import rails.game.action.SellShares; -import rails.game.action.StartCompany; -import rails.game.action.UseSpecialProperty; -import rails.game.move.AddToList; -import rails.game.move.CashMove; -import rails.game.move.DoubleMapChange; -import rails.game.special.ExchangeForShare; -import rails.game.special.SpecialProperty; -import rails.game.special.SpecialPropertyI; -import rails.game.state.BooleanState; -import rails.game.state.IntegerState; -import rails.game.state.State; +import rails.game.action.*; +import rails.game.move.*; +import rails.game.special.*; +import rails.game.state.*; import rails.util.LocalText; /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-07-17 22:45:34
|
Revision: 1347 http://rails.svn.sourceforge.net/rails/?rev=1347&view=rev Author: evos Date: 2010-07-17 22:45:27 +0000 (Sat, 17 Jul 2010) Log Message: ----------- Allow the old object positions in more than one list to be saved in ObjectMove. This should restore ALL lists affected by ObjectMove into original order after an Undo. Modified Paths: -------------- trunk/18xx/rails/game/Bank.java trunk/18xx/rails/game/City.java trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/MapHex.java trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/Portfolio.java trunk/18xx/rails/game/PrivateCompany.java trunk/18xx/rails/game/PublicCompany.java trunk/18xx/rails/game/TrainType.java trunk/18xx/rails/game/move/Moveable.java trunk/18xx/rails/game/move/MoveableHolder.java trunk/18xx/rails/game/move/ObjectMove.java trunk/18xx/rails/game/move/RemoveFromList.java Modified: trunk/18xx/rails/game/Bank.java =================================================================== --- trunk/18xx/rails/game/Bank.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/Bank.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -107,9 +107,9 @@ for (PublicCompanyI comp : companies) { for (PublicCertificateI cert : comp.getCertificates()) { if (cert.isInitiallyAvailable()) { - ipo.addCertificate(cert, -1); + ipo.addCertificate(cert); } else { - unavailable.addCertificate(cert, -1); + unavailable.addCertificate(cert); } } } Modified: trunk/18xx/rails/game/City.java =================================================================== --- trunk/18xx/rails/game/City.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/City.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -23,7 +23,7 @@ * tile. However, the City numbers will not change, unless cities are merged * during upgrades; but even then it is attempted to retain the old city numbers * as much as possible. - * + * * @author Erik Vos */ public class City implements TokenHolder { @@ -100,9 +100,9 @@ return result; } - public boolean addObject(Moveable object, int position) { + public boolean addObject(Moveable object, int[] position) { if (object instanceof TokenI) { - return addToken((TokenI) object, position); + return addToken((TokenI) object, position == null ? -1 : position[0]); } else { return false; } @@ -163,11 +163,11 @@ return false; } - public int getListIndex (Moveable object) { + public int[] getListIndex (Moveable object) { if (object instanceof BaseToken) { - return tokens.indexOf(object); + return new int[] {tokens.indexOf(object)}; } else { - return -1; + return Moveable.AT_END; } } Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/GameManager.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -1500,21 +1500,21 @@ * @param object The object to add. * @return True if successful. */ - public boolean addObject(Moveable object, int position) { + public boolean addObject(Moveable object, int[] position) { if (object instanceof SpecialPropertyI) { SpecialPropertyI sp = (SpecialPropertyI) object; sp.setHolder(null); - return addSpecialProperty(sp, position); + return addSpecialProperty(sp, position == null ? -1 : position[0]); } else { return false; } } - public int getListIndex (Moveable object) { + public int[] getListIndex (Moveable object) { if (object instanceof SpecialPropertyI) { - return commonSpecialProperties.indexOf(object); + return new int[] {commonSpecialProperties.indexOf(object)}; } else { - return -1; + return Moveable.AT_END; } } Modified: trunk/18xx/rails/game/MapHex.java =================================================================== --- trunk/18xx/rails/game/MapHex.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/MapHex.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -827,9 +827,9 @@ return offStationTokens.remove(token); } - public boolean addObject(Moveable object, int position) { + public boolean addObject(Moveable object, int[] position) { if (object instanceof TokenI) { - return addToken((TokenI) object, position); + return addToken((TokenI) object, position == null ? -1 : position[0]); } else { return false; } @@ -843,11 +843,11 @@ } } - public int getListIndex (Moveable object) { + public int[] getListIndex (Moveable object) { if (object instanceof TokenI) { - return offStationTokens.indexOf(object); + return new int[] {offStationTokens.indexOf(object)}; } else { - return -1; + return Moveable.AT_END; } } @@ -1015,7 +1015,7 @@ * NOTE: this method currently only checks for prohibitions caused * by the presence of unlaid home base tokens. * It does NOT (yet) check for free space. - * + * * Remark: There are the following cases to check * A) isBlockedForTokenLays is active for the MapHex => return the state of this * (Example: Erie home base in 1830) Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/OperatingRound.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -1716,7 +1716,7 @@ train.getType().addToBoughtFromIPO(); // Clone the train if infinitely available if (train.getType().hasInfiniteAmount()) { - ipo.addTrain(train.getType().cloneTrain(), -1); + ipo.addTrain(train.getType().cloneTrain()); } } @@ -2670,7 +2670,7 @@ * This method can be extended to perform other generic checks, * such as if a route exists, * and possibly in subclasses for game-specific checks. - * + * * @param company The company laying a tile. * @param hex The hex on which a tile is laid. * @param station The number of the station/city on which the token Modified: trunk/18xx/rails/game/Portfolio.java =================================================================== --- trunk/18xx/rails/game/Portfolio.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/Portfolio.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -121,23 +121,28 @@ privatesOwnedModel.update(); } - public void addCertificate(PublicCertificateI certificate, int position) { + public void addCertificate(PublicCertificateI certificate){ + addCertificate (certificate, new int[] {-1,-1,-1}); + } + + public void addCertificate(PublicCertificateI certificate, int[] position) { // When undoing a company start, put the President back at the top. - if (certificate.isPresidentShare()) position = 0; + if (certificate.isPresidentShare()) position = new int[] {0,0,0}; + Util.addToList(certificates, certificate, position[0]); + String companyName = certificate.getCompany().getName(); if (!certPerCompany.containsKey(companyName)) { certPerCompany.put(companyName, new ArrayList<PublicCertificateI>()); } - Util.addToList(certificates, certificate, position); - (certPerCompany.get(companyName)).add(certificate); + Util.addToList(certPerCompany.get(companyName), certificate, position[1]); String certTypeId = certificate.getTypeId(); if (!certsPerType.containsKey(certTypeId)) { certsPerType.put(certTypeId, new ArrayList<PublicCertificateI>()); } - certsPerType.get(certTypeId).add(certificate); + Util.addToList(certsPerType.get(certTypeId), certificate, position[2]); certificate.setPortfolio(this); @@ -373,14 +378,18 @@ return swapped; } - public void addTrain(TrainI train, int position) { + public void addTrain (TrainI train) { + addTrain (train, new int[] {-1,-1}); + } - Util.addToList(trains, train, position); + public void addTrain(TrainI train, int[] position) { + + Util.addToList(trains, train, position[0]); TrainTypeI type = train.getType(); if (!trainsPerType.containsKey(type)) { trainsPerType.put(type, new ArrayList<TrainI>()); } - trainsPerType.get(train.getType()).add(train); + Util.addToList(trainsPerType.get(train.getType()), train, position[1]); train.setHolder(this); trainsModel.update(); } @@ -574,20 +583,22 @@ * @param object The object to add. * @return True if successful. */ - public boolean addObject(Moveable object, int position) { + public boolean addObject(Moveable object, int[] position) { if (object instanceof PublicCertificateI) { + if (position == null) position = new int[] {-1, -1, -1}; addCertificate((PublicCertificateI) object, position); return true; } else if (object instanceof PrivateCompanyI) { - addPrivate((PrivateCompanyI) object, position); + addPrivate((PrivateCompanyI) object, position == null ? -1 : position[0]); return true; } else if (object instanceof TrainI) { + if (position == null) position = new int[] {-1, -1}; addTrain((TrainI) object, position); return true; } else if (object instanceof SpecialPropertyI) { - return addSpecialProperty((SpecialPropertyI) object, position); + return addSpecialProperty((SpecialPropertyI) object, position == null ? -1 : position[0]); } else if (object instanceof TokenI) { - return addToken((TokenI) object, position); + return addToken((TokenI) object, position == null ? -1 : position[0]); } else { return false; } @@ -618,19 +629,28 @@ } } - public int getListIndex (Moveable object) { + public int[] getListIndex (Moveable object) { if (object instanceof PublicCertificateI) { - return certificates.indexOf(object); + PublicCertificateI cert = (PublicCertificateI) object; + return new int[] { + certificates.indexOf(object), + certPerCompany.get(cert.getCompany().getName()).indexOf(cert), + certsPerType.get(cert.getTypeId()).indexOf(cert) + }; } else if (object instanceof PrivateCompanyI) { - return privateCompanies.indexOf(object); + return new int[] {privateCompanies.indexOf(object)}; } else if (object instanceof TrainI) { - return trains.indexOf(object); + TrainI train = (TrainI) object; + return new int[] { + trains.indexOf(train), + trainsPerType.get(train.getType()).indexOf(train) + }; } else if (object instanceof SpecialPropertyI) { - return specialProperties.indexOf(object); + return new int[] {specialProperties.indexOf(object)}; } else if (object instanceof TokenI) { - return tokens.indexOf(object); + return new int[] {tokens.indexOf(object)}; } else { - return -1; + return Moveable.AT_END; } } Modified: trunk/18xx/rails/game/PrivateCompany.java =================================================================== --- trunk/18xx/rails/game/PrivateCompany.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/PrivateCompany.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -2,7 +2,6 @@ package rails.game; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import rails.game.move.*; @@ -55,14 +54,14 @@ // sfy 1889 changed to IntegerArray revenue = tag.getAttributeAsIntegerArray("revenue", new int[0]); - + // pld: adding revenue to info text infoText += "<br>Revenue: "; for (int i = 0; i < revenue.length;i++) { infoText += (Bank.format(revenue[i])); if (i < revenue.length-1) {infoText += ", ";}; } - + // Blocked hexes (until bought by a company) Tag blockedTag = tag.getChild("Blocking"); if (blockedTag != null) { @@ -333,9 +332,10 @@ * Stub to satisfy MoveableHolderI. Special properties are never added after * completing the initial setup. */ - public boolean addObject(Moveable object, int position) { + public boolean addObject(Moveable object, int[] position) { if (object instanceof SpecialPropertyI) { - return Util.addToList(specialProperties, (SpecialPropertyI)object, position); + return Util.addToList(specialProperties, (SpecialPropertyI)object, + position == null ? -1 : position[0]); } else { return false; } @@ -356,11 +356,11 @@ } } - public int getListIndex (Moveable object) { + public int[] getListIndex (Moveable object) { if (object instanceof SpecialPropertyI) { - return specialProperties.indexOf(object); + return new int[] {specialProperties.indexOf(object)}; } else { - return -1; + return Moveable.AT_END; } } Modified: trunk/18xx/rails/game/PublicCompany.java =================================================================== --- trunk/18xx/rails/game/PublicCompany.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/PublicCompany.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -1809,18 +1809,10 @@ public boolean addToken(TokenI token, int position) { boolean result = false; - if (token instanceof BaseToken && laidBaseTokens.remove(token)) { + if (token instanceof BaseToken + && laidBaseTokens.remove(token) + && Util.addToList(freeBaseTokens, token, position)) { token.setHolder(this); - if (position == -1) { - result = freeBaseTokens.add(token); - } else { - try { - freeBaseTokens.add(position, token); - result = true; - } catch (IndexOutOfBoundsException e) { - result = false; - } - } this.baseTokensModel.update(); } return result; @@ -1864,9 +1856,9 @@ } - public boolean addObject(Moveable object, int position) { + public boolean addObject(Moveable object, int[] position) { if (object instanceof TokenI) { - return addToken((TokenI) object, position); + return addToken((TokenI) object, position == null ? -1 : position[0]); } else { return false; } @@ -1880,11 +1872,11 @@ } } - public int getListIndex (Moveable object) { + public int[] getListIndex (Moveable object) { if (object instanceof BaseToken) { - return freeBaseTokens.indexOf(object); + return new int[] {freeBaseTokens.indexOf(object)}; } else { - return -1; + return Moveable.AT_END; } } Modified: trunk/18xx/rails/game/TrainType.java =================================================================== --- trunk/18xx/rails/game/TrainType.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/TrainType.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -230,7 +230,7 @@ for (TrainI train : trains) { train.init(this, lastIndex++); - unavailable.addTrain(train, -1); + unavailable.addTrain(train); } } Modified: trunk/18xx/rails/game/move/Moveable.java =================================================================== --- trunk/18xx/rails/game/move/Moveable.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/move/Moveable.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -2,6 +2,8 @@ public interface Moveable { + public static final int[] AT_END = new int[] {-1}; + public void moveTo(MoveableHolder newHolder); public String getName(); Modified: trunk/18xx/rails/game/move/MoveableHolder.java =================================================================== --- trunk/18xx/rails/game/move/MoveableHolder.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/move/MoveableHolder.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -8,12 +8,12 @@ * @param position Position to insert object at. O: at front, -1, at end, >0: at that position. * @return True if successful. */ - public boolean addObject(Moveable object, int position); + public boolean addObject(Moveable object, int[] position); public boolean removeObject(Moveable object); public String getName(); - public int getListIndex (Moveable object); + public int[] getListIndex (Moveable object); } Modified: trunk/18xx/rails/game/move/ObjectMove.java =================================================================== --- trunk/18xx/rails/game/move/ObjectMove.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/move/ObjectMove.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -14,8 +14,8 @@ MoveableHolder from; MoveableHolder to; String objectClassName; - int fromPosition; - int toPosition = -1; // Default: at end + int[] fromPosition; + int[] toPosition = new int[] {-1}; // Default: at end /** * Create a generic ObjectMove object. Any specific side effects must be @@ -30,7 +30,7 @@ public ObjectMove(Moveable moveableObject, MoveableHolder from, MoveableHolder to) { - this (moveableObject, from, to, -1); + this (moveableObject, from, to, null); } /** @@ -46,13 +46,13 @@ */ public ObjectMove(Moveable moveableObject, MoveableHolder from, - MoveableHolder to, int toPosition) { + MoveableHolder to, int[] toPosition) { this.moveableObject = moveableObject; this.from = from; this.to = to; objectClassName = moveableObject.getClass().getSimpleName(); - this.fromPosition = from.getListIndex(moveableObject); + this.fromPosition = from != null ? from.getListIndex(moveableObject) : null; this.toPosition = toPosition; MoveSet.add(this); @@ -78,8 +78,8 @@ if (from == null) log.warn("From is null"); if (to == null) log.error("To is null"); return "Move " + objectClassName + ": " + moveableObject.getName() - + " from " + (from == null ? from : from.getName()) + "["+fromPosition - + "] to " + to.getName() + "["+toPosition+"]"; + + " from " + (from == null ? from : from.getName()) + "["+fromPosition + + "] to " + to.getName() + "["+toPosition+"]"; } } Modified: trunk/18xx/rails/game/move/RemoveFromList.java =================================================================== --- trunk/18xx/rails/game/move/RemoveFromList.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/move/RemoveFromList.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -1,5 +1,5 @@ /* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/move/RemoveFromList.java,v 1.3 2009/09/23 21:38:57 evos Exp $ - * + * * Created on 18-Jul-2006 * Change Log: */ @@ -32,18 +32,21 @@ public RemoveFromList(List<E> list, E object, String listName) { this (list, object, listName, null); - } + } - public boolean execute() { + @Override + public boolean execute() { list.remove(object); return true; } + @Override public boolean undo() { list.add(index, object); return true; } + @Override public String toString() { return "RemoveFromList " + listName + ": " + object.toString(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-07-24 15:47:39
|
Revision: 1356 http://rails.svn.sourceforge.net/rails/?rev=1356&view=rev Author: evos Date: 2010-07-24 15:47:32 +0000 (Sat, 24 Jul 2010) Log Message: ----------- Fixed bug that prevented some cash transfers after the bank has broken. Also fixed an incorrect change in the previous commit (BuyCertificate reorganisation) Modified Paths: -------------- trunk/18xx/rails/game/Bank.java trunk/18xx/rails/game/CashHolder.java trunk/18xx/rails/game/Player.java trunk/18xx/rails/game/PublicCompany.java trunk/18xx/rails/game/StockRound.java trunk/18xx/rails/game/TreasuryShareRound.java trunk/18xx/rails/game/model/CashModel.java trunk/18xx/rails/game/move/CashMove.java Modified: trunk/18xx/rails/game/Bank.java =================================================================== --- trunk/18xx/rails/game/Bank.java 2010-07-23 21:29:38 UTC (rev 1355) +++ trunk/18xx/rails/game/Bank.java 2010-07-24 15:47:32 UTC (rev 1356) @@ -136,9 +136,10 @@ /** * Adds cash back to the bank */ - public boolean addCash(int amount) { - boolean negative = money.addCash(amount); + public void addCash(int amount) { + money.addCash(amount); + /* * Check if the bank has broken. In some games <0 could apply, so this * will become configurable. @@ -147,7 +148,6 @@ broken.set(true); GameManager.getInstance().registerBrokenBank(); } - return negative; } public boolean isBroken() { Modified: trunk/18xx/rails/game/CashHolder.java =================================================================== --- trunk/18xx/rails/game/CashHolder.java 2010-07-23 21:29:38 UTC (rev 1355) +++ trunk/18xx/rails/game/CashHolder.java 2010-07-24 15:47:32 UTC (rev 1356) @@ -18,7 +18,7 @@ /** * Add (or subtract) cash. */ - public abstract boolean addCash(int amount); + public abstract void addCash(int amount); /** Get the cash owner's name (needed for logging) */ public abstract String getName(); Modified: trunk/18xx/rails/game/Player.java =================================================================== --- trunk/18xx/rails/game/Player.java 2010-07-23 21:29:38 UTC (rev 1355) +++ trunk/18xx/rails/game/Player.java 2010-07-24 15:47:32 UTC (rev 1356) @@ -73,9 +73,8 @@ return wallet; } - public boolean addCash(int amount) { - boolean result = wallet.addCash(amount); - return result; + public void addCash(int amount) { + wallet.addCash(amount); } /** Modified: trunk/18xx/rails/game/PublicCompany.java =================================================================== --- trunk/18xx/rails/game/PublicCompany.java 2010-07-23 21:29:38 UTC (rev 1355) +++ trunk/18xx/rails/game/PublicCompany.java 2010-07-24 15:47:32 UTC (rev 1356) @@ -1147,8 +1147,8 @@ * * @param amount The amount to add (may be negative). */ - public boolean addCash(int amount) { - return treasury.addCash(amount); + public void addCash(int amount) { + treasury.addCash(amount); } /** Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2010-07-23 21:29:38 UTC (rev 1355) +++ trunk/18xx/rails/game/StockRound.java 2010-07-24 15:47:32 UTC (rev 1356) @@ -28,7 +28,7 @@ protected BooleanState hasSoldThisTurnBeforeBuying = new BooleanState("HoldSoldBeforeBuyingThisTurn", false); - protected BooleanState hasActed = new BooleanState("HasActed", false); // Is + protected BooleanState hasActed = new BooleanState("HasActed", false); protected IntegerState numPasses = new IntegerState("StockRoundPasses"); Modified: trunk/18xx/rails/game/TreasuryShareRound.java =================================================================== --- trunk/18xx/rails/game/TreasuryShareRound.java 2010-07-23 21:29:38 UTC (rev 1355) +++ trunk/18xx/rails/game/TreasuryShareRound.java 2010-07-24 15:47:32 UTC (rev 1356) @@ -246,7 +246,8 @@ int number = action.getNumberBought(); int shareUnit = company.getShareUnit(); int sharePerCert = action.getSharePerCertificate(); - int shares = number * sharePerCert; + int share = number * sharePerCert; + int shares = share/shareUnit; String errMsg = null; int price = 0; @@ -296,7 +297,7 @@ } // Check if that many shares are available - if (shares > from.getShare(company)) { + if (share > from.getShare(company)) { errMsg = LocalText.getText("NotAvailable", companyName, @@ -308,8 +309,7 @@ // Check if company would exceed the per-company share limit int treasuryShareLimit = getGameParameterAsInt(GameDef.Parm.TREASURY_SHARE_LIMIT); - if (portfolio.getShare(company) + shares * company.getShareUnit() - > treasuryShareLimit) { + if (portfolio.getShare(company) + share > treasuryShareLimit) { errMsg = LocalText.getText("TreasuryOverHoldLimit", String.valueOf(treasuryShareLimit)); @@ -359,7 +359,7 @@ moveStack.start(true); PublicCertificateI cert2; for (int i = 0; i < number; i++) { - cert2 = from.findCertificate(company, sharePerCert, false); + cert2 = from.findCertificate(company, sharePerCert/shareUnit, false); executeTradeCertificate(cert2, portfolio, cert2.getShares() * price); } Modified: trunk/18xx/rails/game/model/CashModel.java =================================================================== --- trunk/18xx/rails/game/model/CashModel.java 2010-07-23 21:29:38 UTC (rev 1355) +++ trunk/18xx/rails/game/model/CashModel.java 2010-07-24 15:47:32 UTC (rev 1356) @@ -1,9 +1,7 @@ /* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/model/CashModel.java,v 1.5 2008/06/04 19:00:37 evos Exp $*/ package rails.game.model; -import rails.game.Bank; -import rails.game.CashHolder; -import rails.game.PublicCompanyI; +import rails.game.*; public class CashModel extends ModelObject { @@ -22,14 +20,9 @@ update(); } - public boolean addCash(int addedCash) { + public void addCash(int addedCash) { cash += addedCash; update(); - - if (cash <= 0) - return false; - else - return true; } public int getCash() { @@ -38,9 +31,10 @@ /* * (non-Javadoc) - * + * * @see rails.rails.game.model.ModelObject#getValue() */ + @Override public String getText() { if (cash == 0 && (option & SUPPRESS_ZERO) > 0 || owner instanceof PublicCompanyI Modified: trunk/18xx/rails/game/move/CashMove.java =================================================================== --- trunk/18xx/rails/game/move/CashMove.java 2010-07-23 21:29:38 UTC (rev 1355) +++ trunk/18xx/rails/game/move/CashMove.java 2010-07-24 15:47:32 UTC (rev 1356) @@ -48,9 +48,10 @@ return true; } - private boolean transferCash(CashHolder from, CashHolder to, + private void transferCash(CashHolder from, CashHolder to, int amount) { - return to.addCash(amount) && from.addCash(-amount); + to.addCash(amount); + from.addCash(-amount); } @Override This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-06 19:52:59
|
Revision: 1370 http://rails.svn.sourceforge.net/rails/?rev=1370&view=rev Author: stefanfrey Date: 2010-08-06 19:52:53 +0000 (Fri, 06 Aug 2010) Log Message: ----------- Fixed train discard bug in 1856 cgr formation. Started working on undo of cgr formation. Modified Paths: -------------- trunk/18xx/rails/game/move/MoveStack.java trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java Modified: trunk/18xx/rails/game/move/MoveStack.java =================================================================== --- trunk/18xx/rails/game/move/MoveStack.java 2010-08-05 18:53:13 UTC (rev 1369) +++ trunk/18xx/rails/game/move/MoveStack.java 2010-08-06 19:52:53 UTC (rev 1370) @@ -99,6 +99,7 @@ public void linkToPreviousMoveSet() { if (currentMoveSet != null) { currentMoveSet.linkToPreviousMoveSet(); + log.debug("Moveset linked to previous one"); } else { log.warn("No MoveSet open"); } Modified: trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java =================================================================== --- trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java 2010-08-05 18:53:13 UTC (rev 1369) +++ trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java 2010-08-06 19:52:53 UTC (rev 1370) @@ -642,7 +642,8 @@ } // Check the trains, autodiscard any excess non-permanent trains - int trainLimit = cgr.getTrainLimit(gameManager.getCurrentPlayerIndex()); +// int trainLimit = cgr.getTrainLimit(gameManager.getCurrentPlayerIndex()); + int trainLimit = cgr.getCurrentTrainLimit(); List<TrainI> trains = cgr.getPortfolio().getTrainList(); if (cgr.getNumberOfTrains() > trainLimit) { ReportBuffer.add(""); @@ -815,8 +816,7 @@ if (train != null) { - if (action.isForced()) moveStack.linkToPreviousMoveSet(); - +// if (action.isForced()) moveStack.linkToPreviousMoveSet(); train.moveTo(pool); ReportBuffer.add(LocalText.getText("CompanyDiscardsTrain", companyName, @@ -825,6 +825,8 @@ } else { cgrHasDiscardedTrains.set(true); } + // new: link always, see above uncommented + moveStack.linkToPreviousMoveSet(); return true; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-10 21:52:25
|
Revision: 1377 http://rails.svn.sourceforge.net/rails/?rev=1377&view=rev Author: stefanfrey Date: 2010-08-10 21:52:19 +0000 (Tue, 10 Aug 2010) Log Message: ----------- Made numOfORs a state integer variable to support undo behavior Modified Paths: -------------- trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/specific/_18EU/GameManager_18EU.java Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-08-10 21:51:07 UTC (rev 1376) +++ trunk/18xx/rails/game/GameManager.java 2010-08-10 21:52:19 UTC (rev 1377) @@ -108,7 +108,7 @@ new IntegerState("AbsoluteORNUmber"); protected IntegerState relativeORNumber = new IntegerState("RelativeORNumber"); - protected int numOfORs; + protected IntegerState numOfORs = new IntegerState("numOfORs"); protected BooleanState gameOver = new BooleanState("GameOver" ,false); protected Boolean gameOverReportedUI = false; @@ -567,7 +567,9 @@ } else if (skipFirstStockRound) { PhaseI currentPhase = phaseManager.getCurrentPhase(); - numOfORs = currentPhase.getNumberOfOperatingRounds(); + if (currentPhase.getNumberOfOperatingRounds() != numOfORs.intValue()) { + numOfORs.set(currentPhase.getNumberOfOperatingRounds()); + } log.info("Phase=" + currentPhase.getName() + " ORs=" + numOfORs); // Create a new OperatingRound (never more than one Stock Round) @@ -581,7 +583,7 @@ } else if (round instanceof StockRound) { PhaseI currentPhase = getCurrentPhase(); if (currentPhase == null) log.error ("Current Phase is null??", new Exception ("")); - numOfORs = currentPhase.getNumberOfOperatingRounds(); + numOfORs.set(currentPhase.getNumberOfOperatingRounds()); log.info("Phase=" + currentPhase.getName() + " ORs=" + numOfORs); // Create a new OperatingRound (never more than one Stock Round) @@ -594,7 +596,7 @@ finishGame(); - } else if (relativeORNumber.add(1) <= numOfORs) { + } else if (relativeORNumber.add(1) <= numOfORs.intValue()) { // There will be another OR startOperatingRound(true); } else if (startPacket != null && !startPacket.areAllSold()) { @@ -697,7 +699,7 @@ } public String getNumOfORs () { - return new Integer(numOfORs).toString(); + return numOfORs.getText(); } /* (non-Javadoc) @@ -1639,7 +1641,6 @@ } return cm; } - /** Return a list of companies in operation order. * <p>Note that, unlike Round.setOperatingCompanies(), this method does <b>not</b> check * if the companies are actualy allowed to operate. One purpose is to check for upping the Modified: trunk/18xx/rails/game/specific/_18EU/GameManager_18EU.java =================================================================== --- trunk/18xx/rails/game/specific/_18EU/GameManager_18EU.java 2010-08-10 21:51:07 UTC (rev 1376) +++ trunk/18xx/rails/game/specific/_18EU/GameManager_18EU.java 2010-08-10 21:52:19 UTC (rev 1377) @@ -19,7 +19,7 @@ public void nextRound(RoundI round) { if (round instanceof OperatingRound_18EU) { if (playerToStartFMERound.getObject() != null - && relativeORNumber.intValue() == numOfORs) { + && relativeORNumber.intValue() == numOfORs.intValue()) { createRound (FinalMinorExchangeRound.class).start ((Player)playerToStartFMERound.getObject()); playerToStartFMERound.set(null); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-17 20:07:53
|
Revision: 1393 http://rails.svn.sourceforge.net/rails/?rev=1393&view=rev Author: stefanfrey Date: 2010-08-17 20:07:46 +0000 (Tue, 17 Aug 2010) Log Message: ----------- Fixed several bugs: - IOException error on reload of rails 1.3 files - IsHome function did not recognize companies with undecided city - BuyTrain toString() was not defined for unlimited trains on reload in ListandFixGames function Modified Paths: -------------- trunk/18xx/rails/game/Game.java trunk/18xx/rails/game/MapHex.java trunk/18xx/rails/game/action/BuyTrain.java Modified: trunk/18xx/rails/game/Game.java =================================================================== --- trunk/18xx/rails/game/Game.java 2010-08-16 19:48:31 UTC (rev 1392) +++ trunk/18xx/rails/game/Game.java 2010-08-17 20:07:46 UTC (rev 1393) @@ -310,8 +310,10 @@ if (object instanceof SortedMap) { ReportBuffer.setCommentItems((SortedMap<Integer, String>) object); } - } catch (EOFException e) { - // continue without comments + } catch (IOException e) { + // continue without comments, if any IOException occurs + // sometimes not only the EOF Exception is raised + // but also the java.io.StreamCorruptedException: invalid type code } } Modified: trunk/18xx/rails/game/MapHex.java =================================================================== --- trunk/18xx/rails/game/MapHex.java 2010-08-16 19:48:31 UTC (rev 1392) +++ trunk/18xx/rails/game/MapHex.java 2010-08-17 20:07:46 UTC (rev 1393) @@ -949,7 +949,7 @@ } public boolean isHomeFor(PublicCompanyI company) { - boolean result = homes != null && homes.get(company) != null; + boolean result = homes != null && homes.containsKey(company); return result; } Modified: trunk/18xx/rails/game/action/BuyTrain.java =================================================================== --- trunk/18xx/rails/game/action/BuyTrain.java 2010-08-16 19:48:31 UTC (rev 1392) +++ trunk/18xx/rails/game/action/BuyTrain.java 2010-08-17 20:07:46 UTC (rev 1393) @@ -209,7 +209,11 @@ StringBuffer b = new StringBuffer(); b.append(company.getName()); - b.append(": buy ").append(getTrain().getName()); + if (train != null) { + b.append(": buy ").append(getTrain().getName()); + } else { + b.append(": buy unlimited train, unique id = ").append(trainUniqueId); + } b.append("-train from ").append(from.getName()); if (fixedCost > 0) { b.append(" for ").append(Bank.format(fixedCost)); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-22 15:32:33
|
Revision: 1400 http://rails.svn.sourceforge.net/rails/?rev=1400&view=rev Author: stefanfrey Date: 2010-08-22 15:32:27 +0000 (Sun, 22 Aug 2010) Log Message: ----------- Added HashMapState Used that to fix problems with TileLaysPerColour And fixed wrong valuation of bankrupt player Modified Paths: -------------- trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/Player.java trunk/18xx/rails/game/ShareSellingRound.java trunk/18xx/rails/game/move/MapChange.java trunk/18xx/rails/game/state/ArrayListState.java Added Paths: ----------- trunk/18xx/rails/game/move/RemoveFromMap.java trunk/18xx/rails/game/state/HashMapState.java Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-08-22 15:30:41 UTC (rev 1399) +++ trunk/18xx/rails/game/GameManager.java 2010-08-22 15:32:27 UTC (rev 1400) @@ -995,12 +995,12 @@ File recoveryFile = null; boolean result; try { - log.debug("Created temporary recovery file, path = " + tempFile.getAbsolutePath()); + log.debug("Created temporary recovery file, path = " + tempFile.getPath()); // check if previous save file exists recoveryFile = new File(filePath); - log.debug("Potential recovery filePath = " + recoveryFile.getAbsolutePath()); + log.debug("Potential recovery filePath = " + recoveryFile.getPath()); if (recoveryFile.exists()) { - log.debug("Potential recovery filePath = " + recoveryFile.getAbsolutePath()); + log.debug("Potential recovery filePath = " + recoveryFile.getPath()); File backupFile = new File(filePath + ".bak"); if (recoveryFile.renameTo(backupFile)) { result = tempFile.renameTo(recoveryFile); @@ -1018,7 +1018,7 @@ } if (result) { - log.debug("Renamed to recovery file, path = " + recoveryFile.getAbsolutePath()); + log.debug("Renamed to recovery file, path = " + recoveryFile.getPath()); if (!recoverySaveWarning) { DisplayBuffer.add(LocalText.getText("RecoverySaveSuccessAgain")); recoverySaveWarning = true; Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2010-08-22 15:30:41 UTC (rev 1399) +++ trunk/18xx/rails/game/OperatingRound.java 2010-08-22 15:32:27 UTC (rev 1400) @@ -13,6 +13,7 @@ import rails.game.state.ArrayListState; import rails.game.state.EnumState; import rails.game.state.GenericState; +import rails.game.state.HashMapState; import rails.util.LocalText; import rails.util.SequenceUtil; @@ -49,8 +50,8 @@ protected List<LayTile> currentNormalTileLays = new ArrayList<LayTile>(); - protected Map<String, Integer> tileLaysPerColour = - new HashMap<String, Integer>(); + protected HashMapState<String, Integer> tileLaysPerColour = + new HashMapState<String, Integer>("tileLaysPerColour"); protected List<LayBaseToken> currentNormalTokenLays = new ArrayList<LayBaseToken>(); @@ -450,10 +451,6 @@ protected boolean checkNormalTileLay(TileI tile, boolean update) { - // Map<String,Integer> tileLaysPerColour = tileLaysPerColourState.getObject(); - - // if (tileLaysPerColour.isEmpty()) return false; - String colour = tile.getColourName(); Integer oldAllowedNumberObject = tileLaysPerColour.get(colour); @@ -471,28 +468,23 @@ * different colours may be laid. THIS MAY NOT BE TRUE FOR ALL GAMES! */ - // Map<String,Integer> tileLaysPerColourUpdated = new HashMap<String, Integer>(); // new (empty) map - if (oldAllowedNumber <= 1) { - for (String key:tileLaysPerColour.keySet()) - new MapChange<String,Integer>(tileLaysPerColour, key, new Integer(0)); + for (String key:tileLaysPerColour.viewKeySet()) { + tileLaysPerColour.put(key, new Integer(0)); + } log.debug("No more normal tile lays allowed"); currentNormalTileLays.clear(); } else { - // tileLaysPerColourUpdated.put(colour, new Integer(oldAllowedNumber - 1)); - for (String key:tileLaysPerColour.keySet()) - if (colour.equals(key)) - new MapChange<String,Integer> - (tileLaysPerColour, colour, new Integer(oldAllowedNumber-1)); - else - new MapChange<String,Integer>(tileLaysPerColour, key, new Integer(0)); - + for (String key:tileLaysPerColour.viewKeySet()) { + if (colour.equals(key)) { + tileLaysPerColour.put(colour, new Integer(oldAllowedNumber-1)); + } else { + tileLaysPerColour.put(key, new Integer(0)); + } + } log.debug((oldAllowedNumber - 1) + " more " + colour + " tile lays allowed"); } - - // tileLaysPerColourState.set(tileLaysPerColourUpdated); - return true; } @@ -1306,20 +1298,16 @@ * of the tile laying step. */ protected void getNormalTileLays() { - - // Map<String,Integer> - tileLaysPerColour = - new HashMap<String, Integer>(getCurrentPhase().getTileColours()); // Clone - - int allowedNumber; - for (String colour : tileLaysPerColour.keySet()) { - allowedNumber = operatingCompany.get().getNumberOfTileLays(colour); + + // duplicate the phase colours + Map<String, Integer> newTileColours = new HashMap<String, Integer>(getCurrentPhase().getTileColours()); + for (String colour : newTileColours.keySet()) { + int allowedNumber = operatingCompany.get().getNumberOfTileLays(colour); // Replace the null map value with the allowed number of lays - new MapChange<String, Integer>(tileLaysPerColour, colour, new Integer(allowedNumber)); + newTileColours.put(colour, new Integer(allowedNumber)); } - - // store state - // tileLaysPerColourState = new GenericState<Map<String,Integer>>("tileLaysPerColour", tileLaysPerColour); + // store to state + tileLaysPerColour.initFromMap(newTileColours); } protected void setNormalTileLays() { @@ -1330,11 +1318,11 @@ // Map<String,Integer> tileLaysPerColour = (Map<String,Integer>)(tileLaysPerColourState.getObject()); int sumLays = 0; - for (Integer i: tileLaysPerColour.values()) + for (Integer i: tileLaysPerColour.viewValues()) sumLays = sumLays + i; if (sumLays != 0) { // if (!tileLaysPerColour.isEmpty()) { - currentNormalTileLays.add(new LayTile(tileLaysPerColour)); + currentNormalTileLays.add(new LayTile(tileLaysPerColour.viewMap())); } } Modified: trunk/18xx/rails/game/Player.java =================================================================== --- trunk/18xx/rails/game/Player.java 2010-08-22 15:30:41 UTC (rev 1399) +++ trunk/18xx/rails/game/Player.java 2010-08-22 15:32:27 UTC (rev 1400) @@ -83,8 +83,15 @@ * @return Total worth */ public int getWorth() { - int worth = wallet.getCash(); - + // if player is bankrupt cash is not counted + // as this was generated during forced selling + int worth; + if (bankrupt.booleanValue()) { + worth = 0; + } else { + worth = wallet.getCash(); + } + for (PublicCertificateI cert : portfolio.getCertificates()) { worth += cert.getCompany().getGameEndPrice() * cert.getShares(); } Modified: trunk/18xx/rails/game/ShareSellingRound.java =================================================================== --- trunk/18xx/rails/game/ShareSellingRound.java 2010-08-22 15:30:41 UTC (rev 1399) +++ trunk/18xx/rails/game/ShareSellingRound.java 2010-08-22 15:32:27 UTC (rev 1400) @@ -423,7 +423,7 @@ } else if (getSellableShares().isEmpty()) { DisplayBuffer.add(LocalText.getText("YouMustRaiseCashButCannot", Bank.format(cashToRaise.intValue()))); - + currentPlayer.setBankrupt(); gameManager.registerBankruptcy(); } Modified: trunk/18xx/rails/game/move/MapChange.java =================================================================== --- trunk/18xx/rails/game/move/MapChange.java 2010-08-22 15:30:41 UTC (rev 1399) +++ trunk/18xx/rails/game/move/MapChange.java 2010-08-22 15:32:27 UTC (rev 1400) @@ -20,6 +20,10 @@ protected V oldValue; protected boolean keyExisted; + /** + * Creates a move that changes a map <key,value> pair + */ + public MapChange (Map<K, V> map, K key, V newValue) { this.map = map; @@ -30,29 +34,22 @@ MoveSet.add(this); } - + @Override public boolean execute() { - map.put(key, newValue); - return true; } @Override public boolean undo() { - if (keyExisted) { map.put (key, oldValue); - } else { - map.remove(key); } - return true; } public String toString() { return "MapChange: key="+key+" from "+oldValue+" to "+newValue; } - } Added: trunk/18xx/rails/game/move/RemoveFromMap.java =================================================================== --- trunk/18xx/rails/game/move/RemoveFromMap.java (rev 0) +++ trunk/18xx/rails/game/move/RemoveFromMap.java 2010-08-22 15:32:27 UTC (rev 1400) @@ -0,0 +1,55 @@ +/* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/move/MapChange.java,v 1.4 2010/05/05 21:36:59 evos Exp $ + * + * Created on 19-Jul-2006 + * Change Log: + */ +package rails.game.move; + +import java.util.Map; + +/** + * This Move class handles removable from a stateful map (collection) + * + * @author Erik Vos + */ +public class RemoveFromMap<K, V> extends Move { + + protected Map<K, V> map; + protected K key; + protected V oldValue; + protected boolean keyExisted; + + /** + * Creates a move that removes key from map + */ + + public RemoveFromMap (Map<K, V> map, K key) { + + this.map = map; + this.key = key; + this.keyExisted = map.containsKey(key); + + MoveSet.add(this); + } + + @Override + public boolean execute() { + if (keyExisted) { + map.remove(key); + } + return true; + } + + @Override + public boolean undo() { + if (keyExisted) { + map.put (key, oldValue); + } + return true; + } + + public String toString() { + return "RemoveFromMap: remove key="+key+" from map"; + } + +} Property changes on: trunk/18xx/rails/game/move/RemoveFromMap.java ___________________________________________________________________ Added: svn:mime-type + text/plain Modified: trunk/18xx/rails/game/state/ArrayListState.java =================================================================== --- trunk/18xx/rails/game/state/ArrayListState.java 2010-08-22 15:30:41 UTC (rev 1399) +++ trunk/18xx/rails/game/state/ArrayListState.java 2010-08-22 15:32:27 UTC (rev 1400) @@ -3,7 +3,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.Iterator; import java.util.List; import rails.game.move.AddToList; @@ -12,50 +11,57 @@ /** * State class that wraps an ArrayList * Generates according list moves + * + * Remark: Does not extend State or implements StateI do avoid additional overhead + * All state/move mechanisms already contained in Move objects + * For the future a simpler unified StateI would make things clearer * - * @author freystef - * + * TODO: Replace all stateful lists by this class and simplify according move objects + * */ -public class ArrayListState<E> extends State { +public class ArrayListState<E> { private final ArrayList<E> list = new ArrayList<E>(); + private String listName; + /** * constructor for an empty list * @param name */ - public ArrayListState(String name) { - super(name, ArrayList.class); + public ArrayListState(String listName) { + this.listName = listName; } /** * constructor for a prefilled list * @param element */ - public ArrayListState(String name, Collection<E> collection) { - super(name, ArrayList.class); - for (E element:collection) { - add(element); - } + public ArrayListState(String listName, Collection<E> collection) { + this(listName); + list.addAll(collection); } public void add(E element) { - new AddToList<E>(list, element, name); + new AddToList<E>(list, element, listName); } public void add(int index, E element) { - new AddToList<E>(list, element, name).atIndex(index); + new AddToList<E>(list, element, listName).atIndex(index); } public void remove(E element) { - new RemoveFromList<E>(list, element, name); + new RemoveFromList<E>(list, element, listName); } public void clear() { for (E element:list) { - new RemoveFromList<E>(list, element, name); + remove(element); } } + /** + * returns unmodifiable view of list + */ public List<E> viewList() { return Collections.unmodifiableList(list); } Added: trunk/18xx/rails/game/state/HashMapState.java =================================================================== --- trunk/18xx/rails/game/state/HashMapState.java (rev 0) +++ trunk/18xx/rails/game/state/HashMapState.java 2010-08-22 15:32:27 UTC (rev 1400) @@ -0,0 +1,103 @@ +package rails.game.state; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import rails.game.move.MapChange; +import rails.game.move.RemoveFromMap; + +/** + * State class that wraps a HashMap + * Generates according map moves + * + * Remark: Does not extend State or implements StateI do avoid additional overhead + * All state/move mechanisms already contained in Move objects + * For the future a simpler unified StateI would make things clearer + * + * TODO: Replace all stateful HashMaps by this class and simplify according move objects + * + */ + +public class HashMapState<K,V>{ + + private final HashMap<K,V> map = new HashMap<K,V>(); + private String mapName; + + /** + * constructor for an empty map + */ + public HashMapState(String listName) { + this.mapName = listName; + } + /** + * constructor for a prefilled map + */ + public HashMapState(String listName, Map<K,V> map) { + this(listName); + } + + public void put(K key, V value) { + new MapChange<K,V>(map, key, value); + } + + public void putAll(Map<K,V> map) { + for (K key:map.keySet()) { + new MapChange<K,V>(map, key, map.get(key)); + } + } + + public V get(K key) { + return map.get(key); + } + + public void remove(K key) { + new RemoveFromMap<K,V>(map, key); + } + + public void clear() { + for (K key:map.keySet()) { + remove(key); + } + } + + /** + * (re)intializes the state map from another map + * efficiently generates the required moves + */ + public void initFromMap(Map<K,V> initMap) { + for (K key:map.keySet()) { + // union elements + if (initMap.containsKey(key)) { + new MapChange<K,V>(map, key, initMap.get(key)); + } else { // only in the old map + new RemoveFromMap<K,V>(map, key); + } + } + for (K key:initMap.keySet()) { + // new elements + if (!map.containsKey(key)) { + new MapChange<K,V>(map, key, initMap.get(key)); + } + } + } + + /** + * @return unmodifiable view of map + */ + public Map<K,V> viewMap() { + return Collections.unmodifiableMap(map); + } + /** + * @return unmodifiable view of keyset + */ + public Set<K> viewKeySet() { + return Collections.unmodifiableSet(map.keySet()); + } + + public Collection<V> viewValues() { + return Collections.unmodifiableCollection(map.values()); + } +} Property changes on: trunk/18xx/rails/game/state/HashMapState.java ___________________________________________________________________ Added: svn:mime-type + text/plain This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-09-07 19:14:54
|
Revision: 1414 http://rails.svn.sourceforge.net/rails/?rev=1414&view=rev Author: evos Date: 2010-09-07 19:14:48 +0000 (Tue, 07 Sep 2010) Log Message: ----------- Removed redundant actions (such as presidency swapping) when a company price token reaches a "close" area. Modified Paths: -------------- trunk/18xx/rails/game/ShareSellingRound.java trunk/18xx/rails/game/StockRound.java Modified: trunk/18xx/rails/game/ShareSellingRound.java =================================================================== --- trunk/18xx/rails/game/ShareSellingRound.java 2010-09-06 21:20:12 UTC (rev 1413) +++ trunk/18xx/rails/game/ShareSellingRound.java 2010-09-07 19:14:48 UTC (rev 1414) @@ -126,27 +126,27 @@ /* * If the current Player is president, check if he can dump the * presidency onto someone else - * + * * Two reasons for the check: * A) President not allowed to sell that company * Thus keep enough shares to stay president - * + * * Example here * share = 60%, other player holds 40%, maxShareToSell > 30% - * => requires selling of president + * => requires selling of president * B) President allowed to sell that company * In that case the president share can be sold - * + * * Example here * share = 60%, , president share = 20%, maxShareToSell > 40% - * => requires selling of president + * => requires selling of president */ if (company.getPresident() == currentPlayer) { int presidentShare = company.getCertificates().get(0).getShare(); boolean dumpPossible; - log.debug("Forced selling check: company = " + company + + log.debug("Forced selling check: company = " + company + ", share = " + share + ", maxShareToSell = " + maxShareToSell); if (company == cashNeedingCompany || !dumpOtherCompaniesAllowed) { // case A: selling of president not allowed (either company triggered share selling or no dump of others) @@ -377,43 +377,46 @@ companyName, Bank.format(numberSold * price) )); - // Check if the presidency has changed - if (presCert != null && dumpedPlayer != null && presSharesToSell > 0) { - ReportBuffer.add(LocalText.getText("IS_NOW_PRES_OF", - dumpedPlayer.getName(), - companyName)); - // First swap the certificates - Portfolio dumpedPortfolio = dumpedPlayer.getPortfolio(); - List<PublicCertificateI> swapped = - portfolio.swapPresidentCertificate(company, dumpedPortfolio); - for (int i = 0; i < presSharesToSell; i++) { - certsToSell.add(swapped.get(i)); - } - } - - // Transfer the sold certificates - for (PublicCertificateI cert2 : certsToSell) { - if (cert2 != null) { - executeTradeCertificate (cert2, pool, cert2.getShares() * price); - } - } boolean soldBefore = sellPrices.containsKey(companyName); adjustSharePrice (company, numberSold, soldBefore); - // Check if we still have the presidency - if (currentPlayer == company.getPresident()) { - Player otherPlayer; - for (int i = currentIndex + 1; i < currentIndex + numberOfPlayers; i++) { - otherPlayer = gameManager.getPlayerByIndex(i); - if (otherPlayer.getPortfolio().getShare(company) > portfolio.getShare(company)) { - portfolio.swapPresidentCertificate(company, - otherPlayer.getPortfolio()); - ReportBuffer.add(LocalText.getText("IS_NOW_PRES_OF", - otherPlayer.getName(), - company.getName())); - break; - } - } + if (!company.isClosed()) { + // Check if the presidency has changed + if (presCert != null && dumpedPlayer != null && presSharesToSell > 0) { + ReportBuffer.add(LocalText.getText("IS_NOW_PRES_OF", + dumpedPlayer.getName(), + companyName)); + // First swap the certificates + Portfolio dumpedPortfolio = dumpedPlayer.getPortfolio(); + List<PublicCertificateI> swapped = + portfolio.swapPresidentCertificate(company, dumpedPortfolio); + for (int i = 0; i < presSharesToSell; i++) { + certsToSell.add(swapped.get(i)); + } + } + + // Transfer the sold certificates + for (PublicCertificateI cert2 : certsToSell) { + if (cert2 != null) { + executeTradeCertificate (cert2, pool, cert2.getShares() * price); + } + } + + // Check if we still have the presidency + if (currentPlayer == company.getPresident()) { + Player otherPlayer; + for (int i = currentIndex + 1; i < currentIndex + numberOfPlayers; i++) { + otherPlayer = gameManager.getPlayerByIndex(i); + if (otherPlayer.getPortfolio().getShare(company) > portfolio.getShare(company)) { + portfolio.swapPresidentCertificate(company, + otherPlayer.getPortfolio()); + ReportBuffer.add(LocalText.getText("IS_NOW_PRES_OF", + otherPlayer.getName(), + company.getName())); + break; + } + } + } } cashToRaise.add(-numberSold * price); Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2010-09-06 21:20:12 UTC (rev 1413) +++ trunk/18xx/rails/game/StockRound.java 2010-09-07 19:14:48 UTC (rev 1414) @@ -417,8 +417,8 @@ * original price is still valid */ price = getCurrentSellPrice(company); - - // removed as this is done in getCurrentSellPrice + + // removed as this is done in getCurrentSellPrice // price /= company.getShareUnitsForSharePrice(); /* Allow for different share units (as in 1835) */ @@ -1070,44 +1070,51 @@ Bank.format(numberSold * price * shareUnits) )); } - // Check if the presidency has changed - if (presCert != null && dumpedPlayer != null && presSharesToSell > 0) { - ReportBuffer.add(LocalText.getText("IS_NOW_PRES_OF", - dumpedPlayer.getName(), - companyName )); - // First swap the certificates - Portfolio dumpedPortfolio = dumpedPlayer.getPortfolio(); - List<PublicCertificateI> swapped = - portfolio.swapPresidentCertificate(company, dumpedPortfolio); - for (int i = 0; i < presSharesToSell; i++) { - certsToSell.add(swapped.get(i)); - } - } + // PROVISIONALLY MOVED UPWARDS + adjustSharePrice (company, numberSold, soldBefore); - // Transfer the sold certificates - Iterator<PublicCertificateI> it = certsToSell.iterator(); - while (it.hasNext()) { - cert = it.next(); - if (cert != null) { - executeTradeCertificate(cert, pool, cert.getShares() * price); + if (!company.isClosed()) { + + // Check if the presidency has changed + if (presCert != null && dumpedPlayer != null && presSharesToSell > 0) { + ReportBuffer.add(LocalText.getText("IS_NOW_PRES_OF", + dumpedPlayer.getName(), + companyName )); + // First swap the certificates + Portfolio dumpedPortfolio = dumpedPlayer.getPortfolio(); + List<PublicCertificateI> swapped = + portfolio.swapPresidentCertificate(company, dumpedPortfolio); + for (int i = 0; i < presSharesToSell; i++) { + certsToSell.add(swapped.get(i)); + } } - } - adjustSharePrice (company, numberSold, soldBefore); - // Check if we still have the presidency - if (currentPlayer == company.getPresident()) { - Player otherPlayer; - for (int i = currentIndex + 1; i < currentIndex + numberOfPlayers; i++) { - otherPlayer = gameManager.getPlayerByIndex(i); - if (otherPlayer.getPortfolio().getShare(company) > portfolio.getShare(company)) { - portfolio.swapPresidentCertificate(company, - otherPlayer.getPortfolio()); - ReportBuffer.add(LocalText.getText("IS_NOW_PRES_OF", - otherPlayer.getName(), - company.getName() )); - break; - } - } + // Transfer the sold certificates + Iterator<PublicCertificateI> it = certsToSell.iterator(); + while (it.hasNext()) { + cert = it.next(); + if (cert != null) { + executeTradeCertificate(cert, pool, cert.getShares() * price); + } + } + // PROVISIONALLY MOVED UPWARDS + //adjustSharePrice (company, numberSold, soldBefore); + + // Check if we still have the presidency + if (currentPlayer == company.getPresident()) { + Player otherPlayer; + for (int i = currentIndex + 1; i < currentIndex + numberOfPlayers; i++) { + otherPlayer = gameManager.getPlayerByIndex(i); + if (otherPlayer.getPortfolio().getShare(company) > portfolio.getShare(company)) { + portfolio.swapPresidentCertificate(company, + otherPlayer.getPortfolio()); + ReportBuffer.add(LocalText.getText("IS_NOW_PRES_OF", + otherPlayer.getName(), + company.getName() )); + break; + } + } + } } // Remember that the player has sold this company this round. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-09-07 19:42:07
|
Revision: 1415 http://rails.svn.sourceforge.net/rails/?rev=1415&view=rev Author: evos Date: 2010-09-07 19:42:01 +0000 (Tue, 07 Sep 2010) Log Message: ----------- Some share selling code reorganisation to allow (later) centralizing of follow-up actions. Modified Paths: -------------- trunk/18xx/rails/game/StockRound.java trunk/18xx/rails/game/specific/_1856/StockRound_1856.java Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2010-09-07 19:14:48 UTC (rev 1414) +++ trunk/18xx/rails/game/StockRound.java 2010-09-07 19:42:01 UTC (rev 1415) @@ -1070,7 +1070,6 @@ Bank.format(numberSold * price * shareUnits) )); } - // PROVISIONALLY MOVED UPWARDS adjustSharePrice (company, numberSold, soldBefore); if (!company.isClosed()) { @@ -1097,8 +1096,6 @@ executeTradeCertificate(cert, pool, cert.getShares() * price); } } - // PROVISIONALLY MOVED UPWARDS - //adjustSharePrice (company, numberSold, soldBefore); // Check if we still have the presidency if (currentPlayer == company.getPresident()) { Modified: trunk/18xx/rails/game/specific/_1856/StockRound_1856.java =================================================================== --- trunk/18xx/rails/game/specific/_1856/StockRound_1856.java 2010-09-07 19:14:48 UTC (rev 1414) +++ trunk/18xx/rails/game/specific/_1856/StockRound_1856.java 2010-09-07 19:42:01 UTC (rev 1415) @@ -64,24 +64,21 @@ @Override protected void adjustSharePrice (PublicCompanyI company, int numberSold, boolean soldBefore) { + if (!company.canSharePriceVary()) return; + + int numberOfSpaces = numberSold; if (company instanceof PublicCompany_CGR) { - if (company.canSharePriceVary()) { - int numberOfSpaces; - if (company.getShareUnit() == 5) { - // Take care for selling 5% shares in multiple blocks per turn - numberOfSpaces - = (sharesSoldSoFar.intValue() + numberSold)/2 - - squaresDownSoFar.intValue(); - sharesSoldSoFar.add(numberSold); - squaresDownSoFar.add(numberOfSpaces); - } else { - numberOfSpaces = numberSold; - } - stockMarket.sell(company, numberOfSpaces); + if (company.getShareUnit() == 5) { + // Take care for selling 5% shares in multiple blocks per turn + numberOfSpaces + = (sharesSoldSoFar.intValue() + numberSold)/2 + - squaresDownSoFar.intValue(); + sharesSoldSoFar.add(numberSold); + squaresDownSoFar.add(numberOfSpaces); } - } else { - super.adjustSharePrice (company, numberSold, soldBefore); } + + super.adjustSharePrice (company, numberOfSpaces, soldBefore); } @Override This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-09-10 21:57:25
|
Revision: 1419 http://rails.svn.sourceforge.net/rails/?rev=1419&view=rev Author: evos Date: 2010-09-10 21:57:19 +0000 (Fri, 10 Sep 2010) Log Message: ----------- Further refactoring of (very old) share selling code to simplify structure and unravel cash and certificate movements. There now is a central pay() method for cash transfer. Modified Paths: -------------- trunk/18xx/rails/game/Round.java trunk/18xx/rails/game/ShareSellingRound.java trunk/18xx/rails/game/StartRound.java trunk/18xx/rails/game/StockMarket.java trunk/18xx/rails/game/StockRound.java trunk/18xx/rails/game/TreasuryShareRound.java Modified: trunk/18xx/rails/game/Round.java =================================================================== --- trunk/18xx/rails/game/Round.java 2010-09-10 16:30:21 UTC (rev 1418) +++ trunk/18xx/rails/game/Round.java 2010-09-10 21:57:19 UTC (rev 1419) @@ -113,7 +113,7 @@ protected int getNumberOfPlayers() { return gameManager.getNumberOfPlayers(); } - + protected int getNumberOfActivePlayers () { int number = 0; for (Player player : getPlayers()) { @@ -268,7 +268,7 @@ int minorNo = 0; for (PublicCompanyI company : companyManager.getAllPublicCompanies()) { if (!canCompanyOperateThisRound(company)) continue; - + // Key must put companies in reverse operating order, because sort // is ascending. if (company.hasStockPrice()) { @@ -291,7 +291,7 @@ protected boolean canCompanyOperateThisRound (PublicCompanyI company) { return company.hasFloated() && !company.isClosed(); } - + /** * Check if a company must be floated, and if so, do it. <p>This method is * included here because it is used in various types of Round. @@ -423,15 +423,32 @@ return getClass().getName().replaceAll(".*\\.", ""); } - protected void executeTradeCertificate(Certificate cert, Portfolio newHolder, int price) { + protected void transferCertificate(Certificate cert, Portfolio newHolder) { - Portfolio oldHolder = (Portfolio) cert.getHolder(); cert.moveTo(newHolder); + } - if (price != 0) { - new CashMove(newHolder.getOwner(), oldHolder.getOwner(), price); + // Note: all transferred shares must come from the same old shareholder. + protected void transferCertificates(List<? extends Certificate> certs, + Portfolio newHolder) { + + for (Certificate cert : certs) { + if (cert != null) { + cert.moveTo(newHolder); + } + } + } + + protected void pay (CashHolder from, CashHolder to, int amount) { + if (to != null && amount != 0) { + new CashMove (from, to, amount); } + } + protected void pay (Portfolio from, Portfolio to, int amount) { + if (to != null && amount != 0) { + new CashMove (from.getOwner(), to.getOwner(), amount); + } } public GameManagerI getGameManager() { Modified: trunk/18xx/rails/game/ShareSellingRound.java =================================================================== --- trunk/18xx/rails/game/ShareSellingRound.java 2010-09-10 16:30:21 UTC (rev 1418) +++ trunk/18xx/rails/game/ShareSellingRound.java 2010-09-10 21:57:19 UTC (rev 1419) @@ -366,6 +366,7 @@ price = sellPrice.getPrice(); sellPrices.put(companyName, sellPrice); } + int cashAmount = numberSold * price * shareUnits; moveStack.start(true).linkToPreviousMoveSet(); @@ -375,48 +376,17 @@ company.getShareUnit(), numberSold * company.getShareUnit(), companyName, - Bank.format(numberSold * price) )); + Bank.format(cashAmount) )); boolean soldBefore = sellPrices.containsKey(companyName); + + pay (bank, company, cashAmount); adjustSharePrice (company, numberSold, soldBefore); if (!company.isClosed()) { - // Check if the presidency has changed - if (presCert != null && dumpedPlayer != null && presSharesToSell > 0) { - ReportBuffer.add(LocalText.getText("IS_NOW_PRES_OF", - dumpedPlayer.getName(), - companyName)); - // First swap the certificates - Portfolio dumpedPortfolio = dumpedPlayer.getPortfolio(); - List<PublicCertificateI> swapped = - portfolio.swapPresidentCertificate(company, dumpedPortfolio); - for (int i = 0; i < presSharesToSell; i++) { - certsToSell.add(swapped.get(i)); - } - } - // Transfer the sold certificates - for (PublicCertificateI cert2 : certsToSell) { - if (cert2 != null) { - executeTradeCertificate (cert2, pool, cert2.getShares() * price); - } - } - - // Check if we still have the presidency - if (currentPlayer == company.getPresident()) { - Player otherPlayer; - for (int i = currentIndex + 1; i < currentIndex + numberOfPlayers; i++) { - otherPlayer = gameManager.getPlayerByIndex(i); - if (otherPlayer.getPortfolio().getShare(company) > portfolio.getShare(company)) { - portfolio.swapPresidentCertificate(company, - otherPlayer.getPortfolio()); - ReportBuffer.add(LocalText.getText("IS_NOW_PRES_OF", - otherPlayer.getName(), - company.getName())); - break; - } - } - } + executeShareTransfer (company, certsToSell, + dumpedPlayer, presSharesToSell); } cashToRaise.add(-numberSold * price); Modified: trunk/18xx/rails/game/StartRound.java =================================================================== --- trunk/18xx/rails/game/StartRound.java 2010-09-10 16:30:21 UTC (rev 1418) +++ trunk/18xx/rails/game/StartRound.java 2010-09-10 21:57:19 UTC (rev 1419) @@ -257,14 +257,15 @@ player.getName(), primary.getName(), Bank.format(price) )); - executeTradeCertificate (primary, player.getPortfolio(), price); + pay (player, bank, price); + transferCertificate (primary, player.getPortfolio()); checksOnBuying(primary, sharePrice); if (item.hasSecondary()) { Certificate extra = item.getSecondary(); ReportBuffer.add(LocalText.getText("ALSO_GETS", player.getName(), extra.getName() )); - executeTradeCertificate (extra, player.getPortfolio(), 0); + transferCertificate (extra, player.getPortfolio()); checksOnBuying(extra, sharePrice); } item.setSold(player, price); Modified: trunk/18xx/rails/game/StockMarket.java =================================================================== --- trunk/18xx/rails/game/StockMarket.java 2010-09-10 16:30:21 UTC (rev 1418) +++ trunk/18xx/rails/game/StockMarket.java 2010-09-10 21:57:19 UTC (rev 1419) @@ -248,6 +248,7 @@ if (newrow > row) { newsquare = getStockSpace(newrow, col); } + /* if (newsquare != oldsquare && newsquare.closesCompany()) { company.setClosed(); oldsquare.removeToken(company); @@ -257,6 +258,10 @@ } else { prepareMove(company, oldsquare, newsquare); } + */ + if (newsquare != oldsquare) { + prepareMove(company, oldsquare, newsquare); + } } protected void moveRightOrUp(PublicCompanyI company) { Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2010-09-10 16:30:21 UTC (rev 1418) +++ trunk/18xx/rails/game/StockRound.java 2010-09-10 21:57:19 UTC (rev 1419) @@ -1045,6 +1045,7 @@ // Selling price int price = getCurrentSellPrice (company); + int cashAmount = numberSold * price * shareUnits; // Save original price as it may be reused in subsequent sale actions in the same turn boolean soldBefore = sellPrices.containsKey(companyName); @@ -1059,7 +1060,7 @@ playerName, company.getShareUnit() * shareUnits, companyName, - Bank.format(numberSold * price * shareUnits) )); + Bank.format(cashAmount) )); } else { ReportBuffer.add(LocalText.getText("SELL_SHARES_LOG", playerName, @@ -1067,51 +1068,16 @@ company.getShareUnit() * shareUnits, numberSold * company.getShareUnit() * shareUnits, companyName, - Bank.format(numberSold * price * shareUnits) )); + Bank.format(cashAmount) )); } + pay (bank, currentPlayer, cashAmount); adjustSharePrice (company, numberSold, soldBefore); if (!company.isClosed()) { - // Check if the presidency has changed - if (presCert != null && dumpedPlayer != null && presSharesToSell > 0) { - ReportBuffer.add(LocalText.getText("IS_NOW_PRES_OF", - dumpedPlayer.getName(), - companyName )); - // First swap the certificates - Portfolio dumpedPortfolio = dumpedPlayer.getPortfolio(); - List<PublicCertificateI> swapped = - portfolio.swapPresidentCertificate(company, dumpedPortfolio); - for (int i = 0; i < presSharesToSell; i++) { - certsToSell.add(swapped.get(i)); - } - } - - // Transfer the sold certificates - Iterator<PublicCertificateI> it = certsToSell.iterator(); - while (it.hasNext()) { - cert = it.next(); - if (cert != null) { - executeTradeCertificate(cert, pool, cert.getShares() * price); - } - } - - // Check if we still have the presidency - if (currentPlayer == company.getPresident()) { - Player otherPlayer; - for (int i = currentIndex + 1; i < currentIndex + numberOfPlayers; i++) { - otherPlayer = gameManager.getPlayerByIndex(i); - if (otherPlayer.getPortfolio().getShare(company) > portfolio.getShare(company)) { - portfolio.swapPresidentCertificate(company, - otherPlayer.getPortfolio()); - ReportBuffer.add(LocalText.getText("IS_NOW_PRES_OF", - otherPlayer.getName(), - company.getName() )); - break; - } - } - } + executeShareTransfer (company, certsToSell, + dumpedPlayer, presSharesToSell); } // Remember that the player has sold this company this round. @@ -1125,6 +1091,46 @@ return true; } + protected void executeShareTransfer (PublicCompanyI company, + List<PublicCertificateI> certsToSell, + Player dumpedPlayer, int presSharesToSell) { + + Portfolio portfolio = currentPlayer.getPortfolio(); + + // Check if the presidency has changed + if (dumpedPlayer != null && presSharesToSell > 0) { + ReportBuffer.add(LocalText.getText("IS_NOW_PRES_OF", + dumpedPlayer.getName(), + company.getName() )); + // First swap the certificates + Portfolio dumpedPortfolio = dumpedPlayer.getPortfolio(); + List<PublicCertificateI> swapped = + portfolio.swapPresidentCertificate(company, dumpedPortfolio); + for (int i = 0; i < presSharesToSell; i++) { + certsToSell.add(swapped.get(i)); + } + } + + transferCertificates (certsToSell, pool); + + // Check if we still have the presidency + if (currentPlayer == company.getPresident()) { + Player otherPlayer; + int currentIndex = getCurrentPlayerIndex(); + for (int i = currentIndex + 1; i < currentIndex + numberOfPlayers; i++) { + otherPlayer = gameManager.getPlayerByIndex(i); + if (otherPlayer.getPortfolio().getShare(company) > portfolio.getShare(company)) { + portfolio.swapPresidentCertificate(company, + otherPlayer.getPortfolio()); + ReportBuffer.add(LocalText.getText("IS_NOW_PRES_OF", + otherPlayer.getName(), + company.getName() )); + break; + } + } + } + } + protected int getCurrentSellPrice (PublicCompanyI company) { String companyName = company.getName(); @@ -1143,9 +1149,22 @@ protected void adjustSharePrice (PublicCompanyI company, int numberSold, boolean soldBefore) { - if (company.canSharePriceVary()) { - stockMarket.sell(company, numberSold); + if (!company.canSharePriceVary()) return; + + stockMarket.sell(company, numberSold); + + StockSpaceI newSpace = company.getCurrentSpace(); + + if (newSpace.closesCompany() && company.canClose()) { + company.setClosed(); + ReportBuffer.add(LocalText.getText("CompanyClosesAt", + company.getName(), + newSpace.getName())); + return; } + + // Company is still open + } public boolean useSpecialProperty(UseSpecialProperty action) { Modified: trunk/18xx/rails/game/TreasuryShareRound.java =================================================================== --- trunk/18xx/rails/game/TreasuryShareRound.java 2010-09-10 16:30:21 UTC (rev 1418) +++ trunk/18xx/rails/game/TreasuryShareRound.java 2010-09-10 21:57:19 UTC (rev 1419) @@ -338,6 +338,8 @@ return false; } + int cashAmount = shares * price; + // All seems OK, now buy the shares. if (number == 1) { ReportBuffer.add(LocalText.getText("BUY_SHARE_LOG", @@ -345,7 +347,7 @@ shareUnit, companyName, from.getName(), - Bank.format(shares * price) )); + Bank.format(cashAmount) )); } else { ReportBuffer.add(LocalText.getText("BUY_SHARES_LOG", companyName, @@ -354,14 +356,16 @@ number * shareUnit, companyName, from.getName(), - Bank.format(shares * price) )); + Bank.format(cashAmount) )); } moveStack.start(true); + + pay (company, bank, cashAmount); PublicCertificateI cert2; for (int i = 0; i < number; i++) { cert2 = from.findCertificate(company, sharePerCert/shareUnit, false); - executeTradeCertificate(cert2, portfolio, cert2.getShares() * price); + transferCertificate(cert2, portfolio); } hasBought.set(true); @@ -481,20 +485,25 @@ moveStack.start(true); + int cashAmount = numberSold * price; ReportBuffer.add(LocalText.getText("SELL_SHARES_LOG", companyName, numberSold, company.getShareUnit(), (numberSold * company.getShareUnit()), companyName, - Bank.format(numberSold * price) )); + Bank.format(cashAmount) )); + pay (bank, company, cashAmount); // Transfer the sold certificates + transferCertificates (certsToSell, pool); + /* for (PublicCertificateI cert2 : certsToSell) { if (cert2 != null) { - executeTradeCertificate (cert2, pool, cert2.getShares() * price); + transferCertificate (cert2, pool, cert2.getShares() * price); } } + */ stockMarket.sell(company, numberSold); hasSold.set(true); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-09-19 19:30:41
|
Revision: 1428 http://rails.svn.sourceforge.net/rails/?rev=1428&view=rev Author: evos Date: 2010-09-19 19:30:35 +0000 (Sun, 19 Sep 2010) Log Message: ----------- Bugfix: company closure after withholding crashed the game. Modified Paths: -------------- trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/StockMarket.java Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2010-09-18 15:20:17 UTC (rev 1427) +++ trunk/18xx/rails/game/OperatingRound.java 2010-09-19 19:30:35 UTC (rev 1428) @@ -984,7 +984,7 @@ Bank.format(part), shares, operatingCompany.get().getShareUnit())); - new CashMove(bank, recipient, part); + pay (bank, recipient, part); } // Move the token @@ -1031,9 +1031,26 @@ * @param The revenue amount. */ public void withhold(int amount) { - if (amount > 0) new CashMove(bank, operatingCompany.get(), amount); + + PublicCompanyI company = operatingCompany.get(); + + // Payout revenue to company + pay (bank, company, amount); + // Move the token - operatingCompany.get().withhold(amount); + company.withhold(amount); + + // Check if company has entered a closing area + StockSpaceI newSpace = company.getCurrentSpace(); + if (newSpace.closesCompany() && company.canClose()) { + company.setClosed(); + ReportBuffer.add(LocalText.getText("CompanyClosesAt", + company.getName(), + newSpace.getName())); + finishTurn(); + return; + } + } /** Split a dividend. TODO Optional rounding down the payout @@ -1048,7 +1065,7 @@ int numberOfShares = operatingCompany.get().getNumberOfShares(); int withheld = (amount / (2 * numberOfShares)) * numberOfShares; - new CashMove(bank, operatingCompany.get(), withheld); + pay (bank, operatingCompany.get(), withheld); ReportBuffer.add(operatingCompany.get().getName() + " receives " + Bank.format(withheld)); // Payout the remainder Modified: trunk/18xx/rails/game/StockMarket.java =================================================================== --- trunk/18xx/rails/game/StockMarket.java 2010-09-18 15:20:17 UTC (rev 1427) +++ trunk/18xx/rails/game/StockMarket.java 2010-09-19 19:30:35 UTC (rev 1428) @@ -248,17 +248,6 @@ if (newrow > row) { newsquare = getStockSpace(newrow, col); } - /* - if (newsquare != oldsquare && newsquare.closesCompany()) { - company.setClosed(); - oldsquare.removeToken(company); - ReportBuffer.add(LocalText.getText("CompanyClosesAt", - company.getName(), - newsquare.getName())); - } else { - prepareMove(company, oldsquare, newsquare); - } - */ if (newsquare != oldsquare) { prepareMove(company, oldsquare, newsquare); } @@ -288,16 +277,7 @@ else { newsquare = oldsquare; } - if (newsquare.closesCompany()) { - if (!company.canClose()) return; // E.g. 1856 CGR - company.setClosed(); - oldsquare.removeToken(company); - ReportBuffer.add(LocalText.getText("CompanyClosesAt", - company.getName(), - newsquare.getName())); - } else { - prepareMove(company, oldsquare, newsquare); - } + prepareMove(company, oldsquare, newsquare); } protected void prepareMove(PublicCompanyI company, StockSpaceI from, This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-10-08 19:25:12
|
Revision: 1437 http://rails.svn.sourceforge.net/rails/?rev=1437&view=rev Author: evos Date: 2010-10-08 19:25:05 +0000 (Fri, 08 Oct 2010) Log Message: ----------- Skip creating train actions if no cash and at least 1 train. Modified Paths: -------------- trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/specific/_18EU/OperatingRound_18EU.java Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2010-10-08 19:23:59 UTC (rev 1436) +++ trunk/18xx/rails/game/OperatingRound.java 2010-10-08 19:25:05 UTC (rev 1437) @@ -1040,6 +1040,8 @@ // Move the token company.withhold(amount); + if (!company.hasStockPrice()) return; + // Check if company has entered a closing area StockSpaceI newSpace = company.getCurrentSpace(); if (newSpace.closesCompany() && company.canClose()) { @@ -2491,18 +2493,22 @@ if (operatingCompany.get() == null) return; - TrainManager trainMgr = gameManager.getTrainManager(); + int cash = operatingCompany.get().getCash(); - int cash = operatingCompany.get().getCash(); int cost; List<TrainI> trains; boolean hasTrains = operatingCompany.get().getPortfolio().getNumberOfTrains() > 0; + + // Cannot buy a train without any cash, unless you have to + if (cash == 0 && hasTrains) return; + boolean canBuyTrainNow = canBuyTrainNow(); boolean presidentMayHelp = !hasTrains && operatingCompany.get().mustOwnATrain(); TrainI cheapestTrain = null; int costOfCheapestTrain = 0; + TrainManager trainMgr = gameManager.getTrainManager(); // First check if any more trains may be bought from the Bank // Postpone train limit checking, because an exchange might be possible Modified: trunk/18xx/rails/game/specific/_18EU/OperatingRound_18EU.java =================================================================== --- trunk/18xx/rails/game/specific/_18EU/OperatingRound_18EU.java 2010-10-08 19:23:59 UTC (rev 1436) +++ trunk/18xx/rails/game/specific/_18EU/OperatingRound_18EU.java 2010-10-08 19:25:05 UTC (rev 1437) @@ -40,22 +40,25 @@ if (operatingCompany.get() == null) return; - TrainManager trainMgr = gameManager.getTrainManager(); + int cash = operatingCompany.get().getCash(); - int cash = operatingCompany.get().getCash(); int cost; List<TrainI> trains; BuyTrain bt; boolean hasTrains = operatingCompany.get().getPortfolio().getNumberOfTrains() > 0; + + // Cannot buy a train without any cash, unless you have to + if (cash == 0 && hasTrains) return; + boolean canBuyTrainNow = canBuyTrainNow(); - if (!canBuyTrainNow) return; boolean presidentMayHelp = operatingCompany.get().mustOwnATrain(); TrainI cheapestTrain = null; int costOfCheapestTrain = 0; + TrainManager trainMgr = gameManager.getTrainManager(); String extraMessage = null; boolean mustExchangePullmann = !isBelowTrainLimit() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-10-11 17:20:44
|
Revision: 1443 http://rails.svn.sourceforge.net/rails/?rev=1443&view=rev Author: evos Date: 2010-10-11 17:20:38 +0000 (Mon, 11 Oct 2010) Log Message: ----------- At each OR turn end, check if the company order has changed (if dynamic; this does not apply to 1825) Modified Paths: -------------- trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/Round.java trunk/18xx/rails/game/specific/_1825/OperatingRound_1825.java Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2010-10-11 17:19:02 UTC (rev 1442) +++ trunk/18xx/rails/game/OperatingRound.java 2010-10-11 17:20:38 UTC (rev 1443) @@ -1523,6 +1523,20 @@ if (++index >= operatingCompanies.size()) { return false; } + + // Check if the operating order has changed + List<PublicCompanyI> newOperatingCompanies + = setOperatingCompanies (operatingCompanies.viewList(), operatingCompany.get()); + PublicCompanyI company; + for (int i=0; i<newOperatingCompanies.size(); i++) { + company = newOperatingCompanies.get(i); + log.debug("+++ Index "+i+" new company="+company.getName()); + if (company != operatingCompanies.get(i)) { + log.debug("+++ Index "+i+" old company="+operatingCompanies.get(i).getName()); + operatingCompanies.move(company, i); + } + } + setOperatingCompany(operatingCompanies.get(index)); } Modified: trunk/18xx/rails/game/Round.java =================================================================== --- trunk/18xx/rails/game/Round.java 2010-10-11 17:19:02 UTC (rev 1442) +++ trunk/18xx/rails/game/Round.java 2010-10-11 17:20:38 UTC (rev 1443) @@ -260,26 +260,44 @@ /** Set the operating companies in their current acting order */ public List<PublicCompanyI> setOperatingCompanies() { + return setOperatingCompanies (null, null); + } + public List<PublicCompanyI> setOperatingCompanies(List<PublicCompanyI> oldOperatingCompanies, + PublicCompanyI lastOperatingCompany) { + Map<Integer, PublicCompanyI> operatingCompanies = new TreeMap<Integer, PublicCompanyI>(); StockSpaceI space; int key; int minorNo = 0; + boolean reorder = gameManager.isDynamicOperatingOrder() + && oldOperatingCompanies != null && lastOperatingCompany != null; + + int lastOperatingCompanyIndex; + if (reorder) { + lastOperatingCompanyIndex = oldOperatingCompanies.indexOf(lastOperatingCompany); + } else { + lastOperatingCompanyIndex = -1; + } + for (PublicCompanyI company : companyManager.getAllPublicCompanies()) { if (!canCompanyOperateThisRound(company)) continue; - // Key must put companies in reverse operating order, because sort - // is ascending. - if (company.hasStockPrice()) { + if (reorder + && oldOperatingCompanies.indexOf(company) <= lastOperatingCompanyIndex) { + // Companies that have operated this round get lowest keys + key = oldOperatingCompanies.indexOf(company); + } else if (company.hasStockPrice()) { + // Key must put companies in reverse operating order, because sort + // is ascending. space = company.getCurrentSpace(); - key = - 1000000 * (999 - space.getPrice()) + 10000 - * (99 - space.getColumn()) + 100 - * space.getRow() - + space.getStackPosition(company); + key = 1000000 * (999 - space.getPrice()) + + 10000 * (99 - space.getColumn()) + + 100 * (space.getRow()+1) + + space.getStackPosition(company); } else { - key = ++minorNo; + key = 50 + ++minorNo; } operatingCompanies.put(new Integer(key), company); } Modified: trunk/18xx/rails/game/specific/_1825/OperatingRound_1825.java =================================================================== --- trunk/18xx/rails/game/specific/_1825/OperatingRound_1825.java 2010-10-11 17:19:02 UTC (rev 1442) +++ trunk/18xx/rails/game/specific/_1825/OperatingRound_1825.java 2010-10-11 17:20:38 UTC (rev 1443) @@ -1,13 +1,8 @@ package rails.game.specific._1825; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; +import java.util.*; -import rails.game.GameManagerI; -import rails.game.OperatingRound; -import rails.game.PublicCompanyI; +import rails.game.*; public class OperatingRound_1825 extends OperatingRound { @@ -21,7 +16,7 @@ int space; int key; for (PublicCompanyI company : companyManager.getAllPublicCompanies()) { - if (!canCompanyOperateThisRound(company)) continue; + if (!canCompanyOperateThisRound(company)) continue; // Key must put companies in reverse operating order, because sort // is ascending. space = company.getIPOPrice(); @@ -34,7 +29,12 @@ key = 1000000 - (space - company.getFormationOrderIndex()); operatingCompanies.put(new Integer(key), company); } - return new ArrayList<PublicCompanyI>(operatingCompanies.values()); - } - + return new ArrayList<PublicCompanyI>(operatingCompanies.values()); + } + + @Override + public List<PublicCompanyI> setOperatingCompanies(List<PublicCompanyI> oldOperatingCompanies, + PublicCompanyI lastOperatingCompany) { + return setOperatingCompanies(); + } } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-10-11 17:22:55
|
Revision: 1445 http://rails.svn.sourceforge.net/rails/?rev=1445&view=rev Author: evos Date: 2010-10-11 17:22:49 +0000 (Mon, 11 Oct 2010) Log Message: ----------- At each OR turn end, check if the company order has changed (if dynamic; this does not apply to 1825) Modified Paths: -------------- trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/GameManagerI.java Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-10-11 17:22:10 UTC (rev 1444) +++ trunk/18xx/rails/game/GameManager.java 2010-10-11 17:22:49 UTC (rev 1445) @@ -87,6 +87,8 @@ protected int gameEndsWhenBankHasLessOrEqual = 0; protected boolean gameEndsAfterSetOfORs = true; + protected boolean dynamicOperatingOrder = true; + protected EnumMap<GameDef.Parm, Object> gameParameters = new EnumMap<GameDef.Parm, Object>(GameDef.Parm.class); @@ -330,6 +332,12 @@ throw new ConfigurationException("Cannot find class " + orClassName, e); } + + Tag orderTag = orTag.getChild("OperatingOrder"); + if (orderTag != null) { + dynamicOperatingOrder = orderTag.getAttributeAsBoolean("dynamic", + dynamicOperatingOrder); + } } /* Max. % of shares of one company that a player may hold */ @@ -1179,7 +1187,12 @@ createRound(EndOfGameRound.class); } - /* (non-Javadoc) + + public boolean isDynamicOperatingOrder() { + return dynamicOperatingOrder; + } + + /* (non-Javadoc) * @see rails.game.GameManagerI#isGameOver() */ public boolean isGameOver() { Modified: trunk/18xx/rails/game/GameManagerI.java =================================================================== --- trunk/18xx/rails/game/GameManagerI.java 2010-10-11 17:22:10 UTC (rev 1444) +++ trunk/18xx/rails/game/GameManagerI.java 2010-10-11 17:22:49 UTC (rev 1445) @@ -68,6 +68,8 @@ public abstract void registerBrokenBank(); + public boolean isDynamicOperatingOrder(); + /** * To be called by the UI to check if the rails.game is over. * This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-10-13 19:07:45
|
Revision: 1450 http://rails.svn.sourceforge.net/rails/?rev=1450&view=rev Author: evos Date: 2010-10-13 19:07:38 +0000 (Wed, 13 Oct 2010) Log Message: ----------- 1. Reset Autopass if the player gets over a share/certificate limit during a Stock Round. 2. Skip Treasury trading step if nothing can be done. Modified Paths: -------------- trunk/18xx/rails/game/Game.java trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/GameManagerI.java trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/StockRound.java Modified: trunk/18xx/rails/game/Game.java =================================================================== --- trunk/18xx/rails/game/Game.java 2010-10-12 18:50:32 UTC (rev 1449) +++ trunk/18xx/rails/game/Game.java 2010-10-13 19:07:38 UTC (rev 1450) @@ -261,6 +261,8 @@ log.debug("Starting to execute loaded actions"); + gameManager.setReloading(true); + Object actionObject = null; while (true) { // Single-pass loop. try { @@ -299,7 +301,7 @@ } break; } - + // load user comments (is the last if (actionObject instanceof SortedMap) { ReportBuffer.setCommentItems((SortedMap<Integer, String>) actionObject); @@ -316,10 +318,11 @@ // but also the java.io.StreamCorruptedException: invalid type code } } - + ois.close(); - game.getGameManager().finishLoading(); + gameManager.setReloading(false); + gameManager.finishLoading(); return game; } catch (Exception e) { Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-10-12 18:50:32 UTC (rev 1449) +++ trunk/18xx/rails/game/GameManager.java 2010-10-13 19:07:38 UTC (rev 1450) @@ -89,6 +89,9 @@ protected boolean dynamicOperatingOrder = true; + /** Will only be set during game reload */ + protected boolean reloading = false; + protected EnumMap<GameDef.Parm, Object> gameParameters = new EnumMap<GameDef.Parm, Object>(GameDef.Parm.class); @@ -198,6 +201,14 @@ /** indicates that the recoverySave already issued a warning, avoids displaying several warnings */ protected boolean recoverySaveWarning = true; + /** Flag to skip a subsequent Done action (if present) during reloading. + * <br>This is a fix to maintain backwards compatibility when redundant + * actions are skipped in new code versions (such as the bypassing of + * a treasury trading step if it cannot be executed). + * <br>This flag will be reset after processing <i>any</i> action (not just Done). + */ + protected boolean skipNextDone = false; + protected static Logger log = Logger.getLogger(GameManager.class.getPackage().getName()); @@ -938,7 +949,8 @@ public boolean processOnReload(PossibleAction action) throws Exception { DisplayBuffer.clear(); - // TEMPORARY FIX TO ALLOW OLD 1856 SAVED FILES TO BE PROCESSED + + // XXX TEMPORARY FIX TO ALLOW OLD 1856 SAVED FILES TO BE PROCESSED if (gameName.equals("1856") && possibleActions.contains(RepayLoans.class) && (!possibleActions.contains(action.getClass()) @@ -954,7 +966,20 @@ try { log.debug("Action ("+action.getPlayerName()+"): " + action); - if (!processCorrectionActions(action) && !getCurrentRound().process(action)) { + + // XXX FOR BACKWARDS COMPATIBILITY + boolean doProcess = true; + log.debug("SkipNextDone="+skipNextDone); + if (skipNextDone) { + if (action instanceof NullAction + && ((NullAction)action).getMode() == NullAction.DONE) { + log.info("Skipping processing a Done action during reload"); + doProcess = false; + } + } + skipNextDone = false; + + if (doProcess && !processCorrectionActions(action) && !getCurrentRound().process(action)) { String msg = "Player "+action.getPlayerName()+"\'s action \"" +action.toString()+"\"\n in "+getCurrentRound().getRoundName() +" is considered invalid by the game engine"; @@ -1684,5 +1709,16 @@ return new ArrayList<PublicCompanyI>(operatingCompanies.values()); } + public boolean isReloading() { + return reloading; + } + + public void setReloading(boolean reloading) { + this.reloading = reloading; + } + + public void setSkipDone () { + skipNextDone = true; + } } Modified: trunk/18xx/rails/game/GameManagerI.java =================================================================== --- trunk/18xx/rails/game/GameManagerI.java 2010-10-12 18:50:32 UTC (rev 1449) +++ trunk/18xx/rails/game/GameManagerI.java 2010-10-13 19:07:38 UTC (rev 1450) @@ -205,5 +205,7 @@ public CorrectionManagerI getCorrectionManager(CorrectionType ct); public List<PublicCompanyI> getCompaniesInRunningOrder (); - + public boolean isReloading(); + public void setReloading(boolean reloading); + public void setSkipDone (); } \ No newline at end of file Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2010-10-12 18:50:32 UTC (rev 1449) +++ trunk/18xx/rails/game/OperatingRound.java 2010-10-13 19:07:38 UTC (rev 1450) @@ -247,8 +247,8 @@ NullAction nullAction = (NullAction) action; switch (nullAction.getMode()) { + case NullAction.DONE: case NullAction.PASS: - case NullAction.DONE: result = done(); break; case NullAction.SKIP: @@ -1201,6 +1201,9 @@ /** Take the next step after a given one (see nextStep()) */ protected void nextStep(GameDef.OrStep step) { + + PublicCompanyI company = operatingCompany.get(); + // Cycle through the steps until we reach one where a user action is // expected. int stepIndex; @@ -1212,13 +1215,13 @@ log.debug("Step " + step); if (step == GameDef.OrStep.LAY_TOKEN - && operatingCompany.get().getNumberOfFreeBaseTokens() == 0) { + && company.getNumberOfFreeBaseTokens() == 0) { continue; } if (step == GameDef.OrStep.CALC_REVENUE) { - if (!operatingCompany.get().canRunTrains()) { + if (!company.canRunTrains()) { // No trains, then the revenue is zero. executeSetRevenueAndDividend ( new SetDividend (0, false, new int[] {SetDividend.NO_TRAIN})); @@ -1235,11 +1238,40 @@ if (step == GameDef.OrStep.TRADE_SHARES) { // Is company allowed to trade trasury shares? - if (!operatingCompany.get().mayTradeShares() - || !operatingCompany.get().hasOperated()) { + if (!company.mayTradeShares() + || !company.hasOperated()) { continue; } + /* Check if any trading is possible. + * If not, skip this step. + * (but register a Done action for BACKWARDS COMPATIBILITY only) + */ + // Preload some expensive results + int ownShare = company.getPortfolio().getShare(company); + int poolShare = pool.getShare(company); // Expensive, do it once + // Can it buy? + boolean canBuy = + ownShare < getGameParameterAsInt (GameDef.Parm.TREASURY_SHARE_LIMIT) + && company.getCash() >= company.getCurrentSpace().getPrice() + && poolShare > 0; + // Can it sell? + boolean canSell = + company.getPortfolio().getShare(company) > 0 + && poolShare < getGameParameterAsInt (GameDef.Parm.POOL_SHARE_LIMIT); + // Above we ignore the possible existence of double shares (as in 1835). + + if (!canBuy && !canSell) { + // XXX For BACKWARDS COMPATIBILITY only, + // register a Done skip action during reloading. + if (gameManager.isReloading()) { + gameManager.setSkipDone(); + log.debug("If the next saved action is 'Done', skip it"); + } + log.info("Skipping Treasury share trading step"); + continue; + } + gameManager.startTreasuryShareTradingRound(); } Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2010-10-12 18:50:32 UTC (rev 1449) +++ trunk/18xx/rails/game/StockRound.java 2010-10-13 19:07:38 UTC (rev 1450) @@ -1365,8 +1365,13 @@ setNextPlayer(); sellPrices.clear(); if (hasAutopassed(currentPlayer)) { - // Process a pass for a player that has set Autopass - done (currentPlayer.getName(), true); + if (isPlayerOverLimits(currentPlayer)) { + // Being over a share/certificate limit undoes an Autopass setting + setAutopass (currentPlayer, false); + } else { + // Process a pass for a player that has set Autopass + done (currentPlayer.getName(), true); + } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-12-18 21:42:09
|
Revision: 1462 http://rails.svn.sourceforge.net/rails/?rev=1462&view=rev Author: evos Date: 2010-12-18 21:42:03 +0000 (Sat, 18 Dec 2010) Log Message: ----------- Fixed bug in ArrayListState / AddToList that caused CGR always to operate last in its formation OR. Modified Paths: -------------- trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/move/AddToList.java trunk/18xx/rails/game/specific/_1856/OperatingRound_1856.java trunk/18xx/rails/game/state/ArrayListState.java Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2010-12-18 21:40:56 UTC (rev 1461) +++ trunk/18xx/rails/game/OperatingRound.java 2010-12-18 21:42:03 UTC (rev 1462) @@ -2282,7 +2282,8 @@ } public int getOperatingCompanyIndex() { - return operatingCompanies.indexOf(getOperatingCompany()); + int index = operatingCompanies.indexOf(getOperatingCompany()); + return index; } /** Modified: trunk/18xx/rails/game/move/AddToList.java =================================================================== --- trunk/18xx/rails/game/move/AddToList.java 2010-12-18 21:40:56 UTC (rev 1461) +++ trunk/18xx/rails/game/move/AddToList.java 2010-12-18 21:42:03 UTC (rev 1462) @@ -19,7 +19,7 @@ protected String listName; protected Integer index; // if supplied insert at index position - public AddToList(List<E> list, E object, String listName, + public AddToList(List<E> list, E object, String listName, ModelObject modelToUpdate) { this.object = object; this.list = list; @@ -29,15 +29,25 @@ MoveSet.add(this); } - + public AddToList(List<E> list, E object, String listName) { - this (list, object, listName, null); + this.object = object; + this.list = list; + this.listName = listName; + this.index = null; + + MoveSet.add(this); } - - public void atIndex(int index) { + + public AddToList(List<E> list, E object, int index, String listName) { + this.object = object; + this.list = list; + this.listName = listName; this.index = index; - } + MoveSet.add(this); + } + @Override public boolean execute() { if (index == null) { @@ -58,7 +68,7 @@ @Override public String toString() { - if (index == null) + if (index == null) return "AddToList " + listName + ": " + object.toString(); else return "AddToList " + listName + ": " + object.toString() + " at index " + index; Modified: trunk/18xx/rails/game/specific/_1856/OperatingRound_1856.java =================================================================== --- trunk/18xx/rails/game/specific/_1856/OperatingRound_1856.java 2010-12-18 21:40:56 UTC (rev 1461) +++ trunk/18xx/rails/game/specific/_1856/OperatingRound_1856.java 2010-12-18 21:42:03 UTC (rev 1462) @@ -1,6 +1,7 @@ package rails.game.specific._1856; -import java.util.*; +import java.util.ArrayList; +import java.util.List; import rails.common.GuiDef; import rails.game.*; @@ -9,7 +10,6 @@ import rails.game.special.SellBonusToken; import rails.game.special.SpecialPropertyI; import rails.game.state.BooleanState; -import rails.game.state.IntegerState; import rails.util.LocalText; public class OperatingRound_1856 extends OperatingRound { Modified: trunk/18xx/rails/game/state/ArrayListState.java =================================================================== --- trunk/18xx/rails/game/state/ArrayListState.java 2010-12-18 21:40:56 UTC (rev 1461) +++ trunk/18xx/rails/game/state/ArrayListState.java 2010-12-18 21:42:03 UTC (rev 1462) @@ -43,7 +43,7 @@ } public void add(int index, E element) { - new AddToList<E>(list, element, listName).atIndex(index); + new AddToList<E>(list, element, index, listName); } public boolean remove(E element) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2011-02-05 15:10:29
|
Revision: 1480 http://rails.svn.sourceforge.net/rails/?rev=1480&view=rev Author: evos Date: 2011-02-05 15:10:22 +0000 (Sat, 05 Feb 2011) Log Message: ----------- Fixed bug that mangled operating sequence after PR formation in 1835. Was caused by introduction of dynamic operating sequence, which did not cover (minor) company closures. Modified Paths: -------------- trunk/18xx/rails/game/Round.java trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java Modified: trunk/18xx/rails/game/Round.java =================================================================== --- trunk/18xx/rails/game/Round.java 2011-02-03 23:22:49 UTC (rev 1479) +++ trunk/18xx/rails/game/Round.java 2011-02-05 15:10:22 UTC (rev 1480) @@ -268,6 +268,7 @@ Map<Integer, PublicCompanyI> operatingCompanies = new TreeMap<Integer, PublicCompanyI>(); + List<PublicCompanyI> newOperatingCompanies; StockSpaceI space; int key; int minorNo = 0; @@ -276,13 +277,15 @@ int lastOperatingCompanyIndex; if (reorder) { + newOperatingCompanies = oldOperatingCompanies; lastOperatingCompanyIndex = oldOperatingCompanies.indexOf(lastOperatingCompany); } else { + newOperatingCompanies = companyManager.getAllPublicCompanies(); lastOperatingCompanyIndex = -1; } - for (PublicCompanyI company : companyManager.getAllPublicCompanies()) { - if (!canCompanyOperateThisRound(company)) continue; + for (PublicCompanyI company : newOperatingCompanies) { + if (!reorder && !canCompanyOperateThisRound(company)) continue; if (reorder && oldOperatingCompanies.indexOf(company) <= lastOperatingCompanyIndex) { Modified: trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java =================================================================== --- trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java 2011-02-03 23:22:49 UTC (rev 1479) +++ trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java 2011-02-05 15:10:22 UTC (rev 1480) @@ -138,7 +138,6 @@ @Override public void resume() { - PublicCompanyI prussian = companyManager.getPublicCompany(GameManager_1835.PR_ID); if (prussian.hasFloated() && !prussian.hasOperated() @@ -149,7 +148,7 @@ log.debug("M2 has not operated: PR can operate"); // Insert the Prussian before the first major company - // with a lower current price that hoas not yet operated + // with a lower current price that has not yet operated // and isn't currently operating int index = 0; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2011-02-05 20:00:23
|
Revision: 1481 http://rails.svn.sourceforge.net/rails/?rev=1481&view=rev Author: evos Date: 2011-02-05 20:00:15 +0000 (Sat, 05 Feb 2011) Log Message: ----------- Fix: in 1835, tile laying can hang if OBB owner lays first OBB special property tile. Modified Paths: -------------- trunk/18xx/rails/game/Game.java trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java Modified: trunk/18xx/rails/game/Game.java =================================================================== --- trunk/18xx/rails/game/Game.java 2011-02-05 15:10:22 UTC (rev 1480) +++ trunk/18xx/rails/game/Game.java 2011-02-05 20:00:15 UTC (rev 1481) @@ -13,7 +13,7 @@ import rails.util.Tag; public class Game { - public static final String version = "1.4.1"; + public static final String version = "1.4.1+"; /** The component Manager */ protected ComponentManager componentManager; Modified: trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java =================================================================== --- trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java 2011-02-05 15:10:22 UTC (rev 1480) +++ trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java 2011-02-05 20:00:15 UTC (rev 1481) @@ -219,10 +219,12 @@ } @Override public boolean layTile(LayTile action) { + + boolean hasJustLaidExtraOBBTile = action.getSpecialProperty() != null + && action.getSpecialProperty().getLocationNameString().matches("M1(5|7)"); // The extra OBB tiles may not both be laid in the same round - if (action.getSpecialProperty() != null - && action.getSpecialProperty().getLocationNameString().matches("M1(5|7)")) { + if (hasJustLaidExtraOBBTile) { if (hasLaidExtraOBBTile.booleanValue()) { String errMsg = LocalText.getText("InvalidTileLay"); DisplayBuffer.add(LocalText.getText("CannotLayTileOn", @@ -232,14 +234,18 @@ Bank.format(0), errMsg )); return false; + } else { + hasLaidExtraOBBTile.set(true); + // Done here to make getSpecialTileLays() return the correct value. + // It's provisional, on the assumption that other validations are OK. } } boolean result = super.layTile(action); - if (result && action.getSpecialProperty() != null - && action.getSpecialProperty().getLocationNameString().matches("M1(5|7)")) { - hasLaidExtraOBBTile.set(true); + if (!result && hasJustLaidExtraOBBTile) { + // Revert if tile lay is unsuccessful + hasLaidExtraOBBTile.set(false); } return result; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2011-04-01 10:04:05
|
Revision: 1505 http://rails.svn.sourceforge.net/rails/?rev=1505&view=rev Author: evos Date: 2011-04-01 10:03:59 +0000 (Fri, 01 Apr 2011) Log Message: ----------- Added city number check for home hexes, throwing a ConfigurationException in case of errors. Modified Paths: -------------- trunk/18xx/rails/game/MapHex.java trunk/18xx/rails/game/MapManager.java Modified: trunk/18xx/rails/game/MapHex.java =================================================================== --- trunk/18xx/rails/game/MapHex.java 2011-03-30 14:57:13 UTC (rev 1504) +++ trunk/18xx/rails/game/MapHex.java 2011-04-01 10:03:59 UTC (rev 1505) @@ -950,7 +950,7 @@ return foundCity; } - public void addHome(PublicCompanyI company, int cityNumber) { + public void addHome(PublicCompanyI company, int cityNumber) throws ConfigurationException { if (homes == null) homes = new HashMap<PublicCompanyI, City>(); if (cities.isEmpty()) { log.error("No cities for home station on hex " + name); @@ -959,6 +959,9 @@ if (cityNumber == 0) { homes.put(company, null); log.debug("Added home of " + company + " in hex " + this.toString() + " city not yet decided"); + } else if (cityNumber > cities.size()) { + throw new ConfigurationException ("Invalid city number "+cityNumber+" for hex "+name + +" which has "+cities.size()+" cities"); } else { City homeCity = cities.get(Math.max(cityNumber - 1, 0)); homes.put(company, homeCity); Modified: trunk/18xx/rails/game/MapManager.java =================================================================== --- trunk/18xx/rails/game/MapManager.java 2011-03-30 14:57:13 UTC (rev 1504) +++ trunk/18xx/rails/game/MapManager.java 2011-04-01 10:03:59 UTC (rev 1505) @@ -112,7 +112,7 @@ } } - public void finishConfiguration (GameManagerI gameManager) { + public void finishConfiguration (GameManagerI gameManager) throws ConfigurationException { MapHex hex; int i, j, k, dx, dy; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2011-04-26 15:15:44
|
Revision: 1529 http://rails.svn.sourceforge.net/rails/?rev=1529&view=rev Author: evos Date: 2011-04-26 15:15:37 +0000 (Tue, 26 Apr 2011) Log Message: ----------- Allow a company to have multiple Home hexes. Limitations: - must be fixed (i.e. assigned in the XML) - may not have different station (city) numbers. Modified Paths: -------------- trunk/18xx/rails/game/MapManager.java trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/PublicCompany.java trunk/18xx/rails/game/PublicCompanyI.java trunk/18xx/rails/game/action/MergeCompanies.java trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java trunk/18xx/rails/game/specific/_18EU/StockRound_18EU.java Modified: trunk/18xx/rails/game/MapManager.java =================================================================== --- trunk/18xx/rails/game/MapManager.java 2011-04-26 10:12:34 UTC (rev 1528) +++ trunk/18xx/rails/game/MapManager.java 2011-04-26 15:15:37 UTC (rev 1529) @@ -28,7 +28,7 @@ // upgrade costs on the map for noMapMode protected SortedSet<Integer> possibleTileCosts; - // information to define neighbors + // information to define neighbours protected static final int[] xDeltaNS = new int[] { 0, -1, -1, 0, +1, +1 }; protected static final int[] yXEvenDeltaNS = new int[] { +1, 0, -1, -1, -1, 0 }; @@ -148,9 +148,12 @@ } } + List<MapHex> homeHexes; for (PublicCompanyI company : gameManager.getCompanyManager().getAllPublicCompanies()) { - if ((hex = company.getHomeHex()) != null) { - hex.addHome(company, company.getHomeCityNumber()); + if ((homeHexes = company.getHomeHexes()) != null) { + for (MapHex homeHex : homeHexes) { + homeHex.addHome(company, company.getHomeCityNumber()); + } } if ((hex = company.getDestinationHex()) != null) { hex.addDestination(company); Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2011-04-26 10:12:34 UTC (rev 1528) +++ trunk/18xx/rails/game/OperatingRound.java 2011-04-26 15:15:37 UTC (rev 1529) @@ -2362,7 +2362,7 @@ if (!operatingCompany.get().hasLaidHomeBaseTokens()) { // This can occur if the home hex has two cities and track, // such as the green OO tile #59 - possibleActions.add(new LayBaseToken (operatingCompany.get().getHomeHex())); + possibleActions.add(new LayBaseToken (operatingCompany.get().getHomeHexes())); forced = true; } else { possibleActions.addAll(getNormalTileLays(true)); Modified: trunk/18xx/rails/game/PublicCompany.java =================================================================== --- trunk/18xx/rails/game/PublicCompany.java 2011-04-26 10:12:34 UTC (rev 1528) +++ trunk/18xx/rails/game/PublicCompany.java 2011-04-26 15:15:37 UTC (rev 1529) @@ -14,7 +14,7 @@ /** * This class provides an implementation of a (perhaps only basic) public - * company. Public companies emcompass all 18xx company-like entities that lay + * company. Public companies encompass all 18xx company-like entities that lay * tracks and run trains. <p> Ownership of companies will always be performed by * holding certificates. Some minor company types may have only one certificate, * but this will still be the form in which ownership is expressed. <p> Company @@ -55,9 +55,13 @@ /** Hexadecimal representation (RRGGBB) of the background colour. */ protected String bgHexColour = "000000"; - /** Home hex & city * */ - protected String homeHexName = null; - protected MapHex homeHex = null; + /** Home hex & city * + * Two home hexes is supported, but only if:<br> + * 1. The locations are fixed (i.e. configured by XML), and<br> + * 2. Any station (city) numbers are equal for the two home stations. + * There is no provision yet for two home hexes having different tile station numbers. */ + protected String homeHexNames = null; + protected List<MapHex> homeHexes = null; protected int homeCityNumber = 1; protected boolean homeAllCitiesBlocked = false; @@ -319,7 +323,7 @@ Tag homeBaseTag = tag.getChild("Home"); if (homeBaseTag != null) { - homeHexName = homeBaseTag.getAttributeAsString("hex"); + homeHexNames = homeBaseTag.getAttributeAsString("hex"); homeCityNumber = homeBaseTag.getAttributeAsInteger("city", 1); homeAllCitiesBlocked = homeBaseTag.getAttributeAsBoolean("allCitiesBlocked", false); } @@ -707,14 +711,19 @@ freeBaseTokens.add(token); } - if (homeHexName != null) { - homeHex = mapManager.getHex(homeHexName); - if (homeHex == null) { - throw new ConfigurationException("Invalid home hex " - + homeHexName - + " for company " + name); + if (homeHexNames != null) { + homeHexes = new ArrayList<MapHex>(2); + MapHex homeHex; + for (String homeHexName : homeHexNames.split(",")) { + homeHex = mapManager.getHex(homeHexName); + if (homeHex == null) { + throw new ConfigurationException("Invalid home hex " + + homeHexName + + " for company " + name); + } + homeHexes.add (homeHex); + infoText += "<br>Home: " + homeHex.getInfo(); } - infoText += "<br>Home: " + homeHex.getInfo(); } if (destinationHexName != null) { @@ -789,17 +798,22 @@ } /** + * Return the company's Home hexes (usually one). * @return Returns the homeHex. */ - public MapHex getHomeHex() { - return homeHex; + public List<MapHex> getHomeHexes() { + return homeHexes; } /** + * Set a non-fixed company home hex. + * Only covers setting <i>one</i> home hex. + * Having <i>two</i> home hexes is currently only supported if the locations are preconfigured. * @param homeHex The homeHex to set. */ public void setHomeHex(MapHex homeHex) { - this.homeHex = homeHex; + if (homeHexes == null) homeHexes = new ArrayList<MapHex>(1); + homeHexes.set(0, homeHex); } /** @@ -1662,7 +1676,7 @@ /** * Calculate the cost of laying a token, given the hex where - * the token is laid. This only makes a diofference for de "distance" method. + * the token is laid. This only makes a difference for de "distance" method. * @param hex The hex where the token is to be laid. * @return The cost of laying that token. */ @@ -1683,7 +1697,8 @@ if (hex == null) { return baseTokenLayCost[0]; } else { - return mapManager.getHexDistance(homeHex, hex) * baseTokenLayCost[0]; + // WARNING: no provision yet for multiple home hexes. + return mapManager.getHexDistance(homeHexes.get(0), hex) * baseTokenLayCost[0]; } } else { return 0; @@ -1699,7 +1714,8 @@ if (baseTokenLayCostMethod.equals(BASE_COST_SEQUENCE)) { return new int[] {getBaseTokenLayCost(null)}; } else if (baseTokenLayCostMethod.equals(BASE_COST_DISTANCE)) { - int[] distances = mapManager.getCityDistances(homeHex); + // WARNING: no provision yet for multiple home hexes. + int[] distances = mapManager.getCityDistances(homeHexes.get(0)); int[] costs = new int[distances.length]; int i = 0; for (int distance : distances) { @@ -1763,28 +1779,27 @@ // Return value is not used public boolean layHomeBaseTokens() { - // TODO Assume for now that companies have only one home base. - // This is not true in 1841! - // TODO This does not yet cover cases where the user - // has a choice, such in 1830 Erie. if (hasLaidHomeBaseTokens()) return true; - if (homeCityNumber == 0) { - // This applies to cases like 1830 Erie and 1856 THB. - // On a trackless tile it does not matter, but if - // the tile has track (such as the green OO tile), - // the player must select a city. - Map<Integer, List<Track>> tracks - = homeHex.getCurrentTile().getTracksPerStationMap(); - if (tracks == null || tracks.isEmpty()) { - homeCityNumber = 1; - } else { - return false; + for (MapHex homeHex : homeHexes) { + if (homeCityNumber == 0) { + // This applies to cases like 1830 Erie and 1856 THB. + // On a trackless tile it does not matter, but if + // the tile has track (such as the green OO tile), + // the player must select a city. + Map<Integer, List<Track>> tracks + = homeHex.getCurrentTile().getTracksPerStationMap(); + if (tracks == null || tracks.isEmpty()) { + homeCityNumber = 1; + } else { + return false; + } } + log.debug(name + " lays home base on " + homeHex.getName() + " city " + + homeCityNumber); + homeHex.layBaseToken(this, homeCityNumber); } - log.debug(name + " lays home base on " + homeHex.getName() + " city " - + homeCityNumber); - return homeHex.layBaseToken(this, homeCityNumber); + return true; } public BaseToken getFreeToken() { Modified: trunk/18xx/rails/game/PublicCompanyI.java =================================================================== --- trunk/18xx/rails/game/PublicCompanyI.java 2011-04-26 10:12:34 UTC (rev 1528) +++ trunk/18xx/rails/game/PublicCompanyI.java 2011-04-26 15:15:37 UTC (rev 1529) @@ -313,7 +313,7 @@ public boolean removeBonus (String name); public List<Bonus> getBonuses(); - public MapHex getHomeHex(); + public List<MapHex> getHomeHexes(); public void setHomeHex(MapHex homeHex); Modified: trunk/18xx/rails/game/action/MergeCompanies.java =================================================================== --- trunk/18xx/rails/game/action/MergeCompanies.java 2011-04-26 10:12:34 UTC (rev 1528) +++ trunk/18xx/rails/game/action/MergeCompanies.java 2011-04-26 15:15:37 UTC (rev 1529) @@ -50,7 +50,7 @@ canReplaceToken.add(false); } else { b.append(target.getName()); - MapHex hex = mergingCompany.getHomeHex(); + MapHex hex = mergingCompany.getHomeHexes().get(0); canReplaceToken.add(target.getNumberOfFreeBaseTokens() > 0 && (!hex.hasTokenOfCompany(target) || hex.getCurrentTile().allowsMultipleBasesOfOneCompany() Modified: trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java =================================================================== --- trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java 2011-04-26 10:12:34 UTC (rev 1528) +++ trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java 2011-04-26 15:15:37 UTC (rev 1529) @@ -532,7 +532,7 @@ if (!bt.isPlaced()) continue; city = (City) bt.getHolder(); hex = city.getHolder(); - if (hex == comp.getHomeHex()) { + if (hex == comp.getHomeHexes()) { homeTokens.add(bt); } else { nonHomeTokens.add(bt); Modified: trunk/18xx/rails/game/specific/_18EU/StockRound_18EU.java =================================================================== --- trunk/18xx/rails/game/specific/_18EU/StockRound_18EU.java 2011-04-26 10:12:34 UTC (rev 1528) +++ trunk/18xx/rails/game/specific/_18EU/StockRound_18EU.java 2011-04-26 15:15:37 UTC (rev 1529) @@ -387,7 +387,7 @@ MapHex homeHex = null; int homeCityNumber = 1; if (minor != null) { - homeHex = minor.getHomeHex(); + homeHex = minor.getHomeHexes().get(0); homeCityNumber = homeHex.getCityOfBaseToken(minor); } else if (selectedHomeCity != null) { homeHex = selectedHomeCity.getHolder(); @@ -536,7 +536,7 @@ } } - MapHex homeHex = minor.getHomeHex(); + MapHex homeHex = minor.getHomeHexes().get(0); int homeCityNumber = homeHex.getCityOfBaseToken(minor); minor.setClosed(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2011-04-27 19:58:16
|
Revision: 1536 http://rails.svn.sourceforge.net/rails/?rev=1536&view=rev Author: evos Date: 2011-04-27 19:58:09 +0000 (Wed, 27 Apr 2011) Log Message: ----------- Fixes for delayed train obsolescence (18AL rules). Modified Paths: -------------- trunk/18xx/rails/game/Game.java trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/TrainType.java Modified: trunk/18xx/rails/game/Game.java =================================================================== --- trunk/18xx/rails/game/Game.java 2011-04-27 12:09:32 UTC (rev 1535) +++ trunk/18xx/rails/game/Game.java 2011-04-27 19:58:09 UTC (rev 1536) @@ -278,20 +278,31 @@ (List<PossibleAction>) actionObject; numberOfActions = executedActions.size(); for (PossibleAction action : executedActions) { - if (!gameManager.processOnReload(action)) { - log.error ("Load interrupted"); - DisplayBuffer.add(LocalText.getText("LoadInterrupted")); - break; + try { + if (!gameManager.processOnReload(action)) { + log.error ("Load interrupted"); + DisplayBuffer.add(LocalText.getText("LoadInterrupted")); + break; + } + } catch (Exception e) { + log.fatal("Action '"+action+"' reload exception", e); + throw new Exception ("Reload exception", e); } } } else if (actionObject instanceof PossibleAction) { // New style: separate PossibleActionsObjects, since Rails 1.3.1 while (actionObject instanceof PossibleAction) { numberOfActions++; - if (!gameManager.processOnReload((PossibleAction)actionObject)) { - log.error ("Load interrupted"); - DisplayBuffer.add(LocalText.getText("LoadInterrupted")); - break; + try { + if (!gameManager.processOnReload((PossibleAction)actionObject)) { + log.error ("Load interrupted"); + DisplayBuffer.add(LocalText.getText("LoadInterrupted")); + break; + } + } catch (Exception e) { + log.fatal("Action '"+((PossibleAction)actionObject).toString() + +"' reload exception", e); + throw new Exception ("Reload exception", e); } try { actionObject = ois.readObject(); @@ -328,7 +339,7 @@ return game; } catch (Exception e) { - log.error("Load failed", e); + log.fatal("Load failed", e); DisplayBuffer.add(LocalText.getText("LoadFailed", e.getMessage())); } Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2011-04-27 12:09:32 UTC (rev 1535) +++ trunk/18xx/rails/game/OperatingRound.java 2011-04-27 19:58:09 UTC (rev 1536) @@ -1805,7 +1805,7 @@ TrainI oldTrain = operatingCompany.get().getPortfolio().getTrainOfType( exchangedTrain.getType()); - pool.buyTrain(oldTrain, 0); + train.moveTo(train.isObsolete() ? scrapHeap : pool); ReportBuffer.add(LocalText.getText("ExchangesTrain", companyName, exchangedTrain.getName(), @@ -1950,7 +1950,7 @@ // if (action.isForced()) moveStack.linkToPreviousMoveSet(); - pool.buyTrain(train, 0); + train.moveTo(train.isObsolete() ? scrapHeap : pool); ReportBuffer.add(LocalText.getText("CompanyDiscardsTrain", companyName, train.getName() )); @@ -2726,7 +2726,6 @@ } // Scan trains per company per player, operating company president // first - //int currentPlayerIndex = operatingCompany.getObject().getPresident().getIndex(); int currentPlayerIndex = getCurrentPlayer().getIndex(); for (int i = currentPlayerIndex; i < currentPlayerIndex + numberOfPlayers; i++) { Modified: trunk/18xx/rails/game/TrainType.java =================================================================== --- trunk/18xx/rails/game/TrainType.java 2011-04-27 12:09:32 UTC (rev 1535) +++ trunk/18xx/rails/game/TrainType.java 2011-04-27 19:58:09 UTC (rev 1536) @@ -435,14 +435,16 @@ public void setRusted(Portfolio lastBuyingCompany) { rusted.set(true); for (TrainI train : trains) { - if (obsoleting && train.getHolder() != lastBuyingCompany) { + Portfolio holder = train.getHolder(); + if (obsoleting && holder.getOwner() instanceof PublicCompanyI + && holder != lastBuyingCompany) { log.debug("Train " + train.getUniqueId() + " (owned by " - + train.getHolder().getName() + ") obsoleted"); + + holder.getName() + ") obsoleted"); train.setObsolete(); - train.getHolder().getTrainsModel().update(); + holder.getTrainsModel().update(); } else { log.debug("Train " + train.getUniqueId() + " (owned by " - + train.getHolder().getName() + ") rusted"); + + holder.getName() + ") rusted"); train.setRusted(); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2011-04-29 13:27:17
|
Revision: 1540 http://rails.svn.sourceforge.net/rails/?rev=1540&view=rev Author: evos Date: 2011-04-29 13:27:11 +0000 (Fri, 29 Apr 2011) Log Message: ----------- 18TN: Enabled private purchase in first OR turn at fixed price. Modified Paths: -------------- trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/GameManagerI.java trunk/18xx/rails/game/specific/_18TN/OperatingRound_18TN.java Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2011-04-29 13:03:56 UTC (rev 1539) +++ trunk/18xx/rails/game/GameManager.java 2011-04-29 13:27:11 UTC (rev 1540) @@ -743,6 +743,10 @@ return String.valueOf(absoluteORNumber.intValue()); } } + + public int getAbsoluteORNumber () { + return absoluteORNumber.intValue(); + } /* (non-Javadoc) * @see rails.game.GameManagerI#getCompositeORNumber() Modified: trunk/18xx/rails/game/GameManagerI.java =================================================================== --- trunk/18xx/rails/game/GameManagerI.java 2011-04-29 13:03:56 UTC (rev 1539) +++ trunk/18xx/rails/game/GameManagerI.java 2011-04-29 13:27:11 UTC (rev 1540) @@ -38,6 +38,7 @@ public String getORId (); public abstract String getCompositeORNumber(); public int getRelativeORNumber(); + public int getAbsoluteORNumber (); public abstract int getSRNumber(); Modified: trunk/18xx/rails/game/specific/_18TN/OperatingRound_18TN.java =================================================================== --- trunk/18xx/rails/game/specific/_18TN/OperatingRound_18TN.java 2011-04-29 13:03:56 UTC (rev 1539) +++ trunk/18xx/rails/game/specific/_18TN/OperatingRound_18TN.java 2011-04-29 13:27:11 UTC (rev 1540) @@ -11,31 +11,30 @@ } protected boolean isPrivateSellingAllowed() { - return getCurrentPhase().isPrivateSellingAllowed() + return super.isPrivateSellingAllowed() // 18TN special - || !operatingCompany.get().hasOperated() && !ownsPrivate(operatingCompany.get()); + || gameManager.getAbsoluteORNumber() == 1 + && !ownsPrivate(operatingCompany.get()); } protected int getPrivateMinimumPrice (PrivateCompanyI privComp) { - int minPrice = privComp.getLowerPrice(); - if (minPrice == PrivateCompanyI.NO_PRICE_LIMIT) { - minPrice = 0; - } else if (!operatingCompany.get().hasOperated()) { + if (gameManager.getAbsoluteORNumber() == 1 + && !getCurrentPhase().isPrivateSellingAllowed()) { // 18TN special - minPrice = privComp.getBasePrice(); + return privComp.getBasePrice(); + } else { + return super.getPrivateMinimumPrice(privComp); } - return minPrice; } protected int getPrivateMaximumPrice (PrivateCompanyI privComp) { - int maxPrice = privComp.getUpperPrice(); - if (maxPrice == PrivateCompanyI.NO_PRICE_LIMIT) { - maxPrice = operatingCompany.get().getCash(); - } else if (!operatingCompany.get().hasOperated()) { + if (gameManager.getAbsoluteORNumber() == 1 + && !getCurrentPhase().isPrivateSellingAllowed()) { // 18TN special - maxPrice = privComp.getBasePrice(); + return privComp.getBasePrice(); + } else { + return super.getPrivateMaximumPrice(privComp); } - return maxPrice; } private boolean ownsPrivate (PublicCompanyI company) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2011-04-29 14:07:57
|
Revision: 1541 http://rails.svn.sourceforge.net/rails/?rev=1541&view=rev Author: evos Date: 2011-04-29 14:07:51 +0000 (Fri, 29 Apr 2011) Log Message: ----------- 18TN: Enabled private purchase in first OR turn at fixed price. Modified Paths: -------------- trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/specific/_18TN/OperatingRound_18TN.java trunk/18xx/rails/game/state/ArrayListState.java Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2011-04-29 13:27:11 UTC (rev 1540) +++ trunk/18xx/rails/game/OperatingRound.java 2011-04-29 14:07:51 UTC (rev 1541) @@ -2426,8 +2426,9 @@ List<Player> players = getPlayers(); int numberOfPlayers = getNumberOfPlayers(); for (int i = currentPlayerIndex; i < currentPlayerIndex - + numberOfPlayers; i++) { + + numberOfPlayers; i++) { player = players.get(i % numberOfPlayers); + if (!maySellPrivate(player)) continue; for (PrivateCompanyI privComp : player.getPortfolio().getPrivateCompanies()) { // check to see if the private can be sold to a company @@ -2536,6 +2537,10 @@ return maxPrice; } + protected boolean maySellPrivate (Player player) { + return true; + } + protected void prepareRevenueAndDividendAction () { // There is only revenue if there are any trains Modified: trunk/18xx/rails/game/specific/_18TN/OperatingRound_18TN.java =================================================================== --- trunk/18xx/rails/game/specific/_18TN/OperatingRound_18TN.java 2011-04-29 13:27:11 UTC (rev 1540) +++ trunk/18xx/rails/game/specific/_18TN/OperatingRound_18TN.java 2011-04-29 14:07:51 UTC (rev 1541) @@ -1,11 +1,15 @@ package rails.game.specific._18TN; -import java.util.List; +import java.util.*; import rails.game.*; +import rails.game.action.BuyPrivate; +import rails.game.state.ArrayListState; public class OperatingRound_18TN extends OperatingRound { + private ArrayListState<Player> playersSoldInOR1; + public OperatingRound_18TN (GameManagerI gameManager) { super (gameManager); } @@ -41,5 +45,33 @@ List<PrivateCompanyI> privates = company.getPortfolio().getPrivateCompanies(); return privates != null && !privates.isEmpty(); } + + protected boolean maySellPrivate (Player player) { + return gameManager.getAbsoluteORNumber() != 1 + || !hasPlayerSoldInOR1(player); + } + + private boolean hasPlayerSoldInOR1 (Player player) { + return playersSoldInOR1 != null && playersSoldInOR1.contains(player); + } + public boolean buyPrivate(BuyPrivate action) { + + Player sellingPlayer = null; + + if (gameManager.getAbsoluteORNumber() == 1) { + sellingPlayer = (Player)((Portfolio)action.getPrivateCompany().getHolder()).getOwner(); + } + + boolean result = super.buyPrivate(action); + + if (result && gameManager.getAbsoluteORNumber() == 1) { + if (playersSoldInOR1 == null) playersSoldInOR1 = new ArrayListState<Player>("PlayersSoldPrivateInOR1"); + if (!playersSoldInOR1.contains(sellingPlayer)) { + playersSoldInOR1.add(sellingPlayer); + } + } + + return result; + } } Modified: trunk/18xx/rails/game/state/ArrayListState.java =================================================================== --- trunk/18xx/rails/game/state/ArrayListState.java 2011-04-29 13:27:11 UTC (rev 1540) +++ trunk/18xx/rails/game/state/ArrayListState.java 2011-04-29 14:07:51 UTC (rev 1541) @@ -58,6 +58,10 @@ public void move (E element, int toIndex) { if (remove (element)) add (toIndex, element); } + + public boolean contains (E element) { + return list.contains(element); + } public void clear() { for (E element:list) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2011-07-04 11:13:00
|
Revision: 1599 http://rails.svn.sourceforge.net/rails/?rev=1599&view=rev Author: evos Date: 2011-07-04 11:12:54 +0000 (Mon, 04 Jul 2011) Log Message: ----------- Fixed that undoing a Coalfields right by action did not reset the UI. HashMapState now extends ModelObject. MapChange and RemoveFromMap now can be passed the ModelObject it is changing, and on execute() and undo() the model update() method is now called to update the Observers; this all works the same way as ArrayListState already did. Modified Paths: -------------- trunk/18xx/rails/game/PublicCompany.java trunk/18xx/rails/game/PublicCompanyI.java trunk/18xx/rails/game/move/MapChange.java trunk/18xx/rails/game/move/RemoveFromMap.java trunk/18xx/rails/game/state/HashMapState.java Removed Paths: ------------- trunk/18xx/rails/game/model/RightsModel.java Modified: trunk/18xx/rails/game/PublicCompany.java =================================================================== --- trunk/18xx/rails/game/PublicCompany.java 2011-07-03 20:06:38 UTC (rev 1598) +++ trunk/18xx/rails/game/PublicCompany.java 2011-07-04 11:12:54 UTC (rev 1599) @@ -280,7 +280,7 @@ /** Rights */ protected HashMapState<String, String> rights = null; - protected RightsModel rightsModel = new RightsModel(); + //protected RightsModel rightsModel = new RightsModel(); /** @@ -765,6 +765,9 @@ for (SpecialPropertyI sp : specialProperties) { if (sp instanceof SpecialRight) { gameManager.setGuiParameter (GuiDef.Parm.HAS_ANY_RIGHTS, true); + // Initialize rights here to prevent overhead if not used, + // but if rights are used, the GUI needs it from the start. + if (rights == null) rights = new HashMapState<String, String>(name+"_Rights"); } } } @@ -1986,8 +1989,9 @@ return currentLoanValue; } - public RightsModel getRightsModel () { - return rightsModel; + public ModelObject getRightsModel () { + //return rightsModel; + return rights; } public boolean canClose() { @@ -1997,10 +2001,10 @@ public void setRight (String nameOfRight, String value) { if (rights == null) { rights = new HashMapState<String, String>(name+"_Rights"); - rightsModel.init (rights); + //rightsModel.init (rights); } rights.put(nameOfRight, value); - rightsModel.update(); + //rightsModel.update(); } public boolean hasRight (String nameOfRight) { Modified: trunk/18xx/rails/game/PublicCompanyI.java =================================================================== --- trunk/18xx/rails/game/PublicCompanyI.java 2011-07-03 20:06:38 UTC (rev 1598) +++ trunk/18xx/rails/game/PublicCompanyI.java 2011-07-04 11:12:54 UTC (rev 1599) @@ -342,7 +342,7 @@ public int getMaxLoansPerRound(); public int getValuePerLoan(); public MoneyModel getLoanValueModel (); - public RightsModel getRightsModel (); + public ModelObject getRightsModel (); public int sharesOwnedByPlayers(); public String getExtraShareMarks (); Deleted: trunk/18xx/rails/game/model/RightsModel.java =================================================================== --- trunk/18xx/rails/game/model/RightsModel.java 2011-07-03 20:06:38 UTC (rev 1598) +++ trunk/18xx/rails/game/model/RightsModel.java 2011-07-04 11:12:54 UTC (rev 1599) @@ -1,37 +0,0 @@ -/* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/model/RightsModel.java,v 1.6 2008/06/04 19:00:37 evos Exp $*/ -package rails.game.model; - -import rails.game.state.HashMapState; -import tools.Util; - -public class RightsModel extends ModelObject { - - private HashMapState<String, String> rights; - - public RightsModel() { - } - - /** Split off from the constructor to allow the rights map to exist only if needed */ - public void init (HashMapState<String, String> rights) { - this.rights = rights; - } - - public String getText() { - - if (rights == null) return ""; - - StringBuilder buf = new StringBuilder("<html>"); - for (String name : rights.viewKeySet()) { - if (buf.length() > 6) buf.append("<br>"); - buf.append(name); - String value = rights.get(name); - if (Util.hasValue(value)) buf.append("=").append(value); - } - if (buf.length() > 6) { - buf.append("</html>"); - } - return buf.toString(); - - } - -} Modified: trunk/18xx/rails/game/move/MapChange.java =================================================================== --- trunk/18xx/rails/game/move/MapChange.java 2011-07-03 20:06:38 UTC (rev 1598) +++ trunk/18xx/rails/game/move/MapChange.java 2011-07-04 11:12:54 UTC (rev 1599) @@ -7,6 +7,8 @@ import java.util.Map; +import rails.game.model.ModelObject; + /** * This Move class handles adding an entry to a Map. * @@ -35,9 +37,22 @@ MoveSet.add(this); } + public MapChange (Map<K, V> map, K key, V newValue, ModelObject modelToUpdate) { + + this.map = map; + this.key = key; + this.newValue = newValue; + this.oldValue = map.get(key); + this.keyExisted = map.containsKey(key); + if (modelToUpdate != null) registerModelToUpdate (modelToUpdate); + + MoveSet.add(this); + } + @Override public boolean execute() { map.put(key, newValue); + updateModels(); return true; } @@ -48,6 +63,7 @@ } else { map.remove(key); } + updateModels(); return true; } Modified: trunk/18xx/rails/game/move/RemoveFromMap.java =================================================================== --- trunk/18xx/rails/game/move/RemoveFromMap.java 2011-07-03 20:06:38 UTC (rev 1598) +++ trunk/18xx/rails/game/move/RemoveFromMap.java 2011-07-04 11:12:54 UTC (rev 1599) @@ -7,6 +7,8 @@ import java.util.Map; +import rails.game.model.ModelObject; + /** * This Move class handles removable from a stateful map (collection) * @@ -34,10 +36,23 @@ MoveSet.add(this); } + public RemoveFromMap (Map<K, V> map, K key, ModelObject modelToUpdate) { + + keyExisted = map.containsKey(key); + if (!keyExisted) return; // Nothing to do + this.map = map; + this.key = key; + this.oldValue = map.get(key); + if (modelToUpdate != null) registerModelToUpdate (modelToUpdate); + + MoveSet.add(this); + } + @Override public boolean execute() { if (keyExisted) { map.remove(key); + updateModels(); } return true; } @@ -46,6 +61,7 @@ public boolean undo() { if (keyExisted) { map.put (key, oldValue); + updateModels(); } return true; } Modified: trunk/18xx/rails/game/state/HashMapState.java =================================================================== --- trunk/18xx/rails/game/state/HashMapState.java 2011-07-03 20:06:38 UTC (rev 1598) +++ trunk/18xx/rails/game/state/HashMapState.java 2011-07-04 11:12:54 UTC (rev 1599) @@ -8,8 +8,10 @@ import java.util.Map; import java.util.Set; +import rails.game.model.ModelObject; import rails.game.move.MapChange; import rails.game.move.RemoveFromMap; +import tools.Util; /** * State class that wraps a HashMap @@ -23,7 +25,7 @@ * */ -public class HashMapState<K,V>{ +public class HashMapState<K,V> extends ModelObject { private final HashMap<K,V> map = new HashMap<K,V>(); private String mapName; @@ -42,12 +44,12 @@ } public void put(K key, V value) { - new MapChange<K,V>(map, key, value); + new MapChange<K,V>(map, key, value, this); } public void putAll(Map<K,V> map) { for (K key:map.keySet()) { - new MapChange<K,V>(map, key, map.get(key)); + new MapChange<K,V>(map, key, map.get(key), this); } } @@ -56,7 +58,7 @@ } public void remove(K key) { - new RemoveFromMap<K,V>(map, key); + new RemoveFromMap<K,V>(map, key, this); } public boolean hasKey(K key) { @@ -72,6 +74,7 @@ for (K key : keys) { remove (key); } + update(); } /** @@ -93,6 +96,7 @@ new MapChange<K,V>(map, key, initMap.get(key)); } } + update(); } /** @@ -115,4 +119,24 @@ public boolean isEmpty() { return map.isEmpty(); } + + @Override + public String getText() { + + if (map == null) return ""; + + StringBuilder buf = new StringBuilder("<html>"); + for (K name : map.keySet()) { + if (buf.length() > 6) buf.append("<br>"); + buf.append(name.toString()); + Object value = map.get(name); + if (value != null && Util.hasValue(value.toString())) buf.append("=").append(value.toString()); + } + if (buf.length() > 6) { + buf.append("</html>"); + } + return buf.toString(); + + } + } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |