From: <ste...@us...> - 2010-07-11 16:40:53
|
Revision: 1336 http://rails.svn.sourceforge.net/rails/?rev=1336&view=rev Author: stefanfrey Date: 2010-07-11 16:40:44 +0000 (Sun, 11 Jul 2010) Log Message: ----------- Bug: 1856. THB token spot blocked inappropriately - ID: 3025465 Fixed, added the case of a OO-city home base, where other companies can lay tokens in the other city before the start. Modified Paths: -------------- trunk/18xx/rails/game/MapHex.java trunk/18xx/rails/ui/swing/hexmap/GUIHex.java Modified: trunk/18xx/rails/game/MapHex.java =================================================================== --- trunk/18xx/rails/game/MapHex.java 2010-07-10 22:25:10 UTC (rev 1335) +++ trunk/18xx/rails/game/MapHex.java 2010-07-11 16:40:44 UTC (rev 1336) @@ -921,7 +921,15 @@ if (cities.isEmpty()) { log.error("No cities for home station on hex " + name); } else { - homes.put(company, cities.get(Math.max(cityNumber - 1, 0))); + // not yet decided + if (cityNumber == 0) { + homes.put(company, null); + log.debug("Added home of " + company + " in hex " + this.toString() + " city not yet decided"); + } else { + City homeCity = cities.get(Math.max(cityNumber - 1, 0)); + homes.put(company, homeCity); + log.debug("Added home of " + company + " set to " + homeCity + " id= " +homeCity.getUniqueId()); + } } } @@ -994,30 +1002,44 @@ /** * @return Returns false if no base tokens may yet be laid on this hex and station. * NOTE: this method currently only checks for prohibitions caused - * by the presence of unlaid hoem base tokens. + * 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) + * otherwise + * B) City is decided => check the city if a slot is left (standard) + * C) City is undecided => check all cities if there is a slot left */ public boolean isBlockedForTokenLays(PublicCompanyI company, int cityNumber) { if (isHomeFor(company)) // Company can always lay a home base return false; - else if (isBlockedForTokenLays != null) { + else if (isBlockedForTokenLays != null) { // case A) // if true: token lay blocked because a required home base is not yet laid // if false: token lay allowed if there is any free space // Free space is not checked here (yet) return isBlockedForTokenLays.booleanValue(); } else if (homes != null && !homes.isEmpty()) { - City city; // Check if this token lay does not block an unlaid home base for (PublicCompanyI comp : homes.keySet()) { if (comp.hasLaidHomeBaseTokens() || comp.isClosed()) continue; - city = homes.get(comp); - if (cityNumber == city.getNumber() - // Assume that a city is never home to more than one company - && city.getTokens().isEmpty() - && city.getTokenSlotsLeft() < 2) { - return true; + City homeCity = homes.get(comp); + if (homeCity != null) { // case B) + if (cityNumber == homeCity.getNumber() + // Assume that a city is never home to more than one company + && homeCity.getTokens().isEmpty() + && homeCity.getTokenSlotsLeft() < 2) { + return true; + } + } else { // case C) + int tokenSlotsLeft = 0; + for (City city:cities) { + tokenSlotsLeft += city.getTokenSlotsLeft(); + } + if (tokenSlotsLeft < 2) return true; // not enough tokens left, assume only one company } } } Modified: trunk/18xx/rails/ui/swing/hexmap/GUIHex.java =================================================================== --- trunk/18xx/rails/ui/swing/hexmap/GUIHex.java 2010-07-10 22:25:10 UTC (rev 1335) +++ trunk/18xx/rails/ui/swing/hexmap/GUIHex.java 2010-07-11 16:40:44 UTC (rev 1336) @@ -383,17 +383,26 @@ Map<PublicCompanyI, City> homes = getHexModel().getHomes(); if (homes != null) { - City city; + City homeCity; Point p; for (PublicCompanyI company : homes.keySet()) { if (company.isClosed()) continue; // Only draw the company name if there isn't yet a token of that company if (model.hasTokenOfCompany(company)) continue; - - city = homes.get(company); + homeCity = homes.get(company); + if (homeCity == null) { // not yet decided where the token will be + // find a free slot + List<City> cities = getHexModel().getCities(); + for (City city:cities) { + if (city.hasTokenSlotsLeft()) { + homeCity = city; + break; + } + } + } p = getTokenCenter (1, 0, getHexModel().getCities().size(), - city.getNumber()-1); + homeCity.getNumber()-1); drawHome (g2, company, p); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-17 22:34:58
|
Revision: 1346 http://rails.svn.sourceforge.net/rails/?rev=1346&view=rev Author: stefanfrey Date: 2010-07-17 22:34:52 +0000 (Sat, 17 Jul 2010) Log Message: ----------- Added cmdline log4j configuration Modified Paths: -------------- trunk/18xx/rails/ui/swing/ConfigWindow.java trunk/18xx/rails/util/Config.java Modified: trunk/18xx/rails/ui/swing/ConfigWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-17 20:43:58 UTC (rev 1345) +++ trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-17 22:34:52 UTC (rev 1346) @@ -242,7 +242,7 @@ } private void saveConfig() { - this.dispose(); + Config.saveActiveProfile(); } private void saveAsConfig() { @@ -264,6 +264,8 @@ { File file = fc.getSelectedFile(); Config.setActiveFilepath(file.getPath()); + saveConfig(); + setupButtonPanel(); } } Modified: trunk/18xx/rails/util/Config.java =================================================================== --- trunk/18xx/rails/util/Config.java 2010-07-17 20:43:58 UTC (rev 1345) +++ trunk/18xx/rails/util/Config.java 2010-07-17 22:34:52 UTC (rev 1346) @@ -34,6 +34,10 @@ protected static Logger log = Logger.getLogger(Config.class.getPackage().getName()); + /** Commandline options */ + private static final String LOG4J_CMDLINE = "log4j"; + private static final String CONFIGFILE_CMDLINE = "configfile"; + private static final String PROFILE_CMDLINE = "profile"; /** XML setup */ private static final String CONFIG_XML_DIR = "data"; @@ -173,8 +177,13 @@ /** * save active Profile */ - public static boolean saveActiveProfile(String filepath) { - return storePropertyFile(userProperties, filepath); + public static boolean saveActiveProfile() { + String filepath = userProfiles.getProperty(selectedProfile); + if (Util.hasValue(filepath)) { + return storePropertyFile(userProperties, filepath); + } else { + return false; + } } /** @@ -267,13 +276,18 @@ * Set the system property that tells log4j to use this file. (Note: * this MUST be done before updating Config) */ - System.setProperty("log4j.configuration", LOG4J_CONFIG_FILE); + String log4jSelection = System.getProperty(LOG4J_CMDLINE); + if (!Util.hasValue(log4jSelection)) { + log4jSelection = LOG4J_CONFIG_FILE; + } + System.setProperty("log4j.configuration", log4jSelection); + System.out.println("Log4j selection = " + log4jSelection); /* * Check if the profile has been set from the command line * to do this is adding an option to the java command: -Dprofile=<profile-name> */ - String configSelection = System.getProperty("profile"); + String configSelection = System.getProperty(PROFILE_CMDLINE); System.out.println("Cmdline profile selection = " + configSelection); legacyConfigFile = false; @@ -284,9 +298,9 @@ * * This is for legacy reasons only */ - configSelection = System.getProperty("configfile"); + configSelection = System.getProperty(CONFIGFILE_CMDLINE); - if (configSelection != null) { + if (Util.hasValue(configSelection)) { System.out.println("Cmdline configfile selection (legacy!) = " + configSelection); legacyConfigFile = true; } @@ -298,6 +312,10 @@ } selectedProfile = configSelection; + if (!legacyConfigFile) { + System.out.println("Profile selection = " + selectedProfile); + } + initialLoad(); } @@ -378,7 +396,7 @@ } catch (Exception e) { System.err.println(e + " whilst loading properties file " + filename); - e.printStackTrace(System.err); +// e.printStackTrace(System.err); result = false; } return result; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-18 08:28:43
|
Revision: 1348 http://rails.svn.sourceforge.net/rails/?rev=1348&view=rev Author: stefanfrey Date: 2010-07-18 08:28:37 +0000 (Sun, 18 Jul 2010) Log Message: ----------- Further update of config mechanism Modified Paths: -------------- trunk/18xx/rails/ui/swing/ConfigWindow.java trunk/18xx/rails/ui/swing/StatusWindow.java trunk/18xx/rails/util/Config.java Modified: trunk/18xx/rails/ui/swing/ConfigWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-17 22:45:27 UTC (rev 1347) +++ trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-18 08:28:37 UTC (rev 1348) @@ -1,7 +1,6 @@ package rails.ui.swing; import java.awt.Color; -import java.awt.Component; import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.ActionEvent; @@ -18,20 +17,16 @@ import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JComboBox; -import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; +import javax.swing.JOptionPane; import javax.swing.JPanel; -import javax.swing.JSpinner; import javax.swing.JTabbedPane; -import javax.swing.SpinnerListModel; import javax.swing.SwingConstants; import javax.swing.border.Border; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; import rails.game.ConfigurationException; import rails.util.Config; @@ -41,6 +36,9 @@ class ConfigWindow extends JFrame { private static final long serialVersionUID = 1L; + + private static final String CONFIG_EXTENSION = ".rails_config"; + private static final String CONFIG_DESCRIPTION = "Rails configuration files (.rails_config)"; private JPanel profilePanel; private JTabbedPane configPane; @@ -90,19 +88,23 @@ comboBoxUser.setSelectedItem(Config.getActiveProfileName()); comboBoxUser.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent arg0) { - Config.changeActiveProfile((String)comboBoxUser.getSelectedItem()); - EventQueue.invokeLater(new Runnable() { - public void run() { - init(); - ConfigWindow.this.repaint(); - } - } - ); + changeProfile((String)comboBoxUser.getSelectedItem()); } } ); profilePanel.add(comboBoxUser); + // new button + JButton newButton = new JButton(LocalText.getText("NEW")); + newButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + newProfile(); + } + } + ); + profilePanel.add(newButton); + } private void setupConfigPane() { @@ -206,6 +208,17 @@ private void setupButtonPanel() { buttonPanel.removeAll(); + // saveas button + JButton saveAsButton = new JButton(LocalText.getText("SAVEAS")); + saveAsButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + ConfigWindow.this.saveAsConfig(); + } + } + ); + buttonPanel.add(saveAsButton); + // save button if (Config.isFilePathDefined()) { JButton saveButton = new JButton(LocalText.getText("SAVE")); @@ -219,15 +232,6 @@ buttonPanel.add(saveButton); } - JButton saveAsButton = new JButton(LocalText.getText("SAVEAS")); - saveAsButton.addActionListener( - new ActionListener() { - public void actionPerformed(ActionEvent arg0) { - ConfigWindow.this.saveAsConfig(); - } - } - ); - buttonPanel.add(saveAsButton); JButton cancelButton = new JButton(LocalText.getText("CANCEL")); cancelButton.addActionListener( @@ -241,12 +245,47 @@ } + private void newProfile() { + String newProfile = JOptionPane.showInputDialog(ConfigWindow.this, LocalText.getText("CONFIG_NEW_MESSAGE"), + LocalText.getText("CONFIG_NEW_TITLE"), JOptionPane.QUESTION_MESSAGE); + if (Util.hasValue(newProfile)) { + String defaultProfile = (String)JOptionPane.showInputDialog(ConfigWindow.this, LocalText.getText("CONFIG_DEFAULT_MESSAGE"), + LocalText.getText("CONFIG_DEFAULT_TITLE"), JOptionPane.QUESTION_MESSAGE, null, + Config.getDefaultProfiles().toArray(), Config.getDefaultProfileSelection()); + Config.createUserProfile(newProfile, defaultProfile); + } + EventQueue.invokeLater(new Runnable() { + public void run() { + init(); + ConfigWindow.this.repaint(); + } + }); + } + + private void changeProfile(String profileName) { + Config.changeActiveProfile(profileName); + EventQueue.invokeLater(new Runnable() { + public void run() { + init(); + ConfigWindow.this.repaint(); + } + }); + } + private void saveConfig() { Config.saveActiveProfile(); } private void saveAsConfig() { + String directory = Config.get("save.directory"); + String filepath; + if (Util.hasValue(directory)) { + filepath = directory + File.separator + Config.getActiveProfileName() + CONFIG_EXTENSION; + } else { + filepath = Config.getActiveProfileName() + CONFIG_EXTENSION; + } JFileChooser fc = new JFileChooser(); + fc.setSelectedFile(new File(filepath)); fc.setFileFilter( new FileFilter() { public boolean accept( File f ){ @@ -254,12 +293,11 @@ f.getName().toLowerCase().endsWith( ".rails_config" ); } public String getDescription() { - return "Rails Config"; + return CONFIG_DESCRIPTION; } } ); - - int state = fc.showOpenDialog( null ); + int state = fc.showSaveDialog(this); if ( state == JFileChooser.APPROVE_OPTION ) { File file = fc.getSelectedFile(); Modified: trunk/18xx/rails/ui/swing/StatusWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/StatusWindow.java 2010-07-17 22:45:27 UTC (rev 1347) +++ trunk/18xx/rails/ui/swing/StatusWindow.java 2010-07-18 08:28:37 UTC (rev 1348) @@ -176,12 +176,15 @@ menuItem.addActionListener(this); optMenu.add(menuItem); - menuItem = new JCheckBoxMenuItem(LocalText.getText("CONFIG")); - menuItem.setName(CONFIG_CMD); - menuItem.setActionCommand(CONFIG_CMD); - menuItem.setMnemonic(KeyEvent.VK_C); - menuItem.addActionListener(this); - optMenu.add(menuItem); + // new config menu only for non legacy configgfiles + if (!Config.isLegacyConfigFile()) { + menuItem = new JCheckBoxMenuItem(LocalText.getText("CONFIG")); + menuItem.setName(CONFIG_CMD); + menuItem.setActionCommand(CONFIG_CMD); + menuItem.setMnemonic(KeyEvent.VK_C); + menuItem.addActionListener(this); + optMenu.add(menuItem); + } menuBar.add(optMenu); Modified: trunk/18xx/rails/util/Config.java =================================================================== --- trunk/18xx/rails/util/Config.java 2010-07-17 22:45:27 UTC (rev 1347) +++ trunk/18xx/rails/util/Config.java 2010-07-18 08:28:37 UTC (rev 1348) @@ -3,7 +3,6 @@ import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @@ -14,7 +13,6 @@ import java.util.List; import java.util.Map; import java.util.Properties; -import java.util.Set; import org.apache.log4j.Logger; @@ -26,8 +24,8 @@ * a property object from a property file, to retrieve a particular value from * the property file etc. * - * @author Ramiah Bala, rewritten by Erik Vos - * @version 1.0 + * @author Ramiah Bala, rewritten by Erik Vos, rewritten by Stefan Frey + * @version 2.0 */ public final class Config { @@ -48,8 +46,7 @@ /** Log 4j configuration */ private static final String LOG4J_CONFIG_FILE = "log4j.properties"; - - + /** Rails profile configurations */ private static String defaultProfilesFile = "default.profiles"; private static Properties defaultProfiles = new Properties(); @@ -156,13 +153,6 @@ } - /** - * @return if user location is defined - */ - public static boolean isFilePathDefined() { - return Util.hasValue(userProfiles.getProperty(selectedProfile)); - } - private static boolean storePropertyFile(Properties properties, String filepath) { File outFile = new File(filepath); boolean result = true; @@ -196,6 +186,27 @@ return true; } + /** + * create new profile + */ + public static boolean createUserProfile(String profileName, String defaultProfile) { + userProperties = new Properties(); + defaultProperties = new Properties(); + + + // add to list of user profiles + userProfiles.setProperty(profileName, ""); + // define and load default profile + String defaultConfigFile = defaultProfiles.getProperty(defaultProfile); + userProperties.setProperty(DEFAULT_PROFILE_PROPERTY, defaultProfile); + loadPropertyFile(defaultProperties, defaultConfigFile, true); + setSaveDirDefaults(); + + selectedProfile = profileName; + return true; + } + + private static Map<String, String> convertProperties(Properties properties) { Map<String, String> converted = new HashMap<String, String>(); for (Object key:properties.keySet()) { @@ -204,16 +215,18 @@ return converted; } - /** * get all default profiles */ public static List<String> getDefaultProfiles() { List<String> profiles = new ArrayList<String>(convertProperties(defaultProfiles).keySet()); - profiles.remove(DEFAULT_PROFILE_PROPERTY); Collections.sort(profiles); return profiles; } + + public static String getDefaultProfileSelection() { + return DEFAULT_PROFILE_SELECTION; + } /** * get all user profiles @@ -239,6 +252,13 @@ } /** + * returns true if legacy configfile is used + */ + public static boolean isLegacyConfigFile() { + return legacyConfigFile; + } + + /** * sets filename for an active profile (and store list of profiles) */ public static boolean setActiveFilepath(String filepath) { @@ -252,6 +272,14 @@ public static String getActiveFilepath() { return userProfiles.getProperty(selectedProfile); } + + /** + * @return if user location is defined + */ + public static boolean isFilePathDefined() { + return Util.hasValue(userProfiles.getProperty(selectedProfile)); + } + /** * activates settings used for testing This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-07-23 20:05:41
|
Revision: 1354 http://rails.svn.sourceforge.net/rails/?rev=1354&view=rev Author: evos Date: 2010-07-23 20:05:34 +0000 (Fri, 23 Jul 2010) Log Message: ----------- Changed BuyCertificate to pass on share size per certificate rather that the certificate ID. This is to make BuyCertificate consistent will SellShares and help preventing saved file loading problems. Various minor fixes have als been applied for issues detected during testing. Modified Paths: -------------- trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/GameManagerI.java trunk/18xx/rails/game/Portfolio.java trunk/18xx/rails/game/ReportBuffer.java trunk/18xx/rails/game/StockRound.java trunk/18xx/rails/game/TreasuryShareRound.java trunk/18xx/rails/game/action/BuyCertificate.java trunk/18xx/rails/game/action/StartCompany.java trunk/18xx/rails/game/move/ObjectMove.java trunk/18xx/rails/game/specific/_1835/StockRound_1835.java trunk/18xx/rails/game/specific/_1856/StockRound_1856.java trunk/18xx/rails/game/specific/_18EU/StartCompany_18EU.java trunk/18xx/rails/game/specific/_18EU/StockRound_18EU.java trunk/18xx/rails/ui/swing/GameStatus.java trunk/18xx/rails/ui/swing/GameUIManager.java trunk/18xx/rails/ui/swing/gamespecific/_18EU/GameUIManager_18EU.java trunk/18xx/rails/util/Util.java Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/GameManager.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -68,12 +68,16 @@ protected State currentPlayer = new State("CurrentPlayer", Player.class); protected State priorityPlayer = new State("PriorityPlayer", Player.class); - /** Map relating portfolio names and objects, to enable deserialization */ + /** Map relating portfolio names and objects, to enable deserialization. + * OBSOLETE since Rails 1.3.1, but still required to enable reading old saved files */ protected Map<String, Portfolio> portfolioMap = new HashMap<String, Portfolio> (); + /** Map relating portfolio unique names and objects, to enable deserialization */ + protected Map<String, Portfolio> portfolioUniqueNameMap = + 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; @@ -83,7 +87,7 @@ 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); @@ -893,11 +897,15 @@ DisplayBuffer.clear(); // TEMPORARY FIX TO ALLOW OLD 1856 SAVED FILES TO BE PROCESSED - if (!possibleActions.contains(action.getClass()) - && possibleActions.contains(RepayLoans.class)) { + if (gameName.equals("1856") + && possibleActions.contains(RepayLoans.class) + && (!possibleActions.contains(action.getClass()) + || (action.getClass() == NullAction.class + && ((NullAction)action).getMode() != NullAction.DONE))) { // Insert "Done" log.debug("Action DONE inserted"); getCurrentRound().process(new NullAction (NullAction.DONE)); + possibleActions.clear(); getCurrentRound().setPossibleActions(); if (!isGameOver()) setCorrectionActions(); } @@ -913,11 +921,16 @@ if (moveStack.isOpen()) moveStack.finish(); return false; } + possibleActions.clear(); getCurrentRound().setPossibleActions(); - //String playerName = getCurrentPlayer().getName(); - //for (PossibleAction a : possibleActions.getList()) { - // log.debug(playerName+" may: "+a.toString()); - //} + + // Log possible actions (normally this is outcommented) + String playerName = getCurrentPlayer().getName(); + for (PossibleAction a : possibleActions.getList()) { + log.debug(playerName+" may: "+a.toString()); + } + + if (!isGameOver()) setCorrectionActions(); } catch (Exception e) { @@ -1352,12 +1365,18 @@ public void addPortfolio (Portfolio portfolio) { portfolioMap.put(portfolio.getName(), portfolio); + portfolioUniqueNameMap.put(portfolio.getUniqueName(), portfolio); } + /* since Rails 1.3.1, but still required to enable loading old saved files */ public Portfolio getPortfolioByName (String name) { return portfolioMap.get(name); } + public Portfolio getPortfolioByUniqueName (String name) { + return portfolioUniqueNameMap.get(name); + } + /* (non-Javadoc) * @see rails.game.GameManagerI#getStartPacket() */ Modified: trunk/18xx/rails/game/GameManagerI.java =================================================================== --- trunk/18xx/rails/game/GameManagerI.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/GameManagerI.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -146,6 +146,7 @@ public void addPortfolio (Portfolio portfolio); public Portfolio getPortfolioByName (String name); + public Portfolio getPortfolioByUniqueName (String name); /** * @return the StartPacket Modified: trunk/18xx/rails/game/Portfolio.java =================================================================== --- trunk/18xx/rails/game/Portfolio.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/Portfolio.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -71,6 +71,8 @@ /** Name of portfolio */ protected String name; + /** Unique name (including owner class name) */ + protected String uniqueName; /** Specific portfolio names */ public static final String IPO_NAME = "IPO"; @@ -84,7 +86,8 @@ public Portfolio(String name, CashHolder holder) { this.name = name; this.owner = holder; - //portfolioMap.put(name, this); + this.uniqueName = holder.getClass().getSimpleName() + "_" + name; + GameManager.getInstance().addPortfolio(this); if (owner instanceof PublicCompanyI) { @@ -303,6 +306,14 @@ return name; } + /** Get unique name (prefixed by the owners class type, to avoid Bank, Player and Company + * namespace clashes). + * @return + */ + public String getUniqueName () { + return uniqueName; + } + /** * Returns percentage that a portfolio contains of one company. * Modified: trunk/18xx/rails/game/ReportBuffer.java =================================================================== --- trunk/18xx/rails/game/ReportBuffer.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/ReportBuffer.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -14,12 +14,12 @@ /** * Class to write a log, and also to maintain a log message stack for writing to * the UI. - * + * * Each gameManager has one unique ReportBuffer, which is used by the public static methods. * Messages before the creation of that buffer are kept in an internal initial queue. - * + * * Also used for regression testing comparing the output of the report buffer. - * + * */ public final class ReportBuffer { /** @@ -28,7 +28,7 @@ * rails.game report. */ private List<String> reportQueue = new ArrayList<String>(); - + /** Another stack for messages that must "wait" for other messages */ private List<String> waitQueue = new ArrayList<String> (); @@ -44,7 +44,7 @@ private static final String DEFAULT_REPORT_EXTENSION = "txt"; static { - reportDirectory = Config.get("report.directory"); + reportDirectory = Config.get("report.directory").trim(); wantReport = Util.hasValue(reportDirectory); } @@ -69,7 +69,7 @@ private void clearReportQueue() { reportQueue.clear(); } - + private void addMessage (String message) { if (message != null) { if (message.equals("")) @@ -81,11 +81,11 @@ if (wantReport) writeToReport(message); } } - + private void writeToReport(String message) { /* Get out if we don't want a report */ - if (!Util.hasValue(reportDirectory) || !wantReport) return; + if (!wantReport) return; if (report == null) openReportFile(); @@ -97,6 +97,9 @@ private void openReportFile() { + /* Get out if we don't want a report */ + if (!wantReport) return; + /* Get any configured date/time pattern, or else set the default */ String reportFilenamePattern = Config.get("report.filename.date_time_pattern"); @@ -132,15 +135,15 @@ /** Get the current log buffer, and clear it */ public static String get() { ReportBuffer instance = getInstance(); - + // convert to String StringBuffer result = new StringBuffer(); - for (String msg:instance.getReportQueue()) + for (String msg:instance.getReportQueue()) result.append(msg).append("\n"); // clear current queue instance.clearReportQueue(); - + return result.toString(); } @@ -160,23 +163,23 @@ /** return the current buffer as list */ public static List<String> getAsList() { ReportBuffer instance = getInstance(); - - if (instance == null) + + if (instance == null) return initialQueue; else return instance.getReportQueue(); } - + /** clear the current buffer */ public static void clear() { ReportBuffer instance = getInstance(); - - if (instance == null) + + if (instance == null) initialQueue.clear(); else instance.clearReportQueue(); } - + private static ReportBuffer getInstance() { return GameManager.getInstance().getReportBuffer(); } Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/StockRound.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -196,14 +196,14 @@ if (!cert.isPresidentShare()) { price = comp.getIPOPrice() / unitsForPrice; if (price <= playerCash) { - possibleActions.add(new BuyCertificate(cert, from, - price)); + possibleActions.add(new BuyCertificate(comp, cert.getShare(), + from, price)); } } else if (!comp.hasStarted()) { if (comp.getIPOPrice() != 0) { price = comp.getIPOPrice() * cert.getShares() / unitsForPrice; if (price <= playerCash) { - possibleActions.add(new StartCompany(cert, price)); + possibleActions.add(new StartCompany(comp, price)); } } else { List<Integer> startPrices = new ArrayList<Integer>(); @@ -218,7 +218,7 @@ for (int i = 0; i < prices.length; i++) { prices[i] = startPrices.get(i); } - possibleActions.add(new StartCompany(cert, prices)); + possibleActions.add(new StartCompany(comp, prices)); } } } @@ -247,7 +247,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; @@ -296,7 +296,8 @@ } if (number > 0) { - possibleActions.add(new BuyCertificate(uniqueCerts[shares], + possibleActions.add(new BuyCertificate(comp, + uniqueCerts[shares].getShare(), from, price, number)); } @@ -320,7 +321,7 @@ if (!stockSpace.isNoCertLimit() && !mayPlayerBuyCertificate(currentPlayer, company, 1)) continue; if (company.getMarketPrice() <= playerCash) { - possibleActions.add(new BuyCertificate(cert, + possibleActions.add(new BuyCertificate(company, cert.getShare(), company.getPortfolio(), company.getMarketPrice())); } } @@ -524,7 +525,7 @@ * @return True if the company could be started. False indicates an error. */ public boolean startCompany(String playerName, StartCompany action) { - PublicCompanyI company = action.getCertificate().getCompany(); + PublicCompanyI company = action.getCompany(); int price = action.getPrice(); int shares = action.getNumberBought(); @@ -618,7 +619,7 @@ // All is OK, now start the company company.start(startSpace); - CashHolder priceRecipient = getSharePriceRecipient (cert, price); + CashHolder priceRecipient = getSharePriceRecipient (company, ipo, price); // Transfer the President's certificate cert.moveTo(currentPlayer.getPortfolio()); @@ -668,17 +669,18 @@ */ public boolean buyShares(String playerName, BuyCertificate action) { - PublicCertificateI cert = action.getCertificate(); - Portfolio from = cert.getPortfolio(); - String companyName = cert.getCompany().getName(); + PublicCompanyI company = action.getCompany(); + Portfolio from = action.getFromPortfolio(); + String companyName = company.getName(); int number = action.getNumberBought(); - int shares = number * cert.getShares(); - int shareUnit = cert.getShare(); + int shareUnit = company.getShareUnit(); + int sharePerCert = action.getSharePerCertificate(); + int share = number * sharePerCert; + int shares = share / shareUnit; String errMsg = null; int price = 0; int cost = 0; - PublicCompanyI company = null; currentPlayer = getCurrentPlayer(); @@ -748,6 +750,10 @@ // Check if player would not exceed the certificate limit. // (shortcut: assume 1 cert == 1 certificate) + PublicCertificateI cert = from.findCertificate(company, sharePerCert/shareUnit, false); + if (cert == null) { + log.fatal("Cannot find "+sharePerCert+"% of "+company.getName()+" in "+from.getName()); + } if (!currentSpace.isNoCertLimit() && !mayPlayerBuyCertificate(currentPlayer, company, number * cert.getCertificateCount())) { errMsg = @@ -791,7 +797,7 @@ // All seems OK, now buy the shares. moveStack.start(true); - CashHolder priceRecipient = getSharePriceRecipient (cert, cost); + CashHolder priceRecipient = getSharePriceRecipient (company, from, cost); if (number == 1) { ReportBuffer.add(LocalText.getText("BUY_SHARE_LOG", @@ -814,9 +820,9 @@ PublicCertificateI cert2; for (int i = 0; i < number; i++) { - cert2 = from.findCertificate(company, cert.getShares(), false); + cert2 = from.findCertificate(company, sharePerCert/shareUnit, false); if (cert2 == null) { - log.error("Cannot find " + companyName + " " + shareUnit + log.error("Cannot find " + companyName + " " + shareUnit*sharePerCert + "% share in " + from.getName()); } cert2.moveTo(currentPlayer.getPortfolio()); @@ -864,17 +870,16 @@ * @param cert * @return */ - protected CashHolder getSharePriceRecipient (PublicCertificateI cert, int price) { + protected CashHolder getSharePriceRecipient (PublicCompanyI comp, + Portfolio from, int price) { - Portfolio oldHolder = (Portfolio) cert.getHolder(); - PublicCompanyI comp; CashHolder recipient; - if ((comp = (cert).getCompany()).hasFloated() - && oldHolder == ipo + if (comp.hasFloated() + && from == ipo && comp.getCapitalisation() == PublicCompanyI.CAPITALISE_INCREMENTAL) { recipient = comp; } else { - recipient = oldHolder.getOwner(); + recipient = from.getOwner(); } return recipient; } Modified: trunk/18xx/rails/game/TreasuryShareRound.java =================================================================== --- trunk/18xx/rails/game/TreasuryShareRound.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/TreasuryShareRound.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -141,7 +141,7 @@ number--; if (number > 0) { - possibleActions.add(new BuyCertificate(cert, from, price, + possibleActions.add(new BuyCertificate(comp, cert.getShare(), from, price, number)); } } @@ -240,16 +240,16 @@ @Override public boolean buyShares(String playerName, BuyCertificate action) { - PublicCertificateI cert = action.getCertificate(); - Portfolio from = cert.getPortfolio(); - String companyName = cert.getCompany().getName(); + PublicCompanyI company = action.getCompany(); + Portfolio from = action.getFromPortfolio(); + String companyName = company.getName(); int number = action.getNumberBought(); - int shares = number * cert.getShares(); - int shareUnit = cert.getShare(); + int shareUnit = company.getShareUnit(); + int sharePerCert = action.getSharePerCertificate(); + int shares = number * sharePerCert; String errMsg = null; int price = 0; - PublicCompanyI company = null; Portfolio portfolio = null; currentPlayer = getCurrentPlayer(); @@ -359,7 +359,7 @@ moveStack.start(true); PublicCertificateI cert2; for (int i = 0; i < number; i++) { - cert2 = from.findCertificate(company, cert.getShares(), false); + cert2 = from.findCertificate(company, sharePerCert, false); executeTradeCertificate(cert2, portfolio, cert2.getShares() * price); } Modified: trunk/18xx/rails/game/action/BuyCertificate.java =================================================================== --- trunk/18xx/rails/game/action/BuyCertificate.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/action/BuyCertificate.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -16,10 +16,22 @@ public class BuyCertificate extends PossibleAction { // Server-side settings - transient protected PublicCertificateI certificate; - protected String certUniqueId; + + /* Some obsolete properties, which are only retained for backwards compatibility + * (i.e. to remain able to load older saved files). + * The certificate was in fact only used to find the below replacement + * attributes. It was NOT actually used to select the bought certificate! + */ + transient protected PublicCertificateI certificate = null; + protected String certUniqueId = null; + + /* Replacement for the above.*/ + transient protected PublicCompanyI company; + protected String companyName; + protected int sharePerCert; // Share % per buyable certificate. + transient protected Portfolio from; - protected String fromName; + protected String fromName; // Old: portfolio name. New: portfolio unique name. protected int price; protected int maximumNumber; @@ -28,30 +40,24 @@ public static final long serialVersionUID = 1L; - /** - * Common constructor. - */ - public BuyCertificate(PublicCertificateI certificate, Portfolio from, + public BuyCertificate(PublicCompanyI company, int sharePerCert, + Portfolio from, int price, int maximumNumber) { - this.certificate = certificate; - this.certUniqueId = certificate.getUniqueId(); // TODO: Must be - // replaced by a unique - // Id! + this.company = company; + this.sharePerCert = sharePerCert; this.from = from; - this.fromName = from.getName(); + this.fromName = from.getUniqueName(); this.price = price; this.maximumNumber = maximumNumber; + + companyName = company.getName(); } - /** Buy a certificate from some portfolio at the current price */ - //public BuyCertificate(PublicCertificateI certificate, Portfolio from) { - // this(certificate, from, certificate.getCertificatePrice(), 1); - //} - /** Buy a certificate from some portfolio at a given price */ - public BuyCertificate(PublicCertificateI certificate, Portfolio from, + public BuyCertificate(PublicCompanyI company, int sharePerCert, + Portfolio from, int price) { - this(certificate, from, price, 1); + this(company, sharePerCert, from, price, 1); } /** Required for deserialization */ @@ -61,10 +67,6 @@ return from; } - public String getFromName() { - return fromName; - } - /** * @return Returns the maximumNumber. */ @@ -79,13 +81,22 @@ return price; } - /** - * @return Returns the certificate. - */ - public PublicCertificateI getCertificate() { - return certificate; + public PublicCompanyI getCompany() { + return company; } + public String getCompanyName() { + return companyName; + } + + public int getSharePerCertificate() { + return sharePerCert; + } + + public int getSharesPerCertificate() { + return sharePerCert / company.getShareUnit(); + } + public int getNumberBought() { return numberBought; } @@ -106,26 +117,46 @@ public String toString() { StringBuffer text = new StringBuffer(); text.append("BuyCertificate: "); - if (numberBought > 1) { - text.append(numberBought).append(" of "); - } else if (numberBought == 0 && maximumNumber > 1) { - text.append("up to ").append(maximumNumber).append(" of "); - } - text.append(certificate.getName()).append(" from ").append( - from.getName()).append(" price=").append( - Bank.format(certificate.getShares() * price)); + if (acted) text.append("Bought "+numberBought +" of "); + if (maximumNumber > 1) text.append ("max."+maximumNumber+" of "); + text.append(sharePerCert).append("% ").append(companyName) + .append(" from ").append(from.getName()) + .append(" price=").append(Bank.format((sharePerCert/company.getShareUnit()) * price)); return text.toString(); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); + //in.defaultReadObject(); + // Custom reading for backwards compatibility + ObjectInputStream.GetField fields = in.readFields(); + certUniqueId = (String) fields.get("certUniqueId", null); + companyName = (String) fields.get("companyName", null); + fromName = (String) fields.get("fromName", fromName); + price = fields.get("price", price); + maximumNumber = fields.get("maximumNumber", maximumNumber); + sharePerCert = fields.get("sharePerCert", -1); + + numberBought = fields.get("numberBought", numberBought); + GameManagerI gameManager = GameManager.getInstance(); - certificate = PublicCertificate.getByUniqueId(certUniqueId); - from = gameManager.getPortfolioByName(fromName); + if (certUniqueId != null) { + // Old style + certificate = PublicCertificate.getByUniqueId(certUniqueId); + from = gameManager.getPortfolioByName(fromName); + company = certificate.getCompany(); + companyName = company.getName(); + sharePerCert = certificate.getShare(); + } else if (companyName != null) { + // New style (since Rails.1.3.1) + company = gameManager.getCompanyManager().getPublicCompany(companyName); + from = gameManager.getPortfolioByUniqueName(fromName); + // We don't need the certificate anymore. + } + } } Modified: trunk/18xx/rails/game/action/StartCompany.java =================================================================== --- trunk/18xx/rails/game/action/StartCompany.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/action/StartCompany.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -9,24 +9,28 @@ public static final long serialVersionUID = 1L; - public StartCompany(PublicCertificateI certificate, int[] prices, + public StartCompany(PublicCompanyI company, int[] prices, int maximumNumber) { - super(certificate, GameManager.getInstance().getBank().getIpo(), 0, maximumNumber); + super(company, company.getPresidentsShare().getShare(), + GameManager.getInstance().getBank().getIpo(), + 0, maximumNumber); this.startPrices = prices.clone(); } - public StartCompany(PublicCertificateI certificate, int[] startPrice) { - this(certificate, startPrice, 1); + public StartCompany(PublicCompanyI company, int[] startPrice) { + this(company, startPrice, 1); } - public StartCompany(PublicCertificateI certificate, int price, + public StartCompany(PublicCompanyI company, int price, int maximumNumber) { - super(certificate, GameManager.getInstance().getBank().getIpo(), 0, maximumNumber); + super(company, company.getPresidentsShare().getShare(), + GameManager.getInstance().getBank().getIpo(), + 0, maximumNumber); this.price = price; } - public StartCompany(PublicCertificateI certificate, int price) { - this(certificate, price, 1); + public StartCompany(PublicCompanyI company, int price) { + this(company, price, 1); } public int[] getStartPrices() { @@ -44,7 +48,7 @@ @Override public String toString() { StringBuffer text = new StringBuffer(); - text.append("StartCompany: ").append(certificate.getName()); + text.append("StartCompany: ").append(company.getName()); if (price > 0) { text.append(" price=").append(Bank.format(price)); if (numberBought > 1) { Modified: trunk/18xx/rails/game/move/ObjectMove.java =================================================================== --- trunk/18xx/rails/game/move/ObjectMove.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/move/ObjectMove.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -5,6 +5,8 @@ */ package rails.game.move; +import rails.util.Util; + /** * @author Erik Vos */ @@ -77,9 +79,18 @@ if (moveableObject == null) log.error("Token is null"); 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+"]"; + StringBuilder buf = new StringBuilder(); + + buf.append("Move ").append(objectClassName).append(": ").append(moveableObject.getName()) + .append(" from ").append(from == null ? from : from.getName()); + if (fromPosition != null) { + buf.append("[").append(Util.joinWithDelimiter(fromPosition, ",")).append("]"); + } + buf.append(" to ").append(to == null ? to : to.getName()); + if (toPosition != null) { + buf.append("[").append(Util.joinWithDelimiter(toPosition, ",")).append("]"); + } + return buf.toString(); } } Modified: trunk/18xx/rails/game/specific/_1835/StockRound_1835.java =================================================================== --- trunk/18xx/rails/game/specific/_1835/StockRound_1835.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/specific/_1835/StockRound_1835.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -12,7 +12,7 @@ import rails.util.LocalText; public class StockRound_1835 extends StockRound { - + /** * Constructor with the GameManager, will call super class (StockRound's) Constructor to initialize * @@ -22,19 +22,21 @@ public StockRound_1835 (GameManagerI aGameManager) { super (aGameManager); } - + /** Add nationalisations */ + @Override protected void setGameSpecificActions() { if (!mayCurrentPlayerBuyAnything()) return; if (companyBoughtThisTurnWrapper.getObject() != null) return; - + List<Player> otherPlayers = new ArrayList<Player>(); Portfolio holder; CashHolder owner; Player otherPlayer; int price; int cash = currentPlayer.getCash(); - + + // Nationalization for (PublicCompanyI company : companyManager.getAllPublicCompanies()) { if (!company.getTypeName().equalsIgnoreCase("Major")) continue; if (!company.hasFloated()) continue; @@ -49,7 +51,8 @@ if (!otherPlayers.contains(otherPlayer)) { price = (int)(1.5 * company.getCurrentPriceModel().getPrice().getPrice()); if (price <= cash) { - possibleActions.add(new BuyCertificate (cert, holder, + possibleActions.add(new BuyCertificate (company, cert.getShare(), + holder, (int)(1.5 * company.getCurrentPriceModel().getPrice().getPrice()), 1)); } @@ -61,10 +64,12 @@ } } + @Override public boolean checkAgainstHoldLimit(Player player, PublicCompanyI company, int number) { return true; } + @Override protected int getBuyPrice (BuyCertificate action, StockSpaceI currentSpace) { int price = currentSpace.getPrice(); if (action.getFromPortfolio().getOwner() instanceof Player) { @@ -72,9 +77,10 @@ } return price; } - + /** Share price goes down 1 space for any number of shares sold. */ + @Override protected void adjustSharePrice (PublicCompanyI company, int numberSold, boolean soldBefore) { // No more changes if it has already dropped if (!soldBefore) { Modified: trunk/18xx/rails/game/specific/_1856/StockRound_1856.java =================================================================== --- trunk/18xx/rails/game/specific/_1856/StockRound_1856.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/specific/_1856/StockRound_1856.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -85,16 +85,15 @@ } @Override - protected CashHolder getSharePriceRecipient(PublicCertificateI cert, int cost) { + protected CashHolder getSharePriceRecipient(PublicCompanyI company, Portfolio from, int price) { CashHolder recipient; - Portfolio oldHolder = (Portfolio) cert.getHolder(); - if (cost != 0 - && !cert.getCompany().getName().equalsIgnoreCase(PublicCompany_CGR.NAME) - && oldHolder == ipo) { + if (price != 0 + && !company.getName().equalsIgnoreCase(PublicCompany_CGR.NAME) + && from == ipo) { - PublicCompany_1856 comp = (PublicCompany_1856)(cert).getCompany(); + PublicCompany_1856 comp = (PublicCompany_1856)company; switch (comp.getTrainNumberAvailableAtStart()) { case 2: @@ -104,9 +103,9 @@ if (getSoldPercentage(comp) >= 50 && !comp.hasReachedDestination()) { recipient = bank; - comp.addMoneyInEscrow(cost); + comp.addMoneyInEscrow(price); ReportBuffer.addWaiting(LocalText.getText("HoldMoneyInEscrow", - Bank.format(cost), + Bank.format(price), Bank.format(comp.getMoneyInEscrow()), comp.getName() )); break; @@ -120,7 +119,7 @@ recipient = bank; } } else { - recipient = oldHolder.getOwner(); + recipient = from.getOwner(); } return recipient; } @@ -183,10 +182,10 @@ } else { // Player has enough cash if (cert1 != null && price1 <= cash) { - possibleActions.add(new BuyCertificate(cert1, ipo, price1)); + possibleActions.add(new BuyCertificate(cgr, 1, ipo, price1)); } if (cert2 != null && price2 <= cash) { - possibleActions.add(new BuyCertificate(cert2, pool, price2)); + possibleActions.add(new BuyCertificate(cgr, 1, pool, price2)); } } Modified: trunk/18xx/rails/game/specific/_18EU/StartCompany_18EU.java =================================================================== --- trunk/18xx/rails/game/specific/_18EU/StartCompany_18EU.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/specific/_18EU/StartCompany_18EU.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -29,8 +29,8 @@ public static final long serialVersionUID = 1L; - public StartCompany_18EU(PublicCertificateI certificate, int[] prices) { - super(certificate, prices, 1); + public StartCompany_18EU(PublicCompanyI company, int[] prices) { + super(company, prices, 1); } public void setMinorsToMerge(List<PublicCompanyI> minors) { Modified: trunk/18xx/rails/game/specific/_18EU/StockRound_18EU.java =================================================================== --- trunk/18xx/rails/game/specific/_18EU/StockRound_18EU.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/specific/_18EU/StockRound_18EU.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -149,7 +149,7 @@ prices[i] = startPrices.get(i); } StartCompany_18EU action = - new StartCompany_18EU(cert, prices); + new StartCompany_18EU(comp, prices); if (mustMergeMinor) { action.setMinorsToMerge(minors); } else { @@ -158,7 +158,8 @@ possibleActions.add(action); } } else if (comp.getMarketPrice() <= playerCash) { - possibleActions.add(new BuyCertificate(cert, from, + possibleActions.add(new BuyCertificate(comp, cert.getShare(), + from, comp.getMarketPrice())); } @@ -187,7 +188,7 @@ // Does the player have enough cash? if (playerCash < price) continue; - possibleActions.add(new BuyCertificate(cert, from, price, 1)); + possibleActions.add(new BuyCertificate(comp, cert.getShare(), from, price, 1)); } // Get any shares in company treasuries that can be bought @@ -207,7 +208,7 @@ if (!stockSpace.isNoCertLimit() && !mayPlayerBuyCertificate(currentPlayer, company, 1)) continue; if (company.getMarketPrice() <= playerCash) { - possibleActions.add(new BuyCertificate(cert, + possibleActions.add(new BuyCertificate(company, cert.getShare(), company.getPortfolio(), company.getMarketPrice())); } @@ -271,7 +272,7 @@ */ @Override public boolean startCompany(String playerName, StartCompany action) { - PublicCompanyI company = action.getCertificate().getCompany(); + PublicCompanyI company = action.getCompany(); int price = action.getPrice(); int shares = action.getNumberBought(); Modified: trunk/18xx/rails/ui/swing/GameStatus.java =================================================================== --- trunk/18xx/rails/ui/swing/GameStatus.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/ui/swing/GameStatus.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -509,14 +509,14 @@ addField(futureTrains, futureTrainsXOffset, futureTrainsYOffset, futureTrainsWidth, 1, 0, true); - // Train cost overview + // Train cost overview String text = gameUIManager.getGameManager().getTrainManager().getTrainCostOverview(); addField (new Caption(text), poolTrainsXOffset, newTrainsYOffset + 1, futureTrainsWidth + 2, 1, 0, true); dummyButton = new ClickField("", "", "", this, buySellGroup); } - + public void actionPerformed(ActionEvent actor) { JComponent source = (JComponent) actor.getSource(); List<PossibleAction> actions; @@ -589,13 +589,19 @@ PublicCertificateI cert; String companyName = ""; String playerName = ""; + int sharePerCert; + int sharesPerCert; + int shareUnit; for (PossibleAction action : actions) { buy = (BuyCertificate) action; - cert = buy.getCertificate(); + //cert = buy.getCertificate(); playerName = buy.getPlayerName (); - PublicCompanyI company = cert.getCompany(); + PublicCompanyI company = buy.getCompany(); companyName = company.getName(); + sharePerCert = buy.getSharePerCertificate(); + shareUnit = company.getShareUnit(); + sharesPerCert = sharePerCert / shareUnit; if (buy instanceof StartCompany) { @@ -608,9 +614,8 @@ for (int i = 0; i < startPrices.length; i++) { options.add(LocalText.getText("StartCompany", Bank.format(startPrices[i]), - cert.getShare(), - Bank.format(cert.getShares() - * startPrices[i]) )); + sharePerCert, + Bank.format(sharesPerCert * startPrices[i]) )); buyActions.add(buy); buyAmounts.add(startPrices[i]); } @@ -618,7 +623,7 @@ startPrices = new int[] {((StartCompany) buy).getPrice()}; options.add(LocalText.getText("StartCompanyFixed", companyName, - cert.getShare(), + sharePerCert, Bank.format(startPrices[0]) )); buyActions.add(buy); buyAmounts.add(startPrices[0]); @@ -627,20 +632,19 @@ } else { options.add(LocalText.getText("BuyCertificate", - cert.getShare(), - cert.getCompany().getName(), - cert.getPortfolio().getName(), - Bank.format(cert.getShares() - * buy.getPrice()) )); + sharePerCert, + companyName, + buy.getFromPortfolio().getName(), + Bank.format(sharesPerCert * buy.getPrice()) )); buyActions.add(buy); buyAmounts.add(1); for (int i = 2; i <= buy.getMaximumNumber(); i++) { options.add(LocalText.getText("BuyCertificates", i, - cert.getShare(), - cert.getCompany().getName(), - cert.getPortfolio().getName(), - Bank.format(i * cert.getShares() + sharePerCert, + companyName, + buy.getFromPortfolio().getName(), + Bank.format(i * sharesPerCert * buy.getPrice()) )); buyActions.add(buy); buyAmounts.add(i); @@ -683,7 +687,7 @@ } else if (startCompany) { chosenAction = buyActions.get(index); ((StartCompany) chosenAction).setStartPrice(buyAmounts.get(index)); - ((StartCompany) chosenAction).setNumberBought(((StartCompany) chosenAction).getCertificate().getShares()); + ((StartCompany) chosenAction).setNumberBought(((StartCompany) chosenAction).getSharesPerCertificate()); } else { chosenAction = buyActions.get(index); ((BuyCertificate) chosenAction).setNumberBought(buyAmounts.get(index)); @@ -767,7 +771,7 @@ treasurySharesCaption.setHighlight(true); } - PublicCertificateI cert; + PublicCompanyI company; Portfolio holder; int index; CashHolder owner; @@ -776,8 +780,8 @@ possibleActions.getType(BuyCertificate.class); if (buyableCerts != null) { for (BuyCertificate bCert : buyableCerts) { - cert = bCert.getCertificate(); - index = cert.getCompany().getPublicNumber(); + company = bCert.getCompany(); + index = company.getPublicNumber(); holder = bCert.getFromPortfolio(); owner = holder.getOwner(); if (holder == ipo) { @@ -792,7 +796,6 @@ } } - PublicCompanyI company; List<SellShares> sellableShares = possibleActions.getType(SellShares.class); if (sellableShares != null) { @@ -831,7 +834,7 @@ * Initializes the CashCorrectionActions */ public boolean initCashCorrectionActions() { - + // Clear all buttons for (int i = 0; i < nc; i++) { setCompanyCashButton(i, false, null); @@ -839,7 +842,7 @@ for (int j = 0; j < np; j++) { setPlayerCashButton(j, false, null); } - + List<CashCorrectionAction> actions = possibleActions.getType(CashCorrectionAction.class); @@ -860,9 +863,9 @@ } return (actions != null && !actions.isEmpty()); - + } - + public void setPriorityPlayer(int index) { for (int j = 0; j < np; j++) { @@ -990,7 +993,7 @@ } playerCash[i].setVisible(!clickable); playerCashButton[i].setVisible(clickable); - + if (action != null) playerCashButton[i].addPossibleAction(action); } Modified: trunk/18xx/rails/ui/swing/GameUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/GameUIManager.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/ui/swing/GameUIManager.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -130,7 +130,7 @@ } if (font != null) log.debug("Change text fonts globally to " + font.getName() + " / " + (boldStyle ? "Bold" : "Plain")); } - + String fontScale = Config.getGameSpecific("font.ui.scale"); if (Util.hasValue(fontScale)) { try { @@ -143,13 +143,13 @@ } public void gameUIInit() { - + imageLoader = new ImageLoader(); stockChart = new StockChart(this); reportWindow = new ReportWindow(gameManager); orWindow = new ORWindow(this); orUIManager = orWindow.getORUIManager(); - + String statusWindowClassName = getClassName(GuiDef.ClassName.STATUS_WINDOW); try { Class<? extends StatusWindow> statusWindowClass = @@ -230,7 +230,7 @@ // // return true; // -// } +// } // else if (gameManager.getBank().isJustBroken()) { // // statusWindow.reportBankBroken(); @@ -252,7 +252,7 @@ return true; } } - + // display the end of game report if (gameManager.isGameOver()) statusWindow.endOfGameReport(); @@ -412,8 +412,8 @@ orWindow.setVisible(true); orWindow.toFront(); } - - + + // Update the currently visible round window // "Switchable" rounds will be handled from subclasses of this class. if (StartRoundWindow.class.isAssignableFrom(activeWindow.getClass())) { @@ -554,7 +554,7 @@ public void dialogActionPerformed (boolean ready) { if (!ready) { - + if (checkGameSpecificDialogAction()) { ; } else if (currentDialog instanceof RadioButtonDialog @@ -567,7 +567,7 @@ if (index >= 0) { int price = action.getStartPrices()[index]; action.setStartPrice(price); - action.setNumberBought(action.getCertificate().getShares()); + action.setNumberBought(action.getSharesPerCertificate()); } else { // No selection done - no action return; @@ -669,12 +669,12 @@ if(font != null) { float newSize = font.getSize2D() * (float)scale; UIManager.put(key, new FontUIResource(font.deriveFont(newSize))); - } - } - } + } + } + } } - - + + public void exportGame(GameAction exportAction) { JFileChooser jfc = new JFileChooser(); String filename; @@ -699,8 +699,8 @@ processOnServer(exportAction); } } - - + + public void saveGame(GameAction saveAction) { JFileChooser jfc = new JFileChooser(); Modified: trunk/18xx/rails/ui/swing/gamespecific/_18EU/GameUIManager_18EU.java =================================================================== --- trunk/18xx/rails/ui/swing/gamespecific/_18EU/GameUIManager_18EU.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/ui/swing/gamespecific/_18EU/GameUIManager_18EU.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -76,7 +76,7 @@ LocalText.getText("PleaseSelect"), LocalText.getText( "SelectMinorToMerge", - action.getCertificate().getCompany().getName()), + action.getCompanyName()), options, -1); setCurrentDialog(dialog, action); return; @@ -93,7 +93,7 @@ LocalText.getText("PleaseSelect"), LocalText.getText( "SelectHomeStation", - action.getCertificate().getCompany().getName()), + action.getCompanyName()), options, -1); setCurrentDialog(dialog, action); return; Modified: trunk/18xx/rails/util/Util.java =================================================================== --- trunk/18xx/rails/util/Util.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/util/Util.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -42,6 +42,15 @@ return b.toString(); } + public static String joinWithDelimiter (int[] sa, String delimiter) { + StringBuilder b = new StringBuilder(); + for (int s : sa) { + if (b.length() > 0) b.append(delimiter); + b.append(s); + } + return b.toString(); + } + public static int parseInt(String value) throws ConfigurationException { if (!hasValue(value)) return 0; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-07-25 17:08:43
|
Revision: 1357 http://rails.svn.sourceforge.net/rails/?rev=1357&view=rev Author: evos Date: 2010-07-25 17:08:37 +0000 (Sun, 25 Jul 2010) Log Message: ----------- Executed actions are no longer saved as a List<PossibleAction> but as a containerless sequence of PossibleAction objects. This allows postponing object assignment during deserialization until all previous actions have been processed, so that the game always is in the same state as during playing the game. This should fix bugs attributable to assignment to objects that do not exist at the start of the game. Modified Paths: -------------- trunk/18xx/rails/game/Game.java trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/GameManagerI.java trunk/18xx/rails/util/ListAndFixSavedFiles.java Modified: trunk/18xx/rails/game/Game.java =================================================================== --- trunk/18xx/rails/game/Game.java 2010-07-24 15:47:32 UTC (rev 1356) +++ trunk/18xx/rails/game/Game.java 2010-07-25 17:08:37 UTC (rev 1357) @@ -94,7 +94,7 @@ // set special properties and token static variables SpecialProperty.init(); Token.init(); - + // Have the ComponentManager work through the other rails.game files componentManager.finishPreparation(); @@ -163,7 +163,7 @@ "No TileManager XML element found in file " + GAME_XML_FILE); } - + revenueManager = (RevenueManager) componentManager.findComponent("RevenueManager"); // revenueManager is optional so far @@ -189,7 +189,7 @@ bank.finishConfiguration(gameManager); stockMarket.finishConfiguration(gameManager); tileManager.finishConfiguration(gameManager); - if (revenueManager != null) + if (revenueManager != null) revenueManager.finishConfiguration(gameManager); } catch (Exception e) { String message = @@ -251,24 +251,59 @@ throw new ConfigurationException("Error in setting up " + name); } - List<PossibleAction> executedActions = - (List<PossibleAction>) ois.readObject(); - ois.close(); - log.debug("Number of loaded actions: " + executedActions.size()); - String startError = game.start(); if (startError != null) { DisplayBuffer.add(startError); return null; } + GameManagerI gameManager = game.getGameManager(); + int numberOfActions = 0; log.debug("Starting to execute loaded actions"); - if (!game.getGameManager().processOnReload(executedActions)) { - log.error ("Load interrupted"); - DisplayBuffer.add(LocalText.getText("LoadInterrupted")); + while (true) { // Single-pass loop. + Object firstActionObject; + try { + firstActionObject = ois.readObject(); + } catch (EOFException e) { + // Allow saved file at start of game (with no actions). + break; + } + if (firstActionObject instanceof List) { + // Old-style: one List of PossibleActions + List<PossibleAction> executedActions = + (List<PossibleAction>) firstActionObject; + numberOfActions = executedActions.size(); + for (PossibleAction action : executedActions) { + if (!gameManager.processOnReload(action)) { + log.error ("Load interrupted"); + DisplayBuffer.add(LocalText.getText("LoadInterrupted")); + break; + } + } + + } else { + // New style: separate PossibleActionsObjects, since Rails 1.3.1 + PossibleAction action = (PossibleAction) firstActionObject; + while (true) { + numberOfActions++; + if (!gameManager.processOnReload(action)) { + log.error ("Load interrupted"); + DisplayBuffer.add(LocalText.getText("LoadInterrupted")); + break; + } + try { + action = (PossibleAction) ois.readObject(); + } catch (EOFException e) { + break; + } + } + } + break; } + ois.close(); + game.getGameManager().finishLoading(); return game; } catch (Exception e) { Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-07-24 15:47:32 UTC (rev 1356) +++ trunk/18xx/rails/game/GameManager.java 2010-07-25 17:08:37 UTC (rev 1357) @@ -891,64 +891,60 @@ /* (non-Javadoc) * @see rails.game.GameManagerI#processOnReload(java.util.List) */ - public boolean processOnReload(List<PossibleAction> actions) throws Exception { + public boolean processOnReload(PossibleAction action) throws Exception { - for (PossibleAction action : actions) { + DisplayBuffer.clear(); + // TEMPORARY FIX TO ALLOW OLD 1856 SAVED FILES TO BE PROCESSED + if (gameName.equals("1856") + && possibleActions.contains(RepayLoans.class) + && (!possibleActions.contains(action.getClass()) + || (action.getClass() == NullAction.class + && ((NullAction)action).getMode() != NullAction.DONE))) { + // Insert "Done" + log.debug("Action DONE inserted"); + getCurrentRound().process(new NullAction (NullAction.DONE)); + possibleActions.clear(); + getCurrentRound().setPossibleActions(); + if (!isGameOver()) setCorrectionActions(); + } - DisplayBuffer.clear(); - // TEMPORARY FIX TO ALLOW OLD 1856 SAVED FILES TO BE PROCESSED - if (gameName.equals("1856") - && possibleActions.contains(RepayLoans.class) - && (!possibleActions.contains(action.getClass()) - || (action.getClass() == NullAction.class - && ((NullAction)action).getMode() != NullAction.DONE))) { - // Insert "Done" - log.debug("Action DONE inserted"); - getCurrentRound().process(new NullAction (NullAction.DONE)); - possibleActions.clear(); - getCurrentRound().setPossibleActions(); - if (!isGameOver()) setCorrectionActions(); + try { + 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"; + log.error(msg); + DisplayBuffer.add(msg); + if (moveStack.isOpen()) moveStack.finish(); + return false; } + possibleActions.clear(); + getCurrentRound().setPossibleActions(); - try { - 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"; - log.error(msg); - DisplayBuffer.add(msg); - if (moveStack.isOpen()) moveStack.finish(); - return false; - } - possibleActions.clear(); - getCurrentRound().setPossibleActions(); + // Log possible actions (normally this is outcommented) + String playerName = getCurrentPlayer().getName(); + for (PossibleAction a : possibleActions.getList()) { + log.debug(playerName+" may: "+a.toString()); + } - // Log possible actions (normally this is outcommented) - String playerName = getCurrentPlayer().getName(); - for (PossibleAction a : possibleActions.getList()) { - log.debug(playerName+" may: "+a.toString()); - } + if (!isGameOver()) setCorrectionActions(); - if (!isGameOver()) setCorrectionActions(); + } catch (Exception e) { + log.error("Error while reprocessing " + action.toString(), e); + throw new Exception("Reload failure", e); + } + new AddToList<PossibleAction>(executedActions, action, "ExecutedActions"); + if (moveStack.isOpen()) moveStack.finish(); - } catch (Exception e) { - log.error("Error while reprocessing " + action.toString(), e); - throw new Exception("Reload failure", e); - } - new AddToList<PossibleAction>(executedActions, action, - "ExecutedActions"); - if (moveStack.isOpen()) moveStack.finish(); + log.debug("Turn: "+getCurrentPlayer().getName()); + return true; + } - log.debug("Turn: "+getCurrentPlayer().getName()); - } + public void finishLoading () { - // DisplayBuffer.clear(); - // previous line removed to allow display of nextPlayerMessages guiHints.clearVisibilityHints(); - - return true; } /** recoverySave method @@ -1023,7 +1019,9 @@ oos.writeObject(gameName); oos.writeObject(gameOptions); oos.writeObject(playerNames); - oos.writeObject(executedActions); + for (PossibleAction action : executedActions) { + oos.writeObject(action); + } oos.close(); result = true; Modified: trunk/18xx/rails/game/GameManagerI.java =================================================================== --- trunk/18xx/rails/game/GameManagerI.java 2010-07-24 15:47:32 UTC (rev 1356) +++ trunk/18xx/rails/game/GameManagerI.java 2010-07-25 17:08:37 UTC (rev 1357) @@ -55,9 +55,11 @@ */ public abstract boolean process(PossibleAction action); - public abstract boolean processOnReload(List<PossibleAction> actions) + public abstract boolean processOnReload(PossibleAction action) throws Exception; + public void finishLoading (); + public abstract void finishShareSellingRound(); public abstract void finishTreasuryShareRound(); Modified: trunk/18xx/rails/util/ListAndFixSavedFiles.java =================================================================== --- trunk/18xx/rails/util/ListAndFixSavedFiles.java 2010-07-24 15:47:32 UTC (rev 1356) +++ trunk/18xx/rails/util/ListAndFixSavedFiles.java 2010-07-25 17:08:37 UTC (rev 1357) @@ -29,12 +29,12 @@ private JMenuItem trimItem, deleteItem; private StringBuffer headerText = new StringBuffer(); - + private List<Object> savedObjects = new ArrayList<Object>(512); private List<PossibleAction> executedActions; - + private int vbarPos; - + private static String saveDirectory; private String filepath; @@ -44,13 +44,13 @@ * @param args */ public static void main(String[] args) { - + // intialize configuration Config.setConfigSelection(); // delayed setting of logger log = Logger.getLogger(ListAndFixSavedFiles.class.getPackage().getName()); - + saveDirectory = Config.get("save.directory"); System.out.println("Save directory = " + saveDirectory); @@ -142,11 +142,12 @@ setVisible(true); saveDirectory = Config.get("save.directory"); - + load(); } + @SuppressWarnings("unchecked") private void load() { JFileChooser jfc = new JFileChooser(); @@ -211,10 +212,26 @@ throw new ConfigurationException("Error in setting up " + name); } - executedActions = - (List<PossibleAction>) ois.readObject(); - savedObjects.add(executedActions); - + Object firstActionObject = ois.readObject(); + if (firstActionObject instanceof List) { + // Old-style: one List of PossibleActions + executedActions = + (List<PossibleAction>) firstActionObject; + savedObjects.add(executedActions); + } else { + // New style: separate PossibleActionsObjects, since Rails 1.3.1 + executedActions = new ArrayList<PossibleAction>(); + PossibleAction action = (PossibleAction) firstActionObject; + while (true) { + savedObjects.add (action); + executedActions.add(action); + try { + action = (PossibleAction) ois.readObject(); + } catch (EOFException e) { + break; + } + } + } setReportText(true); ois.close(); @@ -232,13 +249,13 @@ headerText.append("\n"); } } - + private void setReportText(boolean initial) { if (initial) vbarPos = -1; else vbarPos = this.vbar.getValue(); - + reportText.setText(headerText.toString()); // append actionText int i=0; @@ -248,8 +265,8 @@ } scrollDown(vbarPos); } - + public void scrollDown (int pos) { SwingUtilities.invokeLater(new Runnable() { public void run() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-25 19:15:40
|
Revision: 1358 http://rails.svn.sourceforge.net/rails/?rev=1358&view=rev Author: stefanfrey Date: 2010-07-25 19:15:33 +0000 (Sun, 25 Jul 2010) Log Message: ----------- Fixed reported bug (feature request): 1889 offboards- rollover scores incorrect ('D' missing) - ID: 3033639 Shows bonus information in tooltip now Modified Paths: -------------- trunk/18xx/rails/algorithms/RevenueBonusTemplate.java trunk/18xx/rails/ui/swing/hexmap/GUIHex.java Modified: trunk/18xx/rails/algorithms/RevenueBonusTemplate.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueBonusTemplate.java 2010-07-25 17:08:37 UTC (rev 1357) +++ trunk/18xx/rails/algorithms/RevenueBonusTemplate.java 2010-07-25 19:15:33 UTC (rev 1358) @@ -13,6 +13,7 @@ import rails.game.PhaseManager; import rails.game.TrainManager; import rails.game.TrainTypeI; +import rails.util.LocalText; import rails.util.Tag; /** @@ -132,6 +133,32 @@ } } } + + /** + * @return bonus name for display + */ + public String getName() { + return name; + } + + /** + * @return bonus toolTip text + */ + public String getToolTip() { + StringBuffer s = new StringBuffer(); + s.append(value); + if (identPhases.size() != 0) { + s.append(identPhases); + if (identTrainTypes.size() != 0) { + s.append(""); + } + } + if (identTrainTypes.size() != 0) { + s.append(identTrainTypes); + } + return s.toString(); + } + public String toString() { StringBuffer s = new StringBuffer(); s.append("RevenueBonusTemplate"); Modified: trunk/18xx/rails/ui/swing/hexmap/GUIHex.java =================================================================== --- trunk/18xx/rails/ui/swing/hexmap/GUIHex.java 2010-07-25 17:08:37 UTC (rev 1357) +++ trunk/18xx/rails/ui/swing/hexmap/GUIHex.java 2010-07-25 19:15:33 UTC (rev 1358) @@ -8,6 +8,8 @@ import org.apache.log4j.Logger; +import rails.algorithms.RevenueBonus; +import rails.algorithms.RevenueBonusTemplate; import rails.game.*; import rails.game.model.ModelObject; import rails.ui.swing.GUIToken; @@ -662,6 +664,29 @@ return toolTip; } + + private String bonusToolTipText(List<RevenueBonusTemplate> bonuses) { + StringBuffer tt = new StringBuffer(); + if (bonuses != null) { + if (bonuses.size() == 1) { + tt.append("<br>Bonus:"); + tt.append(bonuses.get(0).getToolTip()); + } else { + Set<String> bonusNames = new HashSet<String>(); + for (RevenueBonusTemplate bonus:bonuses) { + bonusNames.add(bonus.getName()); + } + tt.append("<br>Bonus:"); + int i=0; + for (String bonusName:bonusNames) { + if (i++ != 0) tt.append(","); + tt.append(bonusName); + } + } + } + return tt.toString(); + } + protected void setToolTip() { StringBuffer tt = new StringBuffer("<html>"); tt.append("<b>Hex</b>: ").append(hexName); @@ -708,7 +733,12 @@ // TEMPORARY tt.append(" <small>pos=" + st.getPosition() + "</small>"); } + tt.append(bonusToolTipText(currentTile.getRevenueBonuses())); } + + // revenueBonuses + tt.append(bonusToolTipText(model.getRevenueBonuses())); + String upgrades = currentTile.getUpgradesString(model); if (upgrades.equals("")) { tt.append("<br>No upgrades"); @@ -726,6 +756,8 @@ tt.append(dest.getName()); } } + + tt.append("</html>"); toolTip = tt.toString(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-11 23:22:05
|
Revision: 1379 http://rails.svn.sourceforge.net/rails/?rev=1379&view=rev Author: stefanfrey Date: 2010-08-11 23:21:59 +0000 (Wed, 11 Aug 2010) Log Message: ----------- Newline copy&paste fix and moved execution of multiple undos to server part of Rails Modified Paths: -------------- trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/ReportBuffer.java trunk/18xx/rails/game/action/GameAction.java trunk/18xx/rails/ui/swing/ReportWindowDynamic.java Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-08-10 23:08:08 UTC (rev 1378) +++ trunk/18xx/rails/game/GameManager.java 2010-08-11 23:21:59 UTC (rev 1379) @@ -773,30 +773,9 @@ // Process undo/redo centrally if (action instanceof GameAction) { - GameAction gameAction = (GameAction) action; - switch (gameAction.getMode()) { - case GameAction.SAVE: - result = save(gameAction); - break; - case GameAction.UNDO: - moveStack.undoMoveSet(false); - result = true; - break; - case GameAction.FORCED_UNDO: - moveStack.undoMoveSet(true); - result = true; - break; - case GameAction.REDO: - moveStack.redoMoveSet(); - result = true; - break; - case GameAction.EXPORT: - result = export(gameAction); - break; - } + result = processGameActions(gameAction); if (result) break; - } // All other actions: process per round @@ -890,6 +869,43 @@ return result; } + private boolean processGameActions(GameAction gameAction) { + // Process undo/redo centrally + boolean result = false; + + int index = gameAction.getmoveStackIndex(); + switch (gameAction.getMode()) { + case GameAction.SAVE: + result = save(gameAction); + break; + case GameAction.UNDO: + moveStack.undoMoveSet(true); + result = true; + break; + case GameAction.FORCED_UNDO: + if (index != -1) { + moveStack.gotoIndex(index); + } else { + moveStack.undoMoveSet(false); + } + result = true; + break; + case GameAction.REDO: + if (index != -1) { + moveStack.gotoIndex(index); + } else { + moveStack.redoMoveSet(); + } + result = true; + break; + case GameAction.EXPORT: + result = export(gameAction); + break; + } + + return result; + } + /* (non-Javadoc) * @see rails.game.GameManagerI#processOnReload(java.util.List) */ Modified: trunk/18xx/rails/game/ReportBuffer.java =================================================================== --- trunk/18xx/rails/game/ReportBuffer.java 2010-08-10 23:08:08 UTC (rev 1378) +++ trunk/18xx/rails/game/ReportBuffer.java 2010-08-11 23:21:59 UTC (rev 1379) @@ -51,10 +51,10 @@ if (init) { s.append("<a href=http://rails:" + index + ">"); s.append(message); - s.append("</a><br>"); + s.append("</a><br> "); // is the linefeed character to induce line feed on copy & paste init = false; } else { - s.append(message + "<br>"); + s.append(message + "<br> "); // see above } } return s.toString(); Modified: trunk/18xx/rails/game/action/GameAction.java =================================================================== --- trunk/18xx/rails/game/action/GameAction.java 2010-08-10 23:08:08 UTC (rev 1378) +++ trunk/18xx/rails/game/action/GameAction.java 2010-08-11 23:21:59 UTC (rev 1379) @@ -20,6 +20,7 @@ // Client-side settings protected String filepath; // Only applies to SAVE and LOAD + protected int moveStackIndex = -1; // target moveStackIndex, only for FORCED_UNDO and REDO public static final long serialVersionUID = 1L; @@ -37,6 +38,14 @@ return filepath; } + public void setmoveStackIndex(int moveStackIndex) { + this.moveStackIndex = moveStackIndex; + } + + public int getmoveStackIndex() { + return moveStackIndex; + } + public int getMode() { return mode; } Modified: trunk/18xx/rails/ui/swing/ReportWindowDynamic.java =================================================================== --- trunk/18xx/rails/ui/swing/ReportWindowDynamic.java 2010-08-10 23:08:08 UTC (rev 1378) +++ trunk/18xx/rails/ui/swing/ReportWindowDynamic.java 2010-08-11 23:21:59 UTC (rev 1379) @@ -146,16 +146,12 @@ MoveStack stack = gameUIManager.getGameManager().getMoveStack(); int currentIndex = stack.getIndex(); if (index > currentIndex) { // move forward - if (index != currentIndex +1) { - stack.gotoIndex(index - 1); - } GameAction action = new GameAction(GameAction.REDO); + action.setmoveStackIndex(index); gameUIManager.processOnServer(action); } else if (index < currentIndex) { // move backward - if (index != currentIndex - 1) { - stack.gotoIndex(index + 1); - } GameAction action = new GameAction(GameAction.FORCED_UNDO); + action.setmoveStackIndex(index); gameUIManager.processOnServer(action); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-13 15:57:52
|
Revision: 1382 http://rails.svn.sourceforge.net/rails/?rev=1382&view=rev Author: stefanfrey Date: 2010-08-13 15:57:46 +0000 (Fri, 13 Aug 2010) Log Message: ----------- Changes to MessagePanel, allows to display revenue results Some fixes to scales, others needed Removed call of updateUI in gameinitUI of GameUIManager Modified Paths: -------------- trunk/18xx/rails/algorithms/RevenueAdapter.java trunk/18xx/rails/algorithms/RevenueTrainRun.java trunk/18xx/rails/ui/swing/GameUIManager.java trunk/18xx/rails/ui/swing/MessagePanel.java trunk/18xx/rails/ui/swing/ORPanel.java trunk/18xx/rails/ui/swing/ORUIManager.java trunk/18xx/rails/ui/swing/Scale.java trunk/18xx/rails/ui/swing/UpgradesPanel.java Modified: trunk/18xx/rails/algorithms/RevenueAdapter.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueAdapter.java 2010-08-12 20:58:05 UTC (rev 1381) +++ trunk/18xx/rails/algorithms/RevenueAdapter.java 2010-08-13 15:57:46 UTC (rev 1382) @@ -628,17 +628,23 @@ } - public String getOptimalRunPrettyPrint() { + public String getOptimalRunPrettyPrint(boolean includeDetails) { List<RevenueTrainRun> listRuns = getOptimalRun(); if (listRuns== null) return "No Optimal Run"; StringBuffer runPrettyPrint = new StringBuffer(); for (RevenueTrainRun run:listRuns) { - runPrettyPrint.append(run.prettyPrint()); + runPrettyPrint.append(run.prettyPrint(includeDetails)); + if (includeDetails) + runPrettyPrint.append("<BR>"); + else if (run != listRuns.get(listRuns.size()-1)) + runPrettyPrint.append("; "); } - // add dynamic Modifier - for (RevenueDynamicModifier modifier:dynamicModifiers) { - runPrettyPrint.append(modifier.prettyPrint(this)); + if (includeDetails) { + // add dynamic Modifier + for (RevenueDynamicModifier modifier:dynamicModifiers) { + runPrettyPrint.append(modifier.prettyPrint(this)); + } } return runPrettyPrint.toString(); Modified: trunk/18xx/rails/algorithms/RevenueTrainRun.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueTrainRun.java 2010-08-12 20:58:05 UTC (rev 1381) +++ trunk/18xx/rails/algorithms/RevenueTrainRun.java 2010-08-13 15:57:46 UTC (rev 1382) @@ -195,75 +195,76 @@ int length = runPrettyPrint.length() - initLength; if (length / PRETTY_PRINT_LENGTH != multiple) { multiple = length / PRETTY_PRINT_LENGTH; - runPrettyPrint.append("\n"); + runPrettyPrint.append("<BR>"); for (int i=0; i < PRETTY_PRINT_INDENT; i++) runPrettyPrint.append(" ") ; } return multiple; } - String prettyPrint() { + String prettyPrint(boolean includeDetails) { StringBuffer runPrettyPrint = new StringBuffer(); runPrettyPrint.append(LocalText.getText("N_Train", train.toString())); - runPrettyPrint.append(": " + getRunValue()); - - Set<NetworkVertex> uniqueVertices = getUniqueVertices(); - int majors = NetworkVertex.numberOfVertexType(uniqueVertices, VertexType.STATION, StationType.MAJOR); - int minors = NetworkVertex.numberOfVertexType(uniqueVertices, VertexType.STATION, StationType.MINOR); - if (train.ignoresMinors() || minors == 0) { - runPrettyPrint.append(LocalText.getText("RevenueStationsIgnoreMinors", majors)); - } else { - runPrettyPrint.append(LocalText.getText("RevenueStations", majors, minors)); - } - - int initLength = runPrettyPrint.length(); - int multiple = prettyPrintNewLine(runPrettyPrint, -1, initLength); - String currentHexName = null; - NetworkVertex startVertex = null; - for (NetworkVertex vertex:vertices) { - if (startVertex == null) { - currentHexName = prettyPrintHexName(vertex); - startVertex = vertex; - runPrettyPrint.append(prettyPrintHexName(vertex) + "("); - } else if (startVertex == vertex) { - currentHexName = prettyPrintHexName(vertex); - runPrettyPrint.append(") / "); - multiple = prettyPrintNewLine(runPrettyPrint, multiple, initLength); - runPrettyPrint.append(prettyPrintHexName(vertex) + "(0"); - continue; - } else if (!currentHexName.equals(prettyPrintHexName(vertex))) { - currentHexName = prettyPrintHexName(vertex); - runPrettyPrint.append("), "); - multiple = prettyPrintNewLine(runPrettyPrint, multiple, initLength); - runPrettyPrint.append(prettyPrintHexName(vertex) + "("); + runPrettyPrint.append(" = " + getRunValue()); + if (includeDetails) { + // details of the run + Set<NetworkVertex> uniqueVertices = getUniqueVertices(); + int majors = NetworkVertex.numberOfVertexType(uniqueVertices, VertexType.STATION, StationType.MAJOR); + int minors = NetworkVertex.numberOfVertexType(uniqueVertices, VertexType.STATION, StationType.MINOR); + if (train.ignoresMinors() || minors == 0) { + runPrettyPrint.append(LocalText.getText("RevenueStationsIgnoreMinors", majors)); } else { - runPrettyPrint.append(","); + runPrettyPrint.append(LocalText.getText("RevenueStations", majors, minors)); } - if (vertex.isStation()) { - runPrettyPrint.append(revenueAdapter.getVertexValueAsString(vertex, train, revenueAdapter.getPhase())); - } else { - runPrettyPrint.append(vertex.getHex().getOrientationName(vertex.getSide())); + int initLength = runPrettyPrint.length(); + int multiple = prettyPrintNewLine(runPrettyPrint, -1, initLength); + String currentHexName = null; + NetworkVertex startVertex = null; + for (NetworkVertex vertex:vertices) { + if (startVertex == null) { + currentHexName = prettyPrintHexName(vertex); + startVertex = vertex; + runPrettyPrint.append(prettyPrintHexName(vertex) + "("); + } else if (startVertex == vertex) { + currentHexName = prettyPrintHexName(vertex); + runPrettyPrint.append(") / "); + multiple = prettyPrintNewLine(runPrettyPrint, multiple, initLength); + runPrettyPrint.append(prettyPrintHexName(vertex) + "(0"); + continue; + } else if (!currentHexName.equals(prettyPrintHexName(vertex))) { + currentHexName = prettyPrintHexName(vertex); + runPrettyPrint.append("), "); + multiple = prettyPrintNewLine(runPrettyPrint, multiple, initLength); + runPrettyPrint.append(prettyPrintHexName(vertex) + "("); + } else { + runPrettyPrint.append(","); + } + if (vertex.isStation()) { + runPrettyPrint.append(revenueAdapter.getVertexValueAsString(vertex, train, revenueAdapter.getPhase())); + } else { + runPrettyPrint.append(vertex.getHex().getOrientationName(vertex.getSide())); + } } - } - - if (currentHexName != null) { - runPrettyPrint.append(")"); - } - - // check revenueBonuses (complex) - List<RevenueBonus> activeBonuses = new ArrayList<RevenueBonus>(); - for (RevenueBonus bonus:revenueAdapter.getRevenueBonuses()) { - if (bonus.checkComplexBonus(vertices, train.getRailsTrain(), revenueAdapter.getPhase())) { - activeBonuses.add(bonus); + + if (currentHexName != null) { + runPrettyPrint.append(")"); } + + // check revenueBonuses (complex) + List<RevenueBonus> activeBonuses = new ArrayList<RevenueBonus>(); + for (RevenueBonus bonus:revenueAdapter.getRevenueBonuses()) { + if (bonus.checkComplexBonus(vertices, train.getRailsTrain(), revenueAdapter.getPhase())) { + activeBonuses.add(bonus); + } + } + Map<String,Integer> printBonuses = RevenueBonus.combineBonuses(activeBonuses); + for (String bonusName:printBonuses.keySet()) { + runPrettyPrint.append(" + "); + runPrettyPrint.append(bonusName + "(" + printBonuses.get(bonusName) + ")"); + multiple = prettyPrintNewLine(runPrettyPrint, multiple, initLength); + } + runPrettyPrint.append("\n"); } - Map<String,Integer> printBonuses = RevenueBonus.combineBonuses(activeBonuses); - for (String bonusName:printBonuses.keySet()) { - runPrettyPrint.append(" + "); - runPrettyPrint.append(bonusName + "(" + printBonuses.get(bonusName) + ")"); - multiple = prettyPrintNewLine(runPrettyPrint, multiple, initLength); - } - runPrettyPrint.append("\n"); return runPrettyPrint.toString(); } @@ -286,50 +287,5 @@ } } return path; - -// NetworkVertex startVertex = null; -// NetworkVertex previousVertex = null; -// for (NetworkVertex vertex:vertices) { -// log.debug("Revenue Path: Next vertex " + vertex); -// Point2D vertexPoint = NetworkVertex.getVertexPoint2D(map, vertex); -// if (startVertex == null) { -// startVertex = vertex; -// previousVertex = vertex; -// path.moveTo((float)vertexPoint.getX(), (float)vertexPoint.getY()); -// continue; -// } else if (startVertex == vertex) { -// path.moveTo((float)vertexPoint.getX(), (float)vertexPoint.getY()); -// previousVertex = vertex; -// continue; -// } -// // draw hidden vertexes -// NetworkEdge edge = revenueAdapter.getRCGraph().getEdge(previousVertex, vertex); -// if (edge != null) { -// log.debug("Revenue Path: draw edge "+ edge.toFullInfoString()); -// List<NetworkVertex> hiddenVertexes = edge.getHiddenVertexes(); -// if (edge.getSource() == vertex) { -// log.debug("Revenue Path: reverse hiddenVertexes"); -// for (int i = hiddenVertexes.size() - 1; i >= 0; i--) { -// NetworkVertex v = hiddenVertexes.get(i); -// Point2D vPoint = NetworkVertex.getVertexPoint2D(map, v); -// if (vPoint != null) { -// path.lineTo((float)vPoint.getX(), (float)vPoint.getY()); -// } -// } -// } else { -// for (NetworkVertex v:hiddenVertexes) { -// Point2D vPoint = NetworkVertex.getVertexPoint2D(map, v); -// if (vPoint != null) { -// path.lineTo((float)vPoint.getX(), (float)vPoint.getY()); -// } -// } -// } -// } -// if (vertexPoint != null) { -// path.lineTo((float)vertexPoint.getX(), (float)vertexPoint.getY()); -// } -// previousVertex = vertex; -// } -// return path; } } \ No newline at end of file Modified: trunk/18xx/rails/ui/swing/GameUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/GameUIManager.java 2010-08-12 20:58:05 UTC (rev 1381) +++ trunk/18xx/rails/ui/swing/GameUIManager.java 2010-08-13 15:57:46 UTC (rev 1382) @@ -141,15 +141,8 @@ if (font != null) log.debug("Change text fonts globally to " + font.getName() + " / " + (boldStyle ? "Bold" : "Plain")); } - String fontScale = Config.getGameSpecific("font.ui.scale"); - if (Util.hasValue(fontScale)) { - try { - changeGlobalFont(font, Double.parseDouble(fontScale)); - log.debug("Change text fonts to relative scale " + fontScale); - } catch (NumberFormatException e) { - // do nothing - } - } + log.debug("Change text fonts to relative scale " + Scale.getFontScale()); + changeGlobalFont(font, Scale.getFontScale()); } @@ -183,7 +176,8 @@ System.exit(1); } - updateUI(); + // uncommented by sfy on 13/08/10 to avoid double revenue calculation +// updateUI(); reportWindow.scrollDown(); @@ -844,6 +838,7 @@ * (after configuration changes) */ public static void updateUILookAndFeel() { + Scale.initFromConfiguration(); instance.initFontSettings(); instance.updateWindowsLookAndFeel(); Modified: trunk/18xx/rails/ui/swing/MessagePanel.java =================================================================== --- trunk/18xx/rails/ui/swing/MessagePanel.java 2010-08-12 20:58:05 UTC (rev 1381) +++ trunk/18xx/rails/ui/swing/MessagePanel.java 2010-08-13 15:57:46 UTC (rev 1382) @@ -2,6 +2,10 @@ package rails.ui.swing; import java.awt.Color; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.ArrayList; +import java.util.List; import javax.swing.*; @@ -9,6 +13,11 @@ private static final long serialVersionUID = 1L; private JLabel message; + + private String currentMessage; + private StringBuffer currentInformation; + private List<String> currentDetails = new ArrayList<String>(); + private boolean showDetails; Color background = new Color(225, 225, 225); @@ -27,15 +36,71 @@ add(message); message.setVisible(true); setVisible(true); + + this.addMouseListener(new MouseListener() { + public void mouseClicked(MouseEvent arg0) { + showDetails = !showDetails; + updateMessageText(); + } + + public void mouseEntered(MouseEvent arg0) {} + public void mouseExited(MouseEvent arg0) {} + public void mousePressed(MouseEvent arg0) {} + public void mouseReleased(MouseEvent arg0) {} + }); + } - public void setMessage(String messageText) { - if (messageText != null) { - int lines = messageText.split("<[Bb][Rr]>").length + 1; + private void updateMessageText() { + StringBuffer messageText = new StringBuffer() ; + if (currentMessage != null) { + messageText.append(currentMessage); + } + if (currentInformation != null) { + messageText.append("<span style='color:green'>"); + messageText.append(currentInformation); + messageText.append("</span>"); + } + if (showDetails) { + messageText.append("<span style='color:blue'>"); + for (String detail:currentDetails) { + messageText.append(detail); + } + messageText.append("</span>"); + } else if (currentDetails.size() != 0) { + messageText.append("<span style='color:blue'>"); + messageText.append("<BR> Click for more details"); + messageText.append("</span>"); + } + if (currentMessage != null) { + String text = messageText.toString(); + int lines = text.split("<[Bb][Rr]>").length + 1; setLines(lines); - message.setText("<html><center>" + messageText + "</center></html>"); + message.setText("<html><center>" + text + "</center></html>"); } + } + + public void setMessage(String messageText) { + currentMessage = messageText; + currentInformation = null; + currentDetails.clear(); + showDetails = false; + updateMessageText(); + } + + public void addInformation(String infoText) { + if (currentInformation == null) { + currentInformation = new StringBuffer(); + } + currentInformation.append("<BR>" + infoText); + updateMessageText(); + } + + public void addDetail(String detailText) { + currentDetails.add("<BR>" + detailText); + updateMessageText(); + } public void setLines(int numberOfLines) { setSize(1000, numberOfLines * 12); Modified: trunk/18xx/rails/ui/swing/ORPanel.java =================================================================== --- trunk/18xx/rails/ui/swing/ORPanel.java 2010-08-12 20:58:05 UTC (rev 1381) +++ trunk/18xx/rails/ui/swing/ORPanel.java 2010-08-13 15:57:46 UTC (rev 1382) @@ -633,11 +633,11 @@ log.info("Revenue Adapter:" + ra); int revenueValue = ra.calculateRevenue(); log.info("Revenue Value:" + revenueValue); - log.info("Revenue Run:" + ra.getOptimalRunPrettyPrint()); + log.info("Revenue Run:" + ra.getOptimalRunPrettyPrint(true)); ra.drawOptimalRunAsPath(orUIManager.getMap()); orUIManager.getMap().repaint(); JOptionPane.showMessageDialog(orWindow, "RevenueValue = " + revenueValue + - "\nRevenueRun = \n" + ra.getOptimalRunPrettyPrint()); + "\nRevenueRun = \n" + ra.getOptimalRunPrettyPrint(true)); // simple ra = RevenueAdapter.createRevenueAdapter(gm, company, gm.getCurrentPhase()); @@ -648,11 +648,11 @@ log.info("Revenue Adapter:" + ra); revenueValue = ra.calculateRevenue(); log.info("Revenue Value:" + revenueValue); - log.info("Revenue Run:" + ra.getOptimalRunPrettyPrint()); + log.info("Revenue Run:" + ra.getOptimalRunPrettyPrint(true)); ra.drawOptimalRunAsPath(orUIManager.getMap()); orUIManager.getMap().repaint(); JOptionPane.showMessageDialog(orWindow, "RevenueValue = " + revenueValue + - "\nRevenueRun = \n" + ra.getOptimalRunPrettyPrint()); + "\nRevenueRun = \n" + ra.getOptimalRunPrettyPrint(true)); String trainString = JOptionPane.showInputDialog(orWindow, "Another train", @@ -831,7 +831,7 @@ private RevenueAdapter initRevenueCalculation(PublicCompanyI company){ GameManagerI gm = orUIManager.getGameUIManager().getGameManager(); RevenueAdapter ra = RevenueAdapter.createRevenueAdapter(gm, company, gm.getCurrentPhase()); - ra.initRevenueCalculator(false); + ra.initRevenueCalculator(true); ra.addRevenueListener(this); return ra; } @@ -841,8 +841,9 @@ if (finalResult) { revenueAdapter.drawOptimalRunAsPath(orUIManager.getMap()); orUIManager.getMap().repaint(); - JOptionPane.showMessageDialog(orWindow, "Best Run Value = " + bestRevenue + - "\n" + revenueAdapter.getOptimalRunPrettyPrint()); + orUIManager.addInformation("Best Run Value = " + bestRevenue + + " with " + revenueAdapter.getOptimalRunPrettyPrint(false)); + orUIManager.addDetail(revenueAdapter.getOptimalRunPrettyPrint(true)); } } Modified: trunk/18xx/rails/ui/swing/ORUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/ORUIManager.java 2010-08-12 20:58:05 UTC (rev 1381) +++ trunk/18xx/rails/ui/swing/ORUIManager.java 2010-08-13 15:57:46 UTC (rev 1382) @@ -1856,6 +1856,14 @@ public void setMessage(String message) { messagePanel.setMessage(message); } + + public void addInformation(String infoText) { + messagePanel.addInformation(infoText); + } + + public void addDetail(String detailText) { + messagePanel.addDetail(detailText); + } public void setLocalAction(boolean value) { localAction = value; Modified: trunk/18xx/rails/ui/swing/Scale.java =================================================================== --- trunk/18xx/rails/ui/swing/Scale.java 2010-08-12 20:58:05 UTC (rev 1381) +++ trunk/18xx/rails/ui/swing/Scale.java 2010-08-13 15:57:46 UTC (rev 1382) @@ -4,12 +4,17 @@ import java.awt.Dimension; import java.awt.Toolkit; +import rails.util.Config; +import rails.util.Util; + /** * Class Scale holds static information used to scale all GUI elements. */ public final class Scale { public static int scale = 15; + + public static double fontScale = 0; static { fitScreenRes(); @@ -23,10 +28,31 @@ Scale.scale = scale; } + public static double getFontScale() { + if (fontScale == 0) { + initFromConfiguration(); + } + return fontScale; + } + + public static void initFromConfiguration() { + String fontScaleString = Config.getGameSpecific("font.ui.scale"); + if (Util.hasValue(fontScaleString)) { + try { + fontScale = Double.parseDouble(fontScaleString); + } catch (NumberFormatException e) { + fontScale = 1; + } + } + + } + + /** * Set the scale so that the MasterBoard fits on the screen. Default scale * should be 15 for screen resolutions with height 1000 or more. For less, * scale it down linearly. + * */ public static void fitScreenRes() { Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); Modified: trunk/18xx/rails/ui/swing/UpgradesPanel.java =================================================================== --- trunk/18xx/rails/ui/swing/UpgradesPanel.java 2010-08-12 20:58:05 UTC (rev 1381) +++ trunk/18xx/rails/ui/swing/UpgradesPanel.java 2010-08-13 15:57:46 UTC (rev 1382) @@ -19,6 +19,7 @@ import rails.ui.swing.elements.ActionLabel; import rails.ui.swing.hexmap.GUIHex; import rails.ui.swing.hexmap.HexMap; +import rails.util.Config; import rails.util.LocalText; public class UpgradesPanel extends Box implements MouseListener, ActionListener { @@ -36,7 +37,7 @@ private JPanel upgradePanel; private JScrollPane scrollPane; - private Dimension preferredSize = new Dimension(100, 200); + private Dimension preferredSize; private Border border = new EtchedBorder(); private final String INIT_CANCEL_TEXT = "NoTile"; private final String INIT_DONE_TEXT = "LayTile"; @@ -55,6 +56,7 @@ this.orUIManager = orUIManager; + preferredSize = new Dimension((int)Math.round(100 * (2 + Scale.getFontScale())/3), 200); setSize(preferredSize); setVisible(true); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-18 22:03:07
|
Revision: 1394 http://rails.svn.sourceforge.net/rails/?rev=1394&view=rev Author: stefanfrey Date: 2010-08-18 22:03:00 +0000 (Wed, 18 Aug 2010) Log Message: ----------- - Fixed display issues on the NetworkInfo->RevenueRun - Added static modifier for 1856 CGR leased Diesel Modified Paths: -------------- trunk/18xx/rails/algorithms/RevenueAdapter.java trunk/18xx/rails/algorithms/RevenueTrainRun.java trunk/18xx/rails/game/specific/_1856/PublicCompany_CGR.java trunk/18xx/rails/ui/swing/ORPanel.java Modified: trunk/18xx/rails/algorithms/RevenueAdapter.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueAdapter.java 2010-08-17 20:07:46 UTC (rev 1393) +++ trunk/18xx/rails/algorithms/RevenueAdapter.java 2010-08-18 22:03:00 UTC (rev 1394) @@ -635,10 +635,9 @@ StringBuffer runPrettyPrint = new StringBuffer(); for (RevenueTrainRun run:listRuns) { runPrettyPrint.append(run.prettyPrint(includeDetails)); - if (includeDetails) - runPrettyPrint.append("<BR>"); - else if (run != listRuns.get(listRuns.size()-1)) - runPrettyPrint.append("; "); + if (!includeDetails && run != listRuns.get(listRuns.size()-1)) { + runPrettyPrint.append("; "); + } } if (includeDetails) { for (RevenueDynamicModifier modifier:dynamicModifiers) { Modified: trunk/18xx/rails/algorithms/RevenueTrainRun.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueTrainRun.java 2010-08-17 20:07:46 UTC (rev 1393) +++ trunk/18xx/rails/algorithms/RevenueTrainRun.java 2010-08-18 22:03:00 UTC (rev 1394) @@ -195,7 +195,7 @@ int length = runPrettyPrint.length() - initLength; if (length / PRETTY_PRINT_LENGTH != multiple) { multiple = length / PRETTY_PRINT_LENGTH; - runPrettyPrint.append("<BR>"); + runPrettyPrint.append("\n"); for (int i=0; i < PRETTY_PRINT_INDENT; i++) runPrettyPrint.append(" ") ; } Modified: trunk/18xx/rails/game/specific/_1856/PublicCompany_CGR.java =================================================================== --- trunk/18xx/rails/game/specific/_1856/PublicCompany_CGR.java 2010-08-17 20:07:46 UTC (rev 1393) +++ trunk/18xx/rails/game/specific/_1856/PublicCompany_CGR.java 2010-08-18 22:03:00 UTC (rev 1394) @@ -3,11 +3,13 @@ import java.util.ArrayList; import java.util.List; +import rails.algorithms.RevenueAdapter; +import rails.algorithms.RevenueStaticModifier; import rails.game.*; import rails.game.move.*; import rails.game.state.*; -public class PublicCompany_CGR extends PublicCompany { +public class PublicCompany_CGR extends PublicCompany implements RevenueStaticModifier { public static final String NAME = "CGR"; @@ -29,8 +31,17 @@ // Share price is initially fixed canSharePriceVary.set(false); + } + + @Override + public void finishConfiguration(GameManagerI gameManager) throws ConfigurationException { + super.finishConfiguration(gameManager); + // add revenue modifier for the case that there is no train + gameManager.getRevenueManager().addStaticModifier(this); + } + public boolean hadPermanentTrain() { return hadPermanentTrain.booleanValue(); } @@ -149,4 +160,14 @@ public String getExtraShareMarks () { return (hasTemporaryPresident() ? "T" : ""); } + + public void modifyCalculator(RevenueAdapter revenueAdapter) { + // check if the running company is the cgr + if (revenueAdapter.getCompany() != this) return; + + // add the diesel train + if (runsWithBorrowedTrain()) { + revenueAdapter.addTrainByString("D"); + } + } } Modified: trunk/18xx/rails/ui/swing/ORPanel.java =================================================================== --- trunk/18xx/rails/ui/swing/ORPanel.java 2010-08-17 20:07:46 UTC (rev 1393) +++ trunk/18xx/rails/ui/swing/ORPanel.java 2010-08-18 22:03:00 UTC (rev 1394) @@ -629,33 +629,18 @@ for (String addTrain:addTrainList) { ra.addTrainByString(addTrain); } - ra.initRevenueCalculator(true); - log.info("Revenue Adapter:" + ra); + ra.initRevenueCalculator(true); // true => multigraph, false => simplegraph + log.debug("Revenue Adapter:" + ra); int revenueValue = ra.calculateRevenue(); - log.info("Revenue Value:" + revenueValue); - log.info("Revenue Run:" + ra.getOptimalRunPrettyPrint(true)); + log.debug("Revenue Value:" + revenueValue); + log.debug("Revenue Run:" + ra.getOptimalRunPrettyPrint(true)); ra.drawOptimalRunAsPath(orUIManager.getMap()); orUIManager.getMap().repaint(); JOptionPane.showMessageDialog(orWindow, "RevenueValue = " + revenueValue + "\nRevenueRun = \n" + ra.getOptimalRunPrettyPrint(true)); - // simple - ra = RevenueAdapter.createRevenueAdapter(gm, company, gm.getCurrentPhase()); - for (String addTrain:addTrainList) { - ra.addTrainByString(addTrain); - } - ra.initRevenueCalculator(false); - log.info("Revenue Adapter:" + ra); - revenueValue = ra.calculateRevenue(); - log.info("Revenue Value:" + revenueValue); - log.info("Revenue Run:" + ra.getOptimalRunPrettyPrint(true)); - ra.drawOptimalRunAsPath(orUIManager.getMap()); - orUIManager.getMap().repaint(); - JOptionPane.showMessageDialog(orWindow, "RevenueValue = " + revenueValue + - "\nRevenueRun = \n" + ra.getOptimalRunPrettyPrint(true)); - String trainString = - JOptionPane.showInputDialog(orWindow, "Another train", + JOptionPane.showInputDialog(null, "Enter train string (Examples: 5, 3+3, 4D, 6E, D)", "Add another train to run?", JOptionPane.QUESTION_MESSAGE); if (trainString == null || trainString.equals("")) { @@ -842,8 +827,8 @@ revenueAdapter.drawOptimalRunAsPath(orUIManager.getMap()); orUIManager.getMap().repaint(); orUIManager.addInformation("Best Run Value = " + bestRevenue + - " with " + revenueAdapter.getOptimalRunPrettyPrint(false)); - orUIManager.addDetail(revenueAdapter.getOptimalRunPrettyPrint(true)); + " with " + Util.convertToHtml(revenueAdapter.getOptimalRunPrettyPrint(false))); + orUIManager.addDetail(Util.convertToHtml(revenueAdapter.getOptimalRunPrettyPrint(true))); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-28 16:58:06
|
Revision: 1407 http://rails.svn.sourceforge.net/rails/?rev=1407&view=rev Author: stefanfrey Date: 2010-08-28 16:57:59 +0000 (Sat, 28 Aug 2010) Log Message: ----------- - Fix of 18AL coalfield token bug: The bonus was not correctly removed at phase 6. - Also changed Set of revenue modifiers to stateful lists. Modified Paths: -------------- trunk/18xx/rails/algorithms/RevenueManager.java trunk/18xx/rails/game/Bonus.java trunk/18xx/rails/game/PublicCompany.java trunk/18xx/rails/game/move/RemoveFromList.java Added Paths: ----------- trunk/18xx/rails/game/state/HashSetState.java Modified: trunk/18xx/rails/algorithms/RevenueManager.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueManager.java 2010-08-22 20:48:44 UTC (rev 1406) +++ trunk/18xx/rails/algorithms/RevenueManager.java 2010-08-28 16:57:59 UTC (rev 1407) @@ -10,6 +10,7 @@ import rails.game.ConfigurableComponentI; import rails.game.ConfigurationException; import rails.game.GameManagerI; +import rails.game.state.HashSetState; import rails.util.LocalText; import rails.util.Tag; @@ -29,15 +30,15 @@ Logger.getLogger(RevenueManager.class.getPackage().getName()); - private final Set<NetworkGraphModifier> graphModifiers; - private final Set<RevenueStaticModifier> staticModifiers; - private final Set<RevenueDynamicModifier> dynamicModifiers; - private final Set<ConfigurableComponentI> configurableModifiers; + private final HashSetState<NetworkGraphModifier> graphModifiers; + private final HashSetState<RevenueStaticModifier> staticModifiers; + private final HashSetState<RevenueDynamicModifier> dynamicModifiers; + private final HashSet<ConfigurableComponentI> configurableModifiers; public RevenueManager() { - graphModifiers = new HashSet<NetworkGraphModifier>(); - staticModifiers = new HashSet<RevenueStaticModifier>(); - dynamicModifiers = new HashSet<RevenueDynamicModifier>(); + graphModifiers = new HashSetState<NetworkGraphModifier>("NetworkGraphModifiers"); + staticModifiers = new HashSetState<RevenueStaticModifier>("RevenueStaticModifiers"); + dynamicModifiers = new HashSetState<RevenueDynamicModifier>("RevenueDynamicModifiers"); configurableModifiers = new HashSet<ConfigurableComponentI>(); } @@ -144,20 +145,20 @@ } void callGraphModifiers(NetworkGraphBuilder graphBuilder) { - for (NetworkGraphModifier modifier:graphModifiers) { + for (NetworkGraphModifier modifier:graphModifiers.viewSet()) { modifier.modifyGraph(graphBuilder); } } void callStaticModifiers(RevenueAdapter revenueAdapter) { - for (RevenueStaticModifier modifier:staticModifiers) { + for (RevenueStaticModifier modifier:staticModifiers.viewSet()) { modifier.modifyCalculator(revenueAdapter); } } Set<RevenueDynamicModifier> callDynamicModifiers(RevenueAdapter revenueAdapter) { Set<RevenueDynamicModifier> activeModifiers = new HashSet<RevenueDynamicModifier>(); - for (RevenueDynamicModifier modifier:dynamicModifiers) { + for (RevenueDynamicModifier modifier:dynamicModifiers.viewSet()) { if (modifier.prepareModifier(revenueAdapter)) activeModifiers.add(modifier); } Modified: trunk/18xx/rails/game/Bonus.java =================================================================== --- trunk/18xx/rails/game/Bonus.java 2010-08-22 20:48:44 UTC (rev 1406) +++ trunk/18xx/rails/game/Bonus.java 2010-08-28 16:57:59 UTC (rev 1407) @@ -40,8 +40,8 @@ // add them to the call list of the RevenueManager GameManager.getInstance().getRevenueManager().addStaticModifier(this); - } + } public boolean isExecutionable() { return false; } @@ -77,38 +77,15 @@ } /** - * Remove the token. + * Remove the bonus * This method can be called by a certain phase when it starts. * See prepareForRemovel(). */ public void close() { - owner.removeBonus(name); - // remove it from the call list of the RevenueManager GameManager.getInstance().getRevenueManager().removeStaticModifier(this); } - /** - * Prepare the bonus token for removal, if so configured. - * The only case currently implemented to trigger removal - * is the start of a given phase. - */ - public void prepareForRemoval (PhaseManager phaseManager) { - - if (removingObjectDesc == null) return; - - if (removingObject == null) { - String[] spec = removingObjectDesc.split(":"); - if (spec[0].equalsIgnoreCase("Phase")) { - removingObject = - phaseManager.getPhaseByName(spec[1]); - } - } - - if (removingObject instanceof Phase) { - ((Phase) removingObject).addObjectToClose(this); - } - } - + public boolean equals (Bonus b) { return (b.name.equals(name)) && b.value == value; Modified: trunk/18xx/rails/game/PublicCompany.java =================================================================== --- trunk/18xx/rails/game/PublicCompany.java 2010-08-22 20:48:44 UTC (rev 1406) +++ trunk/18xx/rails/game/PublicCompany.java 2010-08-28 16:57:59 UTC (rev 1407) @@ -1755,6 +1755,7 @@ } public boolean removeBonus(Bonus bonus) { + bonus.close(); // close the bonus new RemoveFromList<Bonus> (bonuses, bonus, name+"_Bonuses", bonusValue); return true; } Modified: trunk/18xx/rails/game/move/RemoveFromList.java =================================================================== --- trunk/18xx/rails/game/move/RemoveFromList.java 2010-08-22 20:48:44 UTC (rev 1406) +++ trunk/18xx/rails/game/move/RemoveFromList.java 2010-08-28 16:57:59 UTC (rev 1407) @@ -37,12 +37,14 @@ @Override public boolean execute() { list.remove(object); + updateModels(); return true; } @Override public boolean undo() { list.add(index, object); + updateModels(); return true; } Added: trunk/18xx/rails/game/state/HashSetState.java =================================================================== --- trunk/18xx/rails/game/state/HashSetState.java (rev 0) +++ trunk/18xx/rails/game/state/HashSetState.java 2010-08-28 16:57:59 UTC (rev 1407) @@ -0,0 +1,69 @@ +package rails.game.state; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import rails.game.move.SetChange; +/** + * State class that wraps a HashSet + * Generates according set moves + * + * Remark: Does not extend State or implements StateI do avoid additional overhead + * All state/move mechanisms already contained in Move objects + * + * TODO: Replace all stateful sets by this class and simplify according move objects + */ +public class HashSetState<E> { + + private final HashSet<E> set = new HashSet<E>(); + private final String setName; + + /** + * constructor for an empty set + * @param name + */ + public HashSetState(String setName) { + this.setName = setName; + } + /** + * constructor for a prefilled set + * @param element + */ + public HashSetState(String setName, Collection<E> collection) { + this(setName); + set.addAll(collection); + } + + public void add(E element) { + new SetChange<E>(set, element, true); + } + + public boolean remove(E element) { + if (set.contains(element)) { + new SetChange<E>(set, element, false); + return true; + } else { + return false; + } + } + + public void clear() { + for (E element:set) { + remove(element); + } + } + + /** + * returns unmodifiable view of set + */ + public Set<E> viewSet() { + return Collections.unmodifiableSet(set); + } + + public int size() { + return set.size(); + } + +} Property changes on: trunk/18xx/rails/game/state/HashSetState.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: <ste...@us...> - 2010-09-08 21:42:59
|
Revision: 1417 http://rails.svn.sourceforge.net/rails/?rev=1417&view=rev Author: stefanfrey Date: 2010-09-08 21:42:53 +0000 (Wed, 08 Sep 2010) Log Message: ----------- Fixed problem with import functionality in configuration UI Modified Paths: -------------- trunk/18xx/rails/ui/swing/ConfigWindow.java trunk/18xx/rails/util/Config.java Modified: trunk/18xx/rails/ui/swing/ConfigWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-09-08 21:41:33 UTC (rev 1416) +++ trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-09-08 21:42:53 UTC (rev 1417) @@ -535,7 +535,7 @@ { File file = fc.getSelectedFile(); if (Config.importProfileFromFile(file)) { - changeProfile(Config.getActiveProfileName()); + repaintLater(); } else { JOptionPane.showMessageDialog(ConfigWindow.this, LocalText.getText("CONFIG_LOAD_ERROR_MESSAGE", Config.getActiveProfileName()), LocalText.getText("CONFIG_LOAD_TITLE"), JOptionPane.ERROR_MESSAGE); @@ -545,6 +545,10 @@ private void changeProfile(String profileName) { Config.changeActiveProfile(profileName); + repaintLater(); + } + + private void repaintLater() { EventQueue.invokeLater(new Runnable() { public void run() { init(); Modified: trunk/18xx/rails/util/Config.java =================================================================== --- trunk/18xx/rails/util/Config.java 2010-09-08 21:41:33 UTC (rev 1416) +++ trunk/18xx/rails/util/Config.java 2010-09-08 21:42:53 UTC (rev 1417) @@ -441,7 +441,7 @@ * loads an external user profile * defined by the filepath */ - public static boolean importProfileFromFile(File file) { + public static boolean loadProfileFromFile(File file) { String filepath = file.getPath(); if (loadPropertyFile(userProperties, filepath, false)) { String profile = userProperties.getProperty(PROFILENAME_PROPERTY); @@ -449,7 +449,7 @@ profile = STANDARD_PROFILE_SELECTION; } selectedProfile = profile; -// setActiveFilepath(filepath); // do not set filepath on import + setActiveFilepath(filepath); // do not set filepath on import loadDefaultProfile(); setSaveDirDefaults(); return true; @@ -457,6 +457,22 @@ return false; } } + + /** + * imports an external user profile into an existing profile + * defined by the filepath + */ + public static boolean importProfileFromFile(File file) { + String filepath = file.getPath(); + Properties importProperties = new Properties(); + if (loadPropertyFile(importProperties, filepath, false)) { + userProperties.putAll(importProperties); + setSaveDirDefaults(); + return true; + } else { + return false; + } + } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-09-17 21:24:20
|
Revision: 1424 http://rails.svn.sourceforge.net/rails/?rev=1424&view=rev Author: stefanfrey Date: 2010-09-17 21:24:13 +0000 (Fri, 17 Sep 2010) Log Message: ----------- Added support for 1825 revenue calculation Modified Paths: -------------- trunk/18xx/rails/algorithms/NetworkTrain.java trunk/18xx/rails/algorithms/RevenueAdapter.java trunk/18xx/rails/algorithms/RevenueDynamicModifier.java trunk/18xx/rails/algorithms/RevenueManager.java trunk/18xx/rails/algorithms/RevenueTrainRun.java trunk/18xx/rails/game/specific/_18AL/NamedTrainRevenueModifier.java trunk/18xx/rails/game/specific/_18EU/PullmanRevenueModifier.java trunk/18xx/rails/game/state/ArrayListState.java Added Paths: ----------- trunk/18xx/rails/game/specific/_1825/DoubleHeadingModifier.java trunk/18xx/rails/game/specific/_1825/TerminateAtMajorModifier.java Modified: trunk/18xx/rails/algorithms/NetworkTrain.java =================================================================== --- trunk/18xx/rails/algorithms/NetworkTrain.java 2010-09-17 18:39:08 UTC (rev 1423) +++ trunk/18xx/rails/algorithms/NetworkTrain.java 2010-09-17 21:24:13 UTC (rev 1424) @@ -19,7 +19,7 @@ private final TrainI railsTrain; - NetworkTrain(int majors, int minors, boolean ignoreMinors, + public NetworkTrain(int majors, int minors, boolean ignoreMinors, int multiplyMajors, int multiplyMinors, String trainName, TrainI train) { this.majors = majors; this.minors = minors; @@ -110,6 +110,10 @@ return ignoreMinors; } + public String getTrainName() { + return trainName; + } + public TrainI getRailsTrain() { return railsTrain; } Modified: trunk/18xx/rails/algorithms/RevenueAdapter.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueAdapter.java 2010-09-17 18:39:08 UTC (rev 1423) +++ trunk/18xx/rails/algorithms/RevenueAdapter.java 2010-09-17 21:24:13 UTC (rev 1424) @@ -75,7 +75,7 @@ private List<NetworkVertex> rcVertices; private List<NetworkEdge> rcEdges; private List<RevenueTrainRun> optimalRun; - private Set<RevenueDynamicModifier> dynamicModifiers; + private List<RevenueDynamicModifier> dynamicModifiers; // revenue listener to communicate results @@ -163,6 +163,10 @@ } } + public void addTrain(NetworkTrain train) { + trains.add(train); + } + public void removeTrain(NetworkTrain train) { trains.remove(train); } @@ -285,7 +289,7 @@ if (gameManager.getRevenueManager() != null) { dynamicModifiers = gameManager.getRevenueManager().callDynamicModifiers(this); } else { - dynamicModifiers = new HashSet<RevenueDynamicModifier>(); + dynamicModifiers = new ArrayList<RevenueDynamicModifier>(); } // define optimized graph @@ -573,6 +577,10 @@ public List<RevenueTrainRun> getOptimalRun() { if (optimalRun == null) { optimalRun = convertRcRun(rc.getOptimalRun()); + // allow dynamic modifiers to change the optimal run + for (RevenueDynamicModifier modifier:dynamicModifiers) { + modifier.adjustOptimalRun(optimalRun); + } } return optimalRun; } @@ -587,7 +595,7 @@ int dynamicEvaluation() { int value = 0; for (RevenueDynamicModifier modifier:dynamicModifiers) { - value += modifier.evaluationValue(this.getCurrentRun()); + value += modifier.evaluationValue(this.getCurrentRun(), false); } return value; } @@ -641,12 +649,15 @@ } if (includeDetails) { for (RevenueDynamicModifier modifier:dynamicModifiers) { - runPrettyPrint.append(modifier.prettyPrint(this)); + String modifierText = modifier.prettyPrint(this); + if (modifierText != null) { + runPrettyPrint.append(modifierText); + } } } else { int dynamicBonuses = 0; for (RevenueDynamicModifier modifier:dynamicModifiers) { - dynamicBonuses += modifier.evaluationValue(this.getOptimalRun()); + dynamicBonuses += modifier.evaluationValue(this.getOptimalRun(), true); } if (dynamicBonuses != 0) { runPrettyPrint.append("; " + Modified: trunk/18xx/rails/algorithms/RevenueDynamicModifier.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueDynamicModifier.java 2010-09-17 18:39:08 UTC (rev 1423) +++ trunk/18xx/rails/algorithms/RevenueDynamicModifier.java 2010-09-17 21:24:13 UTC (rev 1424) @@ -20,9 +20,12 @@ /** returns the value used for prediction */ public int predictionValue(); - /** returns the value used for evaluation (at the run supplied) */ - public int evaluationValue(List<RevenueTrainRun> runs); + /** returns the value used for evaluation (at the runs supplied) */ + public int evaluationValue(List<RevenueTrainRun> runs, boolean optimalRuns); + /** allows to adjust the run list of the optimal train run output */ + public void adjustOptimalRun(List<RevenueTrainRun> optimalRuns); + /** returns the results as pretty prints */ public String prettyPrint(RevenueAdapter adapter); Modified: trunk/18xx/rails/algorithms/RevenueManager.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueManager.java 2010-09-17 18:39:08 UTC (rev 1423) +++ trunk/18xx/rails/algorithms/RevenueManager.java 2010-09-17 21:24:13 UTC (rev 1424) @@ -1,8 +1,8 @@ package rails.algorithms; +import java.util.ArrayList; import java.util.HashSet; import java.util.List; -import java.util.Set; import org.apache.log4j.Logger; @@ -10,7 +10,7 @@ import rails.game.ConfigurableComponentI; import rails.game.ConfigurationException; import rails.game.GameManagerI; -import rails.game.state.HashSetState; +import rails.game.state.ArrayListState; import rails.util.LocalText; import rails.util.Tag; @@ -30,15 +30,15 @@ Logger.getLogger(RevenueManager.class.getPackage().getName()); - private final HashSetState<NetworkGraphModifier> graphModifiers; - private final HashSetState<RevenueStaticModifier> staticModifiers; - private final HashSetState<RevenueDynamicModifier> dynamicModifiers; + private final ArrayListState<NetworkGraphModifier> graphModifiers; + private final ArrayListState<RevenueStaticModifier> staticModifiers; + private final ArrayListState<RevenueDynamicModifier> dynamicModifiers; private final HashSet<ConfigurableComponentI> configurableModifiers; public RevenueManager() { - graphModifiers = new HashSetState<NetworkGraphModifier>("NetworkGraphModifiers"); - staticModifiers = new HashSetState<RevenueStaticModifier>("RevenueStaticModifiers"); - dynamicModifiers = new HashSetState<RevenueDynamicModifier>("RevenueDynamicModifiers"); + graphModifiers = new ArrayListState<NetworkGraphModifier>("NetworkGraphModifiers"); + staticModifiers = new ArrayListState<RevenueStaticModifier>("RevenueStaticModifiers"); + dynamicModifiers = new ArrayListState<RevenueDynamicModifier>("RevenueDynamicModifiers"); configurableModifiers = new HashSet<ConfigurableComponentI>(); } @@ -145,20 +145,20 @@ } void callGraphModifiers(NetworkGraphBuilder graphBuilder) { - for (NetworkGraphModifier modifier:graphModifiers.viewSet()) { + for (NetworkGraphModifier modifier:graphModifiers.viewList()) { modifier.modifyGraph(graphBuilder); } } void callStaticModifiers(RevenueAdapter revenueAdapter) { - for (RevenueStaticModifier modifier:staticModifiers.viewSet()) { + for (RevenueStaticModifier modifier:staticModifiers.viewList()) { modifier.modifyCalculator(revenueAdapter); } } - Set<RevenueDynamicModifier> callDynamicModifiers(RevenueAdapter revenueAdapter) { - Set<RevenueDynamicModifier> activeModifiers = new HashSet<RevenueDynamicModifier>(); - for (RevenueDynamicModifier modifier:dynamicModifiers.viewSet()) { + List<RevenueDynamicModifier> callDynamicModifiers(RevenueAdapter revenueAdapter) { + List<RevenueDynamicModifier> activeModifiers = new ArrayList<RevenueDynamicModifier>(); + for (RevenueDynamicModifier modifier:dynamicModifiers.viewList()) { if (modifier.prepareModifier(revenueAdapter)) activeModifiers.add(modifier); } Modified: trunk/18xx/rails/algorithms/RevenueTrainRun.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueTrainRun.java 2010-09-17 18:39:08 UTC (rev 1423) +++ trunk/18xx/rails/algorithms/RevenueTrainRun.java 2010-09-17 21:24:13 UTC (rev 1424) @@ -3,6 +3,7 @@ import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.util.ArrayList; +import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -20,10 +21,9 @@ /** * Links the results from the revenue calculator to the rails program * Each object defines the run of one train - * @author freystef * */ -public class RevenueTrainRun { +public class RevenueTrainRun implements Comparable<RevenueTrainRun> { private static final int PRETTY_PRINT_LENGTH = 100; private static final int PRETTY_PRINT_INDENT = 10; @@ -49,16 +49,44 @@ public List<NetworkVertex> getRunVertices() { return vertices; } + + /** + * returns true if train has a valid run (at least two vertices) + */ + public boolean hasAValidRun() { + return vertices.size() >= 2; + } + /** + * returns the first vertex of a train run + */ + public NetworkVertex getFirstVertex() { + NetworkVertex startVertex = null; + NetworkVertex firstVertex = null; + for (NetworkVertex vertex:vertices) { + if (startVertex == vertex) return firstVertex; + if (startVertex == null) startVertex = vertex; + firstVertex = vertex; + } + return startVertex; + } + + /** + * returns the last vertex of a train run + */ + public NetworkVertex getLastVertex() { + return vertices.get(vertices.size()-1); + } + public Set<NetworkVertex> getUniqueVertices() { return new HashSet<NetworkVertex>(vertices); } - + public NetworkTrain getTrain() { return train; } - int getRunValue() { + public int getRunValue() { int value = 0; NetworkVertex startVertex = null; for (NetworkVertex vertex:vertices) { @@ -288,4 +316,9 @@ } return path; } + + public int compareTo(RevenueTrainRun other) { + return ((Integer)this.getRunValue()).compareTo(other.getRunValue()); + } + } \ No newline at end of file Added: trunk/18xx/rails/game/specific/_1825/DoubleHeadingModifier.java =================================================================== --- trunk/18xx/rails/game/specific/_1825/DoubleHeadingModifier.java (rev 0) +++ trunk/18xx/rails/game/specific/_1825/DoubleHeadingModifier.java 2010-09-17 21:24:13 UTC (rev 1424) @@ -0,0 +1,123 @@ +package rails.game.specific._1825; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.apache.log4j.Logger; + +import rails.algorithms.NetworkTrain; +import rails.algorithms.RevenueAdapter; +import rails.algorithms.RevenueDynamicModifier; +import rails.algorithms.RevenueTrainRun; +/** + * 1825 modifiers: + * Trains have to start and end in a major station + * Allows two 2-trains to run as a 3-train (double heading) + */ +public class DoubleHeadingModifier implements RevenueDynamicModifier { + + protected static Logger log = + Logger.getLogger(DoubleHeadingModifier.class.getPackage().getName()); + + private final static String TRAIN_2_NAME = "2"; + private final static String DUALHEAD_NAME = "2&2"; + + public boolean prepareModifier(RevenueAdapter revenueAdapter) { + int nbTrain2 = 0; + for (NetworkTrain train:revenueAdapter.getTrains()) { + // checks name of traintype + if (train.getRailsTrainType().getName().equals(TRAIN_2_NAME)) { + nbTrain2 ++; + } + } + + // add dualhead 3 train for each of a pair of 2-trains + boolean hasDualHead = false; + while (nbTrain2 >= 2) { + NetworkTrain dualHead = new NetworkTrain(3, 0, false, 1, 1, DUALHEAD_NAME, null); + revenueAdapter.addTrain(dualHead); + hasDualHead = true; + nbTrain2 -= 2; + } + + return hasDualHead; + } + + /** + * the prediction value itself is zero, as the add value stems from the train above + */ + public int predictionValue() { + return 0; + } + + /** + * returns the runs of the of the double heading trains + */ + private List<RevenueTrainRun> identifyDoubleHeadingTrains(List<RevenueTrainRun> runs) { + // find and sort the train2Revenues + List<RevenueTrainRun> train2Runs = new ArrayList<RevenueTrainRun>(); + for (RevenueTrainRun run:runs) { + if (run.getTrain().getTrainName().equals(TRAIN_2_NAME)) { + train2Runs.add(run); + } + } + Collections.sort(train2Runs); + + log.debug("Train2Runs=" + train2Runs); + + // keep index on train2Runs + int index2Runs = 0; + // find DualHeads and remove two 2-train revenues + for (RevenueTrainRun run:runs) { + // only if train has non zero value + if (run.getTrain().getTrainName().equals(DUALHEAD_NAME) && run.getRunValue() !=0) { + // two trains get removed + index2Runs += 2; + } + } + return train2Runs.subList(0, index2Runs); + } + + + /** + * - checks if runs start and end at major stations + * - allows doubleheading + */ + public int evaluationValue(List<RevenueTrainRun> runs, boolean optimalRuns) { + + + if (optimalRuns) return 0; // optimalRuns are adjusted + + // count the adjustments + int changeRevenues = 0; + for (RevenueTrainRun run:identifyDoubleHeadingTrains(runs)) { + changeRevenues -= run.getRunValue(); + } + return changeRevenues; + } + + public void adjustOptimalRun(List<RevenueTrainRun> optimalRuns) { + // remove the double heading runs from the revenue list + optimalRuns.removeAll(identifyDoubleHeadingTrains(optimalRuns)); + + // remove double heading trains that do not generate value + List<RevenueTrainRun> removeDoubleHeading = new ArrayList<RevenueTrainRun>(); + for (RevenueTrainRun run:optimalRuns) { + if (run.getTrain().getTrainName().equals(DUALHEAD_NAME) && run.getRunValue() == 0) { + removeDoubleHeading.add(run); + } + } + optimalRuns.removeAll(removeDoubleHeading); + } + + public String prettyPrint(RevenueAdapter adapter) { + // nothing to print + return null; + } + +} Property changes on: trunk/18xx/rails/game/specific/_1825/DoubleHeadingModifier.java ___________________________________________________________________ Added: svn:mime-type + text/plain Added: trunk/18xx/rails/game/specific/_1825/TerminateAtMajorModifier.java =================================================================== --- trunk/18xx/rails/game/specific/_1825/TerminateAtMajorModifier.java (rev 0) +++ trunk/18xx/rails/game/specific/_1825/TerminateAtMajorModifier.java 2010-09-17 21:24:13 UTC (rev 1424) @@ -0,0 +1,55 @@ +package rails.game.specific._1825; + +import java.util.ArrayList; +import java.util.List; + +import rails.algorithms.RevenueAdapter; +import rails.algorithms.RevenueDynamicModifier; +import rails.algorithms.RevenueTrainRun; + +public class TerminateAtMajorModifier implements RevenueDynamicModifier { + + public boolean prepareModifier(RevenueAdapter revenueAdapter) { + // always active + return true; + } + + public int predictionValue() { + // cannot be predicted + return 0; + } + + private List<RevenueTrainRun> identifyInvalidRuns(List<RevenueTrainRun> runs) { + // check if runs end and start at major stations + List<RevenueTrainRun> invalidRuns = new ArrayList<RevenueTrainRun>(); + for (RevenueTrainRun run:runs) { + if (!run.hasAValidRun()) continue; + if (!run.getFirstVertex().isMajor() || !run.getLastVertex().isMajor()) { + invalidRuns.add(run); + } + } + return invalidRuns; + } + + public int evaluationValue(List<RevenueTrainRun> runs, boolean optimalRuns) { + // optimal runs is already adjusted + if (optimalRuns) return 0; + // otherwise check invalid runs + int changeRevenues = 0; + for (RevenueTrainRun run:identifyInvalidRuns(runs)) { + changeRevenues -= run.getRunValue(); + } + return changeRevenues; + } + + public void adjustOptimalRun(List<RevenueTrainRun> optimalRuns) { + // remove invalid runs + optimalRuns.removeAll(identifyInvalidRuns(optimalRuns)); + } + + public String prettyPrint(RevenueAdapter adapter) { + // nothing to do + return null; + } + +} Property changes on: trunk/18xx/rails/game/specific/_1825/TerminateAtMajorModifier.java ___________________________________________________________________ Added: svn:mime-type + text/plain Modified: trunk/18xx/rails/game/specific/_18AL/NamedTrainRevenueModifier.java =================================================================== --- trunk/18xx/rails/game/specific/_18AL/NamedTrainRevenueModifier.java 2010-09-17 18:39:08 UTC (rev 1423) +++ trunk/18xx/rails/game/specific/_18AL/NamedTrainRevenueModifier.java 2010-09-17 21:24:13 UTC (rev 1424) @@ -102,7 +102,7 @@ return bonusMaximum; } - public int evaluationValue(List<RevenueTrainRun> runs) { + public int evaluationValue(List<RevenueTrainRun> runs, boolean optimalRuns) { int bonusValue = 0; // due to the geography (off-map areas!) each train can only score one bonus for (RevenueBonus bonus:bonuses) { @@ -116,6 +116,10 @@ return bonusValue; } + public void adjustOptimalRun(List<RevenueTrainRun> optimalRuns) { + // do nothing here (all is done by changing the evaluation value) + } + public String prettyPrint(RevenueAdapter revenueAdapter) { List<RevenueTrainRun> runs = revenueAdapter.getOptimalRun(); StringBuffer prettyPrint = new StringBuffer(); @@ -131,4 +135,5 @@ } + } Modified: trunk/18xx/rails/game/specific/_18EU/PullmanRevenueModifier.java =================================================================== --- trunk/18xx/rails/game/specific/_18EU/PullmanRevenueModifier.java 2010-09-17 18:39:08 UTC (rev 1423) +++ trunk/18xx/rails/game/specific/_18EU/PullmanRevenueModifier.java 2010-09-17 21:24:13 UTC (rev 1424) @@ -32,7 +32,7 @@ return true; } - public int evaluationValue(List<RevenueTrainRun> runs) { + public int evaluationValue(List<RevenueTrainRun> runs, boolean optimalRuns) { return pullmanValue(runs); } @@ -49,6 +49,10 @@ return maxValue; } + public void adjustOptimalRun(List<RevenueTrainRun> optimalRuns) { + // do nothing here (all is done by changing the evaluation value) + } + public String prettyPrint(RevenueAdapter revenueAdapter) { return LocalText.getText("Pullman") + " = " + pullmanValue(revenueAdapter.getOptimalRun()); } @@ -61,4 +65,5 @@ } return maximum; } + } Modified: trunk/18xx/rails/game/state/ArrayListState.java =================================================================== --- trunk/18xx/rails/game/state/ArrayListState.java 2010-09-17 18:39:08 UTC (rev 1423) +++ trunk/18xx/rails/game/state/ArrayListState.java 2010-09-17 21:24:13 UTC (rev 1424) @@ -7,6 +7,7 @@ import rails.game.move.AddToList; import rails.game.move.RemoveFromList; +import rails.game.move.SetChange; /** * State class that wraps an ArrayList @@ -49,8 +50,13 @@ new AddToList<E>(list, element, listName).atIndex(index); } - public void remove(E element) { - new RemoveFromList<E>(list, element, listName); + public boolean remove(E element) { + if (list.contains(element)) { + new RemoveFromList<E>(list, element, listName); + return true; + } else { + return false; + } } public void clear() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-10-16 22:43:32
|
Revision: 1452 http://rails.svn.sourceforge.net/rails/?rev=1452&view=rev Author: stefanfrey Date: 2010-10-16 22:43:25 +0000 (Sat, 16 Oct 2010) Log Message: ----------- Added ScoreTileOnlyOnceModifier for 1825 A few minor fixes Modified Paths: -------------- trunk/18xx/rails/algorithms/RevenueAdapter.java trunk/18xx/rails/algorithms/RevenueTrainRun.java trunk/18xx/rails/game/specific/_1825/DoubleHeadingModifier.java Added Paths: ----------- trunk/18xx/rails/game/specific/_1825/ScoreTileOnlyOnceModifier.java Modified: trunk/18xx/rails/algorithms/RevenueAdapter.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueAdapter.java 2010-10-14 22:34:21 UTC (rev 1451) +++ trunk/18xx/rails/algorithms/RevenueAdapter.java 2010-10-16 22:43:25 UTC (rev 1452) @@ -272,7 +272,6 @@ List<RevenueBonusTemplate> tileBonuses = hex.getCurrentTile().getRevenueBonuses(); if (tileBonuses != null) bonuses.addAll(tileBonuses); - if (bonuses == null) continue; for (RevenueBonusTemplate bonus:bonuses) { addRevenueBonus(bonus.toRevenueBonus(hex, gameManager, graphBuilder)); } Modified: trunk/18xx/rails/algorithms/RevenueTrainRun.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueTrainRun.java 2010-10-14 22:34:21 UTC (rev 1451) +++ trunk/18xx/rails/algorithms/RevenueTrainRun.java 2010-10-16 22:43:25 UTC (rev 1452) @@ -139,7 +139,7 @@ NetworkEdge previousEdge = null; NetworkVertex startVertex = null; for (NetworkEdge edge:edges) { - log.info("Processing edge " + edge.toFullInfoString() ); + log.debug("Processing edge " + edge.toFullInfoString() ); // process startEdge if (previousEdge == null) { previousEdge = edge; @@ -151,7 +151,7 @@ if (startVertex == null) { // if there is a joint route => other vertex of previousEdge if (commonVertex != null) { - log.info("Head Run"); + log.debug("Head Run"); startVertex = previousEdge.getOtherVertex(commonVertex); vertices.add(startVertex); vertices.add(commonVertex); @@ -162,12 +162,12 @@ } else { // start vertex is known // if there is a common vertex => continuous route if (commonVertex != null) { - log.info("Added common vertex"); + log.debug("Added common vertex"); vertices.add(commonVertex); } else { // otherwise it is bottom run // add the last vertex of the head train - log.info("Bottom Run"); + log.debug("Bottom Run"); vertices.add(previousEdge.getOtherVertex(vertices.get(vertices.size()-1))); vertices.add(startVertex); } @@ -176,7 +176,7 @@ } // add the last vertex of the route vertices.add(previousEdge.getOtherVertex(vertices.get(vertices.size()-1))); - log.info("Converted edges to vertices " + vertices); + log.debug("Converted edges to vertices " + vertices); } /** defines the edges from the list of vertices */ Modified: trunk/18xx/rails/game/specific/_1825/DoubleHeadingModifier.java =================================================================== --- trunk/18xx/rails/game/specific/_1825/DoubleHeadingModifier.java 2010-10-14 22:34:21 UTC (rev 1451) +++ trunk/18xx/rails/game/specific/_1825/DoubleHeadingModifier.java 2010-10-16 22:43:25 UTC (rev 1452) @@ -2,14 +2,8 @@ import java.util.ArrayList; import java.util.Collections; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; -import org.apache.log4j.Logger; - import rails.algorithms.NetworkTrain; import rails.algorithms.RevenueAdapter; import rails.algorithms.RevenueDynamicModifier; @@ -21,9 +15,6 @@ */ public class DoubleHeadingModifier implements RevenueDynamicModifier { - protected static Logger log = - Logger.getLogger(DoubleHeadingModifier.class.getPackage().getName()); - private final static String TRAIN_2_NAME = "2"; private final static String DUALHEAD_NAME = "2&2"; @@ -68,8 +59,6 @@ } Collections.sort(train2Runs); - log.debug("Train2Runs=" + train2Runs); - // keep index on train2Runs int index2Runs = 0; // find DualHeads and remove two 2-train revenues Added: trunk/18xx/rails/game/specific/_1825/ScoreTileOnlyOnceModifier.java =================================================================== --- trunk/18xx/rails/game/specific/_1825/ScoreTileOnlyOnceModifier.java (rev 0) +++ trunk/18xx/rails/game/specific/_1825/ScoreTileOnlyOnceModifier.java 2010-10-16 22:43:25 UTC (rev 1452) @@ -0,0 +1,40 @@ +package rails.game.specific._1825; + +import java.util.ArrayList; +import java.util.Map; +import java.util.HashMap; +import java.util.List; + +import rails.algorithms.NetworkVertex; +import rails.algorithms.RevenueAdapter; +import rails.algorithms.RevenueStaticModifier; +import rails.game.MapHex; + +/** + * This modifier ensures that on each tile only one station can be visited + */ + +public class ScoreTileOnlyOnceModifier implements RevenueStaticModifier { + + public void modifyCalculator(RevenueAdapter revenueAdapter) { + // 1. define for each hex a list of stations + HashMap<MapHex, List<NetworkVertex>> hexStations = new HashMap<MapHex, List<NetworkVertex>>(); + for (NetworkVertex v:revenueAdapter.getVertices()) { + if (v.isStation()) { + if (!hexStations.containsKey(v.getHex())) { + List<NetworkVertex> stations = new ArrayList<NetworkVertex>(); + hexStations.put(v.getHex(), stations); + } + hexStations.get(v.getHex()).add(v); + } + } + // 2. convert those with more than one station to a vertex visit set + for (MapHex hex:hexStations.keySet()) { + if (hexStations.get(hex).size() >= 2) { + revenueAdapter.addVertexVisitSet(revenueAdapter.new VertexVisit(hexStations.get(hex))); + } + } + + } + +} Property changes on: trunk/18xx/rails/game/specific/_1825/ScoreTileOnlyOnceModifier.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-10-27 21:54:18
|
Revision: 1454 http://rails.svn.sourceforge.net/rails/?rev=1454&view=rev Author: evos Date: 2010-10-27 21:54:11 +0000 (Wed, 27 Oct 2010) Log Message: ----------- Partial fix of the map display problem when a game is started via RunGame with a saved file parameter. Modified Paths: -------------- trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/GameManagerI.java trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/ui/swing/ORUIManager.java trunk/18xx/rails/ui/swing/UpgradesPanel.java trunk/18xx/rails/ui/swing/hexmap/GUITile.java Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-10-16 22:43:59 UTC (rev 1453) +++ trunk/18xx/rails/game/GameManager.java 2010-10-27 21:54:11 UTC (rev 1454) @@ -158,7 +158,7 @@ * It will only be used inside the GM objects. * All other objects will access it via NDC. */ - protected static final String GM_KEY = "01"; + public static final String GM_KEY = "01"; public static final String GM_NAME = "GameManager"; /** @@ -205,9 +205,14 @@ * <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). + * <br>This flag must be reset after processing <i>any</i> action (not just Done). */ protected boolean skipNextDone = false; + /** Step that must be in effect to do an actual Done skip during reloading. + * <br> This is to ensure that Done actions in different OR steps are + * considered separately. + */ + protected GameDef.OrStep skippedStep = null; protected static Logger log = Logger.getLogger(GameManager.class.getPackage().getName()); @@ -950,7 +955,7 @@ DisplayBuffer.clear(); - // XXX TEMPORARY FIX TO ALLOW OLD 1856 SAVED FILES TO BE PROCESSED + // TEMPORARY FIX TO ALLOW OLD 1856 SAVED FILES TO BE PROCESSED if (gameName.equals("1856") && possibleActions.contains(RepayLoans.class) && (!possibleActions.contains(action.getClass()) @@ -967,17 +972,19 @@ try { log.debug("Action ("+action.getPlayerName()+"): " + action); - // XXX FOR BACKWARDS COMPATIBILITY + // 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; + if (currentRound.get() instanceof OperatingRound + && ((OperatingRound)currentRound.get()).getStep() == skippedStep) { + doProcess = false; + } } } skipNextDone = false; + skippedStep = null; if (doProcess && !processCorrectionActions(action) && !getCurrentRound().process(action)) { String msg = "Player "+action.getPlayerName()+"\'s action \"" @@ -1717,8 +1724,9 @@ this.reloading = reloading; } - public void setSkipDone () { + public void setSkipDone (GameDef.OrStep step) { skipNextDone = true; + skippedStep = step; } } Modified: trunk/18xx/rails/game/GameManagerI.java =================================================================== --- trunk/18xx/rails/game/GameManagerI.java 2010-10-16 22:43:59 UTC (rev 1453) +++ trunk/18xx/rails/game/GameManagerI.java 2010-10-27 21:54:11 UTC (rev 1454) @@ -207,5 +207,5 @@ public List<PublicCompanyI> getCompaniesInRunningOrder (); public boolean isReloading(); public void setReloading(boolean reloading); - public void setSkipDone (); + public void setSkipDone (GameDef.OrStep step); } \ No newline at end of file Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2010-10-16 22:43:59 UTC (rev 1453) +++ trunk/18xx/rails/game/OperatingRound.java 2010-10-27 21:54:11 UTC (rev 1454) @@ -1265,7 +1265,7 @@ // XXX For BACKWARDS COMPATIBILITY only, // register a Done skip action during reloading. if (gameManager.isReloading()) { - gameManager.setSkipDone(); + gameManager.setSkipDone(GameDef.OrStep.TRADE_SHARES); log.debug("If the next saved action is 'Done', skip it"); } log.info("Skipping Treasury share trading step"); Modified: trunk/18xx/rails/ui/swing/ORUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/ORUIManager.java 2010-10-16 22:43:59 UTC (rev 1453) +++ trunk/18xx/rails/ui/swing/ORUIManager.java 2010-10-27 21:54:11 UTC (rev 1454) @@ -31,6 +31,7 @@ private RemainingTilesWindow remainingTiles; public GameUIManager gameUIManager; + protected TileManager tileManager; private OperatingRound oRound; private PublicCompanyI[] companies; @@ -95,6 +96,7 @@ public void setGameUIManager (GameUIManager gameUIManager) { this.gameUIManager = gameUIManager; + this.tileManager = gameUIManager.getGameManager().getTileManager(); } public void init(ORWindow orWindow) { @@ -1904,8 +1906,12 @@ return gameUIManager; } - private void displayRemainingTiles() { + public TileManager getTileManager() { + return tileManager; + } + private void displayRemainingTiles() { + if (remainingTiles == null) { remainingTiles = new RemainingTilesWindow(orWindow); } else { Modified: trunk/18xx/rails/ui/swing/UpgradesPanel.java =================================================================== --- trunk/18xx/rails/ui/swing/UpgradesPanel.java 2010-10-16 22:43:59 UTC (rev 1453) +++ trunk/18xx/rails/ui/swing/UpgradesPanel.java 2010-10-27 21:54:11 UTC (rev 1454) @@ -19,12 +19,11 @@ import rails.ui.swing.elements.ActionLabel; import rails.ui.swing.hexmap.GUIHex; import rails.ui.swing.hexmap.HexMap; -import rails.util.Config; import rails.util.LocalText; public class UpgradesPanel extends Box implements MouseListener, ActionListener { private static final long serialVersionUID = 1L; - + private ORUIManager orUIManager; private List<ActionLabel> tokenLabels; private List<CorrectionTokenLabel> correctionTokenLabels; @@ -34,7 +33,7 @@ static private Color defaultLabelBgColour = new JLabel("").getBackground(); static private Color selectedLabelBgColour = new Color(255, 220, 150); private static final int defaultNbPanelElements = 15; - + private JPanel upgradePanel; private JScrollPane scrollPane; private Dimension preferredSize; @@ -109,10 +108,10 @@ } } } - + public void showUpgrades() { upgradePanel.removeAll(); - + // reset to the number of elements GridLayout panelLayout = (GridLayout)upgradePanel.getLayout(); panelLayout.setRows(defaultNbPanelElements); @@ -200,12 +199,12 @@ // deactivate correctionTokenMode and tokenmode correctionTokenMode = false; tokenMode = false; - + // activate upgrade panel upgradePanel.removeAll(); GridLayout panelLayout = (GridLayout)upgradePanel.getLayout(); List<TileI> tiles = orUIManager.tileUpgrades; - + if (tiles == null || tiles.size() == 0) { // reset to the number of elements panelLayout.setRows(defaultNbPanelElements); @@ -249,12 +248,12 @@ // activate correctionTokenMode and deactivate standard tokenMode correctionTokenMode = true; tokenMode = false; - + // activate upgrade panel upgradePanel.removeAll(); GridLayout panelLayout = (GridLayout)upgradePanel.getLayout(); List<? extends TokenI> tokens = orUIManager.tokenLays; - + if (tokens == null || tokens.size() == 0) { // reset to the number of elements panelLayout.setRows(defaultNbPanelElements); @@ -288,16 +287,16 @@ correctionTokenLabels.add(tokenLabel); upgradePanel.add(tokenLabel); } - + } upgradePanel.add(doneButton); upgradePanel.add(cancelButton); // repaint(); revalidate(); - + } - + public void clear() { upgradePanel.removeAll(); upgradePanel.add(doneButton); @@ -456,25 +455,25 @@ setCancelEnabled(false); } - + /** ActionLabel extension that allows to attach the token */ private class CorrectionTokenLabel extends ActionLabel { - + private static final long serialVersionUID = 1L; - + private TokenI token; - + CorrectionTokenLabel(Icon tokenIcon, TokenI token) { super(tokenIcon); this.token = token; } - + TokenI getToken() { return token; } - + } - + /** JLabel extension to allow attaching the internal hex ID */ private class HexLabel extends JLabel { @@ -496,11 +495,11 @@ public String getToolTip() { return toolTip; } - + void setTextFromTile(TileI tile) { StringBuffer text = new StringBuffer(); if (tile.getExternalId() > 0) { - text.append("<HTML><BODY>" + tile.getExternalId()); + text.append("<HTML><BODY>" + tile.getExternalId()); if (tile.countFreeTiles() != -1) { text.append("<BR> (" + tile.countFreeTiles() + ")"); } Modified: trunk/18xx/rails/ui/swing/hexmap/GUITile.java =================================================================== --- trunk/18xx/rails/ui/swing/hexmap/GUITile.java 2010-10-16 22:43:59 UTC (rev 1453) +++ trunk/18xx/rails/ui/swing/hexmap/GUITile.java 2010-10-27 21:54:11 UTC (rev 1454) @@ -51,7 +51,8 @@ this.guiHex = guiHex; this.tileId = tileId; this.hex = (MapHex)guiHex.getModel(); - tile = GameManager.getInstance().getTileManager().getTile(tileId); + TileManager tileManager = guiHex.getHexMap().orUIManager.getTileManager(); + tile = tileManager.getTile(tileId); if (hex.getTileOrientation() == MapHex.EW) { baseRotation = 0.5 * DEG60; @@ -248,6 +249,7 @@ public void paintTile(Graphics2D g2, int x, int y) { int zoomStep = guiHex.getHexMap().getZoomStep(); + tileImage = imageLoader.getTile(tileId, zoomStep); if (tileImage != null) { @@ -280,6 +282,8 @@ AffineTransformOp aop = new AffineTransformOp(af, rh); g2.drawImage(tileImage, aop, x - xCenter, y - yCenter); + } else { + log.error("No image for tile "+tileId+" on hex "+guiHex.getName()); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-12-15 21:49:18
|
Revision: 1459 http://rails.svn.sourceforge.net/rails/?rev=1459&view=rev Author: evos Date: 2010-12-15 21:49:12 +0000 (Wed, 15 Dec 2010) Log Message: ----------- Fix UI bug when only one start price is possible because of lack of cash Modified Paths: -------------- trunk/18xx/rails/game/action/StartCompany.java trunk/18xx/rails/ui/swing/GameStatus.java Modified: trunk/18xx/rails/game/action/StartCompany.java =================================================================== --- trunk/18xx/rails/game/action/StartCompany.java 2010-11-09 15:45:47 UTC (rev 1458) +++ trunk/18xx/rails/game/action/StartCompany.java 2010-12-15 21:49:12 UTC (rev 1459) @@ -38,7 +38,7 @@ } public boolean mustSelectAPrice() { - return startPrices != null && startPrices.length > 1; + return startPrices != null/* && startPrices.length > 1*/; } public void setStartPrice(int startPrice) { Modified: trunk/18xx/rails/ui/swing/GameStatus.java =================================================================== --- trunk/18xx/rails/ui/swing/GameStatus.java 2010-11-09 15:45:47 UTC (rev 1458) +++ trunk/18xx/rails/ui/swing/GameStatus.java 2010-12-15 21:49:12 UTC (rev 1459) @@ -623,13 +623,22 @@ startPrices = ((StartCompany) buy).getStartPrices(); Arrays.sort(startPrices); - for (int i = 0; i < startPrices.length; i++) { - options.add(LocalText.getText("StartCompany", - Bank.format(startPrices[i]), - sharePerCert, - Bank.format(sharesPerCert * startPrices[i]) )); + if (startPrices.length > 1) { + for (int i = 0; i < startPrices.length; i++) { + options.add(LocalText.getText("StartCompany", + Bank.format(startPrices[i]), + sharePerCert, + Bank.format(sharesPerCert * startPrices[i]) )); + buyActions.add(buy); + buyAmounts.add(startPrices[i]); + } + } else { + options.add (LocalText.getText("StartACompany", + companyName, + company.getPresidentsShare().getShare(), + Bank.format(company.getPresidentsShare().getShares() * startPrices[0]))); buyActions.add(buy); - buyAmounts.add(startPrices[i]); + buyAmounts.add(startPrices[0]); } } else { startPrices = new int[] {((StartCompany) buy).getPrice()}; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-12-22 20:56:56
|
Revision: 1463 http://rails.svn.sourceforge.net/rails/?rev=1463&view=rev Author: evos Date: 2010-12-22 20:56:50 +0000 (Wed, 22 Dec 2010) Log Message: ----------- Fixed a problem where in 18EU minors were allowed to lay green tiles (bug #3064831). This was caused by the LayTile object have a tileColour allowance map entry {green=0}. This entry shouldn't have existed, but zero values weren't checked for anywhere either. This is now checked in two places. Modified Paths: -------------- trunk/18xx/rails/game/action/LayTile.java trunk/18xx/rails/ui/swing/UpgradesPanel.java Modified: trunk/18xx/rails/game/action/LayTile.java =================================================================== --- trunk/18xx/rails/game/action/LayTile.java 2010-12-18 21:42:03 UTC (rev 1462) +++ trunk/18xx/rails/game/action/LayTile.java 2010-12-22 20:56:50 UTC (rev 1463) @@ -84,7 +84,7 @@ public LayTile(Map<String, Integer> tileColours) { type = GENERIC; - this.tileColours = tileColours; + setTileColours (tileColours); } public LayTile(SpecialTileLay specialProperty) { @@ -189,11 +189,19 @@ } public boolean isTileColourAllowed(String tileColour) { - return tileColours.containsKey(tileColour); + return tileColours != null + && tileColours.containsKey(tileColour) + && tileColours.get(tileColour) > 0; } public void setTileColours(Map<String, Integer> map) { - tileColours = map; + tileColours = new HashMap<String, Integer>(); + // Check the map. Sometimes 0 values creep in, and these can't easily + // be intercepted in the UI code (see comment at previous method). + // TODO This is a dirty fix, but the quickest one too. + for (String colourName : map.keySet()) { + if (map.get(colourName) > 0) tileColours.put(colourName, map.get(colourName)); + } } Modified: trunk/18xx/rails/ui/swing/UpgradesPanel.java =================================================================== --- trunk/18xx/rails/ui/swing/UpgradesPanel.java 2010-12-18 21:42:03 UTC (rev 1462) +++ trunk/18xx/rails/ui/swing/UpgradesPanel.java 2010-12-22 20:56:50 UTC (rev 1463) @@ -91,17 +91,25 @@ for (LayTile layTile : hexMap.getTileAllowancesForHex(hex)) { tiles = layTile.getTiles(); - if (tiles == null) { + if (tiles == null) { for (TileI tile : uiHex.getCurrentTile().getValidUpgrades(hex, orUIManager.gameUIManager.getCurrentPhase())) { + // Skip if not allowed in LayTile + if (!layTile.isTileColourAllowed(tile.getColourName())) continue; + if (!orUIManager.tileUpgrades.contains(tile)) orUIManager.tileUpgrades.add(tile); } } else { for (TileI tile : tiles) { + // Skip if not allowed in LayTile + if (layTile.getTileColours().get(tile.getColourName()) < 1) continue; + // special check: does the tile increase the colour number? // this avoids that a special tile lay down or equalgrades existing tiles - if (tile.getColourNumber() <= uiHex.getCurrentTile().getColourNumber()) continue; + // TODO EV: I'm not sure if this is a necessary precaution. + if (!layTile.isTileColourAllowed(tile.getColourName())) continue; + if (!orUIManager.tileUpgrades.contains(tile)) orUIManager.tileUpgrades.add(tile); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2011-02-03 23:22:56
|
Revision: 1479 http://rails.svn.sourceforge.net/rails/?rev=1479&view=rev Author: evos Date: 2011-02-03 23:22:49 +0000 (Thu, 03 Feb 2011) Log Message: ----------- Fixed bug #3165621: 1889 port token could not be laid. Tile laying code has been generally cleaned up and simplified. Cases where a regular and a special property-originating tile can be laid on the same hex now work correctly (such as in 1899 hex G10 in the saved file provided with the above bug). Modified Paths: -------------- trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/action/LayTile.java trunk/18xx/rails/game/move/MapChange.java trunk/18xx/rails/game/move/RemoveFromMap.java trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java trunk/18xx/rails/game/state/HashMapState.java trunk/18xx/rails/ui/swing/ORUIManager.java trunk/18xx/rails/ui/swing/UpgradesPanel.java trunk/18xx/rails/ui/swing/hexmap/GUIHex.java Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2011-02-01 17:27:05 UTC (rev 1478) +++ trunk/18xx/rails/game/OperatingRound.java 2011-02-03 23:22:49 UTC (rev 1479) @@ -43,9 +43,9 @@ // Non-persistent lists (are recreated after each user action) protected List<SpecialPropertyI> currentSpecialProperties = null; - protected List<LayTile> currentSpecialTileLays = new ArrayList<LayTile>(); + //protected List<LayTile> currentSpecialTileLays = new ArrayList<LayTile>(); - protected List<LayTile> currentNormalTileLays = new ArrayList<LayTile>(); + //protected List<LayTile> currentNormalTileLays = new ArrayList<LayTile>(); protected HashMapState<String, Integer> tileLaysPerColour = new HashMapState<String, Integer>("tileLaysPerColour"); @@ -419,7 +419,7 @@ // Was a special property used? if (stl != null) { stl.setExercised(); - currentSpecialTileLays.remove(action); + //currentSpecialTileLays.remove(action); log.debug("This was a special tile lay, " + (extra ? "" : " not") + " extra"); @@ -428,14 +428,9 @@ log.debug("This was a normal tile lay"); registerNormalTileLay(tile); } - - setSpecialTileLays(); - log.debug("There are now " + currentSpecialTileLays.size() - + " special tile lay objects"); } - if (tile == null || currentNormalTileLays.isEmpty() - && currentSpecialTileLays.isEmpty()) { + if (tile == null || !areTileLaysPossible()) { nextStep(); } @@ -460,33 +455,34 @@ int oldAllowedNumber = oldAllowedNumberObject.intValue(); if (oldAllowedNumber <= 0) return false; - if (!update) return true; + if (update) updateAllowedTileColours(colour, oldAllowedNumber); + return true; + } - /* - * We will assume that in all cases the following assertions hold: 1. If - * the allowed number for the colour of the just laid tile reaches zero, - * all normal tile lays have been consumed. 2. If any colour is laid, no - * different colours may be laid. THIS MAY NOT BE TRUE FOR ALL GAMES! - */ + /* + * We will assume that in all cases the following assertions hold: 1. If + * the allowed number for the colour of the just laid tile reaches zero, + * all normal tile lays have been consumed. 2. If any colour is laid, no + * different colours may be laid. THIS MAY NOT BE TRUE FOR ALL GAMES! + */ + protected void updateAllowedTileColours (String colour, int oldAllowedNumber) { + if (oldAllowedNumber <= 1) { - for (String key:tileLaysPerColour.viewKeySet()) { - tileLaysPerColour.put(key, new Integer(0)); - } + tileLaysPerColour.clear(); log.debug("No more normal tile lays allowed"); - currentNormalTileLays.clear(); + //currentNormalTileLays.clear();// Shouldn't be needed anymore ?? } else { for (String key:tileLaysPerColour.viewKeySet()) { if (colour.equals(key)) { - tileLaysPerColour.put(colour, new Integer(oldAllowedNumber-1)); + tileLaysPerColour.put(colour, oldAllowedNumber-1); } else { - tileLaysPerColour.put(key, new Integer(0)); + tileLaysPerColour.remove(colour); } } - log.debug((oldAllowedNumber - 1) + " more " + colour - + " tile lays allowed"); + log.debug((oldAllowedNumber - 1) + " additional " + colour + + " tile lays allowed; no other colours"); } - return true; } public boolean layBaseToken(LayBaseToken action) { @@ -1351,7 +1347,7 @@ * method should be called only once per company turn in an OR: at the start * of the tile laying step. */ - protected void getNormalTileLays() { + protected void initNormalTileLays() { // duplicate the phase colours Map<String, Integer> newTileColours = new HashMap<String, Integer>(getCurrentPhase().getTileColours()); @@ -1364,46 +1360,80 @@ tileLaysPerColour.initFromMap(newTileColours); } - protected void setNormalTileLays() { + protected List<LayTile> getNormalTileLays(boolean display) { /* Normal tile lays */ - currentNormalTileLays.clear(); + List<LayTile> currentNormalTileLays = new ArrayList<LayTile>(); + + // Check which colours can still be laid + Map <String, Integer> remainingTileLaysPerColour = new HashMap<String, Integer>(); - // Map<String,Integer> tileLaysPerColour = (Map<String,Integer>)(tileLaysPerColourState.getObject()); - - int sumLays = 0; - for (Integer i: tileLaysPerColour.viewValues()) - sumLays = sumLays + i; - if (sumLays != 0) { - // if (!tileLaysPerColour.isEmpty()) { - currentNormalTileLays.add(new LayTile(tileLaysPerColour.viewMap())); + int lays = 0; + for (String colourName: tileLaysPerColour.viewKeySet()) { + lays = tileLaysPerColour.get(colourName); + if (lays != 0) { + remainingTileLaysPerColour.put(colourName, lays); + } } - + if (!remainingTileLaysPerColour.isEmpty()) { + currentNormalTileLays.add(new LayTile(remainingTileLaysPerColour)); + } + + // NOTE: in a later stage tile lays will be specified per hex or set of hexes. + + if (display) { + int size = currentNormalTileLays.size(); + if (size == 0) { + log.debug("No normal tile lays"); + } else { + for (LayTile tileLay : currentNormalTileLays) { + log.debug("Normal tile lay: " + tileLay.toString()); + } + } + } + return currentNormalTileLays; } /** * Create a List of allowed special tile lays (see LayTile class). This * method should be called before each user action in the tile laying step. */ - protected void setSpecialTileLays() { + protected List<LayTile> getSpecialTileLays(boolean display) { /* Special-property tile lays */ - currentSpecialTileLays.clear(); + List<LayTile> currentSpecialTileLays = new ArrayList<LayTile>(); - if (!operatingCompany.get().canUseSpecialProperties()) return; + if (operatingCompany.get().canUseSpecialProperties()) { - for (SpecialTileLay stl : getSpecialProperties(SpecialTileLay.class)) { - if ( -// stl.getTile() != null && getCurrentPhase().isTileColourAllowed(stl.getTile().getColourName()) && - // if a tile is specified it must have a tile colour currently available - // commented out as it is not required and makes 1856 save files invalid - (stl.isExtra() || !currentNormalTileLays.isEmpty())) { - // If the special tile lay is not extra, it is only allowed if - // normal tile lays are also (still) allowed - currentSpecialTileLays.add(new LayTile(stl)); + for (SpecialTileLay stl : getSpecialProperties(SpecialTileLay.class)) { + if (stl.isExtra() + // If the special tile lay is not extra, it is only allowed if + // normal tile lays are also (still) allowed + || stl.getTile() != null + && checkNormalTileLay(stl.getTile(), false)) { + currentSpecialTileLays.add(new LayTile(stl)); + } } } + + if (display) { + int size = currentSpecialTileLays.size(); + if (size == 0) { + log.debug("No special tile lays"); + } else { + for (LayTile tileLay : currentSpecialTileLays) { + log.debug("Special tile lay: " + tileLay.toString()); + } + } + } + + return currentSpecialTileLays; } + + protected boolean areTileLaysPossible() { + return !tileLaysPerColour.isEmpty() + || !getSpecialTileLays(false).isEmpty(); + } protected void setNormalTokenLays() { @@ -2307,7 +2337,7 @@ if (noMapMode) { nextStep (GameDef.OrStep.LAY_TOKEN); } else { - getNormalTileLays(); // new: only called once per turn ? + initNormalTileLays(); // new: only called once per turn ? setStep (GameDef.OrStep.LAY_TRACK); } } @@ -2321,13 +2351,8 @@ possibleActions.add(new LayBaseToken (operatingCompany.get().getHomeHex())); forced = true; } else { - setNormalTileLays(); - setSpecialTileLays(); - log.debug("Normal tile lays: " + currentNormalTileLays.size()); - log.debug("Special tile lays: " + currentSpecialTileLays.size()); - - possibleActions.addAll(currentNormalTileLays); - possibleActions.addAll(currentSpecialTileLays); + possibleActions.addAll(getNormalTileLays(true)); + possibleActions.addAll(getSpecialTileLays(true)); possibleActions.add(new NullAction(NullAction.SKIP)); } Modified: trunk/18xx/rails/game/action/LayTile.java =================================================================== --- trunk/18xx/rails/game/action/LayTile.java 2011-02-01 17:27:05 UTC (rev 1478) +++ trunk/18xx/rails/game/action/LayTile.java 2011-02-03 23:22:49 UTC (rev 1479) @@ -85,6 +85,7 @@ public LayTile(Map<String, Integer> tileColours) { type = GENERIC; setTileColours (tileColours); + // NOTE: tileColours is currently only used for Help purposes. } public LayTile(SpecialTileLay specialProperty) { @@ -100,6 +101,8 @@ tiles.add(tile); } } + + } /** @@ -199,8 +202,10 @@ // Check the map. Sometimes 0 values creep in, and these can't easily // be intercepted in the UI code (see comment at previous method). // TODO This is a dirty fix, but the quickest one too. - for (String colourName : map.keySet()) { - if (map.get(colourName) > 0) tileColours.put(colourName, map.get(colourName)); + if (map != null) { + for (String colourName : map.keySet()) { + if (map.get(colourName) > 0) tileColours.put(colourName, map.get(colourName)); + } } } Modified: trunk/18xx/rails/game/move/MapChange.java =================================================================== --- trunk/18xx/rails/game/move/MapChange.java 2011-02-01 17:27:05 UTC (rev 1478) +++ trunk/18xx/rails/game/move/MapChange.java 2011-02-03 23:22:49 UTC (rev 1479) @@ -45,6 +45,8 @@ public boolean undo() { if (keyExisted) { map.put (key, oldValue); + } else { + map.remove(key); } return true; } Modified: trunk/18xx/rails/game/move/RemoveFromMap.java =================================================================== --- trunk/18xx/rails/game/move/RemoveFromMap.java 2011-02-01 17:27:05 UTC (rev 1478) +++ trunk/18xx/rails/game/move/RemoveFromMap.java 2011-02-03 23:22:49 UTC (rev 1479) @@ -25,9 +25,11 @@ public RemoveFromMap (Map<K, V> map, K key) { + keyExisted = map.containsKey(key); + if (!keyExisted) return; // Nothing to do this.map = map; this.key = key; - this.keyExisted = map.containsKey(key); + this.oldValue = map.get(key); MoveSet.add(this); } @@ -49,7 +51,7 @@ } public String toString() { - return "RemoveFromMap: remove key="+key+" from map"; + return "RemoveFromMap: remove key="+key+" value="+oldValue+" from map"; } } Modified: trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java =================================================================== --- trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java 2011-02-01 17:27:05 UTC (rev 1478) +++ trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java 2011-02-03 23:22:49 UTC (rev 1479) @@ -182,25 +182,42 @@ } @Override - protected void setSpecialTileLays() { + protected List<LayTile> getSpecialTileLays(boolean display) { /* Special-property tile lays */ - currentSpecialTileLays.clear(); + List<LayTile> currentSpecialTileLays = new ArrayList<LayTile>(); - if (!operatingCompany.get().canUseSpecialProperties()) return; + if (operatingCompany.get().canUseSpecialProperties()) { - for (SpecialTileLay stl : getSpecialProperties(SpecialTileLay.class)) { - if (stl.isExtra() || !currentNormalTileLays.isEmpty()) { + for (SpecialTileLay stl : getSpecialProperties(SpecialTileLay.class)) { + if (stl.isExtra() + // If the special tile lay is not extra, it is only allowed if + // normal tile lays are also (still) allowed + || stl.getTile() != null + && getCurrentPhase().isTileColourAllowed(stl.getTile().getColourName())) { - // Exclude the second OBB free tile if the first was laid in this round - if (stl.getLocationNameString().matches("M1(7|9)") - && hasLaidExtraOBBTile.booleanValue()) continue; + // Exclude the second OBB free tile if the first was laid in this round + if (stl.getLocationNameString().matches("M1(7|9)") + && hasLaidExtraOBBTile.booleanValue()) continue; - currentSpecialTileLays.add(new LayTile(stl)); + currentSpecialTileLays.add(new LayTile(stl)); + } } } + + if (display) { + int size = currentSpecialTileLays.size(); + if (size == 0) { + log.debug("No special tile lays"); + } else { + for (LayTile tileLay : currentSpecialTileLays) { + log.debug("Special tile lay: " + tileLay.toString()); + } + } + } + + return currentSpecialTileLays; } - @Override public boolean layTile(LayTile action) { Modified: trunk/18xx/rails/game/state/HashMapState.java =================================================================== --- trunk/18xx/rails/game/state/HashMapState.java 2011-02-01 17:27:05 UTC (rev 1478) +++ trunk/18xx/rails/game/state/HashMapState.java 2011-02-03 23:22:49 UTC (rev 1479) @@ -1,8 +1,10 @@ package rails.game.state; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Set; @@ -58,9 +60,14 @@ } public void clear() { - for (K key:map.keySet()) { - remove(key); + // Two-step process to avoid concurrent modification exception + List<K> keys = new ArrayList<K>(); + for (K key : map.keySet()) { + keys.add(key); } + for (K key : keys) { + remove (key); + } } /** @@ -100,4 +107,8 @@ public Collection<V> viewValues() { return Collections.unmodifiableCollection(map.values()); } + + public boolean isEmpty() { + return map.isEmpty(); + } } Modified: trunk/18xx/rails/ui/swing/ORUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/ORUIManager.java 2011-02-01 17:27:05 UTC (rev 1478) +++ trunk/18xx/rails/ui/swing/ORUIManager.java 2011-02-03 23:22:49 UTC (rev 1479) @@ -748,13 +748,48 @@ if (selectedHex != null && selectedHex.canFixTile()) { List<LayTile> allowances = map.getTileAllowancesForHex(selectedHex.getHexModel()); - LayTile allowance = allowances.get(0); // TODO Wrong if we have an - // additional special - // property (18AL Lumber - // Terminal) + LayTile allowance = null; + TileI tile = selectedHex.getProvisionalTile(); + if (allowances.size() == 1) { + allowance = allowances.get(0); + } else { + // Check which allowance applies + // We'll restrict to cases where we have both a special property + // and a normal 'blanket' allowance. + // First check which is which. + List<TileI> sp_tiles; + List<MapHex> sp_hexes; + LayTile gen_lt = null; + for (LayTile lt : allowances) { + if (lt.getType() == LayTile.SPECIAL_PROPERTY) { + // Cases where a special property is used include: + // 1. SP refers to specified tiles, (one of) which is chosen: + // (examples: 18AL Lumber Terminal, 1889 Port) + if ((((sp_tiles = lt.getTiles()) != null + && sp_tiles.contains(tile)) + // 2. SP does not refer to specific tiles but it does refer to + // specified hexes, (one of) which is chosen: + // (example: 1830 hex B20) + || (sp_tiles == null + && (sp_hexes = lt.getLocations()) != null) + && sp_hexes.contains(selectedHex.getModel()))) { + allowance = lt; + break; + } + } else { + gen_lt = lt; + } + } + + // Default case: the generic allowance + // TODO It is not clear that all possible cases have been covered yet. + // But at least this works for 1830, 1889 + if (allowance == null) allowance = gen_lt; + + } allowance.setChosenHex(selectedHex.getHexModel()); allowance.setOrientation(selectedHex.getProvisionalTileRotation()); - allowance.setLaidTile(selectedHex.getProvisionalTile()); + allowance.setLaidTile(tile); relayBaseTokens (allowance); @@ -1726,7 +1761,7 @@ upgradePanel.setCancelEnabled(true); break; case SELECT_TILE: - upgradePanel.populate(); + upgradePanel.populate(gameUIManager.getCurrentPhase()); upgradePanel.setDoneEnabled(false); break; case ROTATE_OR_CONFIRM_TILE: Modified: trunk/18xx/rails/ui/swing/UpgradesPanel.java =================================================================== --- trunk/18xx/rails/ui/swing/UpgradesPanel.java 2011-02-01 17:27:05 UTC (rev 1478) +++ trunk/18xx/rails/ui/swing/UpgradesPanel.java 2011-02-03 23:22:49 UTC (rev 1479) @@ -6,6 +6,7 @@ import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; +import java.util.Set; import javax.swing.*; import javax.swing.border.Border; @@ -81,13 +82,14 @@ add(scrollPane); } - public void populate() { + public void populate(PhaseI currentPhase) { if (hexMap == null) hexMap = orUIManager.getMapPanel().getMap(); GUIHex uiHex = hexMap.getSelectedHex(); MapHex hex = uiHex.getHexModel(); orUIManager.tileUpgrades = new ArrayList<TileI>(); List<TileI> tiles; + Set<String> allowedColours = currentPhase.getTileColours().keySet(); for (LayTile layTile : hexMap.getTileAllowancesForHex(hex)) { tiles = layTile.getTiles(); @@ -95,21 +97,16 @@ for (TileI tile : uiHex.getCurrentTile().getValidUpgrades(hex, orUIManager.gameUIManager.getCurrentPhase())) { // Skip if not allowed in LayTile - if (!layTile.isTileColourAllowed(tile.getColourName())) continue; - + //if (!layTile.isTileColourAllowed(tile.getColourName())) continue; + if (!orUIManager.tileUpgrades.contains(tile)) orUIManager.tileUpgrades.add(tile); } } else { for (TileI tile : tiles) { - // Skip if not allowed in LayTile - if (layTile.getTileColours().get(tile.getColourName()) < 1) continue; + // Skip if colour is not allowed yet + if (!allowedColours.contains(tile.getColourName())) continue; - // special check: does the tile increase the colour number? - // this avoids that a special tile lay down or equalgrades existing tiles - // TODO EV: I'm not sure if this is a necessary precaution. - if (!layTile.isTileColourAllowed(tile.getColourName())) continue; - if (!orUIManager.tileUpgrades.contains(tile)) orUIManager.tileUpgrades.add(tile); } @@ -327,6 +324,7 @@ } } + // NOTE: NOT USED private void setSelectedCorrectionToken() { if (correctionTokenLabels == null || correctionTokenLabels.isEmpty()) return; int index = -1; @@ -475,7 +473,8 @@ super(tokenIcon); this.token = token; } - + + // NOTE: NOT USED TokenI getToken() { return token; } Modified: trunk/18xx/rails/ui/swing/hexmap/GUIHex.java =================================================================== --- trunk/18xx/rails/ui/swing/hexmap/GUIHex.java 2011-02-01 17:27:05 UTC (rev 1478) +++ trunk/18xx/rails/ui/swing/hexmap/GUIHex.java 2011-02-03 23:22:49 UTC (rev 1479) @@ -871,5 +871,9 @@ hexMap.repaint(getBounds()); } } + + public String toString () { + return getName() + " (" + currentTile.getName() + ")"; + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2011-02-13 19:57:58
|
Revision: 1486 http://rails.svn.sourceforge.net/rails/?rev=1486&view=rev Author: evos Date: 2011-02-13 19:57:47 +0000 (Sun, 13 Feb 2011) Log Message: ----------- Initial commit for 1830 Coalfields (fixed) Modified Paths: -------------- trunk/18xx/rails/game/Tile.java trunk/18xx/rails/game/TileI.java trunk/18xx/rails/game/correct/MapCorrectionManager.java trunk/18xx/rails/ui/swing/UpgradesPanel.java trunk/18xx/rails/util/Tag.java Modified: trunk/18xx/rails/game/Tile.java =================================================================== --- trunk/18xx/rails/game/Tile.java 2011-02-13 18:07:34 UTC (rev 1485) +++ trunk/18xx/rails/game/Tile.java 2011-02-13 19:57:47 UTC (rev 1486) @@ -18,7 +18,7 @@ * The 'external id', which is shown in the UI. Usually equal to the * internal id, but different in case of duplicates. */ - private int externalId; + private String externalId; /** * The 'picture id', identifying the picture number to be loaded. Usually * equal to the internal id, but different in case of graphical variants @@ -90,7 +90,8 @@ public Tile(Integer id) { this.id = id; - externalId = pictureId = id; + pictureId = id; + externalId = String.valueOf(id); name = "" + this.id; for (int i = 0; i < 6; i++) @@ -201,7 +202,7 @@ } /* External (printed) id */ - externalId = setTag.getAttributeAsInteger("extId", externalId); + externalId = setTag.getAttributeAsString("extId", externalId); /* Picture id */ pictureId = setTag.getAttributeAsInteger("pic", pictureId); /* Quantity */ @@ -323,7 +324,7 @@ return id; } - public int getExternalId() { + public String getExternalId() { return externalId; } @@ -520,7 +521,7 @@ Integer colour = this.getColourNumber(); int result = colour.compareTo(anotherTile.getColourNumber()); if (result == 0) { - Integer externalId = this.getExternalId(); + //String externalId = this.getExternalId(); result = externalId.compareTo(anotherTile.getExternalId()); } return result; Modified: trunk/18xx/rails/game/TileI.java =================================================================== --- trunk/18xx/rails/game/TileI.java 2011-02-13 18:07:34 UTC (rev 1485) +++ trunk/18xx/rails/game/TileI.java 2011-02-13 19:57:47 UTC (rev 1486) @@ -23,7 +23,7 @@ */ public int getId(); - public int getExternalId(); + public String getExternalId(); public int getPictureId(); Modified: trunk/18xx/rails/game/correct/MapCorrectionManager.java =================================================================== --- trunk/18xx/rails/game/correct/MapCorrectionManager.java 2011-02-13 18:07:34 UTC (rev 1485) +++ trunk/18xx/rails/game/correct/MapCorrectionManager.java 2011-02-13 19:57:47 UTC (rev 1486) @@ -15,6 +15,7 @@ import rails.game.TileManager; import rails.game.TokenI; import rails.util.LocalText; +import tools.Util; public class MapCorrectionManager extends CorrectionManager { @@ -70,7 +71,8 @@ String errMsg = null; while (true) { // check if chosenTile is still available (not for preprinted) - if (chosenTile != null && chosenTile.getExternalId() > 0 && chosenTile != hex.getCurrentTile() + if (chosenTile != null && Util.hasValue(chosenTile.getExternalId()) + && chosenTile != hex.getCurrentTile() && chosenTile.countFreeTiles() == 0) { errMsg = LocalText.getText("TileNotAvailable", Modified: trunk/18xx/rails/ui/swing/UpgradesPanel.java =================================================================== --- trunk/18xx/rails/ui/swing/UpgradesPanel.java 2011-02-13 18:07:34 UTC (rev 1485) +++ trunk/18xx/rails/ui/swing/UpgradesPanel.java 2011-02-13 19:57:47 UTC (rev 1486) @@ -21,6 +21,7 @@ import rails.ui.swing.hexmap.GUIHex; import rails.ui.swing.hexmap.HexMap; import rails.util.LocalText; +import tools.Util; public class UpgradesPanel extends Box implements MouseListener, ActionListener { private static final long serialVersionUID = 1L; @@ -505,7 +506,7 @@ void setTextFromTile(TileI tile) { StringBuffer text = new StringBuffer(); - if (tile.getExternalId() > 0) { + if (Util.hasValue(tile.getExternalId())) { text.append("<HTML><BODY>" + tile.getExternalId()); if (tile.countFreeTiles() != -1) { text.append("<BR> (" + tile.countFreeTiles() + ")"); Modified: trunk/18xx/rails/util/Tag.java =================================================================== --- trunk/18xx/rails/util/Tag.java 2011-02-13 18:07:34 UTC (rev 1485) +++ trunk/18xx/rails/util/Tag.java 2011-02-13 19:57:47 UTC (rev 1486) @@ -266,7 +266,6 @@ Node attribute; String name, value; List<String> valueList; - String[] valueArray; StringBuffer textBuffer = new StringBuffer(); for (int i = 0; i < childNodes.getLength(); i++) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2011-03-06 13:05:49
|
Revision: 1493 http://rails.svn.sourceforge.net/rails/?rev=1493&view=rev Author: evos Date: 2011-03-06 13:05:43 +0000 (Sun, 06 Mar 2011) Log Message: ----------- Fixed bad neighbour calculation in NS maps with letters vertical and A odd Modified Paths: -------------- trunk/18xx/rails/game/MapHex.java trunk/18xx/rails/game/MapManager.java trunk/18xx/rails/ui/swing/hexmap/GUIHex.java Modified: trunk/18xx/rails/game/MapHex.java =================================================================== --- trunk/18xx/rails/game/MapHex.java 2011-03-05 20:10:40 UTC (rev 1492) +++ trunk/18xx/rails/game/MapHex.java 2011-03-06 13:05:43 UTC (rev 1493) @@ -356,6 +356,7 @@ public void setNeighbor(int orientation, MapHex neighbour) { orientation %= 6; neighbours[orientation] = neighbour; + //log.debug("+++ Hex="+getName()+":"+orientation+"->"+neighbour.getName()); } public MapHex getNeighbor(int orientation) { Modified: trunk/18xx/rails/game/MapManager.java =================================================================== --- trunk/18xx/rails/game/MapManager.java 2011-03-05 20:10:40 UTC (rev 1492) +++ trunk/18xx/rails/game/MapManager.java 2011-03-06 13:05:43 UTC (rev 1493) @@ -124,21 +124,16 @@ } // Initialise the neighbours + int ii, jj; for (i = minX; i <= maxX; i++) { for (j = minY; j <= maxY; j++) { if ((hex = hexes[i][j]) == null) continue; for (k = 0; k < 6; k++) { - if (tileOrientation == MapHex.EW) { - dx = (j % 2 == 0 ? xYEvenDeltaEW[k] : xYOddDeltaEW[k]); - dy = yDeltaEW[k]; - } else { - dx = xDeltaNS[k]; - dy = (i % 2 == 0 ? yXEvenDeltaNS[k] : yXOddDeltaNS[k]); - } - if (i + dx >= minX && i + dx <= maxX && j + dy >= minY - && j + dy <= maxY - && (nb = hexes[i + dx][j + dy]) != null) { + ii = getAdjacentX (i, j, k); + jj = getAdjacentY (i, j, k); + if (ii >= minX && ii <= maxX && jj >= minY && jj <= maxY + && (nb = hexes[ii][jj]) != null) { if (hex.isNeighbour(nb, k) && nb.isNeighbour(hex, k + 3)) { hex.setNeighbor(k, nb); @@ -146,7 +141,6 @@ } if (hex.isImpassable(nb) || nb.isImpassable(hex)) { hex.addImpassableSide(k); - //nb.addImpassableSide(k+3); } } @@ -177,6 +171,25 @@ public boolean lettersGoHorizontal() { return lettersGoHorizontal; } + + public int getAdjacentX (int x, int y, int orientation) { + + if (tileOrientation == MapHex.EW) { + return x + (y % 2 == 0 ? xYEvenDeltaEW[orientation] : xYOddDeltaEW[orientation]); + } else { + return x + xDeltaNS[orientation]; + } + } + + public int getAdjacentY (int x, int y, int orientation) { + + if (tileOrientation == MapHex.EW) { + return y + yDeltaEW[orientation]; + } else { + return y + ((x % 2 == 0) == letterAHasEvenNumbers ? + yXEvenDeltaNS[orientation] : yXOddDeltaNS[orientation]); + } + } /** * @return Returns the currentTileOrientation. Modified: trunk/18xx/rails/ui/swing/hexmap/GUIHex.java =================================================================== --- trunk/18xx/rails/ui/swing/hexmap/GUIHex.java 2011-03-05 20:10:40 UTC (rev 1492) +++ trunk/18xx/rails/ui/swing/hexmap/GUIHex.java 2011-03-06 13:05:43 UTC (rev 1493) @@ -319,21 +319,6 @@ return polygon; } - public void setNeighbor(int i, GUIHex hex) { - if (i >= 0 && i < 6) { - neighbors[i] = hex; - getHexModel().setNeighbor(i, hex.getHexModel()); - } - } - - public GUIHex getNeighbor(int i) { - if (i < 0 || i > 6) { - return null; - } else { - return neighbors[i]; - } - } - public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; @@ -704,9 +689,13 @@ if (Util.hasValue(name)) { tt.append(" (").append(name).append(")"); } + // For debugging: display x,y-coordinates + //tt.append("<small> x=" + x + " y="+y+"</small>"); + tt.append("<br><b>Tile</b>: ").append(currentTile.getId()); - // TEMPORARY - tt.append("<small> rot=" + currentTileOrientation + "</small>"); + + // For debugging: display rotation + //tt.append("<small> rot=" + currentTileOrientation + "</small>"); if (model.hasOffBoardValues()) { tt.append("<br>Value "); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2011-03-30 14:57:20
|
Revision: 1504 http://rails.svn.sourceforge.net/rails/?rev=1504&view=rev Author: evos Date: 2011-03-30 14:57:13 +0000 (Wed, 30 Mar 2011) Log Message: ----------- Autosave/load, fixes and small improvements Modified Paths: -------------- trunk/18xx/rails/ui/swing/AutoLoadPoller.java trunk/18xx/rails/ui/swing/GameSetupWindow.java trunk/18xx/rails/ui/swing/GameStatus.java trunk/18xx/rails/ui/swing/GameUIManager.java trunk/18xx/rails/ui/swing/ORUIManager.java trunk/18xx/rails/ui/swing/ORWindow.java trunk/18xx/rails/ui/swing/ReportWindowDynamic.java trunk/18xx/rails/ui/swing/StartRoundWindow.java trunk/18xx/rails/ui/swing/StatusWindow.java trunk/18xx/rails/ui/swing/gamespecific/_18EU/StatusWindow_18EU.java trunk/18xx/rails/util/RunGame.java Modified: trunk/18xx/rails/ui/swing/AutoLoadPoller.java =================================================================== --- trunk/18xx/rails/ui/swing/AutoLoadPoller.java 2011-03-29 13:13:57 UTC (rev 1503) +++ trunk/18xx/rails/ui/swing/AutoLoadPoller.java 2011-03-30 14:57:13 UTC (rev 1504) @@ -42,6 +42,9 @@ lastSavedFilenameFilepath = saveDirectory + "/" + savePrefix + ".last_rails"; + log.debug("Poller own postfix: "+ownPostfix); + log.debug("Poller last-filename path: "+lastSavedFilenameFilepath); + } @Override @@ -54,7 +57,7 @@ for (;;) { - log.debug ("Polling cycle"); + log.debug ("Polling cycle, status="+pollingStatus+" active="+pollingActive); // Process if (pollingActive && pollingStatus == ON) { log.debug("Polling..."); @@ -72,14 +75,14 @@ // The GUI must be accessed on the event dispatch thread only. SwingUtilities.invokeLater (new Runnable() { public void run() { - guiMgr.processOnServer(reload); + guiMgr.processAction(reload); } }); } } catch (IOException e) { - + log.error("Exception whilst polling "+lastSavedFilenameFilepath, e); } } Modified: trunk/18xx/rails/ui/swing/GameSetupWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/GameSetupWindow.java 2011-03-29 13:13:57 UTC (rev 1503) +++ trunk/18xx/rails/ui/swing/GameSetupWindow.java 2011-03-30 14:57:13 UTC (rev 1504) @@ -218,7 +218,7 @@ JOptionPane.showMessageDialog(this, DisplayBuffer.get(), "", JOptionPane.ERROR_MESSAGE); } - startGameUIManager(game); + startGameUIManager(game, true); if (saveDirectory != null) { gameUIManager.setSaveDirectory (saveDirectory); } @@ -494,7 +494,7 @@ JOptionPane.ERROR_MESSAGE); System.exit(-1); } - startGameUIManager (game); + startGameUIManager (game, false); gameUIManager.gameUIInit(true); // true indicates new game } @@ -503,14 +503,14 @@ killConfigWindow(); } - private void startGameUIManager(Game game) { + private void startGameUIManager(Game game, boolean wasLoaded) { GameManagerI gameManager = game.getGameManager(); String gameUIManagerClassName = gameManager.getClassName(GuiDef.ClassName.GAME_UI_MANAGER); try { Class<? extends GameUIManager> gameUIManagerClass = Class.forName(gameUIManagerClassName).asSubclass(GameUIManager.class); gameUIManager = gameUIManagerClass.newInstance(); - gameUIManager.init(gameManager); + gameUIManager.init(gameManager, wasLoaded); } catch (Exception e) { log.fatal("Cannot instantiate class " + gameUIManagerClassName, e); System.exit(1); Modified: trunk/18xx/rails/ui/swing/GameStatus.java =================================================================== --- trunk/18xx/rails/ui/swing/GameStatus.java 2011-03-29 13:13:57 UTC (rev 1503) +++ trunk/18xx/rails/ui/swing/GameStatus.java 2011-03-30 14:57:13 UTC (rev 1504) @@ -758,8 +758,8 @@ ActionEvent actor, PossibleAction chosenAction) { return chosenAction; } - - public void initTurn(int actorIndex) { + + public void initTurn(int actorIndex, boolean myTurn) { int i, j; dummyButton.setSelected(true); @@ -791,56 +791,58 @@ } else if (j == -1 && treasurySharesCaption != null) { treasurySharesCaption.setHighlight(true); } + + if (myTurn) { - PublicCompanyI company; - Portfolio holder; - int index; - CashHolder owner; - - List<BuyCertificate> buyableCerts = - possibleActions.getType(BuyCertificate.class); - if (buyableCerts != null) { - for (BuyCertificate bCert : buyableCerts) { - company = bCert.getCompany(); - index = company.getPublicNumber(); - holder = bCert.getFromPortfolio(); - owner = holder.getOwner(); - if (holder == ipo) { - setIPOCertButton(index, true, bCert); - } else if (holder == pool) { - setPoolCertButton(index, true, bCert); - } else if (owner instanceof Player) { - setPlayerCertButton(index, ((Player)owner).getIndex(), true, bCert); - } else if (owner instanceof PublicCompanyI && compCanHoldOwnShares) { - setTreasuryCertButton(index, true, bCert); + PublicCompanyI company; + Portfolio holder; + int index; + CashHolder owner; + + List<BuyCertificate> buyableCerts = + possibleActions.getType(BuyCertificate.class); + if (buyableCerts != null) { + for (BuyCertificate bCert : buyableCerts) { + company = bCert.getCompany(); + index = company.getPublicNumber(); + holder = bCert.getFromPortfolio(); + owner = holder.getOwner(); + if (holder == ipo) { + setIPOCertButton(index, true, bCert); + } else if (holder == pool) { + setPoolCertButton(index, true, bCert); + } else if (owner instanceof Player) { + setPlayerCertButton(index, ((Player)owner).getIndex(), true, bCert); + } else if (owner instanceof PublicCompanyI && compCanHoldOwnShares) { + setTreasuryCertButton(index, true, bCert); + } } } - } - - List<SellShares> sellableShares = - possibleActions.getType(SellShares.class); - if (sellableShares != null) { - for (SellShares share : sellableShares) { - company = share.getCompany(); - index = company.getPublicNumber(); - if (j >= 0) { - setPlayerCertButton(index, j, true, share); - } else if (j == -1 && compCanHoldOwnShares) { - setTreasuryCertButton(index, true, share); + + List<SellShares> sellableShares = + possibleActions.getType(SellShares.class); + if (sellableShares != null) { + for (SellShares share : sellableShares) { + company = share.getCompany(); + index = company.getPublicNumber(); + if (j >= 0) { + setPlayerCertButton(index, j, true, share); + } else if (j == -1 && compCanHoldOwnShares) { + setTreasuryCertButton(index, true, share); + } } } - } - - initGameSpecificActions(); - - List<NullAction> nullActions = - possibleActions.getType(NullAction.class); - if (nullActions != null) { - for (NullAction na : nullActions) { - (parent).setPassButton(na); + + initGameSpecificActions(); + + List<NullAction> nullActions = + possibleActions.getType(NullAction.class); + if (nullActions != null) { + for (NullAction na : nullActions) { + (parent).setPassButton(na); + } } } - } repaint(); Modified: trunk/18xx/rails/ui/swing/GameUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/GameUIManager.java 2011-03-29 13:13:57 UTC (rev 1503) +++ trunk/18xx/rails/ui/swing/GameUIManager.java 2011-03-30 14:57:13 UTC (rev 1504) @@ -74,6 +74,9 @@ protected boolean myTurn = true; protected String lastSavedFilenameFilepath; protected String lastSavedFilename = ""; + protected String localPlayerName = ""; + + protected boolean gameWasLoaded = false; protected WindowSettings windowSettings; @@ -92,12 +95,13 @@ } - public void init (GameManagerI gameManager) { + public void init (GameManagerI gameManager, boolean wasLoaded) { instance = this; this.gameManager = gameManager; uiHints = gameManager.getUIHints(); savePrefix = gameManager.getGameName(); + gameWasLoaded = wasLoaded; initWindowSettings(); initSaveSettings(); @@ -147,6 +151,7 @@ } else { saveSuffix = getPlayerNames().get(0); } + log.debug("Initial save suffix: "+saveSuffix); } private void initFontSettings() { @@ -219,11 +224,11 @@ public void startLoadedGame() { gameUIInit(false); // false indicates reload - processOnServer(new NullAction(NullAction.START_GAME)); + processAction(new NullAction(NullAction.START_GAME)); statusWindow.setGameActions(); } - public boolean processOnServer(PossibleAction action) { + public boolean processAction(PossibleAction action) { boolean result = true; @@ -237,42 +242,36 @@ result = previousResult; } else { - action.setActed(); - action.setPlayerName(getCurrentPlayer().getName()); + + Player oldPlayer = getCurrentPlayer(); + boolean wasMyTurn = oldPlayer.getName().equals(localPlayerName); - log.debug("==Passing to server: " + action); - - Player player = getCurrentPlayer(); - if (player != null) { - action.setPlayerName(player.getName()); - } - // Process the action on the server - result = previousResult = gameManager.process(action); + result = previousResult = processOnServer (action); - // Follow-up the result - log.debug("==Result from server: " + result); - reportWindow.updateLog(); - // Process any autosaving and turn relinquishing, resp. autoloading and turn pickup if (autoSaveLoadInitialized && autoSaveLoadStatus != AutoLoadPoller.OFF) { Player newPlayer = getCurrentPlayer(); - boolean wasMyTurn = myTurn; - myTurn = newPlayer.getName().equals(saveSuffix); - if (newPlayer != player) { - if (wasMyTurn && !myTurn) { - log.info ("Relinquishing turn to "+newPlayer.getName()); + boolean isMyTurn = newPlayer.getName().equals(localPlayerName); + if (newPlayer != oldPlayer) { + if (wasMyTurn && !isMyTurn) { autoSave (newPlayer.getName()); autoLoadPoller.setLastSavedFilename(lastSavedFilename); autoLoadPoller.setActive(true); - } else if (!wasMyTurn && myTurn) { - log.info ("Resuming turn as "+saveSuffix); + log.info ("Relinquishing turn to "+newPlayer.getName()); + } else if (!wasMyTurn && isMyTurn) { autoLoadPoller.setActive(false); setCurrentDialog(new MessageDialog(this, LocalText.getText("Message"), - LocalText.getText("YourTurn", saveSuffix)), + LocalText.getText("YourTurn", localPlayerName)), null); - } + log.info ("Resuming turn as "+localPlayerName); + } else { + log.info(newPlayer.getName()+" now has the turn"); + } + myTurn = isMyTurn; + } else { + log.info(oldPlayer.getName()+" keeps the turn"); } } } @@ -301,6 +300,30 @@ return activeWindow.processImmediateAction(); } + protected boolean processOnServer (PossibleAction action) { + + boolean result; + + action.setActed(); + action.setPlayerName(getCurrentPlayer().getName()); + + log.debug("==Passing to server: " + action); + + Player player = getCurrentPlayer(); + if (player != null) { + action.setPlayerName(player.getName()); + } + + // Process the action on the server + result = gameManager.process(action); + + // Follow-up the result + log.debug("==Result from server: " + result); + reportWindow.updateLog(); + + return result; + } + public boolean displayServerMessage() { String[] message = DisplayBuffer.get(); if (message != null) { @@ -674,7 +697,7 @@ } } - if (currentDialogAction != null) processOnServer(currentDialogAction); + if (currentDialogAction != null) processAction(currentDialogAction); } @@ -773,7 +796,7 @@ providedName = filepath; } exportAction.setFilepath(filepath); - processOnServer(exportAction); + processAction(exportAction); } } @@ -790,13 +813,16 @@ if (providedName != null) { filename = providedName; } else { + String currentSuffix; if (NEXT_PLAYER_SUFFIX.equals(saveSuffixSpec)) { - saveSuffix = gameManager.getCurrentPlayer().getName().replaceAll("[^-\\w\\.]", "_"); + currentSuffix = getCurrentPlayer().getName().replaceAll("[^-\\w\\.]", "_"); + } else { + currentSuffix = saveSuffix; } filename = saveDirectory + "/" + savePrefix + "_" + saveDateTimeFormat.format(new Date()) + "_" - + saveSuffix + "." + + currentSuffix + "." + saveExtension; } @@ -824,7 +850,7 @@ } } saveAction.setFilepath(filepath); - processOnServer(saveAction); + processAction(saveAction); } } @@ -838,7 +864,7 @@ File selectedFile = jfc.getSelectedFile(); saveDirectory = selectedFile.getParent(); reloadAction.setFilepath(selectedFile.getPath()); - processOnServer(reloadAction); + processAction(reloadAction); } else { // cancel pressed return; } @@ -847,6 +873,16 @@ public void autoSaveLoadGame () { + localPlayerName = System.getProperty("local.player.name"); + if (!Util.hasValue(localPlayerName)) { + localPlayerName = Config.get("local.player.name"); + } + if (!Util.hasValue(localPlayerName)) { + DisplayBuffer.add("You cannot activate AutoSave/Load without setting local.player.name"); + return; + } + log.debug("Polling local player name: "+localPlayerName); + AutoSaveLoadDialog dialog = new AutoSaveLoadDialog (this, autoSaveLoadStatus, autoSaveLoadPollingInterval); @@ -859,8 +895,9 @@ autoSaveLoadPollingInterval = dialog.getInterval(); if (autoLoadPoller == null && autoSaveLoadStatus > 0) { + autoLoadPoller = new AutoLoadPoller (this, saveDirectory, savePrefix, - saveSuffix, autoSaveLoadStatus, autoSaveLoadPollingInterval); + localPlayerName, autoSaveLoadStatus, autoSaveLoadPollingInterval); autoLoadPoller.start(); } else if (autoLoadPoller != null) { autoLoadPoller.setStatus(autoSaveLoadStatus); @@ -869,14 +906,20 @@ log.debug("AutoSaveLoad parameters: status="+autoSaveLoadStatus +" interval="+autoSaveLoadPollingInterval); + if (gameWasLoaded) { + autoSaveLoadInitialized = true; + lastSavedFilenameFilepath = saveDirectory + "/" + savePrefix + ".last_rails"; + } + if (autoLoadPoller != null && autoSaveLoadStatus != AutoLoadPoller.OFF - && !autoSaveLoadInitialized) { + && !autoSaveLoadInitialized && !gameWasLoaded) { /* The first time (only) we use the normal save process, * so the player can select a directory, and change * the prefix if so desired. */ GameAction saveAction = new GameAction(GameAction.SAVE); + saveSuffix = localPlayerName; saveGame (saveAction); File lastSavedFile = new File (saveAction.getFilepath()); saveDirectory = lastSavedFile.getParentFile().getPath(); @@ -896,7 +939,7 @@ } } - myTurn = getCurrentPlayer().getName().equals(saveSuffix); + myTurn = getCurrentPlayer().getName().equals(localPlayerName); if (!myTurn) { // Start autoload polling @@ -911,6 +954,7 @@ } + /* public boolean isMyTurn() { return myTurn; } @@ -918,6 +962,7 @@ public void setMyTurn(boolean myTurn) { this.myTurn = myTurn; } + */ public void setSaveDirectory(String saveDirectory) { this.saveDirectory = saveDirectory; Modified: trunk/18xx/rails/ui/swing/ORUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/ORUIManager.java 2011-03-29 13:13:57 UTC (rev 1503) +++ trunk/18xx/rails/ui/swing/ORUIManager.java 2011-03-30 14:57:13 UTC (rev 1504) @@ -450,7 +450,7 @@ } else if (actionType == ClosePrivate.class) { - gameUIManager.processOnServer(actions.get(0)); + gameUIManager.processAction(actions.get(0)); } @@ -581,7 +581,7 @@ return; } - gameUIManager.processOnServer(currentDialogAction); + gameUIManager.processAction(currentDialogAction); } public JDialog getCurrentDialog() { @@ -1432,13 +1432,13 @@ /* In fact currently not used */ protected void useSpecialProperty (UseSpecialProperty action) { - gameUIManager.processOnServer(action); + gameUIManager.processAction(action); } protected void processCorrectionAction(CorrectionAction action) { - gameUIManager.processOnServer(action); + gameUIManager.processAction(action); } Modified: trunk/18xx/rails/ui/swing/ORWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/ORWindow.java 2011-03-29 13:13:57 UTC (rev 1503) +++ trunk/18xx/rails/ui/swing/ORWindow.java 2011-03-30 14:57:13 UTC (rev 1504) @@ -151,7 +151,7 @@ // Add the actor for safety checking in the server if (action != null) action.setPlayerName(orPanel.getORPlayer()); // Process the action - boolean result = gameUIManager.processOnServer(action); + boolean result = gameUIManager.processAction(action); // Display any error message //displayServerMessage(); Modified: trunk/18xx/rails/ui/swing/ReportWindowDynamic.java =================================================================== --- trunk/18xx/rails/ui/swing/ReportWindowDynamic.java 2011-03-29 13:13:57 UTC (rev 1503) +++ trunk/18xx/rails/ui/swing/ReportWindowDynamic.java 2011-03-30 14:57:13 UTC (rev 1504) @@ -206,7 +206,7 @@ } - gameUIManager.processOnServer(action); + gameUIManager.processAction(action); } public void hyperlinkUpdate(HyperlinkEvent e) { @@ -231,11 +231,11 @@ if (index > currentIndex) { // move forward GameAction action = new GameAction(GameAction.REDO); action.setmoveStackIndex(index); - gameUIManager.processOnServer(action); + gameUIManager.processAction(action); } else if (index < currentIndex) { // move backward GameAction action = new GameAction(GameAction.FORCED_UNDO); action.setmoveStackIndex(index); - gameUIManager.processOnServer(action); + gameUIManager.processAction(action); } } Modified: trunk/18xx/rails/ui/swing/StartRoundWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/StartRoundWindow.java 2011-03-29 13:13:57 UTC (rev 1503) +++ trunk/18xx/rails/ui/swing/StartRoundWindow.java 2011-03-30 14:57:13 UTC (rev 1504) @@ -736,6 +736,6 @@ public void keyTyped(KeyEvent e) {} public boolean process(PossibleAction action) { - return gameUIManager.processOnServer(action); + return gameUIManager.processAction(action); } } Modified: trunk/18xx/rails/ui/swing/StatusWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/StatusWindow.java 2011-03-29 13:13:57 UTC (rev 1503) +++ trunk/18xx/rails/ui/swing/StatusWindow.java 2011-03-30 14:57:13 UTC (rev 1504) @@ -433,7 +433,14 @@ if (!(currentRound instanceof StockRound || currentRound instanceof EndOfGameRound)) return; - if (!myTurn) return; + passButton.setEnabled(false); + autopassButton.setEnabled(false); + + log.debug ("MyTurn="+myTurn); + if (!myTurn) { + gameStatus.initTurn(getCurrentPlayer().getIndex(), false); + return; + } // Moved here from StatusWindow_1856. It's getting generic... if (possibleActions.contains(DiscardTrain.class)) { @@ -447,14 +454,14 @@ setTitle(LocalText.getText( "TRADE_TREASURY_SHARES_TITLE", ((TreasuryShareRound) currentRound).getOperatingCompany().getName())); - gameStatus.initTurn(-1); + gameStatus.initTurn(-1, true); passButton.setEnabled(true); } else if ((currentRound instanceof ShareSellingRound)) { setTitle(LocalText.getText( "EMERGENCY_SHARE_SELLING_TITLE", (((ShareSellingRound) currentRound).getCompanyNeedingCash().getName()))); - gameStatus.initTurn(gameUIManager.getCurrentPlayer().getIndex()); + gameStatus.initTurn(getCurrentPlayer().getIndex(), true); gameStatus.setPriorityPlayer(gameUIManager.getPriorityPlayer().getIndex()); passButton.setEnabled(false); @@ -488,7 +495,7 @@ setTitle(LocalText.getText( "STOCK_ROUND_TITLE", String.valueOf(((StockRound) currentRound).getStockRoundNumber()))); - gameStatus.initTurn(gameUIManager.getCurrentPlayer().getIndex()); + gameStatus.initTurn(getCurrentPlayer().getIndex(), true); gameStatus.setPriorityPlayer(gameUIManager.getPriorityPlayer().getIndex()); passButton.setEnabled(true); @@ -673,7 +680,7 @@ return false; } - return gameUIManager.processOnServer(executedAction); + return gameUIManager.processAction(executedAction); } public boolean processImmediateAction() { @@ -727,7 +734,7 @@ public void finishRound() { setTitle(LocalText.getText("GAME_STATUS_TITLE")); - gameStatus.initTurn(-1); + gameStatus.initTurn(-1, true); passButton.setEnabled(false); } Modified: trunk/18xx/rails/ui/swing/gamespecific/_18EU/StatusWindow_18EU.java =================================================================== --- trunk/18xx/rails/ui/swing/gamespecific/_18EU/StatusWindow_18EU.java 2011-03-29 13:13:57 UTC (rev 1503) +++ trunk/18xx/rails/ui/swing/gamespecific/_18EU/StatusWindow_18EU.java 2011-03-30 14:57:13 UTC (rev 1504) @@ -32,7 +32,7 @@ if (currentRound instanceof FinalMinorExchangeRound) { setTitle(LocalText.getText("FinalMinorExchangeRoundTitle")); - gameStatus.initTurn(gameUIManager.getCurrentPlayer().getIndex()); + gameStatus.initTurn(getCurrentPlayer().getIndex(), true); return true; } return false; Modified: trunk/18xx/rails/util/RunGame.java =================================================================== --- trunk/18xx/rails/util/RunGame.java 2011-03-29 13:13:57 UTC (rev 1503) +++ trunk/18xx/rails/util/RunGame.java 2011-03-30 14:57:13 UTC (rev 1504) @@ -69,7 +69,7 @@ Class<? extends GameUIManager> gameUIManagerClass = Class.forName(gameUIManagerClassName).asSubclass(GameUIManager.class); gameUIManager = gameUIManagerClass.newInstance(); - gameUIManager.init(gameManager); + gameUIManager.init(gameManager, true); String directory = new java.io.File(filepath).getParent(); if(directory != null) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2011-04-14 20:33:51
|
Revision: 1519 http://rails.svn.sourceforge.net/rails/?rev=1519&view=rev Author: evos Date: 2011-04-14 20:33:44 +0000 (Thu, 14 Apr 2011) Log Message: ----------- SpecialLayTile improvements: - added priority and colour attributes - UI handling rationalised Modified Paths: -------------- trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/action/LayTile.java trunk/18xx/rails/game/special/SpecialProperty.java trunk/18xx/rails/game/special/SpecialPropertyI.java trunk/18xx/rails/game/special/SpecialTileLay.java trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java trunk/18xx/rails/ui/swing/ORUIManager.java Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2011-04-14 20:31:35 UTC (rev 1518) +++ trunk/18xx/rails/game/OperatingRound.java 2011-04-14 20:33:44 UTC (rev 1519) @@ -1415,7 +1415,16 @@ // normal tile lays are also (still) allowed || stl.getTile() != null && checkNormalTileLay(stl.getTile(), false)) { - currentSpecialTileLays.add(new LayTile(stl)); + LayTile lt = new LayTile(stl); + String[] stlc = stl.getTileColours(); + if (stlc != null) { + Map<String, Integer> tc = new HashMap<String, Integer>(); + for (String c : stlc) { + tc.put(c, 1); + } + lt.setTileColours(tc); + } + currentSpecialTileLays.add(lt); } } } Modified: trunk/18xx/rails/game/action/LayTile.java =================================================================== --- trunk/18xx/rails/game/action/LayTile.java 2011-04-14 20:31:35 UTC (rev 1518) +++ trunk/18xx/rails/game/action/LayTile.java 2011-04-14 20:33:44 UTC (rev 1519) @@ -75,6 +75,7 @@ /** * Allow laying a tile on a given location. */ + // NOTE: NOT YET USED public LayTile(List<MapHex> locations, List<TileI> tiles) { type = LOCATION_SPECIFIC; this.locations = locations; Modified: trunk/18xx/rails/game/special/SpecialProperty.java =================================================================== --- trunk/18xx/rails/game/special/SpecialProperty.java 2011-04-14 20:31:35 UTC (rev 1518) +++ trunk/18xx/rails/game/special/SpecialProperty.java 2011-04-14 20:33:44 UTC (rev 1519) @@ -1,8 +1,7 @@ /* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/special/SpecialProperty.java,v 1.27 2010/03/23 18:45:23 stefanfrey Exp $ */ package rails.game.special; -import java.util.HashMap; -import java.util.Map; +import java.util.*; import org.apache.log4j.Logger; @@ -33,7 +32,15 @@ protected boolean permanent = false; protected boolean isORProperty = false; protected boolean isSRProperty = false; - + + /** Priority indicates whether or not the UI should assign priority to + * the execution of a PossibleAction. For instance, if the same tile can + * be laid on a hex using this special property, and by not using it, + * this attribute indicates which option will be used. + * TODO A third value means: ask the user (NOT YET IMPLEMENTED). + */ + protected Priority priority = DEFAULT_PRIORITY; + /** Optional descriptive text, for display in menus and info text. * Subclasses may put real text in it. */ @@ -88,6 +95,16 @@ // sfy 1889 permanent = tag.getAttributeAsBoolean("permanent", false); + + String priorityString = tag.getAttributeAsString("priority"); + if (Util.hasValue(priorityString)) { + try { + priority = Priority.valueOf(priorityString.toUpperCase()); + } catch (IllegalArgumentException e) { + throw new ConfigurationException ("Illegal value for SpecialProperty priority: "+priorityString, e); + } + } + } public void finishConfiguration (GameManagerI gameManager) @@ -216,6 +233,14 @@ return transferText; } + public Priority getPriority() { + return priority; + } + + public void setPriority(Priority priority) { + this.priority = priority; + } + /** * Move the special property to another holder. * Only to be used for special properties that have the "transfer" attribute. Modified: trunk/18xx/rails/game/special/SpecialPropertyI.java =================================================================== --- trunk/18xx/rails/game/special/SpecialPropertyI.java 2011-04-14 20:31:35 UTC (rev 1518) +++ trunk/18xx/rails/game/special/SpecialPropertyI.java 2011-04-14 20:33:44 UTC (rev 1519) @@ -51,6 +51,18 @@ public String getTransferText(); + public enum Priority { + LAST, + ASKUSER, + FIRST; + }; + + public static final Priority DEFAULT_PRIORITY = Priority.FIRST; + + public Priority getPriority(); + + public void setPriority(Priority priority); + public int getUniqueId(); public String toMenu(); Modified: trunk/18xx/rails/game/special/SpecialTileLay.java =================================================================== --- trunk/18xx/rails/game/special/SpecialTileLay.java 2011-04-14 20:31:35 UTC (rev 1518) +++ trunk/18xx/rails/game/special/SpecialTileLay.java 2011-04-14 20:33:44 UTC (rev 1519) @@ -18,6 +18,11 @@ boolean free = false; boolean connected = false; /* sfy 1889 extension */ + /** Tile colours that can be laid with this special property. + * Default is same colours as is allowed in a a normal tile lay. + * Don't use if specific tiles are specified! */ + protected String[] tileColours = null; + @Override public void configureFromXML(Tag tag) throws ConfigurationException { super.configureFromXML(tag); @@ -33,6 +38,11 @@ tileNumber = tileLayTag.getAttributeAsInteger("tile", 0); + String coloursString = tag.getAttributeAsString("colour"); + if (Util.hasValue(coloursString)) { + tileColours = coloursString.split(","); + } + name = tileLayTag.getAttributeAsString("name"); extra = tileLayTag.getAttributeAsBoolean("extra", extra); @@ -118,6 +128,10 @@ return tile; } + public String[] getTileColours() { + return tileColours; + } + public String getName() { return name; } Modified: trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java =================================================================== --- trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java 2011-04-14 20:31:35 UTC (rev 1518) +++ trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java 2011-04-14 20:33:44 UTC (rev 1519) @@ -235,9 +235,11 @@ errMsg )); return false; } else { + moveStack.start(true); // Duplicate, but we have to hasLaidExtraOBBTile.set(true); // Done here to make getSpecialTileLays() return the correct value. // It's provisional, on the assumption that other validations are OK. + // TODO To get it really right, we should separate validation and execution. } } Modified: trunk/18xx/rails/ui/swing/ORUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/ORUIManager.java 2011-04-14 20:31:35 UTC (rev 1518) +++ trunk/18xx/rails/ui/swing/ORUIManager.java 2011-04-14 20:33:44 UTC (rev 1519) @@ -211,9 +211,13 @@ if (sp == null || !(sp instanceof SpecialTileLay) || ((SpecialTileLay)sp).requiresConnection()) break; - case (LayTile.LOCATION_SPECIFIC): - if (layTile.getLocations() != null) + // else fall through + case (LayTile.LOCATION_SPECIFIC): // NOT YET USED + if (layTile.getLocations() != null) { hexUpgrades.addAll(layTile.getLocations()); + } else { + mapHexes = true; + } } } @@ -760,31 +764,29 @@ List<TileI> sp_tiles; List<MapHex> sp_hexes; LayTile gen_lt = null; + LayTile spec_lt = null; for (LayTile lt : allowances) { if (lt.getType() == LayTile.SPECIAL_PROPERTY) { // Cases where a special property is used include: // 1. SP refers to specified tiles, (one of) which is chosen: // (examples: 18AL Lumber Terminal, 1889 Port) - if ((((sp_tiles = lt.getTiles()) != null - && sp_tiles.contains(tile)) - // 2. SP does not refer to specific tiles but it does refer to - // specified hexes, (one of) which is chosen: + if ((sp_tiles = lt.getTiles()) != null + && !sp_tiles.contains(tile)) continue; + // 2. SP refers to specified hexes, (one of) which is chosen: // (example: 1830 hex B20) - || (sp_tiles == null - && (sp_hexes = lt.getLocations()) != null) - && sp_hexes.contains(selectedHex.getModel()))) { - allowance = lt; - break; - } + if ((sp_hexes = lt.getLocations()) != null + && !sp_hexes.contains(selectedHex.getModel())) continue; + spec_lt = lt; } else { + // Default case: the generic allowance gen_lt = lt; } } - // Default case: the generic allowance - // TODO It is not clear that all possible cases have been covered yet. - // But at least this works for 1830, 1889 - if (allowance == null) allowance = gen_lt; + allowance = spec_lt == null ? gen_lt : + gen_lt == null ? spec_lt : + spec_lt.getSpecialProperty().getPriority() + == SpecialPropertyI.Priority.FIRST ? spec_lt : gen_lt; } allowance.setChosenHex(selectedHex.getHexModel()); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2011-05-04 19:10:51
|
Revision: 1544 http://rails.svn.sourceforge.net/rails/?rev=1544&view=rev Author: evos Date: 2011-05-04 19:10:44 +0000 (Wed, 04 May 2011) Log Message: ----------- Autosave/load improvements and fixes. Also fixed a few bugs introduced by the new capability for companies to have more than one home base. Modified Paths: -------------- trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/PublicCompany.java trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java trunk/18xx/rails/ui/swing/ActionPerformer.java trunk/18xx/rails/ui/swing/AutoSaveLoadDialog.java trunk/18xx/rails/ui/swing/GameStatus.java trunk/18xx/rails/ui/swing/GameUIManager.java trunk/18xx/rails/ui/swing/ORUIManager.java trunk/18xx/rails/ui/swing/StatusWindow.java trunk/18xx/rails/ui/swing/elements/Caption.java trunk/18xx/rails/ui/swing/elements/CheckBoxDialog.java trunk/18xx/rails/ui/swing/elements/MessageDialog.java trunk/18xx/rails/ui/swing/elements/RadioButtonDialog.java trunk/18xx/rails/ui/swing/gamespecific/_1835/StatusWindow_1835.java trunk/18xx/rails/ui/swing/gamespecific/_1856/StatusWindow_1856.java trunk/18xx/rails/ui/swing/gamespecific/_18EU/GameStatus_18EU.java trunk/18xx/rails/ui/swing/gamespecific/_18EU/GameUIManager_18EU.java Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/game/OperatingRound.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -1958,6 +1958,8 @@ // Check if any more companies must discard trains, // otherwise continue train buying if (!checkForExcessTrains()) { + // Trains may have been discarded by other players + setCurrentPlayer (operatingCompany.get().getPresident()); stepObject.set(GameDef.OrStep.BUY_TRAIN); } Modified: trunk/18xx/rails/game/PublicCompany.java =================================================================== --- trunk/18xx/rails/game/PublicCompany.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/game/PublicCompany.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -812,8 +812,8 @@ * @param homeHex The homeHex to set. */ public void setHomeHex(MapHex homeHex) { - if (homeHexes == null) homeHexes = new ArrayList<MapHex>(1); - homeHexes.set(0, homeHex); + homeHexes = new ArrayList<MapHex>(1); + homeHexes.add(homeHex); } /** Modified: trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java =================================================================== --- trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -526,13 +526,14 @@ for (PublicCompanyI comp : mergingCompanies) { // Exchange home tokens and collect non-home tokens + List<MapHex> homeHexes = comp.getHomeHexes(); for (TokenI token :comp.getTokens()) { if (token instanceof BaseToken) { bt = (BaseToken) token; if (!bt.isPlaced()) continue; city = (City) bt.getHolder(); hex = city.getHolder(); - if (hex == comp.getHomeHexes()) { + if (homeHexes != null && homeHexes.contains(hex)) { homeTokens.add(bt); } else { nonHomeTokens.add(bt); Modified: trunk/18xx/rails/ui/swing/ActionPerformer.java =================================================================== --- trunk/18xx/rails/ui/swing/ActionPerformer.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/ui/swing/ActionPerformer.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -10,4 +10,6 @@ public boolean process(PossibleAction action); public boolean processImmediateAction(); + + //public void deactivate(); } Modified: trunk/18xx/rails/ui/swing/AutoSaveLoadDialog.java =================================================================== --- trunk/18xx/rails/ui/swing/AutoSaveLoadDialog.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/ui/swing/AutoSaveLoadDialog.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -129,7 +129,8 @@ } interval = ((Integer) intervalSpinner.getValue()).intValue(); } else if (arg0.getSource().equals(cancelButton)) { - status = -1; + //status = -1; + // Better change nothing? } this.setVisible(false); this.dispose(); Modified: trunk/18xx/rails/ui/swing/GameStatus.java =================================================================== --- trunk/18xx/rails/ui/swing/GameStatus.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/ui/swing/GameStatus.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -675,7 +675,9 @@ int index = 0; if (options.size() > 1) { if (startCompany) { - RadioButtonDialog dialog = new RadioButtonDialog (gameUIManager, + RadioButtonDialog dialog = new RadioButtonDialog ( + gameUIManager, + parent, LocalText.getText("PleaseSelect"), LocalText.getText("WHICH_START_PRICE", playerName, @@ -896,7 +898,21 @@ + (j == index ? " PD" : "")); } } + + public void highlightCurrentPlayer (int index) { + for (int j = 0; j < np; j++) { + upperPlayerCaption[j].setHighlight(j == index); + lowerPlayerCaption[j].setHighlight(j == index); + } + } + public void highlightLocalPlayer (int index) { + for (int j = 0; j < np; j++) { + upperPlayerCaption[j].setLocalPlayer(j == index); + lowerPlayerCaption[j].setLocalPlayer(j == index); + } + } + public String getSRPlayer() { if (actorIndex >= 0) return players[actorIndex].getName(); Modified: trunk/18xx/rails/ui/swing/GameUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/GameUIManager.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/ui/swing/GameUIManager.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -262,6 +262,7 @@ } else if (!wasMyTurn && isMyTurn) { autoLoadPoller.setActive(false); setCurrentDialog(new MessageDialog(this, + (JFrame) activeWindow, LocalText.getText("Message"), LocalText.getText("YourTurn", localPlayerName)), null); @@ -280,6 +281,8 @@ // and make sure that the right window is active. updateUI(); + statusWindow.initGameActions(); + if (!myTurn) return true; statusWindow.setGameActions(); statusWindow.setCorrectionMenu(); @@ -328,6 +331,7 @@ String[] message = DisplayBuffer.get(); if (message != null) { setCurrentDialog(new MessageDialog(this, + (JFrame) activeWindow, LocalText.getText("Message"), "<html>" + Util.joinWithDelimiter(message, "<br>")), null); @@ -606,6 +610,7 @@ orWindow.toFront(); CheckBoxDialog dialog = new CheckBoxDialog(this, + orWindow, LocalText.getText("ExchangeTokens"), prompt, options.toArray(new String[0])); @@ -697,7 +702,7 @@ } } - if (currentDialogAction != null) processAction(currentDialogAction); + /*if (currentDialogAction != null)*/ processAction(currentDialogAction); } Modified: trunk/18xx/rails/ui/swing/ORUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/ORUIManager.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/ui/swing/ORUIManager.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -550,6 +550,7 @@ orWindow.toFront(); CheckBoxDialog dialog = new CheckBoxDialog(this, + orWindow, LocalText.getText("DestinationsReached"), LocalText.getText("DestinationsReachedPrompt"), options.toArray(new String[0])); @@ -1226,6 +1227,7 @@ // TODO This must be split off from here, as in the future // different clients may handle the discards of each company. + /* while (possibleActions.contains(DiscardTrain.class)) { // Check if there are any forced discards; // otherwise, nothing to do here @@ -1235,6 +1237,7 @@ gameUIManager.discardTrains(dt); } + */ } int newOffBoardRevenueStep = @@ -1433,6 +1436,7 @@ } } RadioButtonDialog currentDialog = new RadioButtonDialog (gameUIManager, + orWindow, LocalText.getText("Select"), LocalText.getText("SelectLoansToRepay", action.getCompanyName()), options, Modified: trunk/18xx/rails/ui/swing/StatusWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/StatusWindow.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/ui/swing/StatusWindow.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -349,7 +349,7 @@ ws.set(frame); } - public void setGameActions() { + public void initGameActions() { // Check the local Undo/Redo menu items, // which must always be up-to-date. @@ -358,7 +358,9 @@ redoItem.setEnabled(false); redoItem2.setEnabled(false); // SAVE, RELOAD, AUTOSAVELOAD are always enabled + } + public void setGameActions() { List<GameAction> gameActions = possibleActions.getType(GameAction.class); if (gameActions != null) { Modified: trunk/18xx/rails/ui/swing/elements/Caption.java =================================================================== --- trunk/18xx/rails/ui/swing/elements/Caption.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/ui/swing/elements/Caption.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -2,6 +2,7 @@ package rails.ui.swing.elements; import java.awt.Color; +import java.awt.Font; import javax.swing.BorderFactory; import javax.swing.JLabel; @@ -13,19 +14,28 @@ private Border labelBorder = BorderFactory.createEmptyBorder(1, 2, 1, 2); - private static final Color NORMAL_BG_COLOR = new Color(240, 240, 240); + private static final Color NORMAL_BG_COLOUR = new Color(240, 240, 240); private static final Color HIGHLIGHT_BG_COLOUR = new Color(255, 255, 80); + + private static final Color NORMAL_FG_COLOUR = new Color (0, 0, 0); + + private static final Color LOCAL_PLAYER_COLOUR = new Color (255, 0, 0); public Caption(String text) { super(text); - this.setBackground(NORMAL_BG_COLOR); + this.setForeground(NORMAL_FG_COLOUR); + this.setBackground(NORMAL_BG_COLOUR); this.setHorizontalAlignment(SwingConstants.CENTER); this.setBorder(labelBorder); this.setOpaque(true); } public void setHighlight(boolean highlight) { - this.setBackground(highlight ? HIGHLIGHT_BG_COLOUR : NORMAL_BG_COLOR); + this.setBackground(highlight ? HIGHLIGHT_BG_COLOUR : NORMAL_BG_COLOUR); } + + public void setLocalPlayer (boolean highlight) { + this.setForeground(highlight ? LOCAL_PLAYER_COLOUR : NORMAL_FG_COLOUR); + } } Modified: trunk/18xx/rails/ui/swing/elements/CheckBoxDialog.java =================================================================== --- trunk/18xx/rails/ui/swing/elements/CheckBoxDialog.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/ui/swing/elements/CheckBoxDialog.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -35,12 +35,12 @@ protected static Logger log = Logger.getLogger(CheckBoxDialog.class.getPackage().getName()); - public CheckBoxDialog(DialogOwner owner, String title, String message, + public CheckBoxDialog(DialogOwner owner, JFrame window, String title, String message, String[] options) { - this (owner, title, message, options, null, false); + this (owner, window, title, message, options, null, false); } - public CheckBoxDialog(DialogOwner owner, String title, String message, + public CheckBoxDialog(DialogOwner owner, JFrame window, String title, String message, String[] options, boolean[] selectedOptions, boolean addCancelButton) { super((Frame) null, title, false); // Non-modal this.owner = owner; @@ -58,16 +58,10 @@ pack(); // Center on owner - /* - int x = - (int) owner.getLocationOnScreen().getX() - + (owner.getWidth() - getWidth()) / 2; - int y = - (int) owner.getLocationOnScreen().getY() - + (owner.getHeight() - getHeight()) / 2; - */ - int x = 400; - int y = 400; + int x = (int) window.getLocationOnScreen().getX() + + (window.getWidth() - getWidth()) / 2; + int y = (int) window.getLocationOnScreen().getY() + + (window.getHeight() - getHeight()) / 2; setLocation(x, y); setVisible(true); Modified: trunk/18xx/rails/ui/swing/elements/MessageDialog.java =================================================================== --- trunk/18xx/rails/ui/swing/elements/MessageDialog.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/ui/swing/elements/MessageDialog.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -28,7 +28,7 @@ protected static Logger log = Logger.getLogger(MessageDialog.class.getPackage().getName()); - public MessageDialog(DialogOwner owner, String title, String message) { + public MessageDialog(DialogOwner owner, JFrame window, String title, String message) { super((Frame) null, title, false); // Non-modal this.owner = owner; @@ -37,12 +37,15 @@ initialize(); pack(); - int x = 400; - int y = 400; + // Center on window + int x = (int) window.getLocationOnScreen().getX() + + (window.getWidth() - getWidth()) / 2; + int y = (int) window.getLocationOnScreen().getY() + + (window.getHeight() - getHeight()) / 2; setLocation(x, y); setVisible(true); - setAlwaysOnTop(true); + toFront(); } private void initialize() { Modified: trunk/18xx/rails/ui/swing/elements/RadioButtonDialog.java =================================================================== --- trunk/18xx/rails/ui/swing/elements/RadioButtonDialog.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/ui/swing/elements/RadioButtonDialog.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -33,7 +33,7 @@ protected static Logger log = Logger.getLogger(RadioButtonDialog.class.getPackage().getName()); - public RadioButtonDialog(DialogOwner owner, String title, String message, + public RadioButtonDialog(DialogOwner owner, JFrame window, String title, String message, String[] options, int selectedOption) { super((Frame) null, title, false); // Non-modal this.owner = owner; @@ -45,17 +45,11 @@ initialize(); pack(); - // Center on owner - /* - int x = - (int) owner.getLocationOnScreen().getX() - + (owner.getWidth() - getWidth()) / 2; - int y = - (int) owner.getLocationOnScreen().getY() - + (owner.getHeight() - getHeight()) / 2; - */ - int x = 400; - int y = 400; + // Center on window + int x = (int) window.getLocationOnScreen().getX() + + (window.getWidth() - getWidth()) / 2; + int y = (int) window.getLocationOnScreen().getY() + + (window.getHeight() - getHeight()) / 2; setLocation(x, y); setVisible(true); Modified: trunk/18xx/rails/ui/swing/gamespecific/_1835/StatusWindow_1835.java =================================================================== --- trunk/18xx/rails/ui/swing/gamespecific/_1835/StatusWindow_1835.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/ui/swing/gamespecific/_1835/StatusWindow_1835.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -89,6 +89,7 @@ ); } currentDialog = new CheckBoxDialog (gameUIManager, + this, LocalText.getText("Select"), LocalText.getText("SelectCompaniesToFold", getCurrentPlayer().getName(), Modified: trunk/18xx/rails/ui/swing/gamespecific/_1856/StatusWindow_1856.java =================================================================== --- trunk/18xx/rails/ui/swing/gamespecific/_1856/StatusWindow_1856.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/ui/swing/gamespecific/_1856/StatusWindow_1856.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -98,6 +98,7 @@ } RadioButtonDialog currentDialog = new RadioButtonDialog (gameUIManager, + this, LocalText.getText("1856MergerDialog", action.getCompanyName()), message, options, Modified: trunk/18xx/rails/ui/swing/gamespecific/_18EU/GameStatus_18EU.java =================================================================== --- trunk/18xx/rails/ui/swing/gamespecific/_18EU/GameStatus_18EU.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/ui/swing/gamespecific/_18EU/GameStatus_18EU.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -70,6 +70,7 @@ } RadioButtonDialog dialog = new RadioButtonDialog (gameUIManager, + parent, LocalText.getText("PleaseSelect"), LocalText.getText("SelectCompanyToMergeMinorInto", minor.getName()), Modified: trunk/18xx/rails/ui/swing/gamespecific/_18EU/GameUIManager_18EU.java =================================================================== --- trunk/18xx/rails/ui/swing/gamespecific/_18EU/GameUIManager_18EU.java 2011-05-04 19:10:09 UTC (rev 1543) +++ trunk/18xx/rails/ui/swing/gamespecific/_18EU/GameUIManager_18EU.java 2011-05-04 19:10:44 UTC (rev 1544) @@ -73,6 +73,7 @@ + minor.getLongName(); } dialog = new RadioButtonDialog (this, + statusWindow, LocalText.getText("PleaseSelect"), LocalText.getText( "SelectMinorToMerge", @@ -90,6 +91,7 @@ options[i] = cities.get(i).toString(); } dialog = new RadioButtonDialog (this, + statusWindow, LocalText.getText("PleaseSelect"), LocalText.getText( "SelectHomeStation", This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2011-05-21 10:40:50
|
Revision: 1563 http://rails.svn.sourceforge.net/rails/?rev=1563&view=rev Author: evos Date: 2011-05-21 10:40:43 +0000 (Sat, 21 May 2011) Log Message: ----------- Added some Javadoc to Tile.java. Added 'quantityIncrement' attribute to <Tile>. Not used yet, but may be useful for 1825 kits. Integer values may now be prefixed with a '+' sign (which is stripped before parsing by Java). May be helpful with increment values. Modified Paths: -------------- trunk/18xx/rails/game/MapHex.java trunk/18xx/rails/game/Tile.java trunk/18xx/rails/game/TileI.java trunk/18xx/rails/util/Tag.java Modified: trunk/18xx/rails/game/MapHex.java =================================================================== --- trunk/18xx/rails/game/MapHex.java 2011-05-19 12:13:55 UTC (rev 1562) +++ trunk/18xx/rails/game/MapHex.java 2011-05-21 10:40:43 UTC (rev 1563) @@ -804,7 +804,7 @@ + "/" + currentTileRotation + " by " + newTile.getId() + "/" + newTileOrientation); - newTile.lay(this); + newTile.add(this); currentTile = newTile; currentTileRotation = newTileOrientation; Modified: trunk/18xx/rails/game/Tile.java =================================================================== --- trunk/18xx/rails/game/Tile.java 2011-05-19 12:13:55 UTC (rev 1562) +++ trunk/18xx/rails/game/Tile.java 2011-05-21 10:40:43 UTC (rev 1563) @@ -10,6 +10,12 @@ import rails.util.LocalText; import rails.util.Tag; +/** Represents a certain tile <i>type</i>, identified by its id (tile number). + * <p> For each tile number, only one tile object is created. + * The list <b>tilesLaid</b> records in which hexes a certain tile number has been laid. + * @author Erik + * + */ public class Tile extends ModelObject implements TileI, StationHolder, Comparable<TileI> { /** The 'internal id', identifying the tile in the XML files */ @@ -82,6 +88,10 @@ protected static final int TILE_NUMBER_OFFSET = 2; + /** Records in which hexes a certain tile number has been laid. + * The length of this list indicates the number of tiles laid on the map board. + * <p>As this list is not a State object, it must only be updated via the TileMove execute() and undo() methods. + */ private final ArrayList<MapHex> tilesLaid = new ArrayList<MapHex>(); /** Storage of revenueBonus that are bound to the tile */ @@ -204,12 +214,18 @@ externalId = setTag.getAttributeAsString("extId", externalId); /* Picture id */ pictureId = setTag.getAttributeAsInteger("pic", pictureId); + /* Quantity */ quantity = setTag.getAttributeAsInteger("quantity", 0); /* Value '99' and '-1' mean 'unlimited' */ unlimited = (quantity == 99 || quantity == UNLIMITED_TILES || "yes".equalsIgnoreCase(setTag.getGameOptions().get("UnlimitedTiles"))); - if (unlimited) quantity = UNLIMITED_TILES; + if (unlimited) { + quantity = UNLIMITED_TILES; + } else { + quantity += setTag.getAttributeAsInteger("quantityIncrement", 0); + } + /* Multiple base tokens of one company allowed */ allowsMultipleBasesOfOneCompany = setTag.hasChild( "AllowsMultipleBasesOfOneCompany"); @@ -467,16 +483,17 @@ return relayBaseTokensOnUpgrade; } - public boolean lay(MapHex hex) { - + /** Register a tile of this type being laid on the map. + * This method may only be called via the TileMove execute() and undo() methods. */ + public boolean add(MapHex hex) { tilesLaid.add(hex); update(); - return true; } + /** Register a tile of this type being removed from the map. + * This method may only be called via the TileMove execute() and undo() methods. */ public boolean remove(MapHex hex) { - tilesLaid.remove(hex); update(); return true; @@ -498,6 +515,7 @@ return "#" + externalId + ": " + count; } + // NOT USED public int getQuantity() { return quantity; } Modified: trunk/18xx/rails/game/TileI.java =================================================================== --- trunk/18xx/rails/game/TileI.java 2011-05-19 12:13:55 UTC (rev 1562) +++ trunk/18xx/rails/game/TileI.java 2011-05-21 10:40:43 UTC (rev 1563) @@ -62,7 +62,7 @@ public int getNumStations(); - public boolean lay(MapHex hex); + public boolean add(MapHex hex); public boolean remove(MapHex hex); Modified: trunk/18xx/rails/util/Tag.java =================================================================== --- trunk/18xx/rails/util/Tag.java 2011-05-19 12:13:55 UTC (rev 1562) +++ trunk/18xx/rails/util/Tag.java 2011-05-21 10:40:43 UTC (rev 1563) @@ -141,6 +141,8 @@ String value = attributes.get(name); if (value == null) return defaultValue; try { + // Unlike Java, we want to allow '+' signs + if (value.startsWith("+")) value = value.substring(1); return Integer.parseInt(value); } catch (Exception e) { throw new ConfigurationException("Invalid integer value: " + value, @@ -168,11 +170,11 @@ } } -public int getAttributeAsInteger(String name) throws ConfigurationException { + public int getAttributeAsInteger(String name) throws ConfigurationException { + + return getAttributeAsInteger(name, 0); + } -return getAttributeAsInteger(name, 0); -} - public int[] getAttributeAsIntegerArray(String name, int[] defaultArray) throws ConfigurationException { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2011-06-18 21:11:52
|
Revision: 1579 http://rails.svn.sourceforge.net/rails/?rev=1579&view=rev Author: evos Date: 2011-06-18 21:11:45 +0000 (Sat, 18 Jun 2011) Log Message: ----------- Train management refactoring I Modified Paths: -------------- trunk/18xx/rails/algorithms/RevenueAdapter.java trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/Portfolio.java trunk/18xx/rails/game/Train.java trunk/18xx/rails/game/TrainI.java trunk/18xx/rails/game/TrainManager.java trunk/18xx/rails/game/TrainType.java trunk/18xx/rails/game/TrainTypeI.java trunk/18xx/rails/game/specific/_18AL/NameableTrain.java trunk/18xx/rails/util/ListAndFixSavedFiles.java Modified: trunk/18xx/rails/algorithms/RevenueAdapter.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueAdapter.java 2011-06-16 10:58:29 UTC (rev 1578) +++ trunk/18xx/rails/algorithms/RevenueAdapter.java 2011-06-18 21:11:45 UTC (rev 1579) @@ -175,7 +175,7 @@ TrainTypeI trainType = gameManager.getTrainManager().getTypeByName(trainString.trim()); if (trainType != null) { // string defines available trainType log.info("RA: found trainType" + trainType); - TrainI railsTrain = trainType.cloneTrain(); + TrainI railsTrain = gameManager.getTrainManager().cloneTrain(trainType); return addTrain(railsTrain); } else { // otherwise interpret the train NetworkTrain train = NetworkTrain.createFromString(trainString); Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2011-06-16 10:58:29 UTC (rev 1578) +++ trunk/18xx/rails/game/OperatingRound.java 2011-06-18 21:11:45 UTC (rev 1579) @@ -1840,8 +1840,8 @@ train.getType().addToBoughtFromIPO(); trainManager.setAnyTrainBought(true); // Clone the train if infinitely available - if (train.getType().hasInfiniteAmount()) { - ipo.addTrain(train.getType().cloneTrain()); + if (train.getType().hasInfiniteQuantity()) { + ipo.addTrain(trainManager.cloneTrain(train.getType())); } } @@ -1855,15 +1855,14 @@ } // Check if the phase has changed. - TrainManager tm = gameManager.getTrainManager(); - tm.checkTrainAvailability(train, oldHolder); + trainManager.checkTrainAvailability(train, oldHolder); // Check if any companies must discard trains if (getCurrentPhase() != previousPhase && checkForExcessTrains()) { stepObject.set(GameDef.OrStep.DISCARD_TRAINS); } - if (tm.hasPhaseChanged()) newPhaseChecks(); + if (trainManager.hasPhaseChanged()) newPhaseChecks(); return true; } @@ -2896,7 +2895,7 @@ if (getGameParameterAsBoolean(GameDef.Parm.REMOVE_TRAIN_BEFORE_SR) && trainManager.isAnyTrainBought()) { TrainI train = trainManager.getAvailableNewTrains().get(0); - if (train.getType().hasInfiniteAmount()) return; + if (train.getType().hasInfiniteQuantity()) return; new ObjectMove (train, ipo, scrapHeap); ReportBuffer.add(LocalText.getText("RemoveTrain", train.getName())); } Modified: trunk/18xx/rails/game/Portfolio.java =================================================================== --- trunk/18xx/rails/game/Portfolio.java 2011-06-16 10:58:29 UTC (rev 1578) +++ trunk/18xx/rails/game/Portfolio.java 2011-06-18 21:11:45 UTC (rev 1579) @@ -490,7 +490,7 @@ if (trainsOfType != null && !trainsOfType.isEmpty()) { if (b.length() > 0) b.append(" "); b.append(type.getName()).append("("); - if (type.hasInfiniteAmount()) { + if (type.hasInfiniteQuantity()) { b.append("+"); } else { b.append(trainsOfType.size()); Modified: trunk/18xx/rails/game/Train.java =================================================================== --- trunk/18xx/rails/game/Train.java 2011-06-16 10:58:29 UTC (rev 1578) +++ trunk/18xx/rails/game/Train.java 2011-06-18 21:11:45 UTC (rev 1579) @@ -11,13 +11,6 @@ protected TrainTypeI type; - protected int majorStops; - protected int minorStops; - protected int cost; - protected int cityScoreFactor; - protected int townScoreFactor; - protected int townCountIndicator; - /** Some specific trains cannot be traded between companies */ protected boolean tradeable = true; @@ -31,19 +24,11 @@ public Train() {} - public void init(TrainTypeI type, int index) { + public void init(TrainTypeI type, String uniqueId) { this.type = type; - this.majorStops = type.getMajorStops(); - this.minorStops = type.getMinorStops(); - this.cost = type.getCost(); - this.cityScoreFactor = type.getCityScoreFactor(); - this.townScoreFactor = type.getTownScoreFactor(); - this.townCountIndicator = type.getTownCountIndicator(); + this.uniqueId = uniqueId; - uniqueId = type.getName() + "_" + index; - type.getTrainManager().addTrain(uniqueId, this); - obsolete = new BooleanState(uniqueId, false); } @@ -55,42 +40,42 @@ * @return Returns the cityScoreFactor. */ public int getCityScoreFactor() { - return cityScoreFactor; + return type.getCityScoreFactor(); } /** * @return Returns the cost. */ public int getCost() { - return cost; + return type.getCost(); } /** * @return Returns the majorStops. */ public int getMajorStops() { - return majorStops; + return type.getMajorStops(); } /** * @return Returns the minorStops. */ public int getMinorStops() { - return minorStops; + return type.getMinorStops(); } /** * @return Returns the townCountIndicator. */ public int getTownCountIndicator() { - return townCountIndicator; + return type.getTownCountIndicator(); } /** * @return Returns the townScoreFactor. */ public int getTownScoreFactor() { - return townScoreFactor; + return type.getTownScoreFactor(); } /** Modified: trunk/18xx/rails/game/TrainI.java =================================================================== --- trunk/18xx/rails/game/TrainI.java 2011-06-16 10:58:29 UTC (rev 1578) +++ trunk/18xx/rails/game/TrainI.java 2011-06-18 21:11:45 UTC (rev 1579) @@ -5,7 +5,7 @@ public interface TrainI extends Moveable { - public void init(TrainTypeI type, int index); + public void init(TrainTypeI type, String uniqueId); /** * @return Returns the cost. Modified: trunk/18xx/rails/game/TrainManager.java =================================================================== --- trunk/18xx/rails/game/TrainManager.java 2011-06-16 10:58:29 UTC (rev 1578) +++ trunk/18xx/rails/game/TrainManager.java 2011-06-18 21:11:45 UTC (rev 1579) @@ -3,6 +3,8 @@ import java.util.*; +import org.apache.log4j.Logger; + import rails.game.state.BooleanState; import rails.game.state.IntegerState; import rails.util.LocalText; @@ -18,6 +20,8 @@ protected Map<String, TrainI> trainMap = new HashMap<String, TrainI>(); + protected Map<TrainTypeI, List<TrainI>> trainsPerType = new HashMap<TrainTypeI, List<TrainI>>(); + private boolean removeTrain = false; @@ -25,6 +29,8 @@ protected Portfolio unavailable = null; protected IntegerState newTypeIndex; + + protected Map<TrainTypeI, Integer> lastIndexPerType = new HashMap<TrainTypeI, Integer>(); protected boolean trainsHaveRusted = false; protected boolean phaseHasChanged = false; @@ -45,6 +51,9 @@ // For initialisation only boolean trainPriceAtFaceValueIfDifferentPresidents = false; + protected static Logger log = + Logger.getLogger(TrainManager.class.getPackage().getName()); + /** * No-args constructor. */ @@ -129,6 +138,19 @@ for (TrainTypeI type : lTrainTypes) { type.finishConfiguration(gameManager); + + // Now create the trains of this type + TrainI train; + /* If the amount is infinite, only one trains is created. + * Each time this train is bought, another one is created. + */ + for (int i = 0; i < (type.hasInfiniteQuantity() ? 1 : type.getQuantity()); i++) { + train = type.createTrain (); + train.init(type, getNewUniqueId(type)); + addTrain(train); + unavailable.addTrain(train); + } + } // By default, set the first train type to "available". @@ -145,14 +167,47 @@ trainPriceAtFaceValueIfDifferentPresidents); } - public void addTrain (String uniqueID, TrainI train) { - trainMap.put(uniqueID, train); + /** Create train without throwing exceptions. + * To be used <b>after</b> completing initialization, + * i.e. in cloning infinitely available trains. + */ + + public TrainI cloneTrain (TrainTypeI type) { + TrainI train = null; + try { + train = type.createTrain(); + } catch (ConfigurationException e) { + log.warn("Unexpected exception", e); + } + train.init(type, getNewUniqueId(type)); + addTrain(train); + return train; } + public void addTrain (TrainI train) { + trainMap.put(train.getUniqueId(), train); + + TrainTypeI type = train.getType(); + if (!trainsPerType.containsKey(type)) { + trainsPerType.put (type, new ArrayList<TrainI>()); + } + trainsPerType.get(type).add(train); + } + public TrainI getTrainByUniqueId(String id) { return trainMap.get(id); } + + public String getNewUniqueId (TrainTypeI type) { + int newIndex = lastIndexPerType.containsKey(type) ? lastIndexPerType.get(type) + 1 : 0; + lastIndexPerType.put (type, newIndex); + return type.getName() + "_"+ newIndex; + } + public List<TrainI> getTrainsOfType (TrainTypeI type) { + return trainsPerType.get(type); + } + /** * This method handles any consequences of new train buying (from the IPO), * such as rusting and phase changes. It must be called <b>after</b> the Modified: trunk/18xx/rails/game/TrainType.java =================================================================== --- trunk/18xx/rails/game/TrainType.java 2011-06-16 10:58:29 UTC (rev 1578) +++ trunk/18xx/rails/game/TrainType.java 2011-06-18 21:11:45 UTC (rev 1579) @@ -21,11 +21,8 @@ protected String name; protected int quantity; - protected boolean infiniteAmount = false; + protected boolean infiniteQuantity = false; - /** Index: used for sorting trains lists in configured order. */ - protected int index; - private String reachBasis = "stops"; protected boolean countHexes = false; @@ -62,8 +59,6 @@ private String releasedTrainTypeNames = null; protected List<TrainTypeI> releasedTrainTypes = null; - protected ArrayList<TrainI> trains = null; - protected int lastIndex = 0; protected BooleanState available; @@ -98,8 +93,6 @@ } if (real) { - trains = new ArrayList<TrainI>(); - // Name name = tag.getAttributeAsString("name"); if (name == null) { @@ -117,7 +110,7 @@ // Amount quantity = tag.getAttributeAsInteger("quantity"); if (quantity == -1) { - infiniteAmount = true; + infiniteQuantity = true; } else if (quantity <= 0) { throw new ConfigurationException( LocalText.getText("InvalidQuantity", String.valueOf(quantity))); @@ -210,27 +203,10 @@ townCountIndicator = countTowns.equals("no") ? NO_TOWN_COUNT : minorStops > 0 ? TOWN_COUNT_MINOR : TOWN_COUNT_MAJOR; - cityScoreFactor = scoreCities.equals("double") ? 2 : 1; - townScoreFactor = scoreTowns.equals("yes") ? 1 : 0; - // Actually we should meticulously check all values.... + cityScoreFactor = scoreCities.equals("double") ? 2 : 1; + townScoreFactor = scoreTowns.equals("yes") ? 1 : 0; + // Actually we should meticulously check all values.... - // log.debug("Train type "+name+": class "+trainClassName); - - // Now create the trains of this type - TrainI train; - if (infiniteAmount) { - /* - * We create one train, but will add one more each time a train - * of this type is bought. - */ - train = createTrain(); - trains.add(train); - } else { - for (int i = 0; i < quantity; i++) { - train = createTrain (); - trains.add(train); - } - } } // Final initialisations @@ -242,18 +218,10 @@ public void finishConfiguration (GameManagerI gameManager) { trainManager = gameManager.getTrainManager(); - index = trainManager.getTrainTypes().indexOf(this); + } - Portfolio unavailable = gameManager.getBank().getUnavailable(); + public TrainI createTrain () throws ConfigurationException { - for (TrainI train : trains) { - train.init(this, lastIndex++); - unavailable.addTrain(train); - } - } - - protected TrainI createTrain () throws ConfigurationException { - TrainI train; try { train = trainClass.newInstance(); @@ -268,20 +236,12 @@ return train; } - /** Create train without throwing exceptions. - * To be used <b>after</b> completing initialization, - * i.e. in cloning infinitely available trains. - */ + public int getQuantity() { + return quantity; + } - public TrainI cloneTrain () { - TrainI train = null; - try { - train = createTrain(); - } catch (ConfigurationException e) { - log.warn("Unexpected exception", e); - } - train.init(this, lastIndex++); - return train; + public boolean hasInfiniteQuantity() { + return infiniteQuantity; } /** @@ -444,18 +404,14 @@ (initialPortfolio.equalsIgnoreCase("Pool") ? bank.getPool() : bank.getIpo()); - for (TrainI train : trains) { + for (TrainI train : trainManager.getTrainsOfType(this)) { new ObjectMove(train, bank.getUnavailable(), to); } } - public boolean hasInfiniteAmount() { - return infiniteAmount; - } - public void setRusted(Portfolio lastBuyingCompany) { rusted.set(true); - for (TrainI train : trains) { + for (TrainI train : trainManager.getTrainsOfType(this)) { Portfolio holder = train.getHolder(); if (obsoleting && holder.getOwner() instanceof PublicCompanyI && holder != lastBuyingCompany) { @@ -490,10 +446,6 @@ return clone; } - public int getIndex() { - return index; - } - public TrainManager getTrainManager() { return trainManager; } Modified: trunk/18xx/rails/game/TrainTypeI.java =================================================================== --- trunk/18xx/rails/game/TrainTypeI.java 2011-06-16 10:58:29 UTC (rev 1578) +++ trunk/18xx/rails/game/TrainTypeI.java 2011-06-18 21:11:45 UTC (rev 1579) @@ -7,6 +7,11 @@ public interface TrainTypeI extends ConfigurableComponentI, Cloneable { + public TrainI createTrain () throws ConfigurationException; + + public int getQuantity(); + public boolean hasInfiniteQuantity(); + /** * @return Returns the cityScoreFactor. */ @@ -83,8 +88,6 @@ public boolean isObsoleting(); - public boolean hasInfiniteAmount(); - /** * @param available The available to set. */ @@ -106,10 +109,6 @@ public void setRustedTrainType(int index, TrainTypeI rustedTrainType); - public TrainI cloneTrain(); - - public int getIndex(); - public TrainManager getTrainManager(); public String getInfo(); Modified: trunk/18xx/rails/game/specific/_18AL/NameableTrain.java =================================================================== --- trunk/18xx/rails/game/specific/_18AL/NameableTrain.java 2011-06-16 10:58:29 UTC (rev 1578) +++ trunk/18xx/rails/game/specific/_18AL/NameableTrain.java 2011-06-18 21:11:45 UTC (rev 1579) @@ -12,9 +12,9 @@ private State nameToken; @Override - public void init(TrainTypeI type, int index) { + public void init(TrainTypeI type, String uniqueId) { - super.init(type, index); + super.init(type, uniqueId); nameToken = new State(uniqueId + "_nameToken", NamedTrainToken.class); } Modified: trunk/18xx/rails/util/ListAndFixSavedFiles.java =================================================================== --- trunk/18xx/rails/util/ListAndFixSavedFiles.java 2011-06-16 10:58:29 UTC (rev 1578) +++ trunk/18xx/rails/util/ListAndFixSavedFiles.java 2011-06-18 21:11:45 UTC (rev 1579) @@ -229,6 +229,9 @@ action = (PossibleAction) ois.readObject(); } catch (EOFException e) { break; + } catch (ClassCastException e) { + log.error ("Aborting on non-action object: "+ e.getMessage()); + break; } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wak...@us...> - 2011-07-04 22:27:26
|
Revision: 1602 http://rails.svn.sourceforge.net/rails/?rev=1602&view=rev Author: wakko666 Date: 2011-07-04 22:27:18 +0000 (Mon, 04 Jul 2011) Log Message: ----------- - Move ComponentManager to rails.common.parser. - Refactor ComponentManager to be less of a static singleton. - Move DisplayBuffer from rails.game to rails.common. Modified Paths: -------------- trunk/18xx/rails/algorithms/RevenueBonusTemplate.java trunk/18xx/rails/algorithms/RevenueManager.java trunk/18xx/rails/common/parser/GameInfoParser.java trunk/18xx/rails/common/parser/XMLTags.java trunk/18xx/rails/game/Bank.java trunk/18xx/rails/game/BonusToken.java trunk/18xx/rails/game/Company.java trunk/18xx/rails/game/CompanyI.java trunk/18xx/rails/game/CompanyManager.java trunk/18xx/rails/game/CompanyManagerI.java trunk/18xx/rails/game/CompanyType.java trunk/18xx/rails/game/CompanyTypeI.java trunk/18xx/rails/game/Game.java trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/GameManagerI.java trunk/18xx/rails/game/MapHex.java trunk/18xx/rails/game/MapManager.java trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/PhaseI.java trunk/18xx/rails/game/PhaseManager.java trunk/18xx/rails/game/PlayerManager.java trunk/18xx/rails/game/PrivateCompany.java trunk/18xx/rails/game/Round.java trunk/18xx/rails/game/ShareSellingRound.java trunk/18xx/rails/game/StartRound.java trunk/18xx/rails/game/StartRound_1830.java trunk/18xx/rails/game/StartRound_1835.java trunk/18xx/rails/game/StockMarket.java trunk/18xx/rails/game/StockMarketI.java trunk/18xx/rails/game/StockRound.java trunk/18xx/rails/game/TileManager.java trunk/18xx/rails/game/Token.java trunk/18xx/rails/game/TrainManager.java trunk/18xx/rails/game/TrainType.java trunk/18xx/rails/game/TreasuryShareRound.java trunk/18xx/rails/game/correct/CashCorrectionManager.java trunk/18xx/rails/game/correct/CorrectionManager.java trunk/18xx/rails/game/correct/MapCorrectionManager.java trunk/18xx/rails/game/special/SpecialProperty.java trunk/18xx/rails/game/special/SpecialPropertyI.java trunk/18xx/rails/game/specific/_1825/StartRound_1825.java trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java trunk/18xx/rails/game/specific/_1835/PrussianFormationRound.java trunk/18xx/rails/game/specific/_1851/StartRound_1851.java trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java trunk/18xx/rails/game/specific/_1856/OperatingRound_1856.java trunk/18xx/rails/game/specific/_1856/StockRound_1856.java trunk/18xx/rails/game/specific/_1880/StartRound_1880.java trunk/18xx/rails/game/specific/_1889/OperatingRound_1889.java trunk/18xx/rails/game/specific/_18AL/NamedTrainRevenueModifier.java trunk/18xx/rails/game/specific/_18AL/NamedTrainToken.java trunk/18xx/rails/game/specific/_18EU/StartRound_18EU.java trunk/18xx/rails/game/specific/_18EU/StockRound_18EU.java trunk/18xx/rails/game/specific/_18Kaas/RuhrRevenueModifier.java trunk/18xx/rails/ui/swing/GameSetupWindow.java trunk/18xx/rails/ui/swing/GameUIManager.java trunk/18xx/rails/ui/swing/gamespecific/_1856/StatusWindow_1856.java trunk/18xx/rails/util/ListAndFixSavedFiles.java Added Paths: ----------- trunk/18xx/rails/common/DisplayBuffer.java trunk/18xx/rails/common/parser/ComponentManager.java trunk/18xx/rails/common/parser/ConfigurableComponentI.java trunk/18xx/rails/common/parser/GameFileParser.java Removed Paths: ------------- trunk/18xx/rails/game/ComponentManager.java trunk/18xx/rails/game/ConfigurableComponentI.java trunk/18xx/rails/game/DisplayBuffer.java Modified: trunk/18xx/rails/algorithms/RevenueBonusTemplate.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueBonusTemplate.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/algorithms/RevenueBonusTemplate.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -5,9 +5,9 @@ import org.apache.log4j.Logger; +import rails.common.parser.ConfigurableComponentI; import rails.common.parser.ConfigurationException; import rails.common.parser.Tag; -import rails.game.ConfigurableComponentI; import rails.game.GameManagerI; import rails.game.MapHex; import rails.game.PhaseI; Modified: trunk/18xx/rails/algorithms/RevenueManager.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueManager.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/algorithms/RevenueManager.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -8,9 +8,9 @@ import rails.common.LocalText; +import rails.common.parser.ConfigurableComponentI; import rails.common.parser.ConfigurationException; import rails.common.parser.Tag; -import rails.game.ConfigurableComponentI; import rails.game.GameManagerI; import rails.game.state.ArrayListState; Copied: trunk/18xx/rails/common/DisplayBuffer.java (from rev 1601, trunk/18xx/rails/game/DisplayBuffer.java) =================================================================== --- trunk/18xx/rails/common/DisplayBuffer.java (rev 0) +++ trunk/18xx/rails/common/DisplayBuffer.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -0,0 +1,118 @@ +/* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/DisplayBuffer.java,v 1.9 2010/01/31 22:22:28 macfreek Exp $ */ +package rails.common; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +import rails.game.GameManager; +import rails.game.GameManagerI; +import rails.util.Util; + +/** + * Class to write a log, and also to maintain a log message stack for writing to + * the UI. + */ +public final class DisplayBuffer { + + /** List to catch messages before the buffer is instantiated, + * based on the supposition that never 2 games will be initialised simultaneously... + */ + protected static List<String> initialQueue = new ArrayList<String>(); + + protected static Logger log = + Logger.getLogger(DisplayBuffer.class.getPackage().getName()); + + public DisplayBuffer() { + if (!initialQueue.isEmpty()) { + for (String s : initialQueue) { + addMessage (s, true); + } + initialQueue.clear(); + } + } + + /** + * A buffer for displaying messages in a popup window after any user action. + * These include error messages and other notifications of immediate + * interest to players. + */ + private List<String> displayBuffer = new ArrayList<String>(); + + private boolean autoDisplay = true; + + /** + * Add a message to the message (display) buffer (and display it on the + * console) + */ + public static void add(String message) { + add (message, true); + } + + public static void add(String message, boolean autoDisplay) { + GameManagerI gm = GameManager.getInstance(); + DisplayBuffer instance = null; + if (gm != null) instance = gm.getDisplayBuffer(); + if (gm == null || instance == null) { + // Queue in a static buffer until the instance is created + initialQueue.add(message); + } else { + instance.addMessage(message, autoDisplay); + } + } + + private void addMessage (String message, boolean autoDisplay) { + DisplayBuffer instance = getInstance(); + instance.autoDisplay = autoDisplay; + if (Util.hasValue(message)) { + instance.displayBuffer.add(message); + /* Also log the message (don't remove this, + * otherwise the message will not be logged during a reload, + * which may hinder troubleshooting) */ + log.debug("To display: " + message); + } + } + + private static DisplayBuffer getInstance() { + GameManagerI gm = GameManager.getInstance(); + if (gm == null) { + return null; + } else { + return gm.getDisplayBuffer(); + } + } + + /** Get the current message buffer, and clear it */ + public static String[] get() { + DisplayBuffer instance = getInstance(); + if (instance == null) { + if (initialQueue.isEmpty()) { + return null; + } else { + String[] message = initialQueue.toArray(new String[0]); + initialQueue.clear(); + return message; + } + } else if (instance.displayBuffer.size() > 0) { + String[] message = instance.displayBuffer.toArray(new String[0]); + instance.displayBuffer.clear(); + return message; + } else { + return null; + } + } + + public static int getSize() { + return getInstance().displayBuffer.size(); + } + + public static boolean getAutoDisplay () { + return getInstance().autoDisplay; + } + + public static void clear() { + getInstance().displayBuffer.clear(); + } + +} Copied: trunk/18xx/rails/common/parser/ComponentManager.java (from rev 1601, trunk/18xx/rails/game/ComponentManager.java) =================================================================== --- trunk/18xx/rails/common/parser/ComponentManager.java (rev 0) +++ trunk/18xx/rails/common/parser/ComponentManager.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -0,0 +1,115 @@ +/* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/ComponentManager.java,v 1.19 2010/05/18 04:12:23 stefanfrey Exp $ */ +package rails.common.parser; + +import java.lang.reflect.Constructor; +import java.util.*; + +import org.apache.log4j.Logger; + +import rails.common.LocalText; +import rails.common.parser.XMLTags; + +/** + * ComponentManage - an implementation of ComponentManagerI, which handles the + * creation and configuration of rails.game components, and acts as a discovery + * point for other components to find them. + */ +public class ComponentManager { + + private String gameName; + + private List<Tag> componentTags; + + protected Logger log = Logger.getLogger(ComponentManager.class.getPackage().getName()); + protected List<String> directories = new ArrayList<String>(); + + public ComponentManager(String gameName, Tag tag, Map<String, String> gameOptions) + throws ConfigurationException { + this.gameName = gameName; + + componentTags = tag.getChildren(XMLTags.COMPONENT_ELEMENT_ID); + for (Tag component : componentTags) { + String compName = component.getAttributeAsString("name"); + log.debug("Found component " + compName); + configureComponent(component); + component.setGameOptions(gameOptions); + } + } + + private void configureComponent(Tag componentTag) + throws ConfigurationException { + + // Extract the attributes of the Component + String name = componentTag.getAttributeAsString(XMLTags.NAME_ATTR); + if (name == null) { + throw new ConfigurationException( + LocalText.getText("UnnamedComponent")); + } + String clazz = componentTag.getAttributeAsString(XMLTags.CLASS_ATTR); + if (clazz == null) { + throw new ConfigurationException(LocalText.getText( + "ComponentHasNoClass", name)); + } + String file = componentTag.getAttributeAsString(XMLTags.FILE_ATTR); + + // Only one component per name. + if (mComponentMap.get(name) != null) { + throw new ConfigurationException(LocalText.getText( + "ComponentConfiguredTwice", name)); + } + + // Now construct the component + ConfigurableComponentI component; + try { + Class<? extends ConfigurableComponentI> compClass; + compClass = + Class.forName(clazz).asSubclass( + ConfigurableComponentI.class); + Constructor<? extends ConfigurableComponentI> compCons = + compClass.getConstructor(new Class[0]); + component = compCons.newInstance(new Object[0]); + } catch (Exception ex) { + // There are MANY things that could go wrong here. + // They all just mean that the configuration and code + // do not combine to make a well-formed system. + // Debugging aided by chaining the caught exception. + throw new ConfigurationException(LocalText.getText( + "ComponentHasNoClass", clazz), ex); + + } + + // Configure the component, from a file, or the embedded XML. + Tag configElement = componentTag; + if (file != null) { + directories.add("data/" + gameName); + configElement = Tag.findTopTagInFile(file, directories, name); + configElement.setGameOptions(componentTag.getGameOptions()); + } + + try { + component.configureFromXML(configElement); + } catch (ConfigurationException e) { + // Temporarily allow components to be incompletely configured. + log.warn(LocalText.getText("AcceptingConfigFailure"), e); + } + + // Add it to the map of known components. + mComponentMap.put(name, component); + log.debug(LocalText.getText("ComponentInitAs", name, clazz )); + + } + + /** + * Returns the configured parameter with the given name. + * + * @param componentName the of the component sought. + * @return the component sought, or null if it has not been configured. + */ + public ConfigurableComponentI findComponent(String componentName) { + return mComponentMap.get(componentName); + } + + private Map<String, ConfigurableComponentI> mComponentMap = + new HashMap<String, ConfigurableComponentI>(); + +} Copied: trunk/18xx/rails/common/parser/ConfigurableComponentI.java (from rev 1601, trunk/18xx/rails/game/ConfigurableComponentI.java) =================================================================== --- trunk/18xx/rails/common/parser/ConfigurableComponentI.java (rev 0) +++ trunk/18xx/rails/common/parser/ConfigurableComponentI.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -0,0 +1,37 @@ +/* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/ConfigurableComponentI.java,v 1.7 2009/10/31 17:08:26 evos Exp $ */ +package rails.common.parser; + +import rails.game.GameManagerI; + +/** + * Interface for rails.game components which can be configured from an XML + * element. + */ +public interface ConfigurableComponentI { + + /** + * Instructs the component to configure itself from the provided XML + * element. + * + * @param element the XML element containing the configuration + * @throws ConfigurationException + */ + void configureFromXML(Tag tag) throws ConfigurationException; + + /** + * This method is intended to be called for each configurable + * component, to perforn any initialisation activities that + * require any other components to be initialised first. + * This includes creating any required relationships to other + * configured components and objects. + * <p>This method should be called where necessary after all + * XML file parsing has completed, so that all objects that + * need to be related to do exist. + * @param parent The 'parent' configurable component is passed to allow + * the 'child' to access any other object without the need to resort to + * static calls where possible. + */ + void finishConfiguration (GameManagerI parent) + throws ConfigurationException; + +} Added: trunk/18xx/rails/common/parser/GameFileParser.java =================================================================== --- trunk/18xx/rails/common/parser/GameFileParser.java (rev 0) +++ trunk/18xx/rails/common/parser/GameFileParser.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -0,0 +1,12 @@ +package rails.common.parser; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +public class GameFileParser extends XMLParser { + +} Modified: trunk/18xx/rails/common/parser/GameInfoParser.java =================================================================== --- trunk/18xx/rails/common/parser/GameInfoParser.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/common/parser/GameInfoParser.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -1,6 +1,8 @@ package rails.common.parser; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; import org.w3c.dom.Document; import org.w3c.dom.Element; Modified: trunk/18xx/rails/common/parser/XMLTags.java =================================================================== --- trunk/18xx/rails/common/parser/XMLTags.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/common/parser/XMLTags.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -9,7 +9,7 @@ public static final String OPTION_TAG = "Option"; public static final String GAMES_LIST_TAG = "GamesList"; public static final String NOTE_TAG = "Note"; - + /* ATTRIBUTES */ public static final String NAME_ATTR = "name"; public static final String COMPLETE_ATTR = "complete"; @@ -20,6 +20,12 @@ public static final String TYPE_ATTR = "type"; public static final String DEFAULT_ATTR = "default"; public static final String VALUES_ATTR = "values"; + public static final String CLASS_ATTR = "class"; + public static final String FILE_ATTR = "file"; + + public static final String VALUES_DELIM = ","; - public static final String VALUES_DELIM = ","; + /* Used by ComponentManager. */ + public static final String COMPONENT_MANAGER_ELEMENT_ID = "ComponentManager"; + public static final String COMPONENT_ELEMENT_ID = "Component"; } Modified: trunk/18xx/rails/game/Bank.java =================================================================== --- trunk/18xx/rails/game/Bank.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/Bank.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -6,6 +6,7 @@ import rails.common.LocalText; import rails.common.parser.Config; +import rails.common.parser.ConfigurableComponentI; import rails.common.parser.ConfigurationException; import rails.common.parser.Tag; import rails.game.model.CashModel; @@ -63,7 +64,7 @@ } /** - * @see rails.game.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) + * @see rails.common.parser.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) */ public void configureFromXML(Tag tag) throws ConfigurationException { Modified: trunk/18xx/rails/game/BonusToken.java =================================================================== --- trunk/18xx/rails/game/BonusToken.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/BonusToken.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -5,6 +5,7 @@ */ package rails.game; +import rails.common.parser.ConfigurableComponentI; import rails.common.parser.ConfigurationException; import rails.common.parser.Tag; import rails.game.move.ObjectMove; Modified: trunk/18xx/rails/game/Company.java =================================================================== --- trunk/18xx/rails/game/Company.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/Company.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -6,6 +6,7 @@ import org.apache.log4j.Logger; +import rails.common.parser.ConfigurableComponentI; import rails.common.parser.ConfigurationException; import rails.common.parser.Tag; import rails.game.move.MoveableHolder; Modified: trunk/18xx/rails/game/CompanyI.java =================================================================== --- trunk/18xx/rails/game/CompanyI.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/CompanyI.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -3,6 +3,7 @@ import java.util.List; +import rails.common.parser.ConfigurableComponentI; import rails.game.move.MoveableHolder; import rails.game.special.SpecialPropertyI; Modified: trunk/18xx/rails/game/CompanyManager.java =================================================================== --- trunk/18xx/rails/game/CompanyManager.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/CompanyManager.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -6,6 +6,7 @@ import org.apache.log4j.Logger; import rails.common.LocalText; +import rails.common.parser.ConfigurableComponentI; import rails.common.parser.ConfigurationException; import rails.common.parser.Tag; @@ -65,7 +66,7 @@ } /** - * @see rails.game.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) + * @see rails.common.parser.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) */ public void configureFromXML(Tag tag) throws ConfigurationException { Modified: trunk/18xx/rails/game/CompanyManagerI.java =================================================================== --- trunk/18xx/rails/game/CompanyManagerI.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/CompanyManagerI.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -3,6 +3,8 @@ import java.util.List; +import rails.common.parser.ConfigurableComponentI; + /** * Interface for CompanyManager objects. A company manager is a factory which * vends Company objects. Modified: trunk/18xx/rails/game/CompanyType.java =================================================================== --- trunk/18xx/rails/game/CompanyType.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/CompanyType.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -42,7 +42,7 @@ } /** - * @see rails.game.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) + * @see rails.common.parser.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) */ public void configureFromXML(Tag tag) throws ConfigurationException { //No longer needed. Modified: trunk/18xx/rails/game/CompanyTypeI.java =================================================================== --- trunk/18xx/rails/game/CompanyTypeI.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/CompanyTypeI.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -3,6 +3,7 @@ import java.util.List; +import rails.common.parser.ConfigurableComponentI; import rails.common.parser.ConfigurationException; import rails.common.parser.Tag; Deleted: trunk/18xx/rails/game/ComponentManager.java =================================================================== --- trunk/18xx/rails/game/ComponentManager.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/ComponentManager.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -1,157 +0,0 @@ -/* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/ComponentManager.java,v 1.19 2010/05/18 04:12:23 stefanfrey Exp $ */ -package rails.game; - -import java.lang.reflect.Constructor; -import java.util.*; - -import org.apache.log4j.Logger; - -import rails.common.LocalText; -import rails.common.parser.ConfigurationException; -import rails.common.parser.Tag; - -/** - * ComponentManage - an implementation of ComponentManagerI, which handles the - * creation and configuration of rails.game components, and acts as a discovery - * point for other components to find them. - */ -public class ComponentManager { - - private String gameName; - - /** The name of the XML tag used to configure the ComponentManager. */ - public static final String ELEMENT_ID = "ComponentManager"; - - /** The name of the XML tag used to configure a component. */ - public static final String COMPONENT_ELEMENT_ID = "Component"; - - /** The name of the XML attribute for the component's name. */ - public static final String COMPONENT_NAME_TAG = "name"; - - /** The name of the XML attribute for the component's class. */ - public static final String COMPONENT_CLASS_TAG = "class"; - - /** The name of the XML attribute for the component's configuration file. */ - public static final String COMPONENT_FILE_TAG = "file"; - - private List<Tag> componentTags; - private Map<String, String> gameOptions; - - protected static Logger log = - Logger.getLogger(ComponentManager.class.getPackage().getName()); -// protected static List<String> directories = new ArrayList<String>(); - protected List<String> directories = new ArrayList<String>(); - - public static synchronized ComponentManager configureInstance(String gameName, Tag tag, - Map<String, String> gameOptions) - throws ConfigurationException { - return new ComponentManager(gameName, tag, gameOptions); - } - - private ComponentManager(String gameName, Tag tag, Map<String, String> gameOptions) - throws ConfigurationException { - - this.gameOptions = gameOptions; - this.gameName = gameName; - - componentTags = tag.getChildren(COMPONENT_ELEMENT_ID); - for (Tag component : componentTags) { - String compName = component.getAttributeAsString("name"); - log.debug("Found component " + compName); - if (compName.equalsIgnoreCase(GameManager.GM_NAME)) { - configureComponent(component); - break; - } - } - } - - public synchronized void finishPreparation() throws ConfigurationException { - - for (Tag componentTag : componentTags) { - componentTag.setGameOptions(gameOptions); - String compName = componentTag.getAttributeAsString("name"); - if (compName.equalsIgnoreCase(GameManager.GM_NAME)) continue; - log.debug("Found component " + compName); - configureComponent(componentTag); - } - } - - private void configureComponent(Tag componentTag) - throws ConfigurationException { - - // Extract the attributes of the Component - String name = componentTag.getAttributeAsString(COMPONENT_NAME_TAG); - if (name == null) { - throw new ConfigurationException( - LocalText.getText("UnnamedComponent")); - } - String clazz = componentTag.getAttributeAsString(COMPONENT_CLASS_TAG); - if (clazz == null) { - throw new ConfigurationException(LocalText.getText( - "ComponentHasNoClass", name)); - } - String file = componentTag.getAttributeAsString(COMPONENT_FILE_TAG); - - // Only one component per name. - if (mComponentMap.get(name) != null) { - throw new ConfigurationException(LocalText.getText( - "ComponentConfiguredTwice", name)); - } - - // Now construct the component - ConfigurableComponentI component; - try { - Class<? extends ConfigurableComponentI> compClass; - compClass = - Class.forName(clazz).asSubclass( - ConfigurableComponentI.class); - Constructor<? extends ConfigurableComponentI> compCons = - compClass.getConstructor(new Class[0]); - component = compCons.newInstance(new Object[0]); - } catch (Exception ex) { - // Not great to catch Exception, but there are MANY things that - // could go wrong - // here, and they all just mean that the configuration and code - // do not between - // them make a well-formed system. Debugging aided by chaining - // the caught exception. - throw new ConfigurationException(LocalText.getText( - "ComponentHasNoClass", clazz), ex); - - } - - // Configure the component, from a file, or the embedded XML. - Tag configElement = componentTag; - if (file != null) { - directories.add("data/" + gameName); - configElement = Tag.findTopTagInFile(file, directories, name); - configElement.setGameOptions(componentTag.getGameOptions()); - } - - try { - component.configureFromXML(configElement); - } catch (ConfigurationException e) { - // Temporarily allow components to be incompletely configured. - log.warn(LocalText.getText("AcceptingConfigFailure"), e); - } - - // Add it to the map of known components. - mComponentMap.put(name, component); - log.debug(LocalText.getText("ComponentInitAs", name, clazz )); - - } - - /** - * Returns the configured parameter with the given name. - * - * @param componentName the of the component sought. - * @return the component sought, or null if it has not been configured. - */ - public ConfigurableComponentI findComponent(String componentName) { - return mComponentMap.get(componentName); - } - - private Map<String, ConfigurableComponentI> mComponentMap = - new HashMap<String, ConfigurableComponentI>(); - -} Deleted: trunk/18xx/rails/game/ConfigurableComponentI.java =================================================================== --- trunk/18xx/rails/game/ConfigurableComponentI.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/ConfigurableComponentI.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -1,38 +0,0 @@ -/* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/ConfigurableComponentI.java,v 1.7 2009/10/31 17:08:26 evos Exp $ */ -package rails.game; - -import rails.common.parser.ConfigurationException; -import rails.common.parser.Tag; - -/** - * Interface for rails.game components which can be configured from an XML - * element. - */ -public interface ConfigurableComponentI { - - /** - * Instructs the component to configure itself from the provided XML - * element. - * - * @param element the XML element containing the configuration - * @throws ConfigurationException - */ - void configureFromXML(Tag tag) throws ConfigurationException; - - /** - * This method is intended to be called for each configurable - * component, to perforn any initialisation activities that - * require any other components to be initialised first. - * This includes creating any required relationships to other - * configured components and objects. - * <p>This method should be called where necessary after all - * XML file parsing has completed, so that all objects that - * need to be related to do exist. - * @param parent The 'parent' configurable component is passed to allow - * the 'child' to access any other object without the need to resort to - * static calls where possible. - */ - void finishConfiguration (GameManagerI parent) - throws ConfigurationException; - -} Deleted: trunk/18xx/rails/game/DisplayBuffer.java =================================================================== --- trunk/18xx/rails/game/DisplayBuffer.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/DisplayBuffer.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -1,116 +0,0 @@ -/* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/DisplayBuffer.java,v 1.9 2010/01/31 22:22:28 macfreek Exp $ */ -package rails.game; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; - -import rails.util.Util; - -/** - * Class to write a log, and also to maintain a log message stack for writing to - * the UI. - */ -public final class DisplayBuffer { - - /** List to catch messages before the buffer is instantiated, - * based on the supposition that never 2 games will be initialised simultaneously... - */ - protected static List<String> initialQueue = new ArrayList<String>(); - - protected static Logger log = - Logger.getLogger(DisplayBuffer.class.getPackage().getName()); - - public DisplayBuffer() { - if (!initialQueue.isEmpty()) { - for (String s : initialQueue) { - addMessage (s, true); - } - initialQueue.clear(); - } - } - - /** - * A buffer for displaying messages in a popup window after any user action. - * These include error messages and other notifications of immediate - * interest to players. - */ - private List<String> displayBuffer = new ArrayList<String>(); - - private boolean autoDisplay = true; - - /** - * Add a message to the message (display) buffer (and display it on the - * console) - */ - public static void add(String message) { - add (message, true); - } - - public static void add(String message, boolean autoDisplay) { - GameManagerI gm = GameManager.getInstance(); - DisplayBuffer instance = null; - if (gm != null) instance = gm.getDisplayBuffer(); - if (gm == null || instance == null) { - // Queue in a static buffer until the instance is created - initialQueue.add(message); - } else { - instance.addMessage(message, autoDisplay); - } - } - - private void addMessage (String message, boolean autoDisplay) { - DisplayBuffer instance = getInstance(); - instance.autoDisplay = autoDisplay; - if (Util.hasValue(message)) { - instance.displayBuffer.add(message); - /* Also log the message (don't remove this, - * otherwise the message will not be logged during a reload, - * which may hinder troubleshooting) */ - log.debug("To display: " + message); - } - } - - private static DisplayBuffer getInstance() { - GameManagerI gm = GameManager.getInstance(); - if (gm == null) { - return null; - } else { - return gm.getDisplayBuffer(); - } - } - - /** Get the current message buffer, and clear it */ - public static String[] get() { - DisplayBuffer instance = getInstance(); - if (instance == null) { - if (initialQueue.isEmpty()) { - return null; - } else { - String[] message = initialQueue.toArray(new String[0]); - initialQueue.clear(); - return message; - } - } else if (instance.displayBuffer.size() > 0) { - String[] message = instance.displayBuffer.toArray(new String[0]); - instance.displayBuffer.clear(); - return message; - } else { - return null; - } - } - - public static int getSize() { - return getInstance().displayBuffer.size(); - } - - public static boolean getAutoDisplay () { - return getInstance().autoDisplay; - } - - public static void clear() { - getInstance().displayBuffer.clear(); - } - -} Modified: trunk/18xx/rails/game/Game.java =================================================================== --- trunk/18xx/rails/game/Game.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/Game.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -7,10 +7,13 @@ import org.apache.log4j.Logger; import rails.algorithms.RevenueManager; +import rails.common.DisplayBuffer; import rails.common.LocalText; +import rails.common.parser.ComponentManager; import rails.common.parser.ConfigurationException; import rails.common.parser.GameOption; import rails.common.parser.Tag; +import rails.common.parser.XMLTags; import rails.game.action.PossibleAction; import rails.game.special.SpecialProperty; @@ -79,27 +82,22 @@ try { componentManagerTag = Tag.findTopTagInFile(GAME_XML_FILE, directories, - ComponentManager.ELEMENT_ID); + XMLTags.COMPONENT_MANAGER_ELEMENT_ID); if (componentManagerTag == null) { throw new ConfigurationException( "No Game XML element found in file " + GAME_XML_FILE); } componentManagerTag.setGameOptions(gameOptions); - componentManager = - ComponentManager.configureInstance(name, componentManagerTag, gameOptions); + + // Have the ComponentManager work through the other rails.game files + //XXX: Ultimately calls everyone's configureFromXML() methods. + componentManager = new ComponentManager(name, componentManagerTag, gameOptions); log.info("========== Start of rails.game " + name + " =========="); log.info("Rails version "+version); ReportBuffer.add(LocalText.getText("GameIs", name)); - // set special properties and token static variables - SpecialProperty.init(); - Token.init(); - - // Have the ComponentManager work through the other rails.game files - componentManager.finishPreparation(); - playerManager = (PlayerManager) componentManager.findComponent("PlayerManager"); if (playerManager == null) { throw new ConfigurationException( Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/GameManager.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -10,10 +10,12 @@ import org.apache.log4j.NDC; import rails.algorithms.RevenueManager; +import rails.common.DisplayBuffer; import rails.common.GuiDef; import rails.common.GuiHints; import rails.common.LocalText; import rails.common.parser.Config; +import rails.common.parser.ConfigurableComponentI; import rails.common.parser.ConfigurationException; import rails.common.parser.GameOption; import rails.common.parser.Tag; @@ -102,9 +104,6 @@ protected EnumMap<GameDef.Parm, Object> gameParameters = new EnumMap<GameDef.Parm, Object>(GameDef.Parm.class); - // protected EnumSet<CorrectionType> activeCorrections - // = EnumSet.noneOf(CorrectionType.class); - /** * Current round should not be set here but from within the Round classes. * This is because in some cases the round has already changed to another Modified: trunk/18xx/rails/game/GameManagerI.java =================================================================== --- trunk/18xx/rails/game/GameManagerI.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/GameManagerI.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -4,8 +4,10 @@ import java.util.Map; import rails.algorithms.RevenueManager; +import rails.common.DisplayBuffer; import rails.common.GuiDef; import rails.common.GuiHints; +import rails.common.parser.ConfigurableComponentI; import rails.game.action.PossibleAction; import rails.game.correct.CorrectionManagerI; import rails.game.correct.CorrectionType; @@ -17,7 +19,7 @@ public interface GameManagerI extends MoveableHolder, ConfigurableComponentI { /** - * @see rails.game.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) + * @see rails.common.parser.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) */ public abstract void init(String gameName, PlayerManager playerManager, CompanyManagerI companyManager, PhaseManager phaseManager, Modified: trunk/18xx/rails/game/MapHex.java =================================================================== --- trunk/18xx/rails/game/MapHex.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/MapHex.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -9,6 +9,7 @@ import rails.algorithms.RevenueBonusTemplate; import rails.common.LocalText; +import rails.common.parser.ConfigurableComponentI; import rails.common.parser.ConfigurationException; import rails.common.parser.Tag; import rails.game.action.LayTile; @@ -156,7 +157,7 @@ } /** - * @see rails.game.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) + * @see rails.common.parser.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) */ public void configureFromXML(Tag tag) throws ConfigurationException { Pattern namePattern = Pattern.compile("(\\D+?)(-?\\d+)"); Modified: trunk/18xx/rails/game/MapManager.java =================================================================== --- trunk/18xx/rails/game/MapManager.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/MapManager.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -6,6 +6,7 @@ import org.apache.log4j.Logger; import rails.common.parser.Config; +import rails.common.parser.ConfigurableComponentI; import rails.common.parser.ConfigurationException; import rails.common.parser.Tag; import tools.Util; @@ -58,7 +59,7 @@ } /** - * @see rails.game.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) + * @see rails.common.parser.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) */ public void configureFromXML(Tag tag) throws ConfigurationException { String attr = tag.getAttributeAsString("tileOrientation"); Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/OperatingRound.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -3,6 +3,7 @@ import java.util.*; +import rails.common.DisplayBuffer; import rails.common.GuiDef; import rails.common.LocalText; import rails.common.parser.GameOption; Modified: trunk/18xx/rails/game/PhaseI.java =================================================================== --- trunk/18xx/rails/game/PhaseI.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/PhaseI.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -3,6 +3,8 @@ import java.util.Map; +import rails.common.parser.ConfigurableComponentI; + public interface PhaseI extends ConfigurableComponentI { public boolean isTileColourAllowed(String tileColour); Modified: trunk/18xx/rails/game/PhaseManager.java =================================================================== --- trunk/18xx/rails/game/PhaseManager.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/PhaseManager.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -5,6 +5,7 @@ import org.apache.log4j.Logger; +import rails.common.parser.ConfigurableComponentI; import rails.common.parser.ConfigurationException; import rails.common.parser.Tag; import rails.game.model.ModelObject; Modified: trunk/18xx/rails/game/PlayerManager.java =================================================================== --- trunk/18xx/rails/game/PlayerManager.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/PlayerManager.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -4,6 +4,7 @@ import java.util.*; import rails.common.LocalText; +import rails.common.parser.ConfigurableComponentI; import rails.common.parser.ConfigurationException; import rails.common.parser.Tag; Modified: trunk/18xx/rails/game/PrivateCompany.java =================================================================== --- trunk/18xx/rails/game/PrivateCompany.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/PrivateCompany.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -64,7 +64,7 @@ } /** - * @see rails.game.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) + * @see rails.common.parser.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) */ @Override public void configureFromXML(Tag tag) throws ConfigurationException { Modified: trunk/18xx/rails/game/Round.java =================================================================== --- trunk/18xx/rails/game/Round.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/Round.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -9,6 +9,7 @@ import org.apache.log4j.Logger; +import rails.common.DisplayBuffer; import rails.common.GuiHints; import rails.common.LocalText; import rails.game.action.*; Modified: trunk/18xx/rails/game/ShareSellingRound.java =================================================================== --- trunk/18xx/rails/game/ShareSellingRound.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/ShareSellingRound.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -7,6 +7,7 @@ import java.util.*; +import rails.common.DisplayBuffer; import rails.common.GuiDef; import rails.common.LocalText; import rails.common.parser.GameOption; Modified: trunk/18xx/rails/game/StartRound.java =================================================================== --- trunk/18xx/rails/game/StartRound.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/StartRound.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.List; +import rails.common.DisplayBuffer; import rails.common.GuiDef; import rails.common.LocalText; import rails.common.parser.GameOption; Modified: trunk/18xx/rails/game/StartRound_1830.java =================================================================== --- trunk/18xx/rails/game/StartRound_1830.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/StartRound_1830.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -1,6 +1,7 @@ /* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/StartRound_1830.java,v 1.33 2010/06/21 22:57:53 stefanfrey Exp $ */ package rails.game; +import rails.common.DisplayBuffer; import rails.common.LocalText; import rails.common.parser.GameOption; import rails.game.action.*; Modified: trunk/18xx/rails/game/StartRound_1835.java =================================================================== --- trunk/18xx/rails/game/StartRound_1835.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/StartRound_1835.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.List; +import rails.common.DisplayBuffer; import rails.common.LocalText; import rails.game.action.*; import rails.game.state.IntegerState; Modified: trunk/18xx/rails/game/StockMarket.java =================================================================== --- trunk/18xx/rails/game/StockMarket.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/StockMarket.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -4,6 +4,7 @@ import java.util.*; import rails.common.LocalText; +import rails.common.parser.ConfigurableComponentI; import rails.common.parser.ConfigurationException; import rails.common.parser.Tag; import rails.game.move.PriceTokenMove; @@ -44,7 +45,7 @@ } /** - * @see rails.game.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) + * @see rails.common.parser.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) */ public void configureFromXML(Tag tag) throws ConfigurationException { Modified: trunk/18xx/rails/game/StockMarketI.java =================================================================== --- trunk/18xx/rails/game/StockMarketI.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/StockMarketI.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -3,6 +3,8 @@ import java.util.List; +import rails.common.parser.ConfigurableComponentI; + public interface StockMarketI extends ConfigurableComponentI { /** Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/StockRound.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -2,6 +2,7 @@ import java.util.*; +import rails.common.DisplayBuffer; import rails.common.GuiDef; import rails.common.LocalText; import rails.common.parser.GameOption; Modified: trunk/18xx/rails/game/TileManager.java =================================================================== --- trunk/18xx/rails/game/TileManager.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/TileManager.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -6,6 +6,7 @@ import org.apache.log4j.Logger; import rails.common.LocalText; +import rails.common.parser.ConfigurableComponentI; import rails.common.parser.ConfigurationException; import rails.common.parser.Tag; @@ -27,7 +28,7 @@ } /** - * @see rails.game.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) + * @see rails.common.parser.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) */ public void configureFromXML(Tag tileSetTop) throws ConfigurationException { /* Modified: trunk/18xx/rails/game/Token.java =================================================================== --- trunk/18xx/rails/game/Token.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/Token.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -29,18 +29,10 @@ Logger.getLogger(Token.class.getPackage().getName()); public Token() { - uniqueId = "Token_" + (index++); tokenMap.put(uniqueId, this); } - // initialize the special properties static variables - public static void init() { - tokenMap = new HashMap<String, TokenI>(); - index = 0; - log.debug("Init token static variables"); - } - public static TokenI getByUniqueId(String id) { return tokenMap.get(id); } Modified: trunk/18xx/rails/game/TrainManager.java =================================================================== --- trunk/18xx/rails/game/TrainManager.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/TrainManager.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -6,6 +6,7 @@ import org.apache.log4j.Logger; import rails.common.LocalText; +import rails.common.parser.ConfigurableComponentI; import rails.common.parser.ConfigurationException; import rails.common.parser.Tag; import rails.game.move.ObjectMove; @@ -72,7 +73,7 @@ } /** - * @see rails.game.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) + * @see rails.common.parser.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) */ public void configureFromXML(Tag tag) throws ConfigurationException { Modified: trunk/18xx/rails/game/TrainType.java =================================================================== --- trunk/18xx/rails/game/TrainType.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/TrainType.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -54,7 +54,7 @@ } /** - * @see rails.game.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) + * @see rails.common.parser.ConfigurableComponentI#configureFromXML(org.w3c.dom.Element) */ public void configureFromXML(Tag tag) throws ConfigurationException { Modified: trunk/18xx/rails/game/TreasuryShareRound.java =================================================================== --- trunk/18xx/rails/game/TreasuryShareRound.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/TreasuryShareRound.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -7,6 +7,7 @@ import java.util.*; +import rails.common.DisplayBuffer; import rails.common.GuiDef; import rails.common.LocalText; import rails.game.action.*; Modified: trunk/18xx/rails/game/correct/CashCorrectionManager.java =================================================================== --- trunk/18xx/rails/game/correct/CashCorrectionManager.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/correct/CashCorrectionManager.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -1,5 +1,6 @@ package rails.game.correct; +import rails.common.DisplayBuffer; import rails.common.LocalText; import rails.game.*; import rails.game.move.CashMove; Modified: trunk/18xx/rails/game/correct/CorrectionManager.java =================================================================== --- trunk/18xx/rails/game/correct/CorrectionManager.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/correct/CorrectionManager.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -5,8 +5,8 @@ import org.apache.log4j.Logger; +import rails.common.DisplayBuffer; import rails.common.LocalText; -import rails.game.DisplayBuffer; import rails.game.GameManager; import rails.game.ReportBuffer; import rails.game.move.StateChange; Modified: trunk/18xx/rails/game/correct/MapCorrectionManager.java =================================================================== --- trunk/18xx/rails/game/correct/MapCorrectionManager.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/correct/MapCorrectionManager.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -4,10 +4,10 @@ import java.util.HashMap; import java.util.List; +import rails.common.DisplayBuffer; import rails.common.LocalText; import rails.game.BaseToken; import rails.game.City; -import rails.game.DisplayBuffer; import rails.game.GameManager; import rails.game.MapHex; import rails.game.ReportBuffer; Modified: trunk/18xx/rails/game/special/SpecialProperty.java =================================================================== --- trunk/18xx/rails/game/special/SpecialProperty.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/special/SpecialProperty.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -54,20 +54,13 @@ /** To give subclasses access to the various 'managers' */ protected GameManagerI gameManager; - protected static Map<Integer, SpecialPropertyI> spMap = - new HashMap<Integer, SpecialPropertyI>(); + protected static Map<Integer, SpecialPropertyI> spMap = new HashMap<Integer, SpecialPropertyI>(); + protected static int lastIndex = 0; protected static Logger log = Logger.getLogger(SpecialProperty.class.getPackage().getName()); - // initialize the special properties static variables - public static void init() { - spMap = new HashMap<Integer, SpecialPropertyI>(); - lastIndex = 0; - log.debug("Init special property static variables"); - } - public SpecialProperty() { uniqueId = ++lastIndex; spMap.put(uniqueId, this); Modified: trunk/18xx/rails/game/special/SpecialPropertyI.java =================================================================== --- trunk/18xx/rails/game/special/SpecialPropertyI.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/special/SpecialPropertyI.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -1,6 +1,7 @@ /* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/special/SpecialPropertyI.java,v 1.12 2010/03/16 21:21:59 evos Exp $ */ package rails.game.special; +import rails.common.parser.ConfigurableComponentI; import rails.game.*; import rails.game.move.Moveable; import rails.game.move.MoveableHolder; Modified: trunk/18xx/rails/game/specific/_1825/StartRound_1825.java =================================================================== --- trunk/18xx/rails/game/specific/_1825/StartRound_1825.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/specific/_1825/StartRound_1825.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -2,6 +2,7 @@ import java.util.List; +import rails.common.DisplayBuffer; import rails.common.LocalText; import rails.game.*; import rails.game.action.*; Modified: trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java =================================================================== --- trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -2,6 +2,7 @@ import java.util.*; +import rails.common.DisplayBuffer; import rails.common.LocalText; import rails.common.parser.GameOption; import rails.game.*; Modified: trunk/18xx/rails/game/specific/_1835/PrussianFormationRound.java =================================================================== --- trunk/18xx/rails/game/specific/_1835/PrussianFormationRound.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/specific/_1835/PrussianFormationRound.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -2,6 +2,7 @@ import java.util.*; +import rails.common.DisplayBuffer; import rails.common.GuiDef; import rails.common.LocalText; import rails.game.*; Modified: trunk/18xx/rails/game/specific/_1851/StartRound_1851.java =================================================================== --- trunk/18xx/rails/game/specific/_1851/StartRound_1851.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/specific/_1851/StartRound_1851.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -3,6 +3,7 @@ import java.util.List; +import rails.common.DisplayBuffer; import rails.common.LocalText; import rails.game.*; import rails.game.action.*; Modified: trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java =================================================================== --- trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -2,6 +2,7 @@ import java.util.*; +import rails.common.DisplayBuffer; import rails.common.GuiDef; import rails.common.LocalText; import rails.game.*; Modified: trunk/18xx/rails/game/specific/_1856/OperatingRound_1856.java =================================================================== --- trunk/18xx/rails/game/specific/_1856/OperatingRound_1856.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/specific/_1856/OperatingRound_1856.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.List; +import rails.common.DisplayBuffer; import rails.common.GuiDef; import rails.common.LocalText; import rails.game.*; Modified: trunk/18xx/rails/game/specific/_1856/StockRound_1856.java =================================================================== --- trunk/18xx/rails/game/specific/_1856/StockRound_1856.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/specific/_1856/StockRound_1856.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -1,5 +1,6 @@ package rails.game.specific._1856; +import rails.common.DisplayBuffer; import rails.common.LocalText; import rails.game.*; import rails.game.action.BuyCertificate; Modified: trunk/18xx/rails/game/specific/_1880/StartRound_1880.java =================================================================== --- trunk/18xx/rails/game/specific/_1880/StartRound_1880.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/specific/_1880/StartRound_1880.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -3,6 +3,7 @@ */ package rails.game.specific._1880; +import rails.common.DisplayBuffer; import rails.common.LocalText; import rails.game.*; import rails.game.action.*; Modified: trunk/18xx/rails/game/specific/_1889/OperatingRound_1889.java =================================================================== --- trunk/18xx/rails/game/specific/_1889/OperatingRound_1889.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/specific/_1889/OperatingRound_1889.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -1,6 +1,7 @@ /* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/specific/_1889/OperatingRound_1889.java,v 1.1 2010/02/23 22:21:40 stefanfrey Exp $ */ package rails.game.specific._1889; +import rails.common.DisplayBuffer; import rails.common.LocalText; import rails.common.parser.GameOption; import rails.game.*; Modified: trunk/18xx/rails/game/specific/_18AL/NamedTrainRevenueModifier.java =================================================================== --- trunk/18xx/rails/game/specific/_18AL/NamedTrainRevenueModifier.java 2011-07-04 16:31:43 UTC (rev 1601) +++ trunk/18xx/rails/game/specific/_18AL/NamedTrainRevenueModifier.java 2011-07-04 22:27:18 UTC (rev 1602) @@ -10,9 +10,9 @@ import rails.algorithms.RevenueDynamicModifier; import rails.algorithms.RevenueStaticModifier; import rails.algorithms.RevenueTrainRun; +import rails.common.parser.ConfigurableComponentI; import rails.common.parser.ConfigurationException; import rails.common.parser.Tag; -import rails.game.ConfigurableComponentI; import rails.game.GameManagerI; import rails.game.MapHex; import rails.game.TrainI; Modified: trunk/18xx/rails/game/specific/_18AL/NamedTrainToken.java =================================================================== --- trunk/18xx/rails/game/specific/_18AL/Name... [truncated message content] |