You can subscribe to this list here.
2008 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(3) |
Nov
(46) |
Dec
(57) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2009 |
Jan
(51) |
Feb
(10) |
Mar
|
Apr
|
May
(14) |
Jun
|
Jul
(13) |
Aug
(30) |
Sep
(83) |
Oct
(56) |
Nov
(148) |
Dec
(107) |
2010 |
Jan
(260) |
Feb
(164) |
Mar
(183) |
Apr
(99) |
May
(160) |
Jun
(40) |
Jul
(33) |
Aug
(48) |
Sep
(22) |
Oct
(24) |
Nov
(1) |
Dec
(12) |
2011 |
Jan
(6) |
Feb
(15) |
Mar
(13) |
Apr
(37) |
May
(27) |
Jun
(29) |
Jul
(33) |
Aug
(20) |
Sep
(17) |
Oct
(20) |
Nov
(33) |
Dec
(17) |
2012 |
Jan
(39) |
Feb
(38) |
Mar
(20) |
Apr
(21) |
May
(17) |
Jun
(22) |
Jul
(16) |
Aug
(3) |
Sep
(9) |
Oct
(10) |
Nov
|
Dec
|
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-12 20:58:12
|
Revision: 1381 http://rails.svn.sourceforge.net/rails/?rev=1381&view=rev Author: stefanfrey Date: 2010-08-12 20:58:05 +0000 (Thu, 12 Aug 2010) Log Message: ----------- Fixed and updated implementation of blocked token lays Modified Paths: -------------- trunk/18xx/data/1830/CompanyManager.xml trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/MapHex.java Modified: trunk/18xx/data/1830/CompanyManager.xml =================================================================== --- trunk/18xx/data/1830/CompanyManager.xml 2010-08-12 18:46:08 UTC (rev 1380) +++ trunk/18xx/data/1830/CompanyManager.xml 2010-08-12 20:58:05 UTC (rev 1381) @@ -89,7 +89,7 @@ longname="Erie Railroad"> <!-- city = 0 implies that this is not yet decided (OO-tiles), blocks means that in each city one slot has to be available --> - <Home hex="E11" city="0" AllCitiesBlocked="yes"/> + <Home hex="E11" city="0" allCitiesBlocked="yes"/> </Company> <Company name="B&M" type="Public" tokens="2" fgColour="000000" bgColour="60E060" longname="Boston & Maine"> @@ -106,7 +106,7 @@ <IfOption name="Variant" value="Pere Marquette"> <Company name="PM" type="Public" tokens="3" fgColour="FFFF00" bgColour="000080" longname="Pere Marquette"> - <Home hex="E5" city="0" AllCitiesBlocked="yes" /> + <Home hex="E5" city="0" allCitiesBlocked="yes" /> </Company> </IfOption> <StartPacket roundClass="rails.game.StartRound_1830"> Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-08-12 18:46:08 UTC (rev 1380) +++ trunk/18xx/rails/game/GameManager.java 2010-08-12 20:58:05 UTC (rev 1381) @@ -879,14 +879,14 @@ result = save(gameAction); break; case GameAction.UNDO: - moveStack.undoMoveSet(true); + moveStack.undoMoveSet(false); result = true; break; case GameAction.FORCED_UNDO: if (index != -1) { moveStack.gotoIndex(index); } else { - moveStack.undoMoveSet(false); + moveStack.undoMoveSet(true); } result = true; break; Modified: trunk/18xx/rails/game/MapHex.java =================================================================== --- trunk/18xx/rails/game/MapHex.java 2010-08-12 18:46:08 UTC (rev 1380) +++ trunk/18xx/rails/game/MapHex.java 2010-08-12 20:58:05 UTC (rev 1381) @@ -1047,26 +1047,44 @@ // Return MapHex attribute if defined return isBlockedForTokenLays.booleanValue(); } else if (homes != null && !homes.isEmpty()) { - // Check if this token lay does not block an unlaid home base + City cityToLay = this.getCity(cityNumber); + if (cityToLay == null) { // city does not exist, this does not block itself + return false; + } + // check if the city is potential home for other companies + int allBlockCompanies = 0; + int anyBlockCompanies = 0; + int cityBlockCompanies = 0; for (PublicCompanyI comp : homes.keySet()) { if (comp.hasLaidHomeBaseTokens() || comp.isClosed()) continue; - // home base not laid yet, define list of cities to check - List<City> citiesToCheck = new ArrayList<City>(); + // home base not laid yet City homeCity = homes.get(comp); - if (homeCity != null) { - citiesToCheck.add(homeCity); + if (homeCity == null) { + if (comp.isHomeBlockedForAllCities()) { + allBlockCompanies ++; // undecided companies that block all cities + } else { + anyBlockCompanies ++; // undecided companies that block any cities + } + } else if (cityToLay == homeCity) { + cityBlockCompanies ++; // companies which are located in the city in question } else { - citiesToCheck.addAll(cities); + anyBlockCompanies ++; // companies which are located somewhere else } - int tokenSlotsLeft = 0; - for (City city:cities) { - tokenSlotsLeft += city.getTokenSlotsLeft(); - if (comp.isHomeBlockedForAllCities() & city.getTokenSlotsLeft() < 2) { - return true; - } - } - if (tokenSlotsLeft < 2) return true; // not enough tokens left, assume only one company } + log.debug("IsBlockedForTokenLays: allBlockCompanies = " + allBlockCompanies + + ", anyBlockCompanies = " + anyBlockCompanies + " , cityBlockCompanies = " + cityBlockCompanies); + // check if there are sufficient individual city slots + if (allBlockCompanies + cityBlockCompanies + 1 > cityToLay.getTokenSlotsLeft()) { + return true; // the additional token exceeds the number of available slots + } + // check if the overall hex slots are sufficient + int allTokenSlotsLeft = 0; + for (City city:cities) { + allTokenSlotsLeft += city.getTokenSlotsLeft(); + } + if (allBlockCompanies + anyBlockCompanies + cityBlockCompanies + 1 > allTokenSlotsLeft) { + return true; // all located companies plus the additonal token exceeds the available slots + } } return false; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-12 18:46:15
|
Revision: 1380 http://rails.svn.sourceforge.net/rails/?rev=1380&view=rev Author: stefanfrey Date: 2010-08-12 18:46:08 +0000 (Thu, 12 Aug 2010) Log Message: ----------- Added 1856 THB option for token lay and changed blocked hex token lay implementation Modified Paths: -------------- trunk/18xx/data/1830/CompanyManager.xml trunk/18xx/data/1830/Map.xml trunk/18xx/data/1856/CompanyManager.xml trunk/18xx/data/1856/Game.xml trunk/18xx/rails/game/MapHex.java trunk/18xx/rails/game/PublicCompany.java trunk/18xx/rails/game/PublicCompanyI.java Modified: trunk/18xx/data/1830/CompanyManager.xml =================================================================== --- trunk/18xx/data/1830/CompanyManager.xml 2010-08-11 23:21:59 UTC (rev 1379) +++ trunk/18xx/data/1830/CompanyManager.xml 2010-08-12 18:46:08 UTC (rev 1380) @@ -87,7 +87,9 @@ </Company> <Company name="Erie" type="Public" tokens="3" fgColour="000000" bgColour="FFFF00" longname="Erie Railroad"> - <Home hex="E11"/> + <!-- city = 0 implies that this is not yet decided (OO-tiles), blocks means that + in each city one slot has to be available --> + <Home hex="E11" city="0" AllCitiesBlocked="yes"/> </Company> <Company name="B&M" type="Public" tokens="2" fgColour="000000" bgColour="60E060" longname="Boston & Maine"> @@ -104,7 +106,7 @@ <IfOption name="Variant" value="Pere Marquette"> <Company name="PM" type="Public" tokens="3" fgColour="FFFF00" bgColour="000080" longname="Pere Marquette"> - <Home hex="E5"/> + <Home hex="E5" city="0" AllCitiesBlocked="yes" /> </Company> </IfOption> <StartPacket roundClass="rails.game.StartRound_1830"> Modified: trunk/18xx/data/1830/Map.xml =================================================================== --- trunk/18xx/data/1830/Map.xml 2010-08-11 23:21:59 UTC (rev 1379) +++ trunk/18xx/data/1830/Map.xml 2010-08-12 18:46:08 UTC (rev 1380) @@ -36,7 +36,7 @@ <Hex name="E5" tile="-20" label="OO" cost="80"/> <Hex name="E7" tile="-1" impassable="F8"/> <Hex name="E9" tile="-7" orientation="4"/> - <Hex name="E11" tile="-20" label="OO" unlaidHomeBlocksTokens="yes"/> + <Hex name="E11" tile="-20" label="OO"/> <Hex name="E13" tile="0"/> <Hex name="E15" tile="0"/> <Hex name="E17" tile="0" cost="120"/> Modified: trunk/18xx/data/1856/CompanyManager.xml =================================================================== --- trunk/18xx/data/1856/CompanyManager.xml 2010-08-11 23:21:59 UTC (rev 1379) +++ trunk/18xx/data/1856/CompanyManager.xml 2010-08-12 18:46:08 UTC (rev 1380) @@ -113,7 +113,12 @@ <Destination hex="K8"/> </Company> <Company name="THB" type="Public" tokens="2" fgColour="000000" bgColour="B0B040"> - <Home hex="L15" city="0"/><!-- City to be selected in first turn--> + <IfOption name="1856THBHomeBlocked" value="yes"> + <Home hex="L15" city="0" blockedForAllCities = "yes" /> + </IfOption> + <IfOption name="1856THBHomeBlocked" value="no"> + <Home hex="L15" city="0" blockedForAllCities = "no" /> + </IfOption> <Destination hex="J11"/> </Company> <Company name="BBG" type="Public" tokens="3" fgColour="000000" bgColour="FF8080"> Modified: trunk/18xx/data/1856/Game.xml =================================================================== --- trunk/18xx/data/1856/Game.xml 2010-08-11 23:21:59 UTC (rev 1379) +++ trunk/18xx/data/1856/Game.xml 2010-08-12 18:46:08 UTC (rev 1380) @@ -9,7 +9,7 @@ <GameOption name="UnlimitedTiles" type="toggle" default="no"/> <GameOption name="LeaveAuctionOnPass" type="toggle" default="no"/> <GameOption name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> - <GameOption name="1856THBHomeBlocked" type="toggle" default="no" /> + <GameOption name="1856THBHomeBlocked" type="toggle" default="yes" /> <GameParameters> <StockRound class="rails.game.specific._1856.StockRound_1856" sequence="SellBuyOrBuySell"> Modified: trunk/18xx/rails/game/MapHex.java =================================================================== --- trunk/18xx/rails/game/MapHex.java 2010-08-11 23:21:59 UTC (rev 1379) +++ trunk/18xx/rails/game/MapHex.java 2010-08-12 18:46:08 UTC (rev 1380) @@ -1012,46 +1012,60 @@ /** * @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 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 + * + * There are the following cases to check for each company located there + * + * A) City is decided or there is only one city + * => check if the city has a free slot or not + * (examples: NYNH in 1830 for a two city tile, NYC for a one city tile) + * B) City is not decided (example: Erie in 1830) + * two subcases depending on isHomeBlockedForAllCities + * - (true): all cities of the hex have remaining slots available + * - (false): no city of the hex has remaining slots available + * C) Or the company does not block its home city at all (example:Pr in 1835) + * then isBlockedForTokenLays attribute is used + * + * NOTE: It assumes that not two company share the same home city. + * Undecided companies cannot share the same hex with any other company. + * + * Previously used was the variable isBlockedForTokenLays + * which is set to yes to block the whole hex for the token lays + * until the (home) company laid their token + * */ public boolean isBlockedForTokenLays(PublicCompanyI company, int cityNumber) { - if (isHomeFor(company)) + if (isHomeFor(company)) { // Company can always lay a home base return false; - 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) + } else if (isBlockedForTokenLays != null) { + // Return MapHex attribute if defined return isBlockedForTokenLays.booleanValue(); } else if (homes != null && !homes.isEmpty()) { // Check if this token lay does not block an unlaid home base for (PublicCompanyI comp : homes.keySet()) { if (comp.hasLaidHomeBaseTokens() || comp.isClosed()) continue; + // home base not laid yet, define list of cities to check + List<City> citiesToCheck = new ArrayList<City>(); 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; + if (homeCity != null) { + citiesToCheck.add(homeCity); + } else { + citiesToCheck.addAll(cities); + } + int tokenSlotsLeft = 0; + for (City city:cities) { + tokenSlotsLeft += city.getTokenSlotsLeft(); + if (comp.isHomeBlockedForAllCities() & city.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 } + if (tokenSlotsLeft < 2) return true; // not enough tokens left, assume only one company } } return false; Modified: trunk/18xx/rails/game/PublicCompany.java =================================================================== --- trunk/18xx/rails/game/PublicCompany.java 2010-08-11 23:21:59 UTC (rev 1379) +++ trunk/18xx/rails/game/PublicCompany.java 2010-08-12 18:46:08 UTC (rev 1380) @@ -59,6 +59,7 @@ protected String homeHexName = null; protected MapHex homeHex = null; protected int homeCityNumber = 1; + protected boolean homeAllCitiesBlocked = false; /** Destination hex * */ protected String destinationHexName = null; @@ -320,6 +321,7 @@ if (homeBaseTag != null) { homeHexName = homeBaseTag.getAttributeAsString("hex"); homeCityNumber = homeBaseTag.getAttributeAsInteger("city", 1); + homeAllCitiesBlocked = homeBaseTag.getAttributeAsBoolean("allCitiesBlocked", false); } Tag destinationTag = tag.getChild("Destination"); @@ -827,6 +829,15 @@ public void setHomeCityNumber(int number) { this.homeCityNumber = number; } + + /** + * @return true -> requires an open slot in each city of the hex, false -> one slot on the hex + * + */ + public boolean isHomeBlockedForAllCities() { + return homeAllCitiesBlocked; + } + /** * @return Returns the destinationHex. Modified: trunk/18xx/rails/game/PublicCompanyI.java =================================================================== --- trunk/18xx/rails/game/PublicCompanyI.java 2010-08-11 23:21:59 UTC (rev 1379) +++ trunk/18xx/rails/game/PublicCompanyI.java 2010-08-12 18:46:08 UTC (rev 1380) @@ -330,6 +330,7 @@ public int getHomeCityNumber(); public void setHomeCityNumber(int homeCityNumber); + public boolean isHomeBlockedForAllCities(); public MapHex getDestinationHex(); public boolean hasDestination (); 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-10 23:08:15
|
Revision: 1378 http://rails.svn.sourceforge.net/rails/?rev=1378&view=rev Author: stefanfrey Date: 2010-08-10 23:08:08 +0000 (Tue, 10 Aug 2010) Log Message: ----------- Added dynamic (linked to game situations) report window Modified Paths: -------------- trunk/18xx/LocalisedText.properties trunk/18xx/data/Properties.xml trunk/18xx/data/profiles/default.profile trunk/18xx/rails/game/ReportBuffer.java trunk/18xx/rails/game/move/MoveStack.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/ReportWindow.java trunk/18xx/rails/ui/swing/StatusWindow.java Added Paths: ----------- trunk/18xx/rails/ui/swing/AbstractReportWindow.java trunk/18xx/rails/ui/swing/ReportWindowDynamic.java Modified: trunk/18xx/LocalisedText.properties =================================================================== --- trunk/18xx/LocalisedText.properties 2010-08-10 21:52:19 UTC (rev 1377) +++ trunk/18xx/LocalisedText.properties 2010-08-10 23:08:08 UTC (rev 1378) @@ -168,8 +168,9 @@ Config.label.report.directory=Report directory Config.label.report.filename.date_time_pattern=Report filename date pattern Config.label.report.filename.extension=Report filename extension +Config.label.report.window.editable=Report window editable Config.label.report.window.open=Report window open -Config.label.report.window.editable=Report window editable +Config.label.report.window.type=Report window type Config.label.route.colour.1=Route color for first train Config.label.route.colour.2=Route color for second train Config.label.route.colour.3=Route color for third train @@ -185,9 +186,9 @@ Config.section.Format=Format/Colors Config.section.General=General Config.section.Log=Log -Config.section.Map=Map +Config.section.Font=Fonts Config.section.Save=Save -Config.section.UI=Windows/Fonts +Config.section.UI=Map/Report ConfirmToken=Press Lay Token to confirm token, click another city hex, or press the No Token button. connected=connected CorrectCashAddMoney=CORRECTION: {0} receives {1} from the bank @@ -485,6 +486,8 @@ RepayLoans=Repay loan(s) RepayLoan=Repay {0} loan(s) of {1} for {2} REPORT=Report Window +REPORT_MOVE_BACKWARD=<< +REPORT_MOVE_FORWARD=>> REVENUE=Revenue RevenueCalculation=support for revenue calculation RevenueStations=, Cities = {0}, Towns = {1} Modified: trunk/18xx/data/Properties.xml =================================================================== --- trunk/18xx/data/Properties.xml 2010-08-10 21:52:19 UTC (rev 1377) +++ trunk/18xx/data/Properties.xml 2010-08-10 23:08:08 UTC (rev 1378) @@ -19,10 +19,7 @@ <Property name="save.recovery.active" type="BOOLEAN" /> <Property name="save.recovery.filepath" type="FILE" /> </Section> - <Section name="UI"> - <Property name="report.window.open" type="BOOLEAN" /> - <Property name="report.window.editable" type="BOOLEAN" /> - <Property name="stockchart.window.open" type="BOOLEAN" /> + <Section name="Font"> <Property name="font.ui.scale" type="PERCENT" initClass="rails.ui.swing.GameUIManager" initMethod="updateUILookAndFeel" initParameter="no" /> <Property name="font.ui.name" type="FONT" @@ -30,9 +27,13 @@ <Property name="font.ui.style" type="LIST" values="plain,bold" initClass="rails.ui.swing.GameUIManager" initMethod="updateUILookAndFeel" initParameter="no" /> </Section> - <Section name="Map"> + <Section name="UI"> <Property name="map.autoscroll" type="BOOLEAN" /> <Property name="map.zoomstep" type="INTEGER" /> + <Property name="report.window.type" type="LIST" values="static,dynamic" /> + <Property name="report.window.open" type="BOOLEAN" /> + <Property name="report.window.editable" type="BOOLEAN" /> + <Property name="stockchart.window.open" type="BOOLEAN" /> </Section> <Section name="Format"> <Property name="money_format" type="STRING" /> Modified: trunk/18xx/data/profiles/default.profile =================================================================== --- trunk/18xx/data/profiles/default.profile 2010-08-10 21:52:19 UTC (rev 1377) +++ trunk/18xx/data/profiles/default.profile 2010-08-10 23:08:08 UTC (rev 1378) @@ -14,6 +14,7 @@ save.recovery.filepath=18xx_autosave.rails ### Panel UI +report.window.type=dynamic report.window.open=yes report.window.editable=no stockchart.window.open=yes Modified: trunk/18xx/rails/game/ReportBuffer.java =================================================================== --- trunk/18xx/rails/game/ReportBuffer.java 2010-08-10 21:52:19 UTC (rev 1377) +++ trunk/18xx/rails/game/ReportBuffer.java 2010-08-10 23:08:08 UTC (rev 1378) @@ -9,6 +9,7 @@ import org.apache.log4j.Logger; import rails.util.Config; +import rails.util.LocalText; import rails.util.Util; /** @@ -22,16 +23,69 @@ * */ public final class ReportBuffer { + + /** defines the collection of data that is stored in the report buffer */ + private class ReportItem { + private List<String> messages = new ArrayList<String>(); + private int index = 0; + private Player player = null; + private RoundI round = null; + + private void addMessage(String message) { + // ignore undos and redos + messages.add(message); + } + + private String getMessages() { + StringBuffer s = new StringBuffer(); + for (String message:messages) { + s.append(message); + } + return s.toString(); + } + + private String toHtml() { + StringBuffer s = new StringBuffer(); + boolean init = true; + for (String message:messages) { + if (init) { + s.append("<a href=http://rails:" + index + ">"); + s.append(message); + s.append("</a><br>"); + init = false; + } else { + s.append(message + "<br>"); + } + } + return s.toString(); + } + + public String toString() { + StringBuffer s = new StringBuffer(); + s.append("ReportItem for MoveStackIndex = " + index); + s.append(", player = " + player); + s.append(", round = " + round); + s.append(", messages = "); s.append(getMessages()); + return s.toString(); + } + } + + /** * A stack for displaying messages in the Log Window. Such messages are * intended to record the progress of the rails.game and can be used as a * rails.game report. */ - private List<String> reportQueue = new ArrayList<String>(); + private List<String> reportQueue = new ArrayList<String> (); /** Another stack for messages that must "wait" for other messages */ private List<String> waitQueue = new ArrayList<String> (); + /** Archive stack, the integer index corresponds with the moveset items */ + private SortedMap<Integer, ReportItem> reportItems = new TreeMap<Integer, ReportItem>(); + /** Indicator string to find the active message position in the parsed html document */ + public static final String ACTIVE_MESSAGE_INDICATOR = "(**)"; + private String reportPathname = null; private PrintWriter report = null; @@ -42,6 +96,7 @@ private static String reportDirectory = null; private static final String DEFAULT_DTS_PATTERN = "yyyyMMdd_HHmm"; private static final String DEFAULT_REPORT_EXTENSION = "txt"; + static { reportDirectory = Config.get("report.directory").trim(); @@ -53,15 +108,16 @@ public ReportBuffer() { + reportItems.put(0, new ReportItem()); if (!initialQueue.isEmpty()) { for (String s : initialQueue) { - addMessage (s); + addMessage(s, -1); // start of the game } initialQueue.clear(); } } - + private List<String> getReportQueue() { return reportQueue; } @@ -70,11 +126,15 @@ reportQueue.clear(); } - private void addMessage (String message) { + private void addMessage(String message, int moveStackIndex) { if (message != null) { - if (message.equals("")) + if (message.equals("")) { message = "---"; // workaround for testing + } + // legacy report queue reportQueue.add(message); + // new queue + reportItems.get(moveStackIndex).addMessage(message); /* Also log the message */ if (message.length() > 0) log.info(message); /* Also write it to the report file, if requested */ @@ -130,8 +190,58 @@ wantReport = false; } } + + private void addReportItem(int index, Player player, RoundI round) { + ReportItem newItem = new ReportItem(); + newItem.index = index; + newItem.player = player; + newItem.round = round; + reportItems.put(index, newItem); + Set<Integer> deleteIndices = new HashSet<Integer> + (reportItems.tailMap(index + 1).keySet()); + for (Integer i:deleteIndices) { + reportItems.remove(i); + } + } + /** Movestack calls the report item to update */ + public static void createNewReportItem(int index) { + // check availablity + GameManagerI gm = GameManager.getInstance(); + ReportBuffer instance = null; + if (gm != null) { + instance = gm.getReportBuffer(); + } + if (gm == null || instance == null) { + return; + } + // all there, add new report item + Player player = gm.getCurrentPlayer(); + RoundI round = gm.getCurrentRound(); + instance.addReportItem(index, player, round); + } + + public static String getReportItems() { + int index = GameManager.getInstance().getMoveStack().getIndex(); + ReportBuffer instance = getInstance(); + + StringBuffer s = new StringBuffer(); + s.append("<html>"); + for (ReportItem item:instance.reportItems.values()) { + if (item.index == index-1) { + s.append("<p bgcolor=Yellow>" + ACTIVE_MESSAGE_INDICATOR) ; + } + s.append(item.toHtml()); + if (item.index == (index-1)) { + s.append("</p><"); + } + } + s.append("</html>"); + + return s.toString(); + } + /** Get the current log buffer, and clear it */ public static String get() { ReportBuffer instance = getInstance(); @@ -146,17 +256,25 @@ return result.toString(); } - + /** Add a message to the log buffer (and display it on the console) */ public static void add(String message) { GameManagerI gm = GameManager.getInstance(); ReportBuffer instance = null; - if (gm != null) instance = gm.getReportBuffer(); - if (gm == null || instance == null) { + if (gm != null) { + instance = gm.getReportBuffer(); + } + if (instance == null) { // Queue in a static buffer until the instance is created initialQueue.add(message); } else { - instance.addMessage(message); + // ignore undo and redo for the new reportItems + if (message.equals(LocalText.getText("UNDO")) || message.equals(LocalText.getText("REDO"))) { + instance.reportQueue.add(message); + return; + } + int moveStackIndex = gm.getMoveStack().getIndex(); + instance.addMessage(message, moveStackIndex); } } @@ -169,7 +287,7 @@ else return instance.getReportQueue(); } - + /** clear the current buffer */ public static void clear() { ReportBuffer instance = getInstance(); @@ -184,18 +302,17 @@ return GameManager.getInstance().getReportBuffer(); } - - - public static void addWaiting (String string) { - getInstance().waitQueue.add (string); + public static void addWaiting (String message) { + getInstance().waitQueue.add(message); } public static void getAllWaiting () { ReportBuffer instance = getInstance(); for (String message : instance.waitQueue) { - instance.addMessage (message); + add(message); } instance.waitQueue.clear(); } + } Modified: trunk/18xx/rails/game/move/MoveStack.java =================================================================== --- trunk/18xx/rails/game/move/MoveStack.java 2010-08-10 21:52:19 UTC (rev 1377) +++ trunk/18xx/rails/game/move/MoveStack.java 2010-08-10 23:08:08 UTC (rev 1378) @@ -68,6 +68,7 @@ moveStack.add(currentMoveSet); lastIndex++; currentMoveSet = null; + ReportBuffer.createNewReportItem(this.getIndex()); return true; } } @@ -112,7 +113,7 @@ MoveSet undoAction; do { ReportBuffer.add(LocalText.getText("UNDO")); - // log.debug ("MoveStack undo index is "+lastIndex); + log.debug ("MoveStack undo index is "+lastIndex); undoAction = moveStack.get(lastIndex--); undoAction.unexecute(); } while (undoAction.isLinkedToPreviousMove()); @@ -129,14 +130,13 @@ public boolean redoMoveSet () { if (currentMoveSet == null && lastIndex < moveStack.size() - 1) { MoveSet redoAction; - redoAction= moveStack.get(++lastIndex); do { + redoAction = moveStack.get(++lastIndex); ReportBuffer.add(LocalText.getText("REDO")); + log.debug ("MoveStack redo index is "+lastIndex); redoAction.reexecute(); if (lastIndex == moveStack.size() - 1) break; - redoAction= moveStack.get(++lastIndex); - } while (redoAction.isLinkedToPreviousMove()); - // log.debug ("MoveStack redo index is "+lastIndex); + } while (moveStack.get(lastIndex + 1).isLinkedToPreviousMove()); return true; } else { log.error("Invalid redo: index=" + lastIndex + " size=" @@ -164,5 +164,21 @@ public int getIndex() { return lastIndex + 1; } - + + /** + * undo/redo to a given moveStack index + */ + public boolean gotoIndex(int index) { + if (getIndex() == index) return true; + else if (getIndex() < index) { + while (getIndex() < index) { + if (!redoMoveSet()) return false; + } + } else { + while (getIndex() > index) { + if (!undoMoveSet(true)) return false; + } + }; + return true; + } } Added: trunk/18xx/rails/ui/swing/AbstractReportWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/AbstractReportWindow.java (rev 0) +++ trunk/18xx/rails/ui/swing/AbstractReportWindow.java 2010-08-10 23:08:08 UTC (rev 1378) @@ -0,0 +1,34 @@ +package rails.ui.swing; + +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.swing.JFrame; + +import rails.util.Config; +import rails.util.LocalText; + +public abstract class AbstractReportWindow extends JFrame { + private static final long serialVersionUID = 1L; + + public void init() { + setSize(400, 400); + setLocation(600, 400); + setTitle(LocalText.getText("GameReportTitle")); + + final JFrame frame = this; + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + StatusWindow.uncheckMenuItemBox(StatusWindow.REPORT_CMD); + frame.dispose(); + } + }); + setVisible("yes".equalsIgnoreCase(Config.get("report.window.open"))); + } + + public abstract void updateLog(); + + public abstract void scrollDown(); + +} \ No newline at end of file Property changes on: trunk/18xx/rails/ui/swing/AbstractReportWindow.java ___________________________________________________________________ Added: svn:mime-type + text/plain Modified: trunk/18xx/rails/ui/swing/GameUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/GameUIManager.java 2010-08-10 21:52:19 UTC (rev 1377) +++ trunk/18xx/rails/ui/swing/GameUIManager.java 2010-08-10 23:08:08 UTC (rev 1378) @@ -29,7 +29,7 @@ public StockChart stockChart; public StatusWindow statusWindow; - public ReportWindow reportWindow; + public AbstractReportWindow reportWindow; public ConfigWindow configWindow; public ORUIManager orUIManager; public ORWindow orWindow; // TEMPORARY @@ -157,7 +157,11 @@ imageLoader = new ImageLoader(); stockChart = new StockChart(this); - reportWindow = new ReportWindow(gameManager); + if (Config.get("report.window.type").equalsIgnoreCase("static")) { + reportWindow = new ReportWindow(gameManager); + } else { + reportWindow = new ReportWindowDynamic(this); + } orWindow = new ORWindow(this); orUIManager = orWindow.getORUIManager(); @@ -223,7 +227,7 @@ // Follow-up the result log.debug("==Result from server: " + result); - reportWindow.addLog(); + reportWindow.updateLog(); /* if (DisplayBuffer.getAutoDisplay()) { if (displayServerMessage()) { @@ -449,6 +453,7 @@ } updateStatus(activeWindow); + } /** Stub, to be overridden in subclasses for special round types */ Modified: trunk/18xx/rails/ui/swing/ORUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/ORUIManager.java 2010-08-10 21:52:19 UTC (rev 1377) +++ trunk/18xx/rails/ui/swing/ORUIManager.java 2010-08-10 23:08:08 UTC (rev 1378) @@ -472,7 +472,7 @@ } - gameUIManager.reportWindow.addLog(); + gameUIManager.reportWindow.updateLog(); } /** Stub, can be overridden in subclasses */ Modified: trunk/18xx/rails/ui/swing/ORWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/ORWindow.java 2010-08-10 21:52:19 UTC (rev 1377) +++ trunk/18xx/rails/ui/swing/ORWindow.java 2010-08-10 23:08:08 UTC (rev 1378) @@ -101,7 +101,7 @@ } }); - gameUIManager.reportWindow.addLog(); + gameUIManager.reportWindow.updateLog(); } public ORUIManager getORUIManager() { Modified: trunk/18xx/rails/ui/swing/ReportWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/ReportWindow.java 2010-08-10 21:52:19 UTC (rev 1377) +++ trunk/18xx/rails/ui/swing/ReportWindow.java 2010-08-10 23:08:08 UTC (rev 1378) @@ -25,7 +25,7 @@ * This is the UI for the LogWindow. It displays logged messages to the user * during the rails.game. */ -public class ReportWindow extends JFrame implements ActionListener, KeyListener { +public class ReportWindow extends AbstractReportWindow implements ActionListener, KeyListener { private static final long serialVersionUID = 1L; private JTextArea reportText; @@ -156,23 +156,16 @@ setContentPane(messagePanel); - setSize(400, 400); - setLocation(600, 400); - setTitle(LocalText.getText("GameReportTitle")); - - final JFrame frame = this; - addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - StatusWindow.uncheckMenuItemBox(StatusWindow.REPORT_CMD); - frame.dispose(); - } - }); addKeyListener(this); - setVisible("yes".equalsIgnoreCase(Config.get("report.window.open"))); + + // default report window settings + super.init(); } - public void addLog() { + /* (non-Javadoc) + * @see rails.ui.swing.ReportWindowI#updateLog() + */ + public void updateLog() { String newText = ReportBuffer.get(); if (newText.length() > 0) { reportText.append(newText); Added: trunk/18xx/rails/ui/swing/ReportWindowDynamic.java =================================================================== --- trunk/18xx/rails/ui/swing/ReportWindowDynamic.java (rev 0) +++ trunk/18xx/rails/ui/swing/ReportWindowDynamic.java 2010-08-10 23:08:08 UTC (rev 1378) @@ -0,0 +1,163 @@ +package rails.ui.swing; + +import java.awt.EventQueue; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.net.URL; +import java.util.List; + +import javax.swing.JEditorPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.UIManager; +import javax.swing.event.HyperlinkEvent; +import javax.swing.event.HyperlinkListener; +import javax.swing.text.BadLocationException; +import javax.swing.text.html.HTMLDocument; + +import org.apache.log4j.Logger; + +import rails.game.ReportBuffer; +import rails.game.action.GameAction; +import rails.game.action.PossibleActions; +import rails.game.move.MoveStack; +import rails.ui.swing.elements.ActionButton; +import rails.util.LocalText; + +/** + * Dynamic Report window that acts as linked game history + */ + +public class ReportWindowDynamic extends AbstractReportWindow implements ActionListener, HyperlinkListener { + private static final long serialVersionUID = 1L; + + private GameUIManager gameUIManager; + + private JScrollPane reportPane; + private JEditorPane editorPane; + + private JPanel buttonPanel; + private ActionButton forwardButton; + private ActionButton backwardButton; + + protected static Logger log = + Logger.getLogger(ReportWindowDynamic.class.getPackage().getName()); + + public ReportWindowDynamic(GameUIManager gameUIManager) { + super(); + this.gameUIManager = gameUIManager; + init(); + } + + public void init() { + editorPane = new JEditorPane(); + editorPane.setEditable(false); + editorPane.setContentType("text/html"); + editorPane.addHyperlinkListener(this); + editorPane.setOpaque(false); + editorPane.setBorder(null); + + // add a CSS rule to force body tags to use the default label font + // instead of the value in javax.swing.text.html.default.csss + Font font = UIManager.getFont("Label.font"); + String bodyRule = "body { font-family: " + font.getFamily() + "; " + + "font-size: " + font.getSize() + "pt; }"; + ((HTMLDocument)editorPane.getDocument()).getStyleSheet().addRule(bodyRule); + + reportPane = new JScrollPane(editorPane); + add(reportPane, "Center"); + + buttonPanel = new JPanel(); + add(buttonPanel, "South"); + + + backwardButton = new ActionButton(LocalText.getText("REPORT_MOVE_BACKWARD")); + backwardButton.addActionListener(this); + buttonPanel.add(backwardButton); + + forwardButton = new ActionButton(LocalText.getText("REPORT_MOVE_FORWARD")); + forwardButton.addActionListener(this); + buttonPanel.add(forwardButton); + + super.init(); + } + + @Override + public void updateLog() { + // set the content of the pane to the current + editorPane.setText(ReportBuffer.getReportItems()); + scrollDown(); + + forwardButton.setEnabled(false); + backwardButton.setEnabled(true); + List<GameAction> gameActions = PossibleActions.getInstance().getType(GameAction.class); + for (GameAction action:gameActions) { + switch (action.getMode()) { + case GameAction.UNDO: + case GameAction.FORCED_UNDO: + backwardButton.setPossibleAction(action); + backwardButton.setEnabled(true); + break; + case GameAction.REDO: + forwardButton.setPossibleAction(action); + forwardButton.setEnabled(true); + break; + } + } + } + + @Override + public void scrollDown() { + // only set caret if visible + if (!this.isVisible()) return; + + // find the active message in the parsed html code (not identical to the position in the html string) + // thus the message indicator is used + int caretPosition; + try{ + String docText = editorPane.getDocument().getText(0, editorPane.getDocument().getLength()); + caretPosition = docText.indexOf(ReportBuffer.ACTIVE_MESSAGE_INDICATOR); + } catch (BadLocationException e){ + caretPosition = -1; + }; + final int caretPositionStore = caretPosition; + if (caretPosition != -1) { + editorPane.setCaretPosition(caretPositionStore); + } + } + + public void actionPerformed(ActionEvent e) { + ActionButton button = (ActionButton)e.getSource(); + GameAction action = (GameAction)button.getPossibleActions().get(0); + gameUIManager.processOnServer(action); + } + + public void hyperlinkUpdate(HyperlinkEvent e) { + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + URL url = e.getURL(); +// String protocol = e.getURL().getProtocol(); + int index = url.getPort(); + gotoIndex(index + 1); + } + } + + private void gotoIndex(int index) { + 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); + gameUIManager.processOnServer(action); + } else if (index < currentIndex) { // move backward + if (index != currentIndex - 1) { + stack.gotoIndex(index + 1); + } + GameAction action = new GameAction(GameAction.FORCED_UNDO); + gameUIManager.processOnServer(action); + } + } + +} Property changes on: trunk/18xx/rails/ui/swing/ReportWindowDynamic.java ___________________________________________________________________ Added: svn:mime-type + text/plain Modified: trunk/18xx/rails/ui/swing/StatusWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/StatusWindow.java 2010-08-10 21:52:19 UTC (rev 1377) +++ trunk/18xx/rails/ui/swing/StatusWindow.java 2010-08-10 23:08:08 UTC (rev 1378) @@ -602,6 +602,7 @@ System.exit(0); } else if (command.equals(REPORT_CMD)) { gameUIManager.reportWindow.setVisible(((JMenuItem) actor.getSource()).isSelected()); + gameUIManager.reportWindow.scrollDown(); return; } else if (command.equals(MARKET_CMD)) { gameUIManager.stockChart.setVisible(((JMenuItem) actor.getSource()).isSelected()); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-10 21:52:25
|
Revision: 1377 http://rails.svn.sourceforge.net/rails/?rev=1377&view=rev Author: stefanfrey Date: 2010-08-10 21:52:19 +0000 (Tue, 10 Aug 2010) Log Message: ----------- Made numOfORs a state integer variable to support undo behavior Modified Paths: -------------- trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/specific/_18EU/GameManager_18EU.java Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-08-10 21:51:07 UTC (rev 1376) +++ trunk/18xx/rails/game/GameManager.java 2010-08-10 21:52:19 UTC (rev 1377) @@ -108,7 +108,7 @@ new IntegerState("AbsoluteORNUmber"); protected IntegerState relativeORNumber = new IntegerState("RelativeORNumber"); - protected int numOfORs; + protected IntegerState numOfORs = new IntegerState("numOfORs"); protected BooleanState gameOver = new BooleanState("GameOver" ,false); protected Boolean gameOverReportedUI = false; @@ -567,7 +567,9 @@ } else if (skipFirstStockRound) { PhaseI currentPhase = phaseManager.getCurrentPhase(); - numOfORs = currentPhase.getNumberOfOperatingRounds(); + if (currentPhase.getNumberOfOperatingRounds() != numOfORs.intValue()) { + numOfORs.set(currentPhase.getNumberOfOperatingRounds()); + } log.info("Phase=" + currentPhase.getName() + " ORs=" + numOfORs); // Create a new OperatingRound (never more than one Stock Round) @@ -581,7 +583,7 @@ } else if (round instanceof StockRound) { PhaseI currentPhase = getCurrentPhase(); if (currentPhase == null) log.error ("Current Phase is null??", new Exception ("")); - numOfORs = currentPhase.getNumberOfOperatingRounds(); + numOfORs.set(currentPhase.getNumberOfOperatingRounds()); log.info("Phase=" + currentPhase.getName() + " ORs=" + numOfORs); // Create a new OperatingRound (never more than one Stock Round) @@ -594,7 +596,7 @@ finishGame(); - } else if (relativeORNumber.add(1) <= numOfORs) { + } else if (relativeORNumber.add(1) <= numOfORs.intValue()) { // There will be another OR startOperatingRound(true); } else if (startPacket != null && !startPacket.areAllSold()) { @@ -697,7 +699,7 @@ } public String getNumOfORs () { - return new Integer(numOfORs).toString(); + return numOfORs.getText(); } /* (non-Javadoc) @@ -1639,7 +1641,6 @@ } return cm; } - /** Return a list of companies in operation order. * <p>Note that, unlike Round.setOperatingCompanies(), this method does <b>not</b> check * if the companies are actualy allowed to operate. One purpose is to check for upping the Modified: trunk/18xx/rails/game/specific/_18EU/GameManager_18EU.java =================================================================== --- trunk/18xx/rails/game/specific/_18EU/GameManager_18EU.java 2010-08-10 21:51:07 UTC (rev 1376) +++ trunk/18xx/rails/game/specific/_18EU/GameManager_18EU.java 2010-08-10 21:52:19 UTC (rev 1377) @@ -19,7 +19,7 @@ public void nextRound(RoundI round) { if (round instanceof OperatingRound_18EU) { if (playerToStartFMERound.getObject() != null - && relativeORNumber.intValue() == numOfORs) { + && relativeORNumber.intValue() == numOfORs.intValue()) { createRound (FinalMinorExchangeRound.class).start ((Player)playerToStartFMERound.getObject()); playerToStartFMERound.set(null); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-10 21:51:13
|
Revision: 1376 http://rails.svn.sourceforge.net/rails/?rev=1376&view=rev Author: stefanfrey Date: 2010-08-10 21:51:07 +0000 (Tue, 10 Aug 2010) Log Message: ----------- Fixed bug of the alias checks Modified Paths: -------------- trunk/18xx/rails/game/action/BuyCertificate.java Modified: trunk/18xx/rails/game/action/BuyCertificate.java =================================================================== --- trunk/18xx/rails/game/action/BuyCertificate.java 2010-08-10 19:39:41 UTC (rev 1375) +++ trunk/18xx/rails/game/action/BuyCertificate.java 2010-08-10 21:51:07 UTC (rev 1376) @@ -146,10 +146,10 @@ /* Check for aliases (old company names) */ CompanyManagerI companyManager = gameManager.getCompanyManager(); companyName = companyManager.checkAlias (companyName); - certUniqueId = companyManager.checkAliasInCertId(certUniqueId); if (certUniqueId != null) { // Old style + certUniqueId = companyManager.checkAliasInCertId(certUniqueId); certificate = PublicCertificate.getByUniqueId(certUniqueId); from = gameManager.getPortfolioByName(fromName); company = certificate.getCompany(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-08-10 19:39:47
|
Revision: 1375 http://rails.svn.sourceforge.net/rails/?rev=1375&view=rev Author: evos Date: 2010-08-10 19:39:41 +0000 (Tue, 10 Aug 2010) Log Message: ----------- Reclassified 1825 Modified Paths: -------------- trunk/18xx/data/GamesList.xml Modified: trunk/18xx/data/GamesList.xml =================================================================== --- trunk/18xx/data/GamesList.xml 2010-08-10 19:39:00 UTC (rev 1374) +++ trunk/18xx/data/GamesList.xml 2010-08-10 19:39:41 UTC (rev 1375) @@ -194,7 +194,7 @@ </Game> <Game name="1825"> - <Note>Experimental</Note> + <Note>Not yet playable</Note> <Description>1825 Unit 1 (c) 1994 Hartland Trefoil Ltd. Designed by Francis Tresham This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-08-10 19:39:06
|
Revision: 1374 http://rails.svn.sourceforge.net/rails/?rev=1374&view=rev Author: evos Date: 2010-08-10 19:39:00 +0000 (Tue, 10 Aug 2010) Log Message: ----------- Fixed bug that allowed 1835 share selling of unfloated companies. Modified Paths: -------------- trunk/18xx/LocalisedText.properties trunk/18xx/rails/game/ShareSellingRound.java trunk/18xx/rails/game/StockRound.java trunk/18xx/rails/game/TreasuryShareRound.java trunk/18xx/rails/game/specific/_1835/PrussianFormationRound.java Modified: trunk/18xx/LocalisedText.properties =================================================================== --- trunk/18xx/LocalisedText.properties 2010-08-08 15:20:50 UTC (rev 1373) +++ trunk/18xx/LocalisedText.properties 2010-08-10 19:39:00 UTC (rev 1374) @@ -495,6 +495,7 @@ RouteAwareness=support for tile and token lays RunsWithBorrowedTrain={0} runs with a borrowed {1}-train and must withhold revenue RustsTrains=Rusts {0}-trains +SaleNotAllowed=Selling shares of company {0} is not allowed SAVE=Save SAVEAS=Save As ... SaveFailed=Save failed, reason: {0} Modified: trunk/18xx/rails/game/ShareSellingRound.java =================================================================== --- trunk/18xx/rails/game/ShareSellingRound.java 2010-08-08 15:20:50 UTC (rev 1373) +++ trunk/18xx/rails/game/ShareSellingRound.java 2010-08-10 19:39:00 UTC (rev 1374) @@ -108,8 +108,8 @@ */ for (PublicCompanyI company : companyManager.getAllPublicCompanies()) { - // Can't sell shares that have no price - if (!company.hasStarted()) continue; + // Check if shares of this company can be sold at all + if (!mayPlayerSellShareOfCompany(company)) continue; share = maxShareToSell = playerPortfolio.getShare(company); if (maxShareToSell == 0) continue; @@ -231,6 +231,12 @@ break; } + // May player sell this company + if (!mayPlayerSellShareOfCompany(company)) { + errMsg = LocalText.getText("SaleNotAllowed", companyName); + break; + } + // The player must have the share(s) if (portfolio.getShare(company) < numberToSell) { errMsg = LocalText.getText("NoShareOwned"); Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2010-08-08 15:20:50 UTC (rev 1373) +++ trunk/18xx/rails/game/StockRound.java 2010-08-10 19:39:00 UTC (rev 1374) @@ -358,13 +358,9 @@ */ for (PublicCompanyI company : companyManager.getAllPublicCompanies()) { - // Can't sell shares that have no price - if (!company.hasStarted() || !company.hasStockPrice()) continue; + // Check if shares of this company can be sold at all + if (!mayPlayerSellShareOfCompany(company)) continue; - // In some games, can't sell shares if not operated - if (company.mustHaveOperatedToTradeShares() - && !company.hasOperated()) continue; - share = maxShareToSell = playerPortfolio.getShare(company); if (maxShareToSell == 0) continue; @@ -957,6 +953,12 @@ break; } + // May player sell this company + if (!mayPlayerSellShareOfCompany(company)) { + errMsg = LocalText.getText("SaleNotAllowed", companyName); + break; + } + // The player must have the share(s) if (portfolio.getShare(company) < numberToSell) { errMsg = LocalText.getText("NoShareOwned"); @@ -1395,6 +1397,19 @@ return true; } + public boolean mayPlayerSellShareOfCompany(PublicCompanyI company) { + + // Can't sell shares that have no price + if (!company.hasStarted() || !company.hasStockPrice()) return false; + + // In some games, can't sell shares if not operated + if (noSaleIfNotOperated() + && !company.hasOperated()) return false; + + return true; + } + + /** * Can the current player do any buying? * @@ -1408,10 +1423,10 @@ protected boolean isPlayerOverLimits(Player player) { return (isPlayerOverLimitsDetail(player) != null); } - + protected String isPlayerOverLimitsDetail(Player player) { StringBuffer violations = new StringBuffer(); - + // Over the total certificate hold Limit? if (player.getPortfolio().getCertificateCount() > gameManager.getPlayerCertificateLimit(player)) { violations.append(LocalText.getText("ExceedCertificateLimitTotal", @@ -1423,7 +1438,7 @@ // Over the hold limit of any company? for (PublicCompanyI company : companyManager.getAllPublicCompanies()) { if (company.hasStarted() && company.hasStockPrice() - && !checkAgainstHoldLimit(player, company, 0)) { + && !checkAgainstHoldLimit(player, company, 0)) { violations.append(LocalText.getText("ExceedCertificateLimitCompany", company.getName(), player.getPortfolio().getShare(company), Modified: trunk/18xx/rails/game/TreasuryShareRound.java =================================================================== --- trunk/18xx/rails/game/TreasuryShareRound.java 2010-08-08 15:20:50 UTC (rev 1373) +++ trunk/18xx/rails/game/TreasuryShareRound.java 2010-08-10 19:39:00 UTC (rev 1374) @@ -71,7 +71,8 @@ possibleActions.clear(); - if (!operatingCompany.hasOperated()) return true; + if (operatingCompany.mustHaveOperatedToTradeShares() + && !operatingCompany.hasOperated()) return true; if (!hasSold.booleanValue()) setBuyableCerts(); if (!hasBought.booleanValue()) setSellableCerts(); Modified: trunk/18xx/rails/game/specific/_1835/PrussianFormationRound.java =================================================================== --- trunk/18xx/rails/game/specific/_1835/PrussianFormationRound.java 2010-08-08 15:20:50 UTC (rev 1373) +++ trunk/18xx/rails/game/specific/_1835/PrussianFormationRound.java 2010-08-10 19:39:00 UTC (rev 1374) @@ -1,8 +1,6 @@ package rails.game.specific._1835; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import java.util.*; import rails.common.GuiDef; import rails.game.*; @@ -23,7 +21,7 @@ private boolean forcedStart; private boolean mergePr; private boolean forcedMerge; - + private List<CompanyI> foldablePrePrussians; private enum Step { @@ -36,7 +34,7 @@ private static String PR_ID = GameManager_1835.PR_ID; private static String M2_ID = GameManager_1835.M2_ID; - + public PrussianFormationRound (GameManagerI gameManager) { super (gameManager); @@ -60,7 +58,7 @@ +" mergePr="+mergePr+" forcedMerge="+forcedMerge); step = startPr ? Step.START : Step.MERGE; - + if (step == Step.START) { m2 = companyManager.getPublicCompany(M2_ID); setCurrentPlayer(m2.getPresident()); @@ -70,7 +68,7 @@ step = Step.MERGE; } } - + if (step == Step.MERGE) { startingPlayer = ((GameManager_1835)gameManager).getPrussianFormationStartingPlayer(); @@ -116,9 +114,9 @@ } else if (step == Step.MERGE) { possibleActions.add(new FoldIntoPrussian(foldablePrePrussians)); - + } else if (step == Step.DISCARD_TRAINS) { - + if (prussian.getNumberOfTrains() > prussian.getTrainLimit(getCurrentPhase().getIndex())) { possibleActions.add(new DiscardTrain(prussian, prussian.getPortfolio().getUniqueTrains(), true)); @@ -149,14 +147,14 @@ } } } - + @Override protected boolean processGameSpecificAction(PossibleAction action) { if (action instanceof FoldIntoPrussian) { FoldIntoPrussian a = (FoldIntoPrussian) action; - + if (step == Step.START) { if (!startPrussian(a)) { finishRound(); @@ -164,29 +162,29 @@ step = Step.MERGE; findNextMergingPlayer(false); } - + } else if (step == Step.MERGE) { - + mergeIntoPrussian (a); - + } - + return true; - + } else if (action instanceof DiscardTrain) { - + discardTrain ((DiscardTrain) action); return true; - + } else { return false; } } protected boolean findNextMergingPlayer(boolean skipCurrentPlayer) { - + while (true) { - + if (skipCurrentPlayer) { setNextPlayer(); if (getCurrentPlayer() == startingPlayer) { @@ -198,13 +196,13 @@ return false; } } - + setFoldablePrePrussians(); if (!foldablePrePrussians.isEmpty()) return true; skipCurrentPlayer = true; } } - + private boolean startPrussian (FoldIntoPrussian action) { // Validate @@ -237,9 +235,9 @@ return folding; } - + private void executeStartPrussian (boolean display) { - + prussian.start(); String message = LocalText.getText("START_MERGED_COMPANY", PR_ID, @@ -259,7 +257,7 @@ List<CompanyI> folded = action.getFoldedCompanies(); boolean folding = folded != null && !folded.isEmpty(); - + while (folding) { // TODO Some validation needed break; @@ -277,7 +275,7 @@ // Execute if (folding) executeExchange (folded, false, false); - + findNextMergingPlayer(true); return folding; @@ -320,11 +318,11 @@ company.getName()); ReportBuffer.add(message); if (display) DisplayBuffer.add (message); - + if (company instanceof PublicCompanyI) { PublicCompanyI minor = (PublicCompanyI) company; - + // Replace the home token BaseToken token = (BaseToken) minor.getTokens().get(0); City city = (City) token.getHolder(); @@ -337,15 +335,15 @@ city.getName()); ReportBuffer.add(message); if (display) DisplayBuffer.add (message); - + prussian.layBaseToken(hex, 0); } - + // Move any cash if (minor.getCash() > 0) { new CashMove (minor, prussian, minor.getCash()); } - + // Move any trains List<TrainI> trains = new ArrayList<TrainI> (minor.getPortfolio().getTrainList()); for (TrainI train : trains) { @@ -411,24 +409,26 @@ // This always finished this type of round finishRound(); - + return true; } + @Override protected void finishRound() { if (prussian.hasStarted()) prussian.checkPresidency(); + prussian.setOperated(); // To allow immediate share selling super.finishRound(); } public static boolean prussianIsComplete(GameManagerI gameManager) { - + for (PublicCompanyI company : gameManager.getAllPublicCompanies()) { if (!company.getTypeName().equalsIgnoreCase("Minor")) continue; - if (!company.isClosed()) return false; + if (!company.isClosed()) return false; } return true; } - + @Override public String toString() { return "1835 PrussianFormationRound"; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-08-08 15:20:57
|
Revision: 1373 http://rails.svn.sourceforge.net/rails/?rev=1373&view=rev Author: evos Date: 2010-08-08 15:20:50 +0000 (Sun, 08 Aug 2010) Log Message: ----------- 1835 to use "proper" (JDG) company names Modified Paths: -------------- trunk/18xx/data/1835/CompanyManager.xml 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/PublicCompany.java trunk/18xx/rails/game/action/BuyCertificate.java trunk/18xx/rails/game/action/BuyTrain.java trunk/18xx/rails/game/action/SellShares.java trunk/18xx/rails/game/specific/_1835/GameManager_1835.java trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java Modified: trunk/18xx/data/1835/CompanyManager.xml =================================================================== --- trunk/18xx/data/1835/CompanyManager.xml 2010-08-07 14:26:10 UTC (rev 1372) +++ trunk/18xx/data/1835/CompanyManager.xml 2010-08-08 15:20:50 UTC (rev 1373) @@ -155,29 +155,34 @@ </SpecialProperties> </Company> - <Company name="Bay" longname="Bayerische Eisenbahn" type="Major" startspace="C3" tokens="5" fgColour="FFFFFF" bgColour="0000FF"> + <Company name="BY" longname="Bayerische Eisenbahn" type="Major" startspace="C3" tokens="5" fgColour="FFFFFF" bgColour="0000FF" + alias="Bay"> <Home hex="O15"/> <IfOption name="BYFloatsAt" value="20%"> <Float percentage="20"/> </IfOption> </Company> - <Company name="Sax" longname="Sächsische Eisenbahn" type="Major" startspace="C4" tokens="3" fgColour="FFFFFF" bgColour="FF0000"> + <Company name="SX" longname="Sächsische Eisenbahn" type="Major" startspace="C4" tokens="3" fgColour="FFFFFF" bgColour="FF0000" + alias="Sax"> <Home hex="H16"/> <FirstTrainCloses type="Private" name="LD"/> </Company> - <Company name="Bad" longname="Badische Eisenbahn" type="Major" startspace="B4" available="no" tokens="2" fgColour="FFFFFF" bgColour="808000"> + <Company name="BA" longname="Badische Eisenbahn" type="Major" startspace="B4" available="no" tokens="2" fgColour="FFFFFF" bgColour="808000" + alias="Bad"> <Home hex="L6"/> <Certificate type="President" shares="2"/> <Certificate shares="1" number="6"/> <Certificate shares="2" number="1"/> </Company> - <Company name="Wrt" longname="Württembergische Eisenbahn" type="Major" startspace="B4" available="no" tokens="2" fgColour="000000" bgColour="FFFF00"> + <Company name="WT" longname="Württembergische Eisenbahn" type="Major" startspace="B4" available="no" tokens="2" fgColour="000000" bgColour="FFFF00" + alias="Wrt"> <Home hex="M9"/> <Certificate type="President" shares="2"/> <Certificate shares="1" number="6"/> <Certificate shares="2" number="1"/> </Company> - <Company name="Hes" longname="Hessische Eisenbahn" type="Major" startspace="B4" available="no" tokens="2" fgColour="000000" bgColour="00CC00"> + <Company name="HE" longname="Hessische Eisenbahn" type="Major" startspace="B4" available="no" tokens="2" fgColour="000000" bgColour="00CC00" + alias="Hes"> <Home hex="J8"/> <Certificate type="President" shares="2"/> <Certificate shares="1" number="6"/> @@ -189,13 +194,15 @@ <Certificate shares="2" number="2"/> <Certificate shares="1" number="4"/> </Company> - <Company name="Old" longname="Oldenburgische Eisenbahn" type="Major" startspace="B5" available="no" tokens="2" fgColour="000000" bgColour="C0C0C0"> + <Company name="OL" longname="Oldenburgische Eisenbahn" type="Major" startspace="B5" available="no" tokens="2" fgColour="000000" bgColour="C0C0C0" + alias="Old"> <Home hex="D6"/> <Certificate type="President" shares="2"/> <Certificate shares="2" number="2"/> <Certificate shares="1" number="4"/> </Company> - <Company name="Pr" longname="Preußische Eisenbahn" type="Major" startspace="I4" available="no" tokens="7" fgColour="FFFFFF" bgColour="000000"> + <Company name="PR" longname="Preußische Eisenbahn" type="Major" startspace="I4" available="no" tokens="7" fgColour="FFFFFF" bgColour="000000" + alias="Pr"> <Home hex="E19"/> <ShareUnit percentage="5" sharePriceUnits="2"/> <Float percentage="10"/> Modified: trunk/18xx/rails/game/Company.java =================================================================== --- trunk/18xx/rails/game/Company.java 2010-08-07 14:26:10 UTC (rev 1372) +++ trunk/18xx/rails/game/Company.java 2010-08-08 15:20:50 UTC (rev 1373) @@ -17,6 +17,7 @@ protected String name; protected String longName; + protected String alias = null; // To allow reloading files with old names after name changes protected CompanyTypeI type; protected int companyNumber; // For internal use @@ -160,6 +161,10 @@ return longName; } + public String getAlias() { + return alias; + } + public String getInfoText(){ return infoText; } Modified: trunk/18xx/rails/game/CompanyI.java =================================================================== --- trunk/18xx/rails/game/CompanyI.java 2010-08-07 14:26:10 UTC (rev 1372) +++ trunk/18xx/rails/game/CompanyI.java 2010-08-08 15:20:50 UTC (rev 1373) @@ -53,6 +53,8 @@ public String getInfoText(); + public String getAlias(); + /** * Returns the CompanyType of the Company * Modified: trunk/18xx/rails/game/CompanyManager.java =================================================================== --- trunk/18xx/rails/game/CompanyManager.java 2010-08-07 14:26:10 UTC (rev 1372) +++ trunk/18xx/rails/game/CompanyManager.java 2010-08-08 15:20:50 UTC (rev 1373) @@ -40,6 +40,9 @@ private Map<String, StartPacket> startPacketMap = new HashMap<String, StartPacket>(); + /** A map to enable translating aliases to names */ + protected Map<String, String> aliases = null; + private int numberOfPublicCompanies = 0; protected static Logger log = @@ -140,10 +143,15 @@ new HashMap<String, CompanyI>()); (mCompaniesByTypeAndName.get(type)).put( name, company); + + String alias = company.getAlias(); + if (alias != null) createAlias (alias, name); + } catch (Exception e) { throw new ConfigurationException(LocalText.getText( "ClassCannotBeInstantiated", cType.getClassName()), e); } + } /* Read and configure the start packets */ @@ -182,6 +190,30 @@ } } + private void createAlias (String alias, String name) { + if (aliases == null) { + aliases = new HashMap<String, String>(); + } + aliases.put(alias, name); + } + + public String checkAlias (String alias) { + if (aliases != null && aliases.containsKey(alias)) { + return aliases.get(alias); + } else { + return alias; + } + } + + public String checkAliasInCertId (String certId) { + String[] parts = certId.split("-"); + String realName = checkAlias (parts[0]); + if (!parts[0].equals(realName)) { + return realName + "-" + parts[1]; + } else { + return certId; + } + } /** * @see rails.game.CompanyManagerI#getCompany(java.lang.String) * @@ -191,7 +223,7 @@ } public PublicCompanyI getPublicCompany(String name) { - return mPublicCompanies.get(name); + return mPublicCompanies.get(checkAlias(name)); } public List<PrivateCompanyI> getAllPrivateCompanies() { @@ -202,19 +234,6 @@ return lPublicCompanies; } - /* - public PublicCompanyI getCompanyByName(String name) { - for (int i = 0; i < lPublicCompanies.size(); i++) { - PublicCompany co = (PublicCompany) lPublicCompanies.get(i); - if (name.equalsIgnoreCase(co.getName())) { - return lPublicCompanies.get(i); - } - } - - return null; - } - */ - public List<CompanyTypeI> getCompanyTypes() { return lCompanyTypes; } @@ -222,7 +241,7 @@ public CompanyI getCompany(String type, String name) { if (mCompaniesByTypeAndName.containsKey(type)) { - return (mCompaniesByTypeAndName.get(type)).get(name); + return (mCompaniesByTypeAndName.get(type)).get(checkAlias(name)); } else { return null; } Modified: trunk/18xx/rails/game/CompanyManagerI.java =================================================================== --- trunk/18xx/rails/game/CompanyManagerI.java 2010-08-07 14:26:10 UTC (rev 1372) +++ trunk/18xx/rails/game/CompanyManagerI.java 2010-08-08 15:20:50 UTC (rev 1373) @@ -54,7 +54,9 @@ */ public CompanyI getCompany(String type, String name); - //public PublicCompanyI getCompanyByName(String name); + public String checkAlias (String alias); + public String checkAliasInCertId (String certId); + public List<CompanyTypeI> getCompanyTypes(); public void closeAllPrivates(); Modified: trunk/18xx/rails/game/PublicCompany.java =================================================================== --- trunk/18xx/rails/game/PublicCompany.java 2010-08-07 14:26:10 UTC (rev 1372) +++ trunk/18xx/rails/game/PublicCompany.java 2010-08-08 15:20:50 UTC (rev 1373) @@ -93,7 +93,7 @@ /** Company treasury, holding cash */ protected CashModel treasury = null; - + /** PresidentModel */ protected PresidentModel presidentModel = null; @@ -196,9 +196,6 @@ /** Are the certificates available from the first SR? */ boolean certsAreInitiallyAvailable = true; - /** Privates and Certificates owned by the public company */ - //protected Portfolio portfolio; - /** What percentage of ownership constitutes "one share" */ protected IntegerState shareUnit; @@ -289,13 +286,13 @@ longName = tag.getAttributeAsString("longname", name); infoText = "<html>"+longName; + alias = tag.getAttributeAsString("alias", alias); + /* Configure public company features */ fgHexColour = tag.getAttributeAsString("fgColour", fgHexColour); - //fgColour = new Color(Integer.parseInt(fgHexColour, 16)); fgColour = Util.parseColour(fgHexColour); bgHexColour = tag.getAttributeAsString("bgColour", bgHexColour); - //bgColour = new Color(Integer.parseInt(bgHexColour, 16)); bgColour = Util.parseColour(bgHexColour); floatPerc = tag.getAttributeAsInteger("floatPerc", floatPerc); @@ -1990,5 +1987,5 @@ public String getExtraShareMarks () { return ""; } - + } Modified: trunk/18xx/rails/game/action/BuyCertificate.java =================================================================== --- trunk/18xx/rails/game/action/BuyCertificate.java 2010-08-07 14:26:10 UTC (rev 1372) +++ trunk/18xx/rails/game/action/BuyCertificate.java 2010-08-08 15:20:50 UTC (rev 1373) @@ -143,6 +143,11 @@ GameManagerI gameManager = GameManager.getInstance(); + /* Check for aliases (old company names) */ + CompanyManagerI companyManager = gameManager.getCompanyManager(); + companyName = companyManager.checkAlias (companyName); + certUniqueId = companyManager.checkAliasInCertId(certUniqueId); + if (certUniqueId != null) { // Old style certificate = PublicCertificate.getByUniqueId(certUniqueId); Modified: trunk/18xx/rails/game/action/BuyTrain.java =================================================================== --- trunk/18xx/rails/game/action/BuyTrain.java 2010-08-07 14:26:10 UTC (rev 1372) +++ trunk/18xx/rails/game/action/BuyTrain.java 2010-08-08 15:20:50 UTC (rev 1373) @@ -29,17 +29,17 @@ private boolean forcedBuyIfNoRoute = false; // TODO Remove once route checking exists transient private List<TrainI> trainsForExchange = null; private String[] trainsForExchangeUniqueIds; - + /** Obsolete, but left in for backwards compatibility of saved files */ private boolean forcedExchange = false; - + private boolean presidentMustAddCash = false; private boolean presidentMayAddCash = false; private int presidentCashToAdd = 0; transient private SpecialTrainBuy specialProperty = null; private int specialPropertyId = 0; - + private String extraMessage = null; // User settings @@ -91,7 +91,7 @@ public void setForcedBuyIfNoRoute(boolean hasNoTrains) { this.forcedBuyIfNoRoute = hasNoTrains; } - + public void setExtraMessage (String message) { extraMessage = message; } @@ -119,14 +119,14 @@ return specialProperty != null; } - /** - * To be used for all usage of train, also within this class. - * After reloading the 2nd copy etc. of a train with unlimited quantity, + /** + * To be used for all usage of train, also within this class. + * After reloading the 2nd copy etc. of a train with unlimited quantity, * the train attribute will be null (because readObject() is called and the * train is initiated before the actions have been executed - the second * train is in this case only created after buying the first one). * @return - */ + */ public TrainI getTrain() { if (train == null) { train = GameManager.getInstance().getTrainManager().getTrainByUniqueId(trainUniqueId); @@ -269,11 +269,14 @@ GameManagerI gameManager = GameManager.getInstance(); TrainManager trainManager = gameManager.getTrainManager(); + CompanyManagerI companyManager = gameManager.getCompanyManager(); + fromName = companyManager.checkAlias (fromName); + train = trainManager.getTrainByUniqueId(trainUniqueId); // Note: the 2nd etc. copy of an unlimited quantity train will become null this way. // Set getTrain() for how this is fixed. - + from = gameManager.getPortfolioByName(fromName); if (trainsForExchangeUniqueIds != null && trainsForExchangeUniqueIds.length > 0) { Modified: trunk/18xx/rails/game/action/SellShares.java =================================================================== --- trunk/18xx/rails/game/action/SellShares.java 2010-08-07 14:26:10 UTC (rev 1372) +++ trunk/18xx/rails/game/action/SellShares.java 2010-08-08 15:20:50 UTC (rev 1373) @@ -8,8 +8,7 @@ import java.io.IOException; import java.io.ObjectInputStream; -import rails.game.Bank; -import rails.game.PublicCompanyI; +import rails.game.*; import rails.util.Util; /** @@ -115,7 +114,9 @@ in.defaultReadObject(); + CompanyManagerI companyManager = getCompanyManager(); if (Util.hasValue(companyName)) - company = getCompanyManager().getPublicCompany(companyName); + companyName = companyManager.checkAlias(companyName); + company = companyManager.getPublicCompany(companyName); } } Modified: trunk/18xx/rails/game/specific/_1835/GameManager_1835.java =================================================================== --- trunk/18xx/rails/game/specific/_1835/GameManager_1835.java 2010-08-07 14:26:10 UTC (rev 1372) +++ trunk/18xx/rails/game/specific/_1835/GameManager_1835.java 2010-08-08 15:20:50 UTC (rev 1373) @@ -7,16 +7,16 @@ private RoundI previousRound = null; private Player prFormStartingPlayer = null; - + public static String M2_ID = "M2"; - public static String PR_ID = "Pr"; - public static String OL_ID = "Old"; + public static String PR_ID = "PR"; + public static String OL_ID = "OL"; public static String MS_ID = "MS"; - public static String WT_ID = "Wrt"; - public static String HE_ID = "Hes"; - public static String BA_ID = "Bad"; - public static String SX_ID = "Sax"; - public static String BY_ID = "Bay"; + public static String WT_ID = "WT"; + public static String HE_ID = "HE"; + public static String BA_ID = "BA"; + public static String SX_ID = "SX"; + public static String BY_ID = "BY"; public GameManager_1835() { super(); @@ -47,7 +47,7 @@ } } - + public void startPrussianFormationRound(OperatingRound_1835 or) { interruptedRound = or; @@ -61,12 +61,13 @@ public Player getPrussianFormationStartingPlayer() { return prFormStartingPlayer; } - + + @Override public int getPlayerCertificateLimit(Player player) { int limit = playerCertificateLimit.intValue(); for (PublicCompanyI company : companyManager.getAllPublicCompanies()) { if (company.getTypeName().equalsIgnoreCase("Major") - && company.getPresident() == player + && company.getPresident() == player && player.getPortfolio().getShare(company) >= 80) limit++; } return limit; Modified: trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java =================================================================== --- trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java 2010-08-07 14:26:10 UTC (rev 1372) +++ trunk/18xx/rails/game/specific/_1835/OperatingRound_1835.java 2010-08-08 15:20:50 UTC (rev 1373) @@ -1,45 +1,24 @@ package rails.game.specific._1835; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; +import java.util.*; -import rails.game.Bank; -import rails.game.CashHolder; -import rails.game.DisplayBuffer; -import rails.game.GameDef; -import rails.game.GameManagerI; -import rails.game.GameOption; -import rails.game.OperatingRound; -import rails.game.PhaseI; -import rails.game.Player; -import rails.game.Portfolio; -import rails.game.PrivateCompanyI; -import rails.game.PublicCertificateI; -import rails.game.PublicCompanyI; -import rails.game.ReportBuffer; -import rails.game.StockSpaceI; +import rails.game.*; import rails.game.action.DiscardTrain; import rails.game.action.LayTile; import rails.game.move.CashMove; import rails.game.move.MapChange; -import rails.game.special.ExchangeForShare; -import rails.game.special.SpecialPropertyI; -import rails.game.special.SpecialTileLay; +import rails.game.special.*; import rails.game.state.BooleanState; import rails.util.LocalText; public class OperatingRound_1835 extends OperatingRound { - - private BooleanState needPrussianFormationCall + + private BooleanState needPrussianFormationCall = new BooleanState ("NeedPrussianFormationCall", false); private BooleanState hasLaidExtraOBBTile = new BooleanState ("HasLaidExtraOBBTile", false); - - /** + + /** * Registry of percentage of PR revenue to be denied per player * because of having produced revenue in the same OR. */ @@ -51,6 +30,7 @@ } /** Can a public company operate? (1835 special version) */ + @Override protected boolean canCompanyOperateThisRound (PublicCompanyI company) { if (!company.hasFloated() || company.isClosed()) { return false; @@ -66,6 +46,7 @@ return true; } + @Override protected void privatesPayOut() { int count = 0; for (PrivateCompanyI priv : companyManager.getAllPrivateCompanies()) { @@ -79,8 +60,8 @@ Bank.format(revenue), priv.getName())); new CashMove(bank, recipient, revenue); - - /* Register black private equivalent PR share value + + /* Register black private equivalent PR share value * so it can be subtracted if PR operates */ if (recipient instanceof Player && priv.getSpecialProperties() != null && priv.getSpecialProperties().size() > 0) { @@ -92,7 +73,7 @@ Player player = (Player) recipient; addIncomeDenialShare (player, share); } - + } } } @@ -103,11 +84,11 @@ } private void addIncomeDenialShare (Player player, int share) { - + if (!deniedIncomeShare.containsKey(player)) { new MapChange<Player, Integer> (deniedIncomeShare, player, share); } else { - new MapChange<Player, Integer> (deniedIncomeShare, player, + new MapChange<Player, Integer> (deniedIncomeShare, player, share + deniedIncomeShare.get(player)); } //log.debug("+++ Denied "+share+"% share of PR income to "+player.getName()); @@ -117,10 +98,11 @@ * A special rule applies to 1835 to prevent black privates and minors providing * income twice during an OR. */ + @Override protected Map<CashHolder, Integer> countSharesPerRecipient () { - + Map<CashHolder, Integer> sharesPerRecipient = super.countSharesPerRecipient(); - + if (operatingCompany.getName().equalsIgnoreCase(GameManager_1835.PR_ID)) { for (Player player : deniedIncomeShare.keySet()) { if (!sharesPerRecipient.containsKey(player)) continue; @@ -131,19 +113,20 @@ player.getName(), share, GameManager_1835.PR_ID)); - + } } - + return sharesPerRecipient; } - /** - * Register black minors as having operated + /** + * Register black minors as having operated * for the purpose of denying income after conversion to a PR share */ + @Override protected void initTurn() { - + super.initTurn(); List<SpecialPropertyI> sps = operatingCompany.getSpecialProperties(); @@ -152,32 +135,32 @@ addIncomeDenialShare (operatingCompany.getPresident(), efs.getShare()); } } - + @Override public void resume() { - + PublicCompanyI prussian = companyManager.getPublicCompany(GameManager_1835.PR_ID); - + if (prussian.hasFloated() && !prussian.hasOperated() // PR has just started. Check if it can operate this round - // That's only the case if M1 has just bought + // That's only the case if M1 has just bought // the first 4-train or 4+4-train && operatingCompany == companyManager.getPublicCompany("M1")) { log.debug("M2 has not operated: PR can operate"); - + // Insert the Prussian before the first major company // with a lower current price that hoas not yet operated // and isn't currently operating - + int index = 0; int operatingCompanyIndex = getOperatingCompanyIndex(); for (PublicCompanyI company : setOperatingCompanies()) { if (index > operatingCompanyIndex - && company.hasStockPrice() + && company.hasStockPrice() && company.hasFloated() && !company.isClosed() && company != operatingCompany - && company.getCurrentSpace().getPrice() + && company.getCurrentSpace().getPrice() < prussian.getCurrentSpace().getPrice()) { log.debug("PR will operate before "+company.getName()); break; @@ -189,15 +172,16 @@ log.debug("PR will operate at order position "+index); } else { - + log.debug("M2 has operated: PR cannot operate"); - + } - + guiHints.setCurrentRoundType(getClass()); super.resume(); } - + + @Override protected void setSpecialTileLays() { /* Special-property tile lays */ @@ -207,16 +191,17 @@ for (SpecialTileLay stl : getSpecialProperties(SpecialTileLay.class)) { if (stl.isExtra() || !currentNormalTileLays.isEmpty()) { - + // 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)); } } } + @Override public boolean layTile(LayTile action) { // The extra OBB tiles may not both be laid in the same round @@ -233,17 +218,18 @@ return false; } } - + boolean result = super.layTile(action); - + if (result && action.getSpecialProperty() != null && action.getSpecialProperty().getLocationNameString().matches("M1(5|7)")) { hasLaidExtraOBBTile.set(true); } - + return result; } + @Override protected void newPhaseChecks() { PhaseI phase = getCurrentPhase(); if (phase.getName().equals("4") || phase.getName().equals("4+4") @@ -259,13 +245,14 @@ } } } - + + @Override public boolean discardTrain(DiscardTrain action) { - + boolean result = super.discardTrain(action); - if (result && getStep() == GameDef.OrStep.BUY_TRAIN + if (result && getStep() == GameDef.OrStep.BUY_TRAIN && needPrussianFormationCall.booleanValue()) { - // Do the postponed formation calls + // Do the postponed formation calls ((GameManager_1835)gameManager).startPrussianFormationRound (this); needPrussianFormationCall.set(false); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-07 14:26:17
|
Revision: 1372 http://rails.svn.sourceforge.net/rails/?rev=1372&view=rev Author: stefanfrey Date: 2010-08-07 14:26:10 +0000 (Sat, 07 Aug 2010) Log Message: ----------- Fixed bug of wrong cgr train limit Improved undo behavior of cgr formation Added PresidentModel for UI reasons Modified Paths: -------------- trunk/18xx/LocalisedText.properties trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/PublicCompany.java trunk/18xx/rails/game/PublicCompanyI.java trunk/18xx/rails/game/Round.java trunk/18xx/rails/game/model/ShareModel.java trunk/18xx/rails/game/move/MoveStack.java trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java trunk/18xx/rails/ui/swing/GameUIManager.java trunk/18xx/rails/ui/swing/ORPanel.java trunk/18xx/rails/ui/swing/ORUIManager.java trunk/18xx/rails/ui/swing/gamespecific/_1856/StatusWindow_1856.java Added Paths: ----------- trunk/18xx/rails/game/model/PresidentModel.java Modified: trunk/18xx/LocalisedText.properties =================================================================== --- trunk/18xx/LocalisedText.properties 2010-08-07 14:24:24 UTC (rev 1371) +++ trunk/18xx/LocalisedText.properties 2010-08-07 14:26:10 UTC (rev 1372) @@ -1,4 +1,5 @@ # Texts with lowercase keys are intended to be inserted into other messages +1856MergerDialog=Repay loan decision of {0} for CGR merger 1856THBHomeBlocked=THB home hex is blocked for token lays (unless gray tile) 1889PrivateBactive=Player {0} (owner of Private B) may lay port tile 1889PrivateCactive=Player {0} (previous owner of Private C) may lay tile on C4 immediately @@ -247,7 +248,7 @@ ExchangeTokensPrompt1=Select {0} cities where {1} will exchange a base token ExchangeTokensPrompt2=Select {0} through {1} cities where {2} will exchange a base token ExchangesTrain={0} exchanges a {1}-train for a {2}-train from {3} for {4} -ExceedCertificateLimit=<em>{0} exceeds certificate limit!</em><br>{1}<br>Only share selling allowed until certificate limit holds. +ExceedCertificateLimit=<em>{0} exceeds certificate limit!</em><br>{1}<br>Only share selling allowed until certificate limit holds again. ExceedCertificateLimitTotal=-> Player has {0} certificates, exceeds total certificate limit of {1}. ExceedCertificateLimitCompany=-> Player has a {1}% holding of {0}, exceeds company holding limit of {2}%. extra=extra Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2010-08-07 14:24:24 UTC (rev 1371) +++ trunk/18xx/rails/game/OperatingRound.java 2010-08-07 14:26:10 UTC (rev 1372) @@ -233,7 +233,7 @@ } else if (selectedAction instanceof ExchangeTokens) { - result = exchangeTokens ((ExchangeTokens)selectedAction); + result = exchangeTokens ((ExchangeTokens)selectedAction, false); // 2nd parameter: unlinked moveset } else if (selectedAction instanceof ClosePrivate) { Modified: trunk/18xx/rails/game/PublicCompany.java =================================================================== --- trunk/18xx/rails/game/PublicCompany.java 2010-08-07 14:24:24 UTC (rev 1371) +++ trunk/18xx/rails/game/PublicCompany.java 2010-08-07 14:26:10 UTC (rev 1372) @@ -93,6 +93,9 @@ /** Company treasury, holding cash */ protected CashModel treasury = null; + + /** PresidentModel */ + protected PresidentModel presidentModel = null; /** Has the company started? */ protected BooleanState hasStarted = null; @@ -620,6 +623,7 @@ lastRevenue.setOption(MoneyModel.SUPPRESS_INITIAL_ZERO); lastRevenueAllocation = new StringState(name + "_lastAllocation"); baseTokensModel = new BaseTokensModel(this); + presidentModel = new PresidentModel(this); hasStarted = new BooleanState(name + "_hasStarted", false); hasFloated = new BooleanState(name + "_hasFloated", false); @@ -1241,6 +1245,10 @@ return null; } + public PresidentModel getPresidentModel() { + return presidentModel; + } + public PublicCertificateI getPresidentsShare () { return certificates.get(0); } @@ -1982,4 +1990,5 @@ public String getExtraShareMarks () { return ""; } + } Modified: trunk/18xx/rails/game/PublicCompanyI.java =================================================================== --- trunk/18xx/rails/game/PublicCompanyI.java 2010-08-07 14:24:24 UTC (rev 1371) +++ trunk/18xx/rails/game/PublicCompanyI.java 2010-08-07 14:26:10 UTC (rev 1372) @@ -209,6 +209,8 @@ public Player getPresident(); + public PresidentModel getPresidentModel(); + public PublicCertificateI getPresidentsShare(); public int getFloatPercentage(); @@ -355,6 +357,7 @@ public ModelObject getInGameModel (); public ModelObject getIsClosedModel (); + } Modified: trunk/18xx/rails/game/Round.java =================================================================== --- trunk/18xx/rails/game/Round.java 2010-08-07 14:24:24 UTC (rev 1371) +++ trunk/18xx/rails/game/Round.java 2010-08-07 14:26:10 UTC (rev 1372) @@ -167,7 +167,7 @@ return true; } - protected boolean exchangeTokens (ExchangeTokens action) { + protected boolean exchangeTokens(ExchangeTokens action, boolean linkedMoveSet) { String errMsg = null; @@ -199,6 +199,7 @@ } moveStack.start(true); + if (linkedMoveSet) moveStack.linkToPreviousMoveSet(); if (exchanged > 0) { MapHex hex; Added: trunk/18xx/rails/game/model/PresidentModel.java =================================================================== --- trunk/18xx/rails/game/model/PresidentModel.java (rev 0) +++ trunk/18xx/rails/game/model/PresidentModel.java 2010-08-07 14:26:10 UTC (rev 1372) @@ -0,0 +1,34 @@ +package rails.game.model; + +import java.util.Observable; +import java.util.Observer; + +import rails.game.Player; +import rails.game.PublicCompanyI; + +/** + * model object for the current company president + * gets registered by the ShareModels + */ + +public class PresidentModel extends ModelObject implements Observer { + + PublicCompanyI company; + + public PresidentModel(PublicCompanyI company) { + this.company = company; + } + + public void update(Observable o, Object arg) { + // if notified by ShareModels, calls update itself + update(); + } + + @Override + public String getText() { + Player president = company.getPresident(); + if (president == null ) return ""; + else return company.getPresident().getNameAndPriority(); + } + +} Property changes on: trunk/18xx/rails/game/model/PresidentModel.java ___________________________________________________________________ Added: svn:mime-type + text/plain Modified: trunk/18xx/rails/game/model/ShareModel.java =================================================================== --- trunk/18xx/rails/game/model/ShareModel.java 2010-08-07 14:24:24 UTC (rev 1371) +++ trunk/18xx/rails/game/model/ShareModel.java 2010-08-07 14:26:10 UTC (rev 1372) @@ -13,6 +13,8 @@ this.portfolio = portfolio; this.company = company; this.share = 0; + // add companies president model as observer + this.addObserver(company.getPresidentModel()); } public void setShare() { Modified: trunk/18xx/rails/game/move/MoveStack.java =================================================================== --- trunk/18xx/rails/game/move/MoveStack.java 2010-08-07 14:24:24 UTC (rev 1371) +++ trunk/18xx/rails/game/move/MoveStack.java 2010-08-07 14:26:10 UTC (rev 1372) @@ -128,8 +128,14 @@ public boolean redoMoveSet () { if (currentMoveSet == null && lastIndex < moveStack.size() - 1) { - ReportBuffer.add(LocalText.getText("REDO")); - (moveStack.get(++lastIndex)).reexecute(); + MoveSet redoAction; + redoAction= moveStack.get(++lastIndex); + do { + ReportBuffer.add(LocalText.getText("REDO")); + redoAction.reexecute(); + if (lastIndex == moveStack.size() - 1) break; + redoAction= moveStack.get(++lastIndex); + } while (redoAction.isLinkedToPreviousMove()); // log.debug ("MoveStack redo index is "+lastIndex); return true; } else { Modified: trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java =================================================================== --- trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java 2010-08-07 14:24:24 UTC (rev 1371) +++ trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java 2010-08-07 14:26:10 UTC (rev 1372) @@ -15,13 +15,23 @@ public class CGRFormationRound extends SwitchableUIRound { private Player startingPlayer; + private int maxLoansToRepayByPresident = 0; private Map<Player, List<PublicCompanyI>> companiesToRepayLoans = null; + private PublicCompanyI currentCompany = null; - private int maxLoansToRepayByPresident = 0; private List<PublicCompanyI> mergingCompanies = new ArrayList<PublicCompanyI>(); + + /* + * pointers to cgr company + */ private String cgrName = PublicCompany_CGR.NAME; private PublicCompany_CGR cgr = (PublicCompany_CGR)gameManager.getCompanyManager().getPublicCompany(cgrName); + + /* + * effects from the merger, processed at the end + * thus no need for state variables + */ private List<TrainI> trainsToDiscardFrom = null; private boolean forcedTrainDiscard = true; private List<ExchangeableToken> tokensToExchangeFrom = null; @@ -187,14 +197,14 @@ numberOfLoans, currentCompany.getName()), false); - currentCompany.getLoanValueModel().setText(LocalText.getText("MERGE")); +// currentCompany.getLoanValueModel().setText(LocalText.getText("MERGE")); } maxLoansToRepayByPresident = maxNumber; break; } else { // President cannot help, this company will merge into CGR anyway mergingCompanies.add(currentCompany); - currentCompany.getLoanValueModel().setText(LocalText.getText("MERGE")); +// currentCompany.getLoanValueModel().setText(LocalText.getText("MERGE")); message = LocalText.getText("WillMergeInto", currentCompany.getName(), PublicCompany_CGR.NAME); @@ -237,7 +247,7 @@ // TODO Validation skipped for now... - moveStack.start(true); + moveStack.start(true).linkToPreviousMoveSet(); PublicCompanyI company = action.getCompany(); int numberRepaid = action.getNumberRepaid(); @@ -273,7 +283,7 @@ if (action.getCompany().getCurrentNumberOfLoans() > 0) { mergingCompanies.add(currentCompany); - currentCompany.getLoanValueModel().setText(LocalText.getText("MERGE")); +// currentCompany.getLoanValueModel().setText(LocalText.getText("MERGE")); String message = LocalText.getText("WillMergeInto", currentCompany.getName(), PublicCompany_CGR.NAME); @@ -633,7 +643,7 @@ key, oldTokens.get(key))); } } else { - executeExchangeTokens (nonHomeTokens); + executeExchangeTokens(nonHomeTokens); } // Close the merged companies @@ -692,7 +702,7 @@ } else if (action instanceof DiscardTrain) { result = discardTrain((DiscardTrain)action); } else if (action instanceof ExchangeTokens) { - result = exchangeTokens ((ExchangeTokens)action); + result = exchangeTokens((ExchangeTokens)action, true); // 2nd parameter: linked moveset } if (!result) return false; @@ -812,7 +822,8 @@ } /* End of validation, start of execution */ - moveStack.start(true); + // new: link always, see below commented + moveStack.start(true).linkToPreviousMoveSet(); if (train != null) { @@ -825,8 +836,6 @@ } else { cgrHasDiscardedTrains.set(true); } - // new: link always, see above uncommented - moveStack.linkToPreviousMoveSet(); return true; } Modified: trunk/18xx/rails/ui/swing/GameUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/GameUIManager.java 2010-08-07 14:24:24 UTC (rev 1371) +++ trunk/18xx/rails/ui/swing/GameUIManager.java 2010-08-07 14:26:10 UTC (rev 1372) @@ -305,6 +305,9 @@ /* Finish previous round UI processing */ if (previousRoundType != null) { + /* close current dialog */ + setCurrentDialog(null, null); + if (StockRound.class.isAssignableFrom(previousRoundType)) { log.debug("UI leaving Stock Round "+previousRoundName); statusWindow.finishRound(); Modified: trunk/18xx/rails/ui/swing/ORPanel.java =================================================================== --- trunk/18xx/rails/ui/swing/ORPanel.java 2010-08-07 14:24:24 UTC (rev 1371) +++ trunk/18xx/rails/ui/swing/ORPanel.java 2010-08-07 14:26:10 UTC (rev 1372) @@ -407,8 +407,9 @@ f = president[i] = - new Field(c.hasStarted() && !c.isClosed() - ? c.getPresident().getNameAndPriority() : ""); +// new Field(c.hasStarted() && !c.isClosed() +// ? c.getPresident().getNameAndPriority() : ""); + new Field(c.getPresidentModel()); addField(f, presidentXOffset, presidentYOffset + i, 1, 1, 0, visible); f = sharePrice[i] = new Field(c.getCurrentPriceModel()); @@ -468,7 +469,8 @@ addField(f, revXOffset, revYOffset + i, 1, 1, 0, visible); f = revenueSelect[i] = new Spinner(0, 0, 0, 10); addField(f, revXOffset, revYOffset + i, 1, 1, 0, false); - revenue[i].addDependent(revenueSelect[i]); + // deactived below, as this caused problems by gridpanel rowvisibility function -- sfy + // revenue[i].addDependent(revenueSelect[i]); f = decision[i] = new Field(c.getLastRevenueAllocationModel()); addField(f, revXOffset + 1, revYOffset + i, 1, 1, WIDE_RIGHT, visible); @@ -749,6 +751,10 @@ president[i].setHighlight(false); } + if (hasCompanyLoans) { + loansCaption.setHighlight(false); + } + for (JMenuItem item : menuItemsToReset) { item.setEnabled(false); if (item instanceof ActionMenuItem) { @@ -764,6 +770,11 @@ } } + public void resetCurrentRevenueDisplay() { + setSelect(revenue[orCompIndex], revenueSelect[orCompIndex], false); + } + + public void initORCompanyTurn(PublicCompanyI orComp, int orCompIndex) { this.orComp = orComp; Modified: trunk/18xx/rails/ui/swing/ORUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/ORUIManager.java 2010-08-07 14:24:24 UTC (rev 1371) +++ trunk/18xx/rails/ui/swing/ORUIManager.java 2010-08-07 14:26:10 UTC (rev 1372) @@ -619,6 +619,12 @@ orWindow.process(mapCorrectionAction); } } else if (tokenLayingEnabled) { + // if clickedHex == null, then go back to select hex step + if (clickedHex == null) { + upgradePanel.setPossibleTokenLays(null); + setLocalStep(SELECT_HEX_FOR_TOKEN); + return; + } List<LayToken> allowances = map.getTokenAllowanceForHex(clickedHex.getHexModel()); if (allowances.size() > 0) { @@ -640,16 +646,18 @@ && clickedHex == selectedHex) { selectedHex.rotateTile(); map.repaint(selectedHex.getBounds()); - return; } else { - if (selectedHex != null && clickedHex != selectedHex) { selectedHex.removeTile(); map.selectHex(null); } - if (clickedHex != null) { + // if clickedHex == null, then go back to select hex step + if (clickedHex == null) { + upgradePanel.setTileUpgrades(null); + setLocalStep(SELECT_HEX_FOR_TILE); + } else { if (clickedHex.getHexModel().isUpgradeableNow()) /* * Direct call to Model to be replaced later by use of @@ -1443,6 +1451,7 @@ // initial deactivation of revenue calculation if (!possibleActions.contains(SetDividend.class)) { orPanel.stopRevenueUpdate(); + orPanel.resetCurrentRevenueDisplay(); } if (possibleActions.contains(MapCorrectionAction.class)) { Modified: trunk/18xx/rails/ui/swing/gamespecific/_1856/StatusWindow_1856.java =================================================================== --- trunk/18xx/rails/ui/swing/gamespecific/_1856/StatusWindow_1856.java 2010-08-07 14:24:24 UTC (rev 1371) +++ trunk/18xx/rails/ui/swing/gamespecific/_1856/StatusWindow_1856.java 2010-08-07 14:26:10 UTC (rev 1372) @@ -1,5 +1,8 @@ package rails.ui.swing.gamespecific._1856; +import javax.swing.JDialog; +import javax.swing.WindowConstants; + import rails.game.*; import rails.game.action.*; import rails.game.specific._1856.CGRFormationRound; @@ -19,7 +22,6 @@ @Override public void updateStatus() { RoundI currentRound = gameUIManager.getCurrentRound(); - //if (!(currentRound instanceof OperatingRound)) { if (!(currentRound instanceof CGRFormationRound)) { super.updateStatus(); } else if (possibleActions.contains(RepayLoans.class)) { @@ -97,10 +99,11 @@ } RadioButtonDialog currentDialog = new RadioButtonDialog (gameUIManager, - LocalText.getText("Select"), + LocalText.getText("1856MergerDialog", action.getCompanyName()), message, options, 0); + currentDialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); gameUIManager.setCurrentDialog (currentDialog, action); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-07 14:24:30
|
Revision: 1371 http://rails.svn.sourceforge.net/rails/?rev=1371&view=rev Author: stefanfrey Date: 2010-08-07 14:24:24 +0000 (Sat, 07 Aug 2010) Log Message: ----------- Fixed bug of revenue path display Modified Paths: -------------- trunk/18xx/rails/algorithms/NetworkEdge.java trunk/18xx/rails/algorithms/NetworkVertex.java trunk/18xx/rails/algorithms/RevenueTrainRun.java Modified: trunk/18xx/rails/algorithms/NetworkEdge.java =================================================================== --- trunk/18xx/rails/algorithms/NetworkEdge.java 2010-08-06 19:52:53 UTC (rev 1370) +++ trunk/18xx/rails/algorithms/NetworkEdge.java 2010-08-07 14:24:24 UTC (rev 1371) @@ -26,7 +26,7 @@ private final int distance; - private final List<NetworkVertex> hiddenVertexes; + private final List<NetworkVertex> hiddenVertices; // list of vertexes that were merged into the edge private int routeCosts; @@ -40,7 +40,7 @@ this.distance = 1; else this.distance = 0; - hiddenVertexes = new ArrayList<NetworkVertex>(); + hiddenVertices = new ArrayList<NetworkVertex>(); } public NetworkEdge(NetworkVertex source, NetworkVertex target, boolean greedy, @@ -49,7 +49,7 @@ this.target = target; this.greedy = greedy; this.distance = distance; - this.hiddenVertexes = hiddenVertexes; + this.hiddenVertices = hiddenVertexes; } public NetworkVertex getSource() { @@ -116,16 +116,27 @@ this.routeCosts = routeCosts; } - public List<NetworkVertex> getHiddenVertexes() { - return hiddenVertexes; + public List<NetworkVertex> getHiddenVertices() { + return hiddenVertices; } + /** + * all vertices from source to target, including hidden vertices + */ + public List<NetworkVertex> getVertexPath() { + List<NetworkVertex> vertexPath = new ArrayList<NetworkVertex>(); + vertexPath.add(source); + vertexPath.addAll(hiddenVertices); + vertexPath.add(target); + return vertexPath; + } + public String toFullInfoString() { StringBuffer info = new StringBuffer(); info.append("Edge " + getConnection()); info.append(", greedy = " + greedy); info.append(", distance = " + distance); - info.append(", hidden vertexes = " + hiddenVertexes); + info.append(", hidden vertexes = " + hiddenVertices); return info.toString(); } @@ -222,12 +233,12 @@ // create new hiddenVertexes List<NetworkVertex> hiddenVertexes = new ArrayList<NetworkVertex>(); - List<NetworkVertex> hiddenA = edgeA.getHiddenVertexes(); + List<NetworkVertex> hiddenA = edgeA.getHiddenVertices(); if (reverseA) { hiddenA = new ArrayList<NetworkVertex>(hiddenA); // clone Collections.reverse(hiddenA); } - List<NetworkVertex> hiddenB = edgeB.getHiddenVertexes(); + List<NetworkVertex> hiddenB = edgeB.getHiddenVertices(); if (reverseB) { hiddenB = new ArrayList<NetworkVertex>(hiddenB); // clone Collections.reverse(hiddenB); @@ -274,9 +285,9 @@ public static NetworkEdge replaceVertex(NetworkEdge edge, NetworkVertex oldVertex, NetworkVertex newVertex) { NetworkEdge newEdge; if (edge.source == oldVertex) { - newEdge= new NetworkEdge(newVertex, edge.target, edge.greedy, edge.distance, edge.hiddenVertexes); + newEdge= new NetworkEdge(newVertex, edge.target, edge.greedy, edge.distance, edge.hiddenVertices); } else if (edge.target == oldVertex) { - newEdge= new NetworkEdge(edge.source, newVertex, edge.greedy, edge.distance, edge.hiddenVertexes); + newEdge= new NetworkEdge(edge.source, newVertex, edge.greedy, edge.distance, edge.hiddenVertices); } else { newEdge = null; } Modified: trunk/18xx/rails/algorithms/NetworkVertex.java =================================================================== --- trunk/18xx/rails/algorithms/NetworkVertex.java 2010-08-06 19:52:53 UTC (rev 1370) +++ trunk/18xx/rails/algorithms/NetworkVertex.java 2010-08-07 14:24:24 UTC (rev 1371) @@ -361,14 +361,14 @@ for (NetworkEdge edge:edges) { List<NetworkVertex> hiddenVertices; if (edge.getSource() == vertex) { - hiddenVertices = edge.getHiddenVertexes(); + hiddenVertices = edge.getHiddenVertices(); if (addOldVertexAsHidden) hiddenVertices.add(vertex); NetworkEdge newEdge = new NetworkEdge(newVertex, edge.getTarget(), edge.isGreedy(), edge.getDistance(), hiddenVertices); graph.addEdge(newVertex, edge.getTarget(), newEdge); } else { hiddenVertices = new ArrayList<NetworkVertex>(); if (addOldVertexAsHidden) hiddenVertices.add(vertex); - hiddenVertices.addAll(edge.getHiddenVertexes()); + hiddenVertices.addAll(edge.getHiddenVertices()); NetworkEdge newEdge = new NetworkEdge(edge.getSource(), newVertex, edge.isGreedy(), edge.getDistance(), hiddenVertices); graph.addEdge(newEdge.getSource(), newVertex, newEdge); } Modified: trunk/18xx/rails/algorithms/RevenueTrainRun.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueTrainRun.java 2010-08-06 19:52:53 UTC (rev 1370) +++ trunk/18xx/rails/algorithms/RevenueTrainRun.java 2010-08-07 14:24:24 UTC (rev 1371) @@ -270,25 +270,22 @@ GeneralPath getAsPath(HexMap map) { GeneralPath path = new GeneralPath(); -// if (edges.size() != 0) { - for (NetworkEdge edge:edges) { - Point2D sourcePoint = NetworkVertex.getVertexPoint2D(map, edge.getSource()); - if (sourcePoint != null) { - path.moveTo((float)sourcePoint.getX(), (float)sourcePoint.getY()); + for (NetworkEdge edge:edges) { + // check vertices if they exist as points and start from there + List<NetworkVertex> edgeVertices = edge.getVertexPath(); + boolean initPath = false; + for (NetworkVertex edgeVertex:edgeVertices) { + Point2D edgePoint = NetworkVertex.getVertexPoint2D(map, edgeVertex); + if (edgePoint == null) continue; + if (!initPath) { + path.moveTo((float)edgePoint.getX(), (float)edgePoint.getY()); + initPath = true; + } else { + path.lineTo((float)edgePoint.getX(), (float)edgePoint.getY()); } - for (NetworkVertex hiddenVertex:edge.getHiddenVertexes()) { - Point2D hiddenPoint = NetworkVertex.getVertexPoint2D(map, hiddenVertex); - if (hiddenPoint != null) { - path.lineTo((float)hiddenPoint.getX(), (float)hiddenPoint.getY()); - } - } - Point2D targetPoint = NetworkVertex.getVertexPoint2D(map, edge.getTarget()); - if (targetPoint != null) { - path.lineTo((float)targetPoint.getX(), (float)targetPoint.getY()); - } } - return path; -// } + } + return path; // NetworkVertex startVertex = null; // NetworkVertex previousVertex = null; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-06 19:52:59
|
Revision: 1370 http://rails.svn.sourceforge.net/rails/?rev=1370&view=rev Author: stefanfrey Date: 2010-08-06 19:52:53 +0000 (Fri, 06 Aug 2010) Log Message: ----------- Fixed train discard bug in 1856 cgr formation. Started working on undo of cgr formation. Modified Paths: -------------- trunk/18xx/rails/game/move/MoveStack.java trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java Modified: trunk/18xx/rails/game/move/MoveStack.java =================================================================== --- trunk/18xx/rails/game/move/MoveStack.java 2010-08-05 18:53:13 UTC (rev 1369) +++ trunk/18xx/rails/game/move/MoveStack.java 2010-08-06 19:52:53 UTC (rev 1370) @@ -99,6 +99,7 @@ public void linkToPreviousMoveSet() { if (currentMoveSet != null) { currentMoveSet.linkToPreviousMoveSet(); + log.debug("Moveset linked to previous one"); } else { log.warn("No MoveSet open"); } Modified: trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java =================================================================== --- trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java 2010-08-05 18:53:13 UTC (rev 1369) +++ trunk/18xx/rails/game/specific/_1856/CGRFormationRound.java 2010-08-06 19:52:53 UTC (rev 1370) @@ -642,7 +642,8 @@ } // Check the trains, autodiscard any excess non-permanent trains - int trainLimit = cgr.getTrainLimit(gameManager.getCurrentPlayerIndex()); +// int trainLimit = cgr.getTrainLimit(gameManager.getCurrentPlayerIndex()); + int trainLimit = cgr.getCurrentTrainLimit(); List<TrainI> trains = cgr.getPortfolio().getTrainList(); if (cgr.getNumberOfTrains() > trainLimit) { ReportBuffer.add(""); @@ -815,8 +816,7 @@ if (train != null) { - if (action.isForced()) moveStack.linkToPreviousMoveSet(); - +// if (action.isForced()) moveStack.linkToPreviousMoveSet(); train.moveTo(pool); ReportBuffer.add(LocalText.getText("CompanyDiscardsTrain", companyName, @@ -825,6 +825,8 @@ } else { cgrHasDiscardedTrains.set(true); } + // new: link always, see above uncommented + moveStack.linkToPreviousMoveSet(); return true; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-05 18:53:19
|
Revision: 1369 http://rails.svn.sourceforge.net/rails/?rev=1369&view=rev Author: stefanfrey Date: 2010-08-05 18:53:13 +0000 (Thu, 05 Aug 2010) Log Message: ----------- 1. Added DisplayBuffer report for forced selling due to certificate limit 2. Fixed problem of hermit base token in revenue calculation 3. Added gameoption for 1856 THB (but not implementation yet) Modified Paths: -------------- trunk/18xx/LocalisedText.properties trunk/18xx/data/1856/Game.xml trunk/18xx/rails/algorithms/NetworkGraphBuilder.java trunk/18xx/rails/algorithms/RevenueAdapter.java trunk/18xx/rails/game/StockRound.java trunk/18xx/rails/ui/swing/ORUIManager.java Modified: trunk/18xx/LocalisedText.properties =================================================================== --- trunk/18xx/LocalisedText.properties 2010-08-04 22:05:57 UTC (rev 1368) +++ trunk/18xx/LocalisedText.properties 2010-08-05 18:53:13 UTC (rev 1369) @@ -1,4 +1,5 @@ # Texts with lowercase keys are intended to be inserted into other messages +1856THBHomeBlocked=THB home hex is blocked for token lays (unless gray tile) 1889PrivateBactive=Player {0} (owner of Private B) may lay port tile 1889PrivateCactive=Player {0} (previous owner of Private C) may lay tile on C4 immediately 18ALOptimizeNamedTrains=Optimize named train assignment @@ -246,6 +247,9 @@ ExchangeTokensPrompt1=Select {0} cities where {1} will exchange a base token ExchangeTokensPrompt2=Select {0} through {1} cities where {2} will exchange a base token ExchangesTrain={0} exchanges a {1}-train for a {2}-train from {3} for {4} +ExceedCertificateLimit=<em>{0} exceeds certificate limit!</em><br>{1}<br>Only share selling allowed until certificate limit holds. +ExceedCertificateLimitTotal=-> Player has {0} certificates, exceeds total certificate limit of {1}. +ExceedCertificateLimitCompany=-> Player has a {1}% holding of {0}, exceeds company holding limit of {2}%. extra=extra ExtraTile= You can lay an unconnected tile on {0}. ExtraToken= You can lay an unconnected base token on {0}. @@ -501,7 +505,7 @@ SelectNoBid=Select, No Bid SelectTrain=Select a train and press OK, or press Done. SelectCheapTrain=You can buy a cheaper new train by using {0}. -SelectStationForToken={0}, select a station on tile {1} for the {2} home base token +SelectStationForToken={0}, select a station on hex {1} for the {2} home base token SelectStationForTokenOption=Place token in station {0} with tracks to {1} SelectForAuctioning=\n{0} selects {1} for auctioning SELL=Sell Modified: trunk/18xx/data/1856/Game.xml =================================================================== --- trunk/18xx/data/1856/Game.xml 2010-08-04 22:05:57 UTC (rev 1368) +++ trunk/18xx/data/1856/Game.xml 2010-08-05 18:53:13 UTC (rev 1369) @@ -9,6 +9,7 @@ <GameOption name="UnlimitedTiles" type="toggle" default="no"/> <GameOption name="LeaveAuctionOnPass" type="toggle" default="no"/> <GameOption name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> + <GameOption name="1856THBHomeBlocked" type="toggle" default="no" /> <GameParameters> <StockRound class="rails.game.specific._1856.StockRound_1856" sequence="SellBuyOrBuySell"> Modified: trunk/18xx/rails/algorithms/NetworkGraphBuilder.java =================================================================== --- trunk/18xx/rails/algorithms/NetworkGraphBuilder.java 2010-08-04 22:05:57 UTC (rev 1368) +++ trunk/18xx/rails/algorithms/NetworkGraphBuilder.java 2010-08-05 18:53:13 UTC (rev 1369) @@ -265,6 +265,11 @@ for (NetworkVertex vertex:graph.vertexSet()) { Set<NetworkEdge> vertexEdges = graph.edgesOf(vertex); + // always keep protected vertices + if (protectedVertices.contains(vertex)) { + continue; + } + // remove hermit if (vertexEdges.size() == 0) { log.info("Remove hermit (no connection) = " + vertex); @@ -282,7 +287,7 @@ removed = true; break; } // vertex is not necessary and not on the protected list - else if (vertexEdges.size() == 2 && !protectedVertices.contains(vertex)) { + else if (vertexEdges.size() == 2) { NetworkEdge[] edges = vertexEdges.toArray(new NetworkEdge[2]); if (edges[0].isGreedy() == edges[1].isGreedy()) { if (!edges[0].isGreedy()) { Modified: trunk/18xx/rails/algorithms/RevenueAdapter.java =================================================================== --- trunk/18xx/rails/algorithms/RevenueAdapter.java 2010-08-04 22:05:57 UTC (rev 1368) +++ trunk/18xx/rails/algorithms/RevenueAdapter.java 2010-08-05 18:53:13 UTC (rev 1369) @@ -143,10 +143,9 @@ return startVertices; } - public boolean addStartVertex(NetworkVertex startVertex) { - if (startVertices.contains(startVertex)) return false; - - startVertices.add(startVertex); + public boolean addStartVertices(Collection<NetworkVertex> startVertices) { + this.startVertices.addAll(startVertices); + protectedVertices.addAll(startVertices); return true; } @@ -208,7 +207,7 @@ NetworkVertex.initAllRailsVertices(graph.vertexSet(), company, phase); // define startVertexes - startVertices.addAll(companyGraph.getCompanyBaseTokenVertexes(company)); + addStartVertices(companyGraph.getCompanyBaseTokenVertexes(company)); // define visit sets defineVertexVisitSets(); Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2010-08-04 22:05:57 UTC (rev 1368) +++ trunk/18xx/rails/game/StockRound.java 2010-08-05 18:53:13 UTC (rev 1369) @@ -101,7 +101,15 @@ setSellableShares(); - if (isPlayerOverLimits (currentPlayer)) return true; + // check certification limits and display warning + if (isPlayerOverLimits (currentPlayer)) { + DisplayBuffer.add(LocalText.getText("ExceedCertificateLimit" + , currentPlayer.getName() + , isPlayerOverLimitsDetail(currentPlayer) + ) + ); + return true; + } passAllowed = true; @@ -1398,18 +1406,36 @@ } protected boolean isPlayerOverLimits(Player player) { - + return (isPlayerOverLimitsDetail(player) != null); + } + + protected String isPlayerOverLimitsDetail(Player player) { + StringBuffer violations = new StringBuffer(); + // Over the total certificate hold Limit? - if (player.getPortfolio().getCertificateCount() > gameManager.getPlayerCertificateLimit(player)) - return true; + if (player.getPortfolio().getCertificateCount() > gameManager.getPlayerCertificateLimit(player)) { + violations.append(LocalText.getText("ExceedCertificateLimitTotal", + player.getPortfolio().getCertificateCount(), + gameManager.getPlayerCertificateLimit(player))); + } + ; // Over the hold limit of any company? for (PublicCompanyI company : companyManager.getAllPublicCompanies()) { if (company.hasStarted() && company.hasStockPrice() - && !checkAgainstHoldLimit(player, company, 0)) return true; + && !checkAgainstHoldLimit(player, company, 0)) { + violations.append(LocalText.getText("ExceedCertificateLimitCompany", + company.getName(), + player.getPortfolio().getShare(company), + getGameParameterAsInt(GameDef.Parm.PLAYER_SHARE_LIMIT) + )); + } } - - return false; + if (violations.length() != 0) { + return violations.toString(); + } else { + return null; + } } /** Modified: trunk/18xx/rails/ui/swing/ORUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/ORUIManager.java 2010-08-04 22:05:57 UTC (rev 1368) +++ trunk/18xx/rails/ui/swing/ORUIManager.java 2010-08-05 18:53:13 UTC (rev 1369) @@ -879,7 +879,11 @@ if (prompts.size () > 1) { String selected = (String) JOptionPane.showInputDialog(orWindow, - LocalText.getText("SelectStationForToken"), + LocalText.getText("SelectStationForToken", + action.getPlayerName(), + hex.getName(), + company.getName() + ), LocalText.getText("WhichStation"), JOptionPane.PLAIN_MESSAGE, null, prompts.toArray(), prompts.get(0)); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-04 22:06:03
|
Revision: 1368 http://rails.svn.sourceforge.net/rails/?rev=1368&view=rev Author: stefanfrey Date: 2010-08-04 22:05:57 +0000 (Wed, 04 Aug 2010) Log Message: ----------- Further updates to configuration dialog Modified Paths: -------------- trunk/18xx/LocalisedText.properties trunk/18xx/data/Properties.xml trunk/18xx/rails/ui/swing/GameUIManager.java trunk/18xx/rails/util/ConfigItem.java Modified: trunk/18xx/LocalisedText.properties =================================================================== --- trunk/18xx/LocalisedText.properties 2010-08-01 21:30:16 UTC (rev 1367) +++ trunk/18xx/LocalisedText.properties 2010-08-04 22:05:57 UTC (rev 1368) @@ -154,8 +154,31 @@ Config.infoText.default_players=Enter player names separated by commas. Config.label.default_game=Default game Config.label.default_players=Default players +Config.label.font.ui.name=Font selection +Config.label.font.ui.scale=Font scaling +Config.label.font.ui.style=Font style Config.label.local.player.name=Local player (for pbem) -Config.label.locale=Language Setting +Config.label.locale=Language setting +Config.label.map.autoscroll=Map autoscroll +Config.label.map.zoomstep=Map zoomstep +Config.label.money_format=Money format +Config.label.or.number_format=Number format +Config.label.report.directory=Report directory +Config.label.report.filename.date_time_pattern=Report filename date pattern +Config.label.report.filename.extension=Report filename extension +Config.label.report.window.open=Report window open +Config.label.report.window.editable=Report window editable +Config.label.route.colour.1=Route color for first train +Config.label.route.colour.2=Route color for second train +Config.label.route.colour.3=Route color for third train +Config.label.route.colour.4=Route color for fourth train +Config.label.stockchart.window.open=Stockchart open +Config.label.save.directory=Save folder +Config.label.save.filename.date_time_pattern=Filename date pattern +Config.label.save.filename.suffix=Filename suffix +Config.label.save.filename.extension=Filename extension +Config.label.save.recovery.active=Automatic save +Config.label.save.recovery.filepath=Automatic save filepath Config.toolTip.local.player.name=Player name used as suffix for game save Config.section.Format=Format/Colors Config.section.General=General Modified: trunk/18xx/data/Properties.xml =================================================================== --- trunk/18xx/data/Properties.xml 2010-08-01 21:30:16 UTC (rev 1367) +++ trunk/18xx/data/Properties.xml 2010-08-04 22:05:57 UTC (rev 1368) @@ -23,9 +23,12 @@ <Property name="report.window.open" type="BOOLEAN" /> <Property name="report.window.editable" type="BOOLEAN" /> <Property name="stockchart.window.open" type="BOOLEAN" /> - <Property name="font.ui.scale" type="PERCENT" /> - <Property name="font.ui.name" type="FONT" /> - <Property name="font.ui.style" type="LIST" values="plain,bold" /> + <Property name="font.ui.scale" type="PERCENT" + initClass="rails.ui.swing.GameUIManager" initMethod="updateUILookAndFeel" initParameter="no" /> + <Property name="font.ui.name" type="FONT" + initClass="rails.ui.swing.GameUIManager" initMethod="updateUILookAndFeel" initParameter="no" /> + <Property name="font.ui.style" type="LIST" values="plain,bold" + initClass="rails.ui.swing.GameUIManager" initMethod="updateUILookAndFeel" initParameter="no" /> </Section> <Section name="Map"> <Property name="map.autoscroll" type="BOOLEAN" /> Modified: trunk/18xx/rails/ui/swing/GameUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/GameUIManager.java 2010-08-01 21:30:16 UTC (rev 1367) +++ trunk/18xx/rails/ui/swing/GameUIManager.java 2010-08-04 22:05:57 UTC (rev 1368) @@ -1,5 +1,6 @@ package rails.ui.swing; +import java.awt.EventQueue; import java.awt.Font; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; @@ -87,6 +88,14 @@ this.gameManager = gameManager; uiHints = gameManager.getUIHints(); + initSaveSettings(); + initFontSettings(); + + configuredStockChartVisibility = "yes".equalsIgnoreCase(Config.get("stockchart.window.open")); + + } + + private void initSaveSettings() { saveDirectory = Config.get("save.directory"); if (!Util.hasValue(saveDirectory)) { saveDirectory = DEFAULT_SAVE_DIRECTORY; @@ -109,9 +118,10 @@ if (Util.hasValue(saveSuffixSpec) && !saveSuffixSpec.equals(NEXT_PLAYER_SUFFIX)) { saveSuffix = "_" + saveSuffixSpec; } + } - configuredStockChartVisibility = "yes".equalsIgnoreCase(Config.get("stockchart.window.open")); - + private void initFontSettings() { + // font settings, can be game specific String fontType = Config.getGameSpecific("font.ui.name"); Font font = null; @@ -120,7 +130,7 @@ String fontStyle = Config.getGameSpecific("font.ui.style"); if (Util.hasValue(fontStyle)) { if (fontStyle.equalsIgnoreCase("plain")) { - boldStyle = false; + boldStyle = false; } } if (boldStyle) { @@ -141,6 +151,7 @@ } } } + public void gameUIInit() { @@ -807,5 +818,31 @@ public boolean getGameParameterAsBoolean (GuiDef.Parm key) { return (Boolean) getGameParameter(key); } - + + private void updateWindowsLookAndFeel() { + SwingUtilities.updateComponentTreeUI(statusWindow); + statusWindow.pack(); + SwingUtilities.updateComponentTreeUI(orWindow); + orWindow.pack(); + SwingUtilities.updateComponentTreeUI(reportWindow); + reportWindow.pack(); + SwingUtilities.updateComponentTreeUI(configWindow); + configWindow.pack(); + SwingUtilities.updateComponentTreeUI(stockChart); + stockChart.pack(); + } + + /** update fonts settings + * (after configuration changes) + */ + public static void updateUILookAndFeel() { + instance.initFontSettings(); + instance.updateWindowsLookAndFeel(); + +// EventQueue.invokeLater(new Runnable() { +// public void run() { +// instance.repaintWindows(); +// } +// }); + } } Modified: trunk/18xx/rails/util/ConfigItem.java =================================================================== --- trunk/18xx/rails/util/ConfigItem.java 2010-08-01 21:30:16 UTC (rev 1367) +++ trunk/18xx/rails/util/ConfigItem.java 2010-08-04 22:05:57 UTC (rev 1368) @@ -121,7 +121,7 @@ clazz.getMethod(initMethod).invoke(null); } } catch (Exception e) { - log.error("Config profile: cannot call initMethod"); + log.error("Config profile: cannot call initMethod, Exception = " + e.toString()); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-08-01 21:30:22
|
Revision: 1367 http://rails.svn.sourceforge.net/rails/?rev=1367&view=rev Author: evos Date: 2010-08-01 21:30:16 +0000 (Sun, 01 Aug 2010) Log Message: ----------- Removed 1870 from the list of companies where the "second sale at lower price in same turn" option would apply (per JDG). Modified Paths: -------------- trunk/18xx/data/1870/Game.xml trunk/18xx/data/GamesList.xml Modified: trunk/18xx/data/1870/Game.xml =================================================================== --- trunk/18xx/data/1870/Game.xml 2010-08-01 15:28:24 UTC (rev 1366) +++ trunk/18xx/data/1870/Game.xml 2010-08-01 21:30:16 UTC (rev 1367) @@ -6,7 +6,6 @@ <GameOption name="RevenueCalculation" values="Suggest,Deactivate" default="Deactivate" /> <GameOption name="UnlimitedTiles" type="toggle" default="no"/> <GameOption name="LeaveAuctionOnPass" type="toggle" default="no"/> - <GameOption name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <GameParameters> <PlayerShareLimit percentage="60"> <PriceProtection/> Modified: trunk/18xx/data/GamesList.xml =================================================================== --- trunk/18xx/data/GamesList.xml 2010-08-01 15:28:24 UTC (rev 1366) +++ trunk/18xx/data/GamesList.xml 2010-08-01 21:30:16 UTC (rev 1367) @@ -190,7 +190,6 @@ <Option name="RevenueCalculation" values="Suggest,Deactivate" default="Suggest" /> <Option name="UnlimitedTiles" type="toggle" default="no"/> <Option name="LeaveAuctionOnPass" type="toggle" default="no"/> - <Option name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <Players minimum="2" maximum="6"/> </Game> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-08-01 15:28:30
|
Revision: 1366 http://rails.svn.sourceforge.net/rails/?rev=1366&view=rev Author: evos Date: 2010-08-01 15:28:24 +0000 (Sun, 01 Aug 2010) Log Message: ----------- Implemented option to sell shares in same turn at decreasong prices for all games except 1835. Modified Paths: -------------- trunk/18xx/data/1825/Game.xml trunk/18xx/data/1851/Game.xml trunk/18xx/data/1856/Game.xml trunk/18xx/data/1870/Game.xml trunk/18xx/data/1889/Game.xml trunk/18xx/data/18AL/Game.xml trunk/18xx/data/18EU/Game.xml trunk/18xx/data/18Kaas/Game.xml trunk/18xx/data/GamesList.xml trunk/18xx/rails/game/StockRound.java trunk/18xx/rails/game/specific/_1835/StockRound_1835.java Modified: trunk/18xx/data/1825/Game.xml =================================================================== --- trunk/18xx/data/1825/Game.xml 2010-08-01 12:17:26 UTC (rev 1365) +++ trunk/18xx/data/1825/Game.xml 2010-08-01 15:28:24 UTC (rev 1366) @@ -14,6 +14,7 @@ --> <GameOption name="RouteAwareness" values="Highlight,Deactivate" default="Deactivate" /> <GameOption name="RevenueCalculation" values="Suggest,Deactivate" default="Deactivate" /> + <GameOption name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <PlayerShareLimit percentage="100"/> <BankPoolLimit percentage="100"></BankPoolLimit> <EndOfGame> Modified: trunk/18xx/data/1851/Game.xml =================================================================== --- trunk/18xx/data/1851/Game.xml 2010-08-01 12:17:26 UTC (rev 1365) +++ trunk/18xx/data/1851/Game.xml 2010-08-01 15:28:24 UTC (rev 1366) @@ -7,6 +7,7 @@ <GameOption name="NoMapMode" type="toggle" default="no" /> <GameOption name="UnlimitedTiles" type="toggle" default="no"/> <GameOption name="UnlimitedTopTrains" parm="8" type="toggle" default="no"/> + <GameOption name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <GameParameters> <PlayerShareLimit percentage="60"/> <BankPoolLimit percentage="50"/> Modified: trunk/18xx/data/1856/Game.xml =================================================================== --- trunk/18xx/data/1856/Game.xml 2010-08-01 12:17:26 UTC (rev 1365) +++ trunk/18xx/data/1856/Game.xml 2010-08-01 15:28:24 UTC (rev 1366) @@ -8,6 +8,7 @@ <GameOption name="UnlimitedBonusTokens" type="toggle" default="no"/> <GameOption name="UnlimitedTiles" type="toggle" default="no"/> <GameOption name="LeaveAuctionOnPass" type="toggle" default="no"/> + <GameOption name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <GameParameters> <StockRound class="rails.game.specific._1856.StockRound_1856" sequence="SellBuyOrBuySell"> Modified: trunk/18xx/data/1870/Game.xml =================================================================== --- trunk/18xx/data/1870/Game.xml 2010-08-01 12:17:26 UTC (rev 1365) +++ trunk/18xx/data/1870/Game.xml 2010-08-01 15:28:24 UTC (rev 1366) @@ -6,6 +6,7 @@ <GameOption name="RevenueCalculation" values="Suggest,Deactivate" default="Deactivate" /> <GameOption name="UnlimitedTiles" type="toggle" default="no"/> <GameOption name="LeaveAuctionOnPass" type="toggle" default="no"/> + <GameOption name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <GameParameters> <PlayerShareLimit percentage="60"> <PriceProtection/> Modified: trunk/18xx/data/1889/Game.xml =================================================================== --- trunk/18xx/data/1889/Game.xml 2010-08-01 12:17:26 UTC (rev 1365) +++ trunk/18xx/data/1889/Game.xml 2010-08-01 15:28:24 UTC (rev 1366) @@ -22,6 +22,7 @@ <GameOption name="WithOptional6Train" type="toggle" default="no"/> <GameOption name="UnlimitedTopTrains" parm="D" type="toggle" default="yes"/> <GameOption name="TwoPlayersCertLimit70Percent" type="toggle" default="yes"/> + <GameOption name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <GameParameters> <PlayerShareLimit percentage="60"> <!-- Option "NumberOfPlayers" is automatically set Modified: trunk/18xx/data/18AL/Game.xml =================================================================== --- trunk/18xx/data/18AL/Game.xml 2010-08-01 12:17:26 UTC (rev 1365) +++ trunk/18xx/data/18AL/Game.xml 2010-08-01 15:28:24 UTC (rev 1366) @@ -9,6 +9,7 @@ <GameOption name="Obsolete4Trains" type="toggle" default="yes"/> <GameOption name="UnlimitedTiles" type="toggle" default="no"/> <GameOption name="LeaveAuctionOnPass" type="toggle" default="no"/> + <GameOption name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <GameParameters> <OperatingRound class="rails.game.specific._18AL.OperatingRound_18AL"/> <PlayerShareLimit percentage="60"/> Modified: trunk/18xx/data/18EU/Game.xml =================================================================== --- trunk/18xx/data/18EU/Game.xml 2010-08-01 12:17:26 UTC (rev 1365) +++ trunk/18xx/data/18EU/Game.xml 2010-08-01 15:28:24 UTC (rev 1366) @@ -8,6 +8,7 @@ <GameOption name="Extra4Trains" values="0,1" default="0"/> <GameOption name="NoMapMode" type="toggle" default="no" /> <GameOption name="UnlimitedTiles" type="toggle" default="no"/> + <GameOption name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <GameParameters> <StockRound class="rails.game.specific._18EU.StockRound_18EU" sequence="sellBuy" Modified: trunk/18xx/data/18Kaas/Game.xml =================================================================== --- trunk/18xx/data/18Kaas/Game.xml 2010-08-01 12:17:26 UTC (rev 1365) +++ trunk/18xx/data/18Kaas/Game.xml 2010-08-01 15:28:24 UTC (rev 1366) @@ -9,6 +9,7 @@ <GameOption name="WithOptional6Train" type="toggle" default="no"/> <GameOption name="UnlimitedTiles" type="toggle" default="no"/> <GameOption name="LeaveAuctionOnPass" type="toggle" default="no"/> + <GameOption name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <GameParameters> <PlayerShareLimit percentage="60"/> <BankPoolLimit percentage="50"/> Modified: trunk/18xx/data/GamesList.xml =================================================================== --- trunk/18xx/data/GamesList.xml 2010-08-01 12:17:26 UTC (rev 1365) +++ trunk/18xx/data/GamesList.xml 2010-08-01 15:28:24 UTC (rev 1366) @@ -47,6 +47,7 @@ <Option name="NoMapMode" type="toggle" default="no" /> <Option name="UnlimitedTiles" type="toggle" default="no"/> <Option name="UnlimitedTopTrains" parm="8" type="toggle" default="no"/> + <Option name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <Players minimum="3" maximum="5"/> </Game> @@ -65,6 +66,7 @@ <Option name="UnlimitedBonusTokens" type="toggle" default="no"/> <Option name="UnlimitedTiles" type="toggle" default="no"/> <Option name="LeaveAuctionOnPass" type="toggle" default="no"/> + <Option name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <Players minimum="3" maximum="6"/> </Game> @@ -85,6 +87,7 @@ <Option name="WithOptional6Train" type="toggle" default="no"/> <Option name="UnlimitedTopTrains" parm="D" type="toggle" default="yes"/> <Option name="TwoPlayersCertLimit70Percent" type="toggle" default="no"/> + <Option name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> </Game> <Game name="18AL"> @@ -105,6 +108,7 @@ <Option name="Obsolete4Trains" type="toggle" default="yes"/> <Option name="UnlimitedTiles" type="toggle" default="no"/> <Option name="LeaveAuctionOnPass" type="toggle" default="no"/> + <Option name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <Players minimum="3" maximum="5"/> </Game> @@ -142,6 +146,7 @@ <Option name="UnlimitedTopTrains" parm="D" type="toggle" default="no"/> <Option name="UnlimitedTiles" type="toggle" default="no"/> <Option name="LeaveAuctionOnPass" type="toggle" default="no"/> + <Option name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <Players minimum="3" maximum="6"/> </Game> @@ -185,6 +190,7 @@ <Option name="RevenueCalculation" values="Suggest,Deactivate" default="Suggest" /> <Option name="UnlimitedTiles" type="toggle" default="no"/> <Option name="LeaveAuctionOnPass" type="toggle" default="no"/> + <Option name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <Players minimum="2" maximum="6"/> </Game> @@ -201,13 +207,14 @@ <Option name="RouteAwareness" values="Highlight,Deactivate" default="Highlight" /> <Option name="RevenueCalculation" values="Suggest,Deactivate" default="Suggest" /> <Option name="UnlimitedTiles" type="toggle" default="no"/> + <Option name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> </Game> <Credits>Rails is a computer implementation of a number of railroad board games, that are collectively known as the "18xx" railway game system. Rails is a Sourceforge project. Project founder: Brett Lentz. -Developers: Erik Vos and Brett Lentz. +Developers: Erik Vos, Stefan Frey and Brett Lentz. The 18xx railway game system was originated by Francis Tresham and Hartland Trefoil Ltd. Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2010-08-01 12:17:26 UTC (rev 1365) +++ trunk/18xx/rails/game/StockRound.java 2010-08-01 15:28:24 UTC (rev 1366) @@ -412,12 +412,7 @@ * Check the price. If a cert was sold before this turn, the * original price is still valid */ - if (sellPrices.containsKey(compName) - && GameOption.convertValueToBoolean(getGameOption("SeparateSalesAtSamePrice"))) { - price = (sellPrices.get(compName)).getPrice(); - } else { - price = company.getMarketPrice(); - } + price = getCurrentSellPrice(company); price /= company.getShareUnitsForSharePrice(); /* Allow for different share units (as in 1835) */ @@ -1035,18 +1030,14 @@ } // All seems OK, now do the selling. - StockSpaceI sellPrice; - int price; + // Selling price + int price = getCurrentSellPrice (company); + + // Save original price as it may be reused in subsequent sale actions in the same turn boolean soldBefore = sellPrices.containsKey(companyName); - // Get the sell price (does not change within a turn) - if (soldBefore - && GameOption.convertValueToBoolean(getGameOption("SeparateSalesAtSamePrice"))) { - price = (sellPrices.get(companyName)).getPrice(); - } else { - sellPrice = company.getCurrentSpace(); - price = sellPrice.getPrice() / company.getShareUnitsForSharePrice(); - sellPrices.put(companyName, sellPrice); + if (!soldBefore) { + sellPrices.put(companyName, company.getCurrentSpace()); } moveStack.start(true); @@ -1118,6 +1109,20 @@ return true; } + protected int getCurrentSellPrice (PublicCompanyI company) { + + String companyName = company.getName(); + int price; + + if (sellPrices.containsKey(companyName) + && GameOption.convertValueToBoolean(getGameOption("SeparateSalesAtSamePrice"))) { + price = (sellPrices.get(companyName)).getPrice(); + } else { + price = company.getCurrentSpace().getPrice() / company.getShareUnitsForSharePrice(); + } + return price; + } + protected void adjustSharePrice (PublicCompanyI company, int numberSold, boolean soldBefore) { if (company.canSharePriceVary()) { Modified: trunk/18xx/rails/game/specific/_1835/StockRound_1835.java =================================================================== --- trunk/18xx/rails/game/specific/_1835/StockRound_1835.java 2010-08-01 12:17:26 UTC (rev 1365) +++ trunk/18xx/rails/game/specific/_1835/StockRound_1835.java 2010-08-01 15:28:24 UTC (rev 1366) @@ -78,6 +78,22 @@ return price; } + @Override + // The sell-in-same-turn-at-decreasing-price option does not apply here + protected int getCurrentSellPrice (PublicCompanyI company) { + + String companyName = company.getName(); + int price; + + if (sellPrices.containsKey(companyName)) { + price = (sellPrices.get(companyName)).getPrice(); + } else { + price = company.getCurrentSpace().getPrice() / company.getShareUnitsForSharePrice(); + } + return price; + } + + /** Share price goes down 1 space for any number of shares sold. */ @Override This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-01 12:17:32
|
Revision: 1365 http://rails.svn.sourceforge.net/rails/?rev=1365&view=rev Author: stefanfrey Date: 2010-08-01 12:17:26 +0000 (Sun, 01 Aug 2010) Log Message: ----------- Changed location for default.profiles Modified Paths: -------------- trunk/18xx/rails/util/Config.java Added Paths: ----------- trunk/18xx/data/profiles/default.profiles Removed Paths: ------------- trunk/18xx/default.profiles Copied: trunk/18xx/data/profiles/default.profiles (from rev 1363, trunk/18xx/default.profiles) =================================================================== --- trunk/18xx/data/profiles/default.profiles (rev 0) +++ trunk/18xx/data/profiles/default.profiles 2010-08-01 12:17:26 UTC (rev 1365) @@ -0,0 +1,2 @@ +default=data/profiles/default.profile +.test=data/profiles/test.profile Deleted: trunk/18xx/default.profiles =================================================================== --- trunk/18xx/default.profiles 2010-08-01 11:46:26 UTC (rev 1364) +++ trunk/18xx/default.profiles 2010-08-01 12:17:26 UTC (rev 1365) @@ -1,2 +0,0 @@ -default=data/profiles/default.profile -.test=data/profiles/test.profile Modified: trunk/18xx/rails/util/Config.java =================================================================== --- trunk/18xx/rails/util/Config.java 2010-08-01 11:46:26 UTC (rev 1364) +++ trunk/18xx/rails/util/Config.java 2010-08-01 12:17:26 UTC (rev 1365) @@ -46,7 +46,7 @@ private static final String LOG4J_CONFIG_FILE = "log4j.properties"; /** Rails profile configurations */ - private static String defaultProfilesFile = "default.profiles"; + private static String defaultProfilesFile = "data/profiles/default.profiles"; private static Properties defaultProfiles = new Properties(); private static String userProfilesFile = "user.profiles"; private static Properties userProfiles = new Properties(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-08-01 11:46:32
|
Revision: 1364 http://rails.svn.sourceforge.net/rails/?rev=1364&view=rev Author: stefanfrey Date: 2010-08-01 11:46:26 +0000 (Sun, 01 Aug 2010) Log Message: ----------- Updated and improved configuration settings Modified Paths: -------------- trunk/18xx/LocalisedText.properties trunk/18xx/data/Properties.xml trunk/18xx/rails/ui/swing/ConfigWindow.java trunk/18xx/rails/ui/swing/StartRoundWindow.java trunk/18xx/rails/util/Config.java trunk/18xx/rails/util/LocalText.java Added Paths: ----------- trunk/18xx/rails/ui/swing/elements/RailsIcon.java Property Changed: ---------------- trunk/18xx/ Property changes on: trunk/18xx ___________________________________________________________________ Modified: svn:ignore - *.bat *.txt .cvsignore .classpath .externalToolBuilders 18xx.zip deploy.xml .project zip.xml NewUIstuff.zip COMP.WPS rails.jar rails.jardesc Rails-1.0.1.jar my_my.properties log rails-1.0.1.jar rails*.zip rails-*.jar tools rails-?.*.* jar/* classes/* 18xx_autosave.rails 18xx_autosave.rails.tmp + *.bat *.txt .cvsignore .classpath .externalToolBuilders 18xx.zip deploy.xml .project zip.xml NewUIstuff.zip COMP.WPS rails.jar rails.jardesc Rails-1.0.1.jar my_my.properties log rails-1.0.1.jar rails*.zip rails-*.jar tools rails-?.*.* jar/* classes/* 18xx_autosave.rails 18xx_autosave.rails.tmp user.profiles Modified: trunk/18xx/LocalisedText.properties =================================================================== --- trunk/18xx/LocalisedText.properties 2010-07-30 20:59:08 UTC (rev 1363) +++ trunk/18xx/LocalisedText.properties 2010-08-01 11:46:26 UTC (rev 1364) @@ -67,18 +67,19 @@ COMPANY=Company COMPANY_DETAILS=Company details CONFIG=Configuration -CONFIG_APPLY_MESSAGE=Current changes (will be) applied +CONFIG_APPLY_MESSAGE=<html>Current changes (will be) applied.<br>Be aware that some changes to be active require <br> UI redraws or a restart of Rails.</html> CONFIG_APPLY_TITLE=Apply confirmation CONFIG_CURRENT_PROFILE=Active profile = {0} (based on = {1}) CONFIG_DEFAULT_TITLE=Default profile CONFIG_DEFAULT_MESSAGE=Select a template for settings +CONFIG_INFO_TITLE=Info text for {0} CONFIG_NEW_MESSAGE=Select a name of the new profile CONFIG_NEW_TITLE=Create profile CONFIG_SELECT_PROFILE=Select profile -> CONFIG_SETTINGS=Profile settings CONFIG_SAVE_MESSAGE=Active profile {0} was saved CONFIG_SAVE_TITLE=Save confirmation -CONFIG_WINDOW_TITLE=Rails Configuration +CONFIG_WINDOW_TITLE=Rails Configuration CORRECT_CASH=Cash Correction CORRECT_MAP=Map Correction CURRENT=Current @@ -149,6 +150,19 @@ ComponentInitAs=Component {0} is initialized as class {1} ComponentManagerNotReconfigured=Cannot reconfigure the ComponentManager. ComponentManagerNotYetConfigured=ComponentManager has not yet been configured. +Config.infoText.locale=<html>te_ST shows local text keys. <br> Requires restart.</html> +Config.infoText.default_players=Enter player names separated by commas. +Config.label.default_game=Default game +Config.label.default_players=Default players +Config.label.local.player.name=Local player (for pbem) +Config.label.locale=Language Setting +Config.toolTip.local.player.name=Player name used as suffix for game save +Config.section.Format=Format/Colors +Config.section.General=General +Config.section.Log=Log +Config.section.Map=Map +Config.section.Save=Save +Config.section.UI=Windows/Fonts ConfirmToken=Press Lay Token to confirm token, click another city hex, or press the No Token button. connected=connected CorrectCashAddMoney=CORRECTION: {0} receives {1} from the bank Modified: trunk/18xx/data/Properties.xml =================================================================== --- trunk/18xx/data/Properties.xml 2010-07-30 20:59:08 UTC (rev 1363) +++ trunk/18xx/data/Properties.xml 2010-08-01 11:46:26 UTC (rev 1364) @@ -2,7 +2,7 @@ <!-- Supported properties Defines rails configuration options, but do not stores the actual values --> <Properties> - <Panel name="General"> + <Section name="General"> <Property name="locale" type="LIST" values="en_US,te_ST" initClass="rails.util.LocalText" initMethod="setLocale" initParameter="yes" /> @@ -10,28 +10,28 @@ <Property name="default_players" type="STRING" /> <Property name="local.player.name" type="STRING" /> - </Panel> - <Panel name="Save"> + </Section> + <Section name="Save"> <Property name="save.directory" type="DIRECTORY" /> <Property name="save.filename.date_time_pattern" type="STRING" /> <Property name="save.filename.suffix" type="STRING" /> <Property name="save.filename.extension" type="STRING" /> <Property name="save.recovery.active" type="BOOLEAN" /> <Property name="save.recovery.filepath" type="FILE" /> - </Panel> - <Panel name="UI"> + </Section> + <Section name="UI"> <Property name="report.window.open" type="BOOLEAN" /> <Property name="report.window.editable" type="BOOLEAN" /> <Property name="stockchart.window.open" type="BOOLEAN" /> <Property name="font.ui.scale" type="PERCENT" /> <Property name="font.ui.name" type="FONT" /> <Property name="font.ui.style" type="LIST" values="plain,bold" /> - </Panel> - <Panel name="Map"> + </Section> + <Section name="Map"> <Property name="map.autoscroll" type="BOOLEAN" /> <Property name="map.zoomstep" type="INTEGER" /> - </Panel> - <Panel name="Format"> + </Section> + <Section name="Format"> <Property name="money_format" type="STRING" /> <Property name="or.number_format" type="LIST" values="simple,composite" /> <Property name="route.colour.1" type="COLOR" @@ -42,10 +42,10 @@ initClass="rails.ui.swing.hexmap.HexMap" initMethod="setRouteColours" /> <Property name="route.colour.4" type="COLOR" initClass="rails.ui.swing.hexmap.HexMap" initMethod="setRouteColours" /> - </Panel> - <Panel name="Log"> + </Section> + <Section name="Log"> <Property name="report.directory" type="DIRECTORY" /> <Property name="report.filename.date_time_pattern" type="STRING" /> <Property name="report.filename.extension" type="STRING" /> - </Panel> + </Section> </Properties> \ No newline at end of file Modified: trunk/18xx/rails/ui/swing/ConfigWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-30 20:59:08 UTC (rev 1363) +++ trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-08-01 11:46:26 UTC (rev 1364) @@ -14,8 +14,12 @@ import java.awt.event.FocusListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; import java.io.File; import java.util.Map; import java.util.List; @@ -28,6 +32,7 @@ import javax.swing.filechooser.FileFilter; import javax.swing.JCheckBox; import javax.swing.JComponent; +import javax.swing.JDialog; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; @@ -42,6 +47,7 @@ import javax.swing.border.Border; import rails.game.ConfigurationException; +import rails.ui.swing.elements.RailsIcon; import rails.util.Config; import rails.util.ConfigItem; import rails.util.LocalText; @@ -151,10 +157,10 @@ Border titled = BorderFactory.createTitledBorder(etched, LocalText.getText("CONFIG_SETTINGS")); configPane.setBorder(titled); - Map<String, List<ConfigItem>> configPanels = Config.getConfigPanels(); + Map<String, List<ConfigItem>> configSections = Config.getConfigSections(); int maxElements = Config.getMaxElementsInPanels(); - for (String panelName:configPanels.keySet()) { + for (String sectionName:configSections.keySet()) { JPanel newPanel = new JPanel(); newPanel.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); @@ -164,18 +170,18 @@ gbc.weighty = 0.8; gbc.insets = new Insets(5,5,5,5); gbc.anchor = GridBagConstraints.WEST; - for (ConfigItem item:configPanels.get(panelName)) { + for (ConfigItem item:configSections.get(sectionName)) { gbc.gridx = 0; gbc.gridy++; defineElement(newPanel, item, gbc); } // fill up to maxElements gbc.gridx = 0; - for (gbc.gridy++; gbc.gridy < maxElements; gbc.gridy++) { + while (++gbc.gridy < maxElements) { JLabel emptyLabel = new JLabel(""); newPanel.add(emptyLabel, gbc); } - configPane.addTab(LocalText.getText("Config.panel." + panelName), newPanel); + configPane.addTab(LocalText.getText("Config.section." + sectionName), newPanel); } } @@ -192,13 +198,17 @@ private void defineElement(JPanel panel, final ConfigItem item, GridBagConstraints gbc) { - // standard components + // current value (based on current changes and properties) String configValue = item.getCurrentValue(); -// final String toolTip = item.toolTip; - // item label - JLabel label = new JLabel(LocalText.getText("Config." + item.name)); -// label.setToolTipText(toolTip); + // item label, toolTip and infoText + final String itemLabel = LocalText.getText("Config.label." + item.name); + final String toolTip = LocalText.getTextWithDefault("Config.toolTip." + item.name, null); + final String infoText = LocalText.getTextWithDefault("Config.infoText." + item.name, null); + + // define label + JLabel label = new JLabel(itemLabel); + label.setToolTipText(toolTip); gbc.fill = GridBagConstraints.NONE; addToGridBag(panel, label, gbc); @@ -277,7 +287,7 @@ } final JComboBox comboBox = new JComboBox(allowedValues); comboBox.setSelectedItem(configValue); -// comboBox.setToolTipText(toolTip)); + comboBox.setToolTipText(toolTip); comboBox.addFocusListener(new FocusListener() { public void focusGained(FocusEvent arg0) { // do nothing @@ -295,19 +305,20 @@ case FILE: final JLabel dirLabel = new JLabel(configValue); dirLabel.setHorizontalAlignment(SwingConstants.CENTER); -// dirLabel.setToolTipText(toolTip); + dirLabel.setToolTipText(toolTip); gbc.fill = GridBagConstraints.HORIZONTAL; addToGridBag(panel, dirLabel, gbc); JButton dirButton = new JButton("Choose..."); dirButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { - JFileChooser fc = new JFileChooser(dirLabel.getText()); + JFileChooser fc = new JFileChooser(); if (item.type == ConfigItem.ConfigType.DIRECTORY) { fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } else { fc.setFileSelectionMode(JFileChooser.FILES_ONLY); } + fc.setSelectedFile(new File(dirLabel.getText())); int state = fc.showOpenDialog(ConfigWindow.this); if ( state == JFileChooser.APPROVE_OPTION ){ File file = fc.getSelectedFile(); @@ -336,7 +347,7 @@ } else { colorLabel.setForeground(Color.BLACK); } -// colorLabel.setToolTipText(toolTip); + colorLabel.setToolTipText(toolTip); gbc.fill = GridBagConstraints.HORIZONTAL; addToGridBag(panel, colorLabel, gbc); JButton colorButton = new JButton("Choose..."); @@ -378,6 +389,43 @@ addEmptyLabel(panel, gbc); break; } + // add info icon for infoText + if (infoText != null) { + JLabel infoIcon = new JLabel(RailsIcon.INFO.icon); + infoIcon.addMouseListener(new MouseListener() { + public void mousePressed(MouseEvent e) { + final JDialog dialog = new JDialog(ConfigWindow.this, false); + final JOptionPane optionPane = new JOptionPane(); + optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE); + optionPane.setMessage(infoText); + optionPane.addPropertyChangeListener(JOptionPane.VALUE_PROPERTY, + new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent e) { + dialog.dispose(); + } + } + ); + dialog.setTitle(LocalText.getText("CONFIG_INFO_TITLE", itemLabel)); + dialog.getContentPane().add(optionPane); + dialog.pack(); + dialog.setVisible(true); + } + + public void mouseClicked(MouseEvent e) { + } + public void mouseReleased(MouseEvent e) { + } + + public void mouseEntered(MouseEvent e) { + } + + public void mouseExited(MouseEvent e) { + } + }); + gbc.fill = GridBagConstraints.NONE; + addToGridBag(panel, infoIcon, gbc); + addEmptyLabel(panel, gbc); + } } private void setupButtonPanel() { Modified: trunk/18xx/rails/ui/swing/StartRoundWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/StartRoundWindow.java 2010-07-30 20:59:08 UTC (rev 1363) +++ trunk/18xx/rails/ui/swing/StartRoundWindow.java 2010-08-01 11:46:26 UTC (rev 1364) @@ -702,15 +702,7 @@ } private ImageIcon createInfoIcon() { - - String path = "/rails/ui/images/Inform.gif"; - java.net.URL imgURL = getClass().getResource(path); - if (imgURL != null) { - return new ImageIcon(imgURL, "Info"); - } else { - System.err.println("Couldn't find file: " + path); - return null; - } + return RailsIcon.INFO.icon; } public void keyPressed(KeyEvent e) { Added: trunk/18xx/rails/ui/swing/elements/RailsIcon.java =================================================================== --- trunk/18xx/rails/ui/swing/elements/RailsIcon.java (rev 0) +++ trunk/18xx/rails/ui/swing/elements/RailsIcon.java 2010-08-01 11:46:26 UTC (rev 1364) @@ -0,0 +1,30 @@ +package rails.ui.swing.elements; + +import javax.swing.ImageIcon; + +/** + * Enumeration that provides a specific ImageIcon + * Simply use RailsIcon.{IconName}.create + * @author freystef + */ + +public enum RailsIcon { + + // in parentheses the image file + INFO ("Inform.gif"); + + private final static String IMAGE_PATH = "/rails/ui/images/"; + public final ImageIcon icon; + + private RailsIcon(String fileName) { + String path = IMAGE_PATH + fileName; + java.net.URL imgURL = getClass().getResource(path); + if (imgURL != null) { + icon = new ImageIcon(imgURL, "Info"); + } else { + System.err.println("Couldn't find file: " + path); + icon = null; + } + } + +} Property changes on: trunk/18xx/rails/ui/swing/elements/RailsIcon.java ___________________________________________________________________ Added: svn:mime-type + text/plain Modified: trunk/18xx/rails/util/Config.java =================================================================== --- trunk/18xx/rails/util/Config.java 2010-07-30 20:59:08 UTC (rev 1363) +++ trunk/18xx/rails/util/Config.java 2010-08-01 11:46:26 UTC (rev 1364) @@ -39,7 +39,7 @@ private static final String CONFIG_XML_DIR = "data"; private static final String CONFIG_XML_FILE = "Properties.xml"; private static final String CONFIG_TAG = "Properties"; - private static final String PANEL_TAG = "Panel"; + private static final String SECTION_TAG = "Section"; private static final String ITEM_TAG = "Property"; /** Log 4j configuration */ @@ -67,7 +67,7 @@ private static boolean propertiesLoaded = false; /** Map that holds the panel, which contains config items */ - private static Map<String, List<ConfigItem>> configPanels = null; + private static Map<String, List<ConfigItem>> configSections = null; /** * Hidden constructor, the class is never instantiated, everything is static @@ -81,28 +81,30 @@ List<String> directories = new ArrayList<String>(); directories.add(CONFIG_XML_DIR); try { - // Find the <Config> tag + // Find the config tag inside the the config xml file Tag configTag = Tag.findTopTagInFile(CONFIG_XML_FILE, directories, CONFIG_TAG); log.debug("Opened config xml, filename = " + CONFIG_XML_FILE); - configPanels = new LinkedHashMap<String, List<ConfigItem>>(); - // find panels - List<Tag> panelTags = configTag.getChildren(PANEL_TAG); - if (panelTags != null) { - for (Tag panelTag:panelTags) { + // define sections + configSections = new LinkedHashMap<String, List<ConfigItem>>(); + + // find sections + List<Tag> sectionTags = configTag.getChildren(SECTION_TAG); + if (sectionTags != null) { + for (Tag sectionTag:sectionTags) { // find name attribute - String panelName = panelTag.getAttributeAsString("name"); - if (!Util.hasValue(panelName)) continue; + String sectionName = sectionTag.getAttributeAsString("name"); + if (!Util.hasValue(sectionName)) continue; // find items - List<Tag> itemTags = panelTag.getChildren(ITEM_TAG); + List<Tag> itemTags = sectionTag.getChildren(ITEM_TAG); if (itemTags == null || itemTags.size() == 0) continue; - List<ConfigItem> panelItems = new ArrayList<ConfigItem>(); + List<ConfigItem> sectionItems = new ArrayList<ConfigItem>(); for (Tag itemTag:itemTags) { - panelItems.add(new ConfigItem(itemTag)); + sectionItems.add(new ConfigItem(itemTag)); } - configPanels.put(panelName, panelItems); + configSections.put(sectionName, sectionItems); } } @@ -111,20 +113,20 @@ } } - public static Map<String, List<ConfigItem>> getConfigPanels() { - if (configPanels == null) { + public static Map<String, List<ConfigItem>> getConfigSections() { + if (configSections == null) { readConfigSetupXML(); } - log.debug("Configuration setup = " + configPanels); - return configPanels; + log.debug("Configuration setup = " + configSections); + return configSections; } public static int getMaxElementsInPanels() { int maxElements = 0; - for (List<ConfigItem> panel:configPanels.values()) { + for (List<ConfigItem> panel:configSections.values()) { maxElements = Math.max(maxElements, panel.size()); } - log.debug("maxelements" + maxElements); + log.debug("Configuration sections with maximum elements of " + maxElements); return maxElements; } @@ -132,7 +134,7 @@ * updates the profile according to the changes in configitems */ public static void updateProfile() { - for (List<ConfigItem> items:configPanels.values()) { + for (List<ConfigItem> items:configSections.values()) { for (ConfigItem item:items) { if (!item.hasNewValue()) continue; if (item.getNewValue().equals(defaultProperties.get(item.name))) { @@ -151,7 +153,7 @@ * reverts all changes in configitems */ public static void revertProfile() { - for (List<ConfigItem> items:configPanels.values()) { + for (List<ConfigItem> items:configSections.values()) { for (ConfigItem item:items) { item.setNewValue(null); } Modified: trunk/18xx/rails/util/LocalText.java =================================================================== --- trunk/18xx/rails/util/LocalText.java 2010-07-30 20:59:08 UTC (rev 1363) +++ trunk/18xx/rails/util/LocalText.java 2010-08-01 11:46:26 UTC (rev 1364) @@ -29,10 +29,20 @@ } public static String getText(String key, Object parameter) { - return getText(key, new Object[] { parameter }); + return getText(key, new Object[] { parameter }); } + + public static String getText(String key, Object... parameters) { + /* If the text is not found, return the key in brackets */ + return getTextExecute(key, "<" + key + ">", true, parameters); + } + + public static String getTextWithDefault(String key, String defaultText) { + return getTextExecute(key, defaultText, false, (Object[]) null); + } - public static String getText(String key, Object... parameters) { + // actual procedure to retrieve the local text + private static String getTextExecute(String key, String defaultText, boolean errorOnMissing, Object... parameters) { String result = ""; if (key == null || key.length() == 0) return ""; @@ -95,11 +105,12 @@ try { result = localisedText.getString(key); } catch (Exception e) { - System.out.println("Missing text for key " + key + " in locale " + if (errorOnMissing) { + System.out.println("Missing text for key " + key + " in locale " + locale.getDisplayName() + " (" + localeCode + ")"); - /* If the text is not found, return the key in brackets */ - return "<" + key + ">"; + } + return defaultText; } if (parameters != null) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-07-30 20:59:14
|
Revision: 1363 http://rails.svn.sourceforge.net/rails/?rev=1363&view=rev Author: evos Date: 2010-07-30 20:59:08 +0000 (Fri, 30 Jul 2010) Log Message: ----------- New option to enable selling stock of one company in one turn in separate actions at decreasing prices. Only for 1830 at this stage. Modified Paths: -------------- trunk/18xx/LocalisedText.properties trunk/18xx/data/1830/Game.xml trunk/18xx/data/GamesList.xml trunk/18xx/rails/game/ShareSellingRound.java trunk/18xx/rails/game/StockRound.java Modified: trunk/18xx/LocalisedText.properties =================================================================== --- trunk/18xx/LocalisedText.properties 2010-07-30 10:20:42 UTC (rev 1362) +++ trunk/18xx/LocalisedText.properties 2010-07-30 20:59:08 UTC (rev 1363) @@ -472,6 +472,7 @@ SELL_SHARES_LOG={0} sells {1} {2}% shares ({3}%) of {4} to Pool for {5}. SellHowManyShares=Sell how many shares? SellShares=Sell {0} {1}% share(s) ({2}%) of {3} for {4} +SeparateSalesAtSamePrice=Allow separate sales at same price SET_REVENUE=Set Revenue SET_SCALE=Set Scale SharesPutInTreasury=The remaining {0}% shares of {1} are put in its treasury Modified: trunk/18xx/data/1830/Game.xml =================================================================== --- trunk/18xx/data/1830/Game.xml 2010-07-30 10:20:42 UTC (rev 1362) +++ trunk/18xx/data/1830/Game.xml 2010-07-30 20:59:08 UTC (rev 1363) @@ -25,6 +25,7 @@ <GameOption name="UnlimitedTiles" type="toggle" default="no"/> <GameOption name="LeaveAuctionOnPass" type="toggle" default="no"/> <GameOption name="TwoPlayersCertLimit70Percent" type="toggle" default="yes"/> + <GameOption name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <GameParameters> <PlayerShareLimit percentage="60"> <!-- Option "NumberOfPlayers" is automatically set Modified: trunk/18xx/data/GamesList.xml =================================================================== --- trunk/18xx/data/GamesList.xml 2010-07-30 10:20:42 UTC (rev 1362) +++ trunk/18xx/data/GamesList.xml 2010-07-30 20:59:08 UTC (rev 1363) @@ -30,6 +30,7 @@ <Option name="UnlimitedTiles" type="toggle" default="no"/> <Option name="LeaveAuctionOnPass" type="toggle" default="no"/> <Option name="TwoPlayersCertLimit70Percent" type="toggle" default="no"/> + <Option name="SeparateSalesAtSamePrice" type="toggle" default="yes"/> <Players minimum="2" maximum="6"/> </Game> Modified: trunk/18xx/rails/game/ShareSellingRound.java =================================================================== --- trunk/18xx/rails/game/ShareSellingRound.java 2010-07-30 10:20:42 UTC (rev 1362) +++ trunk/18xx/rails/game/ShareSellingRound.java 2010-07-30 20:59:08 UTC (rev 1363) @@ -22,7 +22,7 @@ Player sellingPlayer; IntegerState cashToRaise; PublicCompanyI unsellableCompany = null; - + private List<SellShares> sellableShares; /** @@ -86,15 +86,15 @@ public void setSellableShares() { possibleActions.addAll(sellableShares); } - + /** - * Create a list of certificates that a player may sell in an emergency + * Create a list of certificates that a player may sell in an emergency * share selling round, taking all rules taken into account. */ private List<SellShares> getSellableShares () { - + sellableShares = new ArrayList<SellShares> (); - + String compName; int price; int number; @@ -318,7 +318,8 @@ int price; // Get the sell price (does not change within a turn) - if (sellPrices.containsKey(companyName)) { + if (sellPrices.containsKey(companyName) + && GameOption.convertValueToBoolean(getGameOption("SeparateSalesAtSamePrice"))) { price = (sellPrices.get(companyName)).getPrice(); } else { sellPrice = company.getCurrentSpace(); Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2010-07-30 10:20:42 UTC (rev 1362) +++ trunk/18xx/rails/game/StockRound.java 2010-07-30 20:59:08 UTC (rev 1363) @@ -412,7 +412,8 @@ * Check the price. If a cert was sold before this turn, the * original price is still valid */ - if (sellPrices.containsKey(compName)) { + if (sellPrices.containsKey(compName) + && GameOption.convertValueToBoolean(getGameOption("SeparateSalesAtSamePrice"))) { price = (sellPrices.get(compName)).getPrice(); } else { price = company.getMarketPrice(); @@ -1039,7 +1040,8 @@ boolean soldBefore = sellPrices.containsKey(companyName); // Get the sell price (does not change within a turn) - if (soldBefore) { + if (soldBefore + && GameOption.convertValueToBoolean(getGameOption("SeparateSalesAtSamePrice"))) { price = (sellPrices.get(companyName)).getPrice(); } else { sellPrice = company.getCurrentSpace(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-30 10:20:48
|
Revision: 1362 http://rails.svn.sourceforge.net/rails/?rev=1362&view=rev Author: stefanfrey Date: 2010-07-30 10:20:42 +0000 (Fri, 30 Jul 2010) Log Message: ----------- Fix some problems with config Modified Paths: -------------- trunk/18xx/LocalisedText.properties trunk/18xx/rails/ui/swing/ConfigWindow.java trunk/18xx/rails/util/Config.java Modified: trunk/18xx/LocalisedText.properties =================================================================== --- trunk/18xx/LocalisedText.properties 2010-07-29 23:33:24 UTC (rev 1361) +++ trunk/18xx/LocalisedText.properties 2010-07-30 10:20:42 UTC (rev 1362) @@ -67,6 +67,8 @@ COMPANY=Company COMPANY_DETAILS=Company details CONFIG=Configuration +CONFIG_APPLY_MESSAGE=Current changes (will be) applied +CONFIG_APPLY_TITLE=Apply confirmation CONFIG_CURRENT_PROFILE=Active profile = {0} (based on = {1}) CONFIG_DEFAULT_TITLE=Default profile CONFIG_DEFAULT_MESSAGE=Select a template for settings Modified: trunk/18xx/rails/ui/swing/ConfigWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-29 23:33:24 UTC (rev 1361) +++ trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-30 10:20:42 UTC (rev 1362) @@ -248,9 +248,14 @@ // do nothing } public void focusLost(FocusEvent arg0) { - int value = (Integer)spinner.getValue(); - Double adjValue = (double)value / spinnerMultiple; - item.setNewValue(adjValue.toString()); + Integer value = (Integer)spinner.getValue(); + if (item.type == ConfigItem.ConfigType.PERCENT) { + Double adjValue = (double)value / spinnerMultiple; + item.setNewValue(adjValue.toString()); + } else { + item.setNewValue(value.toString()); + } + } } ); @@ -525,6 +530,8 @@ private void applyConfig() { Config.updateProfile(); // transfer the configitem to the active profile + JOptionPane.showMessageDialog(ConfigWindow.this, LocalText.getText("CONFIG_APPLY_MESSAGE"), + LocalText.getText("CONFIG_APPLY_TITLE"), JOptionPane.INFORMATION_MESSAGE); } private void closeConfig() { Modified: trunk/18xx/rails/util/Config.java =================================================================== --- trunk/18xx/rails/util/Config.java 2010-07-29 23:33:24 UTC (rev 1361) +++ trunk/18xx/rails/util/Config.java 2010-07-30 10:20:42 UTC (rev 1362) @@ -134,7 +134,11 @@ public static void updateProfile() { for (List<ConfigItem> items:configPanels.values()) { for (ConfigItem item:items) { - if (!item.hasNewValue() || item.getNewValue().equals(defaultProperties.get(item.name))) continue; + if (!item.hasNewValue()) continue; + if (item.getNewValue().equals(defaultProperties.get(item.name))) { + userProperties.remove(item.name); + continue; + } userProperties.setProperty(item.name, item.getNewValue()); item.callInitMethod(); log.debug("Changed property name = " + item.name + " to value = " + item.getNewValue()); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-29 23:33:31
|
Revision: 1361 http://rails.svn.sourceforge.net/rails/?rev=1361&view=rev Author: stefanfrey Date: 2010-07-29 23:33:24 +0000 (Thu, 29 Jul 2010) Log Message: ----------- Update configuration mechanism Modified Paths: -------------- trunk/18xx/LocalisedText.properties trunk/18xx/data/Properties.xml trunk/18xx/data/profiles/default.profile trunk/18xx/rails/ui/swing/ConfigWindow.java trunk/18xx/rails/ui/swing/hexmap/HexMap.java trunk/18xx/rails/util/Config.java trunk/18xx/rails/util/ConfigItem.java trunk/18xx/rails/util/LocalText.java trunk/18xx/rails/util/Util.java Modified: trunk/18xx/LocalisedText.properties =================================================================== --- trunk/18xx/LocalisedText.properties 2010-07-25 22:45:34 UTC (rev 1360) +++ trunk/18xx/LocalisedText.properties 2010-07-29 23:33:24 UTC (rev 1361) @@ -7,6 +7,7 @@ ALL=All ALL_PASSED=All players have passed. ALSO_GETS={0} also gets {1} +APPLY=Apply AT_PRICE=at {0} AcceptingConfigFailure=Temporarily accepting configuration failure AcquiresBonus={0} acquires a {1} +{2} bonus on hex(es) {3} Modified: trunk/18xx/data/Properties.xml =================================================================== --- trunk/18xx/data/Properties.xml 2010-07-25 22:45:34 UTC (rev 1360) +++ trunk/18xx/data/Properties.xml 2010-07-29 23:33:24 UTC (rev 1361) @@ -1,17 +1,51 @@ <?xml version="1.0" encoding="utf-8"?> -<!-- Supported properties -Defines rails configuration options, but do not stores the actual values - --> +<!-- Supported properties Defines rails configuration options, but do not + stores the actual values --> <Properties> <Panel name="General"> - <Property name="locale" type="LIST" values="en_US,te_ST" toolTip="Language Selection" - initClass="rails.util.LocalText" initMethod="setLocale" initParameter="yes"/> + <Property name="locale" type="LIST" values="en_US,te_ST" + initClass="rails.util.LocalText" initMethod="setLocale" + initParameter="yes" /> + <Property name="default_game" type="STRING" /> + <Property name="default_players" type="STRING" /> + <Property name="local.player.name" type="STRING" /> + </Panel> <Panel name="Save"> - <Property name="save.directory" type="DIRECTORY" toolTip="Default save file directory" /> - <Property name="save.filename.date_time_pattern" type="STRING" toolTip="Datetime pattern for filename" /> + <Property name="save.directory" type="DIRECTORY" /> + <Property name="save.filename.date_time_pattern" type="STRING" /> + <Property name="save.filename.suffix" type="STRING" /> + <Property name="save.filename.extension" type="STRING" /> + <Property name="save.recovery.active" type="BOOLEAN" /> + <Property name="save.recovery.filepath" type="FILE" /> </Panel> - <Panel name="Colors"> - <Property name="route.colour.1" type="COLOR" toolTip="Route color of first train" /> + <Panel name="UI"> + <Property name="report.window.open" type="BOOLEAN" /> + <Property name="report.window.editable" type="BOOLEAN" /> + <Property name="stockchart.window.open" type="BOOLEAN" /> + <Property name="font.ui.scale" type="PERCENT" /> + <Property name="font.ui.name" type="FONT" /> + <Property name="font.ui.style" type="LIST" values="plain,bold" /> </Panel> + <Panel name="Map"> + <Property name="map.autoscroll" type="BOOLEAN" /> + <Property name="map.zoomstep" type="INTEGER" /> + </Panel> + <Panel name="Format"> + <Property name="money_format" type="STRING" /> + <Property name="or.number_format" type="LIST" values="simple,composite" /> + <Property name="route.colour.1" type="COLOR" + initClass="rails.ui.swing.hexmap.HexMap" initMethod="setRouteColours" /> + <Property name="route.colour.2" type="COLOR" + initClass="rails.ui.swing.hexmap.HexMap" initMethod="setRouteColours" /> + <Property name="route.colour.3" type="COLOR" + initClass="rails.ui.swing.hexmap.HexMap" initMethod="setRouteColours" /> + <Property name="route.colour.4" type="COLOR" + initClass="rails.ui.swing.hexmap.HexMap" initMethod="setRouteColours" /> + </Panel> + <Panel name="Log"> + <Property name="report.directory" type="DIRECTORY" /> + <Property name="report.filename.date_time_pattern" type="STRING" /> + <Property name="report.filename.extension" type="STRING" /> + </Panel> </Properties> \ No newline at end of file Modified: trunk/18xx/data/profiles/default.profile =================================================================== --- trunk/18xx/data/profiles/default.profile 2010-07-25 22:45:34 UTC (rev 1360) +++ trunk/18xx/data/profiles/default.profile 2010-07-29 23:33:24 UTC (rev 1361) @@ -1,7 +1,39 @@ +### Panel General locale=en_US +default_game=1830 +default_players= +local.player.names= + +### Panel Save save.directory= save.filename.date_time_pattern=yyyyMMdd_HHmm save.filename.date_time_zone=UTC save.filename.suffix=NEXT_PLAYER save.filename.extension=rails +save.recovery.active=no +save.recovery.filepath=18xx_autosave.rails +### Panel UI +report.window.open=yes +report.window.editable=no +stockchart.window.open=yes +font.ui.scale=1 +font.ui.name= +font.ui.style=bold + +### Panel Map +map.autoscroll=yes +map.zoomstep=10 + +### Panel Format +money_format= +or.number_format=composite +route.colour.1=00ffff +route.colour.2=ffc0cb +route.colour.3=ffa500 +route.colour.4=808080 + +### Panel Log +#report.directory=log +#report.filename.date_time_pattern=yyyyMMdd +#report.filename.extension=log Modified: trunk/18xx/rails/ui/swing/ConfigWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-25 22:45:34 UTC (rev 1360) +++ trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-29 23:33:24 UTC (rev 1361) @@ -2,6 +2,8 @@ import java.awt.Color; import java.awt.EventQueue; +import java.awt.Font; +import java.awt.GraphicsEnvironment; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; @@ -24,14 +26,18 @@ import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; +import javax.swing.JCheckBox; import javax.swing.JComponent; 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.SpinnerNumberModel; import javax.swing.SwingConstants; +import javax.swing.UIManager; import javax.swing.WindowConstants; import javax.swing.border.Border; @@ -73,7 +79,7 @@ addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { - cancelConfig(); + closeConfig(); } }); } @@ -136,6 +142,8 @@ } + + private void setupConfigPane() { configPane.removeAll(); @@ -144,7 +152,8 @@ configPane.setBorder(titled); Map<String, List<ConfigItem>> configPanels = Config.getConfigPanels(); - + int maxElements = Config.getMaxElementsInPanels(); + for (String panelName:configPanels.keySet()) { JPanel newPanel = new JPanel(); newPanel.setLayout(new GridBagLayout()); @@ -153,14 +162,19 @@ gbc.gridheight = 1; gbc.weightx = 0.8; gbc.weighty = 0.8; - gbc.insets = new Insets(10,10,10,10); + gbc.insets = new Insets(5,5,5,5); gbc.anchor = GridBagConstraints.WEST; - int y = 0; for (ConfigItem item:configPanels.get(panelName)) { gbc.gridx = 0; - gbc.gridy = y++; + gbc.gridy++; defineElement(newPanel, item, gbc); } + // fill up to maxElements + gbc.gridx = 0; + for (gbc.gridy++; gbc.gridy < maxElements; gbc.gridy++) { + JLabel emptyLabel = new JLabel(""); + newPanel.add(emptyLabel, gbc); + } configPane.addTab(LocalText.getText("Config.panel." + panelName), newPanel); } } @@ -171,23 +185,94 @@ gbc.gridx ++; } + private void addEmptyLabel(JComponent container, GridBagConstraints gbc) { + JLabel label = new JLabel(""); + addToGridBag(container, label, gbc ); + } + private void defineElement(JPanel panel, final ConfigItem item, GridBagConstraints gbc) { // standard components - final String configValue = item.getCurrentValue(); - final String toolTip = item.toolTip; + String configValue = item.getCurrentValue(); +// final String toolTip = item.toolTip; // item label JLabel label = new JLabel(LocalText.getText("Config." + item.name)); - label.setToolTipText(toolTip); +// label.setToolTipText(toolTip); gbc.fill = GridBagConstraints.NONE; addToGridBag(panel, label, gbc); switch (item.type) { + case BOOLEAN: + final JCheckBox checkBox = new JCheckBox(); + boolean selected = Util.parseBoolean(configValue); + checkBox.setSelected(selected); + checkBox.addFocusListener(new FocusListener() { + public void focusGained(FocusEvent arg0) { + // do nothing + } + public void focusLost(FocusEvent arg0) { + if (checkBox.isSelected()) { + item.setNewValue("yes"); + } else { + item.setNewValue("no"); + } + } + } + ); + gbc.fill = GridBagConstraints.HORIZONTAL; + addToGridBag(panel, checkBox, gbc); + break; + case PERCENT: // percent uses a spinner with 5 changes + case INTEGER: + int spinnerStepSize; + final int spinnerMultiple; + if (item.type == ConfigItem.ConfigType.PERCENT) { + spinnerStepSize = 5; + spinnerMultiple = 100; + } else { + spinnerStepSize = 1; + spinnerMultiple = 1; + } + int spinnerValue; + try { + spinnerValue = (int)Math.round(Double.parseDouble(configValue) * spinnerMultiple); + } catch (NumberFormatException e) { + spinnerValue = 0; + } + final JSpinner spinner = new JSpinner(new SpinnerNumberModel + (spinnerValue, Integer.MIN_VALUE, Integer.MAX_VALUE, spinnerStepSize)); + ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField(). + addFocusListener(new FocusListener() { + public void focusGained(FocusEvent arg0) { + // do nothing + } + public void focusLost(FocusEvent arg0) { + int value = (Integer)spinner.getValue(); + Double adjValue = (double)value / spinnerMultiple; + item.setNewValue(adjValue.toString()); + } + } + ); + gbc.fill = GridBagConstraints.HORIZONTAL; + addToGridBag(panel, spinner, gbc); + addEmptyLabel(panel, gbc); + break; + case FONT: // fonts are a special list + if (!Util.hasValue(configValue)) { + configValue = ((Font)UIManager.getDefaults().get("Label.font")).getFamily(); + } case LIST: - final JComboBox comboBox = new JComboBox(item.allowedValues.toArray()); + String[] allowedValues; + if (item.type == ConfigItem.ConfigType.FONT) { + allowedValues = GraphicsEnvironment.getLocalGraphicsEnvironment(). + getAvailableFontFamilyNames(); + } else { + allowedValues = (String[])item.allowedValues.toArray(); + } + final JComboBox comboBox = new JComboBox(allowedValues); comboBox.setSelectedItem(configValue); - comboBox.setToolTipText(toolTip); +// comboBox.setToolTipText(toolTip)); comboBox.addFocusListener(new FocusListener() { public void focusGained(FocusEvent arg0) { // do nothing @@ -199,11 +284,13 @@ ); gbc.fill = GridBagConstraints.HORIZONTAL; addToGridBag(panel, comboBox, gbc); + addEmptyLabel(panel, gbc); break; case DIRECTORY: + case FILE: final JLabel dirLabel = new JLabel(configValue); dirLabel.setHorizontalAlignment(SwingConstants.CENTER); - dirLabel.setToolTipText(toolTip); +// dirLabel.setToolTipText(toolTip); gbc.fill = GridBagConstraints.HORIZONTAL; addToGridBag(panel, dirLabel, gbc); JButton dirButton = new JButton("Choose..."); @@ -211,7 +298,11 @@ new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(dirLabel.getText()); - fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + if (item.type == ConfigItem.ConfigType.DIRECTORY) { + fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + } else { + fc.setFileSelectionMode(JFileChooser.FILES_ONLY); + } int state = fc.showOpenDialog(ConfigWindow.this); if ( state == JFileChooser.APPROVE_OPTION ){ File file = fc.getSelectedFile(); @@ -240,7 +331,7 @@ } else { colorLabel.setForeground(Color.BLACK); } - colorLabel.setToolTipText(toolTip); +// colorLabel.setToolTipText(toolTip); gbc.fill = GridBagConstraints.HORIZONTAL; addToGridBag(panel, colorLabel, gbc); JButton colorButton = new JButton("Choose..."); @@ -249,7 +340,7 @@ public void actionPerformed(ActionEvent e) { Color selectedColor=JColorChooser.showDialog(ConfigWindow.this, "", colorLabel.getBackground()); if (selectedColor == null) return; - String newValue = Integer.toHexString(selectedColor.getRGB()).substring(3); + String newValue = Integer.toHexString(selectedColor.getRGB()).substring(2); colorLabel.setText(newValue); item.setNewValue(newValue); colorLabel.setBackground(selectedColor); @@ -279,6 +370,7 @@ ); gbc.fill = GridBagConstraints.HORIZONTAL; addToGridBag(panel, textField, gbc); + addEmptyLabel(panel, gbc); break; } } @@ -310,12 +402,22 @@ buttonPanel.add(saveButton); } + JButton applyButton = new JButton(LocalText.getText("APPLY")); + applyButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + ConfigWindow.this.applyConfig(); + } + } + ); + buttonPanel.add(applyButton); + JButton cancelButton = new JButton(LocalText.getText("CANCEL")); cancelButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { - ConfigWindow.this.cancelConfig(); + ConfigWindow.this.closeConfig(); } } ); @@ -420,8 +522,13 @@ }); } } - - private void cancelConfig() { + + private void applyConfig() { + Config.updateProfile(); // transfer the configitem to the active profile + } + + private void closeConfig() { + Config.revertProfile(); StatusWindow.uncheckMenuItemBox(StatusWindow.CONFIG_CMD); this.setVisible(false); } Modified: trunk/18xx/rails/ui/swing/hexmap/HexMap.java =================================================================== --- trunk/18xx/rails/ui/swing/hexmap/HexMap.java 2010-07-25 22:45:34 UTC (rev 1360) +++ trunk/18xx/rails/ui/swing/hexmap/HexMap.java 2010-07-29 23:33:24 UTC (rev 1361) @@ -69,7 +69,6 @@ protected List<GeneralPath> trainPaths; private static Color colour1, colour2, colour3, colour4; - protected Color[] trainColors = new Color[4]; protected int strokeWidth = 5; protected int strokeCap = BasicStroke.CAP_ROUND; protected int strokeJoin = BasicStroke.JOIN_BEVEL; @@ -85,7 +84,7 @@ protected double coordinateXMargin; protected double coordinateYMargin; - static { + public static void setRouteColours () { try { colour1 = Util.parseColour(Config.get("route.colour.1", null)); colour2 = Util.parseColour(Config.get("route.colour.2", null)); @@ -99,7 +98,7 @@ if (colour4 == null) colour4 = Color.GRAY; } } - + public void init(ORUIManager orUIManager, MapManager mapManager) { this.orUIManager = orUIManager; @@ -120,14 +119,15 @@ setupHexes(); initializeSettings(); + + setRouteColours(); } /** * defines settings from the config files */ private void initializeSettings() { - trainColors = new Color[]{colour1, colour2, colour3, colour4}; - + // define zoomStep from config String zoomStepSetting = Config.getGameSpecific("map.zoomstep"); if (Util.hasValue(zoomStepSetting)) { @@ -143,6 +143,9 @@ } } + + + protected void setupHexesGUI() { hexes = new ArrayList<GUIHex>(); @@ -296,6 +299,8 @@ Stroke trainStroke = new BasicStroke((int)(strokeWidth * zoomFactor), strokeCap, strokeJoin); g2.setStroke(trainStroke); + + Color[] trainColors = new Color[]{colour1, colour2, colour3, colour4}; int color = 0; for (GeneralPath path:trainPaths) { g2.setColor(trainColors[color++ % trainColors.length]); Modified: trunk/18xx/rails/util/Config.java =================================================================== --- trunk/18xx/rails/util/Config.java 2010-07-25 22:45:34 UTC (rev 1360) +++ trunk/18xx/rails/util/Config.java 2010-07-29 23:33:24 UTC (rev 1361) @@ -107,7 +107,7 @@ } } catch (ConfigurationException e) { - log.error("Configuration error in setup of "); + log.error("Configuration error in setup of " + CONFIG_XML_FILE + ", exception = " + e); } } @@ -119,6 +119,15 @@ return configPanels; } + public static int getMaxElementsInPanels() { + int maxElements = 0; + for (List<ConfigItem> panel:configPanels.values()) { + maxElements = Math.max(maxElements, panel.size()); + } + log.debug("maxelements" + maxElements); + return maxElements; + } + /** * updates the profile according to the changes in configitems */ @@ -135,6 +144,17 @@ } /** + * reverts all changes in configitems + */ + public static void revertProfile() { + for (List<ConfigItem> items:configPanels.values()) { + for (ConfigItem item:items) { + item.setNewValue(null); + } + } + } + + /** * First tries to return {key}.{gameName}, if undefined returns {key} */ public static String getGameSpecific(String key) { Modified: trunk/18xx/rails/util/ConfigItem.java =================================================================== --- trunk/18xx/rails/util/ConfigItem.java 2010-07-25 22:45:34 UTC (rev 1360) +++ trunk/18xx/rails/util/ConfigItem.java 2010-07-29 23:33:24 UTC (rev 1361) @@ -1,6 +1,5 @@ package rails.util; -import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; @@ -22,7 +21,7 @@ * Defines possible types (Java classes used as types in ConfigItem below */ public static enum ConfigType { - INTEGER, FLOAT, STRING, BOOLEAN, LIST, DIRECTORY, COLOR; + BOOLEAN, INTEGER, PERCENT, STRING, LIST, FONT, DIRECTORY, FILE, COLOR; } // static attributes @@ -30,8 +29,6 @@ public final ConfigType type; public final List<String> allowedValues; public final String formatMask; - public final String toolTip; - public final String helpText; // method call attributes private final String initClass; @@ -62,7 +59,7 @@ try { this.type = ConfigType.valueOf(type.toUpperCase()); } catch (Exception e) { - throw new ConfigurationException("Missing or invalid type for configuration item"); + throw new ConfigurationException("Missing or invalid type for configuration item, exception = " + e); } } else { throw new ConfigurationException("Missing or invalid type for configuration item"); @@ -74,10 +71,6 @@ // optional: formatMask formatMask = tag.getAttributeAsString("formatMask"); - - // optional: helpText and toolTip - toolTip = tag.getAttributeAsString("toolTip"); - helpText = tag.getAttributeAsString("helpText"); // optional: init method attributes initClass = tag.getAttributeAsString("initClass"); @@ -144,9 +137,6 @@ if (formatMask != null) { s.append(", formatMask = " + formatMask); } - if (helpText != null) { - s.append(", helpText = " + helpText); - } return s.toString(); } Modified: trunk/18xx/rails/util/LocalText.java =================================================================== --- trunk/18xx/rails/util/LocalText.java 2010-07-25 22:45:34 UTC (rev 1360) +++ trunk/18xx/rails/util/LocalText.java 2010-07-29 23:33:24 UTC (rev 1361) @@ -32,7 +32,6 @@ return getText(key, new Object[] { parameter }); } - //public static String getText(String key, Object[] parameters) { public static String getText(String key, Object... parameters) { String result = ""; Modified: trunk/18xx/rails/util/Util.java =================================================================== --- trunk/18xx/rails/util/Util.java 2010-07-25 22:45:34 UTC (rev 1360) +++ trunk/18xx/rails/util/Util.java 2010-07-29 23:33:24 UTC (rev 1361) @@ -126,6 +126,18 @@ } /** + * Parse a boolean value for Rails + * @param value string (allowed values for true: standard Boolean.parseBoolean and yes (after conversion to lowercase) + * @return parsed value + */ + public static boolean parseBoolean(String s) { + if (s.toLowerCase().equals("yes")) { + return true; + } + return Boolean.parseBoolean(s); + } + + /** * Parse a colour definition string. * Currently supported formats: * "RRGGBB" - each character being a hexadecimal digit @@ -159,6 +171,9 @@ return c; } + + + /** * Is a colour dark? (to check if FG colour needs be reversed) */ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-25 22:45:40
|
Revision: 1360 http://rails.svn.sourceforge.net/rails/?rev=1360&view=rev Author: stefanfrey Date: 2010-07-25 22:45:34 +0000 (Sun, 25 Jul 2010) Log Message: ----------- Further update of configuration Modified Paths: -------------- trunk/18xx/LocalisedText.properties trunk/18xx/data/Properties.xml trunk/18xx/default.profiles trunk/18xx/rails/ui/swing/ConfigWindow.java trunk/18xx/rails/util/Config.java trunk/18xx/rails/util/ConfigItem.java trunk/18xx/rails/util/LocalText.java Added Paths: ----------- trunk/18xx/data/profiles/ trunk/18xx/data/profiles/default.profile trunk/18xx/data/profiles/test.profile Removed Paths: ------------- trunk/18xx/test/test.properties Modified: trunk/18xx/LocalisedText.properties =================================================================== --- trunk/18xx/LocalisedText.properties 2010-07-25 19:27:21 UTC (rev 1359) +++ trunk/18xx/LocalisedText.properties 2010-07-25 22:45:34 UTC (rev 1360) @@ -54,6 +54,7 @@ BuysTrainUsingSP={0} buys a {1}-train from {2} for {3} using {4}. BYFloatsAt=Bayern floats at CASH=Cash +CANCEL=Cancel CanOperate={0} can operate this round CannotOperate={0} cannot operate this round CannotBuyAnything={0} cannot buy anything @@ -64,7 +65,17 @@ CLOSE_WINDOW=Do you really want to exit the game? COMPANY=Company COMPANY_DETAILS=Company details -CONFIG_CURRENT_PROFILE=Active profile = {0} (based on = {1}) +CONFIG=Configuration +CONFIG_CURRENT_PROFILE=Active profile = {0} (based on = {1}) +CONFIG_DEFAULT_TITLE=Default profile +CONFIG_DEFAULT_MESSAGE=Select a template for settings +CONFIG_NEW_MESSAGE=Select a name of the new profile +CONFIG_NEW_TITLE=Create profile +CONFIG_SELECT_PROFILE=Select profile -> +CONFIG_SETTINGS=Profile settings +CONFIG_SAVE_MESSAGE=Active profile {0} was saved +CONFIG_SAVE_TITLE=Save confirmation +CONFIG_WINDOW_TITLE=Rails Configuration CORRECT_CASH=Cash Correction CORRECT_MAP=Map Correction CURRENT=Current @@ -440,6 +451,7 @@ RunsWithBorrowedTrain={0} runs with a borrowed {1}-train and must withhold revenue RustsTrains=Rusts {0}-trains SAVE=Save +SAVEAS=Save As ... SaveFailed=Save failed, reason: {0} Select=Select SelectCompanyToMergeMinorInto=Select major company to merge minor {0} into Modified: trunk/18xx/data/Properties.xml =================================================================== --- trunk/18xx/data/Properties.xml 2010-07-25 19:27:21 UTC (rev 1359) +++ trunk/18xx/data/Properties.xml 2010-07-25 22:45:34 UTC (rev 1360) @@ -4,13 +4,14 @@ --> <Properties> <Panel name="General"> - <Property name="locale" type="LIST" values="en_US,te_ST" helpText="Language Selection" /> + <Property name="locale" type="LIST" values="en_US,te_ST" toolTip="Language Selection" + initClass="rails.util.LocalText" initMethod="setLocale" initParameter="yes"/> </Panel> <Panel name="Save"> - <Property name="save.dir" type="DIRECTORY" helpText="Default save file directory" /> - + <Property name="save.directory" type="DIRECTORY" toolTip="Default save file directory" /> + <Property name="save.filename.date_time_pattern" type="STRING" toolTip="Datetime pattern for filename" /> </Panel> <Panel name="Colors"> - <Property name="route.colour.1" type="COLOR"/> + <Property name="route.colour.1" type="COLOR" toolTip="Route color of first train" /> </Panel> </Properties> \ No newline at end of file Added: trunk/18xx/data/profiles/default.profile =================================================================== --- trunk/18xx/data/profiles/default.profile (rev 0) +++ trunk/18xx/data/profiles/default.profile 2010-07-25 22:45:34 UTC (rev 1360) @@ -0,0 +1,7 @@ +locale=en_US +save.directory= +save.filename.date_time_pattern=yyyyMMdd_HHmm +save.filename.date_time_zone=UTC +save.filename.suffix=NEXT_PLAYER +save.filename.extension=rails + Copied: trunk/18xx/data/profiles/test.profile (from rev 1351, trunk/18xx/test/test.properties) =================================================================== --- trunk/18xx/data/profiles/test.profile (rev 0) +++ trunk/18xx/data/profiles/test.profile 2010-07-25 22:45:34 UTC (rev 1360) @@ -0,0 +1,124 @@ +####################### Test preferences ################################ +# +# Those are the settings used for automated testing +# +######################################################################## +# +# Preferred tile format. +# The only currently supported format is svg. Anything else is ignored. +#tile.format_preference=svg +# Root directory for the tile images (just above directory 'tiles'). +# Not required if tile images are provided included in the Rails jar file. +#tile.root_directory= + +### Locale #### +# Language: two-letter ISO code (lower case; default is en=English). +# Country: two-letter ISO code (upper case; specifies country +# (implying a language variant of that country; no default). +# Locale: concatenation of the above. If present, overrides any of the above. +# Examples: en, en_US, en_UK, fr_FR, fr_CA. +locale=te_st +#language= +#country= + +### Money display ### +# Each game has a specific format for monetary amounts (e.g. $100, 100M). +# An overriding format can be specified here, but then applies to all games. +# The @ character must be present and is replaced by the amount. +# Example: \xA3@ to specify a pound sign prefix: \xA3100. +#money_format=$@ + +### Save file directory +# If the below entry exists, is not empty, and specifies an existing +# directory, that directory is used as a starting point for any +# file choosing action for the Save and Load commands. +# The path may be relative or absolute. +save.directory=test/data +# The default Save filename is <gamename>_<datetimepattern>.<extension> +# This name will be initially proposed. +# As soon as that proposal has been changed once in a Save action, +# the last used name is always proposed in stead. +# The default date/time pattern is yyyyMMdd_HHmm +# The pattern codes are as defined in the Java class +# SimpleDateFormat (just Google that name to find the codes). +#save.filename.date_time_pattern=yyyyMMdd_HHmm +# The default timezone is local time. +# A specific timezone (such as UTC) can be set; the value must be a Java timezone ID +#save.filename.date_time_zone=UTC +# Optionally, a suffix (e.g. player name) can be added after the time stamp +# with a preceding underscore (which is automatically added) +# The special value NEXT_PLAYER puts the next moving player name into this spot. +#save.filename.suffix=NEXT_PLAYER +# The default extension is .rails +save.filename.extension=rails + +### Game report directory +# If the below entry exists, is not empty, and specifies an existing +# directory, a copy of the Game Report (as displayed in the Report Window) +# will be saved there. The path may be relative or absolute. +#report.directory=log +# The default file name includes the game name and the game start time: +# 18XX_yyyymmdd_hhmm.txt where 18XX is the game name. +# You can specify different values for the date/time part and teh extension here. +# The date/time pattern must be as defined in the Java SimpleDateFormat class. +#report.filename.date_time_pattern=yyyyMMdd +report.filename.extension=report + +### Windows +## Report window visibility +# By default the report window is hidden when starting or loading a game. +# This property allows to open it automatically. +# Valid values are yes and no (default). +#report.window.open=yes +## Report window editability +# Specify if the report window is editable, so you can add your own comments. +# Valid values are yes and no (default). +#report.window.editable=yes +## Stock Chart window visibility +# By default the stock chart hides at the end of an SR. +# By specifying "yes" here, the window will not be automatically hidden any more +#stockchart.window.open=yes + +### Player info +## Default players +# Comma-separated list of player names. +# Useful for game testing purposes. +#default_players=Alice,Bob,Charlie +# +## Local player name +# Useful for distributed usage (Internet, PBEM, cloud storage/dropbox) +# Required for "request turn" facility with cloud storage (dropbox) +#local.player.name=Alice + +### Default game +# Name of game selected in the game selection window. +# Useful for game testing purposes. +#default_game=1830 + +### Various options +# Show simple (ORx) or composite (ORx.x) OR number. +# Valid values: "simple" and "composite" (default) +#or.number_format=simple + +####################### Log4J properties ############################## +# For information on how to customise log4j logging, see for instance +# http://www.vipan.com/htdocs/log4jhelp.html +# It's a bit outdated: Category is now named Logger, +# and Priority is now named Level. +# But it's the best intro I know on how to configure Appenders. (EV) +####################################################################### +# Set root logger level to DEBUG and use appender F(file) +#log4j.debug=true +log4j.rootLogger=DEBUG, F + +# Define the Log file appender +log4j.appender.F=org.apache.log4j.FileAppender + +# Log file properties +log4j.appender.F.File=test/test.log +log4j.appender.F.append=false + +# Log file layout +log4j.appender.F.layout=org.apache.log4j.PatternLayout +log4j.appender.F.layout.ConversionPattern=%-5p %m%n +################## End of Log4J properties ############################# \ No newline at end of file Modified: trunk/18xx/default.profiles =================================================================== --- trunk/18xx/default.profiles 2010-07-25 19:27:21 UTC (rev 1359) +++ trunk/18xx/default.profiles 2010-07-25 22:45:34 UTC (rev 1360) @@ -1,2 +1,2 @@ -default=my.properties -test=test/test.properties +default=data/profiles/default.profile +.test=data/profiles/test.profile Modified: trunk/18xx/rails/ui/swing/ConfigWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-25 19:27:21 UTC (rev 1359) +++ trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-25 22:45:34 UTC (rev 1360) @@ -53,7 +53,7 @@ ConfigWindow() { // JFrame properties - setTitle(LocalText.getText("ConfigWindowTitle")); + setTitle(LocalText.getText("CONFIG_WINDOW_TITLE")); // setSize(400,300); // add profile panel @@ -96,7 +96,7 @@ Border titled = BorderFactory.createTitledBorder(etched, LocalText.getText("CONFIG_CURRENT_PROFILE", activeProfile, defaultProfile)); profilePanel.setBorder(titled); - JLabel userLabel = new JLabel(LocalText.getText("CONFIG_SELECT_USER")); + JLabel userLabel = new JLabel(LocalText.getText("CONFIG_SELECT_PROFILE")); profilePanel.add(userLabel); final JComboBox comboBoxUser = new JComboBox(Config.getUserProfiles().toArray()); comboBoxUser.setSelectedItem(Config.getActiveProfileName()); @@ -151,17 +151,17 @@ GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = 1; gbc.gridheight = 1; - gbc.gridx = 0; gbc.weightx = 0.8; gbc.weighty = 0.8; gbc.insets = new Insets(10,10,10,10); gbc.anchor = GridBagConstraints.WEST; + int y = 0; for (ConfigItem item:configPanels.get(panelName)) { gbc.gridx = 0; + gbc.gridy = y++; defineElement(newPanel, item, gbc); - gbc.gridy ++; } - configPane.addTab(panelName, newPanel); + configPane.addTab(LocalText.getText("Config.panel." + panelName), newPanel); } } @@ -175,7 +175,7 @@ // standard components final String configValue = item.getCurrentValue(); - final String toolTip = item.helpText; + final String toolTip = item.toolTip; // item label JLabel label = new JLabel(LocalText.getText("Config." + item.name)); @@ -329,8 +329,10 @@ 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.getDefaultProfiles(true).toArray(), Config.getDefaultProfileSelection()); + if (Util.hasValue(defaultProfile)) { Config.createUserProfile(newProfile, defaultProfile); + } } EventQueue.invokeLater(new Runnable() { public void run() { @@ -378,7 +380,7 @@ private void saveConfig() { Config.updateProfile(); // transfer the configitem to the active profile Config.saveActiveProfile(); - JOptionPane.showMessageDialog(ConfigWindow.this, LocalText.getText("CONFIG_SAVE_MESSAGE"), + JOptionPane.showMessageDialog(ConfigWindow.this, LocalText.getText("CONFIG_SAVE_MESSAGE", Config.getActiveProfileName()), LocalText.getText("CONFIG_SAVE_TITLE"), JOptionPane.INFORMATION_MESSAGE); } Modified: trunk/18xx/rails/util/Config.java =================================================================== --- trunk/18xx/rails/util/Config.java 2010-07-25 19:27:21 UTC (rev 1359) +++ trunk/18xx/rails/util/Config.java 2010-07-25 22:45:34 UTC (rev 1360) @@ -32,7 +32,6 @@ protected static Logger log; /** Commandline options */ - private static final String LOG4J_CMDLINE = "log4j"; private static final String CONFIGFILE_CMDLINE = "configfile"; private static final String PROFILE_CMDLINE = "profile"; @@ -52,7 +51,7 @@ private static String userProfilesFile = "user.profiles"; private static Properties userProfiles = new Properties(); private static boolean profilesLoaded = false; - private static final String TEST_PROFILE_SELECTION = "test"; + private static final String TEST_PROFILE_SELECTION = ".test"; private static final String DEFAULT_PROFILE_SELECTION = "default"; private static final String STANDARD_PROFILE_SELECTION = "user"; private static final String DEFAULTPROFILE_PROPERTY = "default.profile"; @@ -128,6 +127,7 @@ for (ConfigItem item:items) { if (!item.hasNewValue() || item.getNewValue().equals(defaultProperties.get(item.name))) continue; userProperties.setProperty(item.name, item.getNewValue()); + item.callInitMethod(); log.debug("Changed property name = " + item.name + " to value = " + item.getNewValue()); item.setNewValue(null); } @@ -210,9 +210,10 @@ } - private static Map<String, String> convertProperties(Properties properties) { + private static Map<String, String> convertProperties(Properties properties, boolean visibleOnly) { Map<String, String> converted = new HashMap<String, String>(); for (Object key:properties.keySet()) { + if (visibleOnly && ((String)key).substring(0,1).equals(".")) continue; converted.put((String) key, (String) properties.get(key)); } return converted; @@ -221,8 +222,8 @@ /** * get all default profiles */ - public static List<String> getDefaultProfiles() { - List<String> profiles = new ArrayList<String>(convertProperties(defaultProfiles).keySet()); + public static List<String> getDefaultProfiles(boolean visibleOnly) { + List<String> profiles = new ArrayList<String>(convertProperties(defaultProfiles, visibleOnly).keySet()); Collections.sort(profiles); return profiles; } @@ -235,7 +236,7 @@ * get all user profiles */ public static List<String> getUserProfiles() { - List<String> profiles = new ArrayList<String>(convertProperties(userProfiles).keySet()); + List<String> profiles = new ArrayList<String>(convertProperties(userProfiles, true).keySet()); Collections.sort(profiles); return profiles; } @@ -509,4 +510,5 @@ defaultProperties.put("save.directory", System.getProperty("user.dir")); } } + } Modified: trunk/18xx/rails/util/ConfigItem.java =================================================================== --- trunk/18xx/rails/util/ConfigItem.java 2010-07-25 19:27:21 UTC (rev 1359) +++ trunk/18xx/rails/util/ConfigItem.java 2010-07-25 22:45:34 UTC (rev 1360) @@ -1,5 +1,6 @@ package rails.util; +import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; @@ -29,8 +30,15 @@ public final ConfigType type; public final List<String> allowedValues; public final String formatMask; + public final String toolTip; public final String helpText; + // method call attributes + private final String initClass; + private final String initMethod; + private final boolean initParameter; + + // dynamic attributes private String newValue; @@ -67,9 +75,16 @@ // optional: formatMask formatMask = tag.getAttributeAsString("formatMask"); - // optional: helpText + // optional: helpText and toolTip + toolTip = tag.getAttributeAsString("toolTip"); helpText = tag.getAttributeAsString("helpText"); + + // optional: init method attributes + initClass = tag.getAttributeAsString("initClass"); + initMethod = tag.getAttributeAsString("initMethod"); + initParameter = tag.getAttributeAsBoolean("initParameter", false); + // initialize newValue newValue = null; } @@ -99,6 +114,25 @@ return Config.get(this.name); } + void callInitMethod() { + if (initClass == null || initMethod == null) return; + + // call without parameter + try { + Class<?> clazz = Class.forName(initClass); + + if (initParameter) { + clazz.getMethod(initMethod, String.class).invoke(null, newValue); + + } else { + clazz.getMethod(initMethod).invoke(null); + } + } catch (Exception e) { + log.error("Config profile: cannot call initMethod"); + } + } + + public String toString() { StringBuffer s = new StringBuffer(); s.append("Configuration Item: name = " + name + ", type = " + type); Modified: trunk/18xx/rails/util/LocalText.java =================================================================== --- trunk/18xx/rails/util/LocalText.java 2010-07-25 19:27:21 UTC (rev 1359) +++ trunk/18xx/rails/util/LocalText.java 2010-07-25 22:45:34 UTC (rev 1360) @@ -117,7 +117,9 @@ String[] codes = localeCode.split("_"); if (codes.length > 0) language = codes[0]; if (codes.length > 1) country = codes[1]; - + + // reset localised text + localisedText = null; } public Enumeration<String> getKeys() { Deleted: trunk/18xx/test/test.properties =================================================================== --- trunk/18xx/test/test.properties 2010-07-25 19:27:21 UTC (rev 1359) +++ trunk/18xx/test/test.properties 2010-07-25 22:45:34 UTC (rev 1360) @@ -1,124 +0,0 @@ -####################### Test preferences ################################ -# -# Those are the settings used for automated testing -# -######################################################################## -# -# Preferred tile format. -# The only currently supported format is svg. Anything else is ignored. -#tile.format_preference=svg -# Root directory for the tile images (just above directory 'tiles'). -# Not required if tile images are provided included in the Rails jar file. -#tile.root_directory= - -### Locale #### -# Language: two-letter ISO code (lower case; default is en=English). -# Country: two-letter ISO code (upper case; specifies country -# (implying a language variant of that country; no default). -# Locale: concatenation of the above. If present, overrides any of the above. -# Examples: en, en_US, en_UK, fr_FR, fr_CA. -locale=te_st -#language= -#country= - -### Money display ### -# Each game has a specific format for monetary amounts (e.g. $100, 100M). -# An overriding format can be specified here, but then applies to all games. -# The @ character must be present and is replaced by the amount. -# Example: \xA3@ to specify a pound sign prefix: \xA3100. -#money_format=$@ - -### Save file directory -# If the below entry exists, is not empty, and specifies an existing -# directory, that directory is used as a starting point for any -# file choosing action for the Save and Load commands. -# The path may be relative or absolute. -save.directory=test/data -# The default Save filename is <gamename>_<datetimepattern>.<extension> -# This name will be initially proposed. -# As soon as that proposal has been changed once in a Save action, -# the last used name is always proposed in stead. -# The default date/time pattern is yyyyMMdd_HHmm -# The pattern codes are as defined in the Java class -# SimpleDateFormat (just Google that name to find the codes). -#save.filename.date_time_pattern=yyyyMMdd_HHmm -# The default timezone is local time. -# A specific timezone (such as UTC) can be set; the value must be a Java timezone ID -#save.filename.date_time_zone=UTC -# Optionally, a suffix (e.g. player name) can be added after the time stamp -# with a preceding underscore (which is automatically added) -# The special value NEXT_PLAYER puts the next moving player name into this spot. -#save.filename.suffix=NEXT_PLAYER -# The default extension is .rails -save.filename.extension=rails - -### Game report directory -# If the below entry exists, is not empty, and specifies an existing -# directory, a copy of the Game Report (as displayed in the Report Window) -# will be saved there. The path may be relative or absolute. -#report.directory=log -# The default file name includes the game name and the game start time: -# 18XX_yyyymmdd_hhmm.txt where 18XX is the game name. -# You can specify different values for the date/time part and teh extension here. -# The date/time pattern must be as defined in the Java SimpleDateFormat class. -#report.filename.date_time_pattern=yyyyMMdd -report.filename.extension=report - -### Windows -## Report window visibility -# By default the report window is hidden when starting or loading a game. -# This property allows to open it automatically. -# Valid values are yes and no (default). -#report.window.open=yes -## Report window editability -# Specify if the report window is editable, so you can add your own comments. -# Valid values are yes and no (default). -#report.window.editable=yes -## Stock Chart window visibility -# By default the stock chart hides at the end of an SR. -# By specifying "yes" here, the window will not be automatically hidden any more -#stockchart.window.open=yes - -### Player info -## Default players -# Comma-separated list of player names. -# Useful for game testing purposes. -#default_players=Alice,Bob,Charlie -# -## Local player name -# Useful for distributed usage (Internet, PBEM, cloud storage/dropbox) -# Required for "request turn" facility with cloud storage (dropbox) -#local.player.name=Alice - -### Default game -# Name of game selected in the game selection window. -# Useful for game testing purposes. -#default_game=1830 - -### Various options -# Show simple (ORx) or composite (ORx.x) OR number. -# Valid values: "simple" and "composite" (default) -#or.number_format=simple - -####################### Log4J properties ############################## -# For information on how to customise log4j logging, see for instance -# http://www.vipan.com/htdocs/log4jhelp.html -# It's a bit outdated: Category is now named Logger, -# and Priority is now named Level. -# But it's the best intro I know on how to configure Appenders. (EV) -####################################################################### -# Set root logger level to DEBUG and use appender F(file) -#log4j.debug=true -log4j.rootLogger=DEBUG, F - -# Define the Log file appender -log4j.appender.F=org.apache.log4j.FileAppender - -# Log file properties -log4j.appender.F.File=test/test.log -log4j.appender.F.append=false - -# Log file layout -log4j.appender.F.layout=org.apache.log4j.PatternLayout -log4j.appender.F.layout.ConversionPattern=%-5p %m%n -################## End of Log4J properties ############################# \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-25 19:27:27
|
Revision: 1359 http://rails.svn.sourceforge.net/rails/?rev=1359&view=rev Author: stefanfrey Date: 2010-07-25 19:27:21 +0000 (Sun, 25 Jul 2010) Log Message: ----------- Changed tooltip implementation for bonuses Modified Paths: -------------- trunk/18xx/rails/ui/swing/hexmap/GUIHex.java Modified: trunk/18xx/rails/ui/swing/hexmap/GUIHex.java =================================================================== --- trunk/18xx/rails/ui/swing/hexmap/GUIHex.java 2010-07-25 19:15:33 UTC (rev 1358) +++ trunk/18xx/rails/ui/swing/hexmap/GUIHex.java 2010-07-25 19:27:21 UTC (rev 1359) @@ -668,20 +668,15 @@ 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) { + Set<String> bonusNames = new HashSet<String>(); + for (RevenueBonusTemplate bonus:bonuses) { + if (bonus.getName() == null) { + tt.append("<br>Bonus:"); + tt.append(bonus.getToolTip()); + } else if (!bonusNames.contains(bonus.getName())) { + tt.append("<br>Bonus:" + bonus.getName()); 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(); 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. |