virtualcommons-svn Mailing List for Virtual Commons Experiment Software (Page 62)
Status: Beta
Brought to you by:
alllee
You can subscribe to this list here.
2008 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
(1) |
Jul
(21) |
Aug
(31) |
Sep
(6) |
Oct
(15) |
Nov
(2) |
Dec
(9) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2009 |
Jan
(4) |
Feb
(6) |
Mar
(12) |
Apr
(52) |
May
(14) |
Jun
(19) |
Jul
(81) |
Aug
(115) |
Sep
(36) |
Oct
(88) |
Nov
(46) |
Dec
(58) |
2010 |
Jan
(52) |
Feb
(55) |
Mar
(48) |
Apr
(15) |
May
(5) |
Jun
(38) |
Jul
(27) |
Aug
(24) |
Sep
(28) |
Oct
(1) |
Nov
(2) |
Dec
(29) |
2011 |
Jan
(87) |
Feb
(39) |
Mar
(63) |
Apr
(42) |
May
(26) |
Jun
(53) |
Jul
(23) |
Aug
(43) |
Sep
(37) |
Oct
(25) |
Nov
(4) |
Dec
(7) |
2012 |
Jan
(73) |
Feb
(79) |
Mar
(62) |
Apr
(28) |
May
(12) |
Jun
(2) |
Jul
(9) |
Aug
(1) |
Sep
(8) |
Oct
|
Nov
(3) |
Dec
(3) |
2013 |
Jan
(8) |
Feb
(16) |
Mar
(38) |
Apr
(74) |
May
(62) |
Jun
(15) |
Jul
(49) |
Aug
(19) |
Sep
(9) |
Oct
|
Nov
|
Dec
|
2014 |
Jan
|
Feb
|
Mar
|
Apr
(2) |
May
(25) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <al...@us...> - 2009-10-20 04:07:27
|
Revision: 307 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=307&view=rev Author: alllee Date: 2009-10-20 04:07:18 +0000 (Tue, 20 Oct 2009) Log Message: ----------- more refactoring of GUI components, getting rid of unnecessarily nested components and making it so that the GUI components can be initialized and added to the ExperimentGameWindow's CardLayout without generating NPEs. Getting rid of isPracticeRound() check in RoundConfiguration.isChatEnabled() method. Modified Paths: -------------- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChatPanel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/RoundConfiguration.java Added Paths: ----------- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/InfrastructureEfficiencyChartPanel.java Removed Paths: ------------- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChartWindowPanelTokenBandwidth.java Deleted: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChartWindowPanelTokenBandwidth.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChartWindowPanelTokenBandwidth.java 2009-10-20 02:36:40 UTC (rev 306) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChartWindowPanelTokenBandwidth.java 2009-10-20 04:07:18 UTC (rev 307) @@ -1,131 +0,0 @@ -package edu.asu.commons.irrigation.client; - -import java.awt.CardLayout; -import java.awt.Dimension; -import java.awt.GridLayout; - -import javax.swing.JPanel; - -import org.jfree.chart.ChartFactory; -import org.jfree.chart.ChartPanel; -import org.jfree.chart.JFreeChart; -import org.jfree.chart.plot.PlotOrientation; -import org.jfree.data.xy.XYSeries; -import org.jfree.data.xy.XYSeriesCollection; - -import edu.asu.commons.irrigation.server.GroupDataModel; - -/** - * $Id$ - * - * - * @author Sanket Joshi - * @version $Rev$ - */ -public class ChartWindowPanelTokenBandwidth extends JPanel { - - private static final long serialVersionUID = 5555080117985336199L; - - private int numberofFilesDownloaded = 10; - - private Dimension screenSize; - - private JPanel jPanel; - - private IrrigationClient client; - - - - /** - * A demonstration application showing an XY series containing a null value. - * - * @param title the frame title. - */ - public ChartWindowPanelTokenBandwidth(IrrigationClient client) { - this.client = client; - initialize(); - } - - - - public void initialize() { - this.setLayout(new CardLayout()); - this.setSize(new Dimension(530/2, 326/2)); - //this.setSize(screenSize.width, screenSize.height); - this.add(getJPanel(), getJPanel().getName()); - repaint(); - - } - - /** - * This method initializes jPanel - * - * @return javax.swing.JPanel - */ - private JPanel getJPanel() { - if (jPanel == null) { - jPanel = new JPanel(); - GridLayout gridLayout = new GridLayout(); - gridLayout.setColumns(2); - jPanel.setLayout(gridLayout); - jPanel.add(getChartPanel()); - //jPanel.add(getchartPanel1()); - jPanel.setName("jPanel"); - } - return jPanel; - } - - private ChartPanel getChartPanel() { - // TODO Auto-generated method stub - final XYSeries actualFlowCapacitySeries = new XYSeries("Actual"); - final XYSeries potentialFlowCapacitySeries = new XYSeries("Potential"); - // final XYSeries actualFlowCapacitySeriesY = new XYSeries("Actual"); - final XYSeries initialInfrastructureEfficiencySeries = new XYSeries("Initial"); - int x,y; - GroupDataModel group = client.getClientDataModel().getGroupDataModel(); - final int infrastructureEfficiency = group.getInfrastructureEfficiency(); - final int actualFlowCapacity = group.getFlowCapacity(); - for(y = 0; y <= actualFlowCapacity; y++) { - actualFlowCapacitySeries.add(infrastructureEfficiency, y); - } - for(x =0; x<=client.getRoundConfiguration().getMaximumInfrastructureEfficiency();x++){ - y = group.calculateFlowCapacity(x); - potentialFlowCapacitySeries.add(x,y); - } - final int initialInfrastructureEfficiency = group.getInitialInfrastructureEfficiency(); - final int initialFlowCapacity = group.calculateFlowCapacity(initialInfrastructureEfficiency); - for (y = 0; y <= initialFlowCapacity; y++) { - initialInfrastructureEfficiencySeries.add(initialInfrastructureEfficiency, y); - } - - // for(y = 0; y <= actualFlowCapacity; y++) { - // actualFlowCapacitySeriesY.add(infrastructureEfficiency,y); - // } - - final XYSeriesCollection data = new XYSeriesCollection(); - data.addSeries(initialInfrastructureEfficiencySeries); - data.addSeries(actualFlowCapacitySeries); - data.addSeries(potentialFlowCapacitySeries); - - // data.addSeries(actualFlowCapacitySeriesY); - - final JFreeChart chart = ChartFactory.createXYLineChart( - "Total Flow Capacity", - "Infrastructure Efficiency", - "Actual Flow Capacity", - data, - PlotOrientation.VERTICAL, - true, - true, - false - ); - final ChartPanel chartPanel = new ChartPanel(chart); - //chartPanel.chartProgress(arg0) - chartPanel.setLayout(new CardLayout()); - chartPanel.setPreferredSize(new Dimension(500, 270)); - repaint(); - //setContentPane(chartPanel); - return chartPanel; - //y=4*x; - } -} \ No newline at end of file Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChatPanel.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChatPanel.java 2009-10-20 02:36:40 UTC (rev 306) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChatPanel.java 2009-10-20 04:07:18 UTC (rev 307) @@ -52,7 +52,6 @@ private IrrigationClient irrigationClient; - private Identifier clientId; private JScrollPane messageScrollPane; @@ -109,18 +108,13 @@ private void sendMessage() { String message = chatField.getText(); - // System.err.println("message: " + message); - if (message == null || "".equals(message)) { - return; + if (message != null && ! message.isEmpty() && targetIdentifier != null) { + chatField.setText(""); + irrigationClient.transmit(new ChatRequest(getClientId(), message, targetIdentifier)); + displayMessage( + String.format("%s -> %s", getChatHandle(getClientId()), getChatHandle(targetIdentifier)), + message); } - if (targetIdentifier == null) { - return; - } - chatField.setText(""); - irrigationClient.transmit(new ChatRequest(clientId, message, targetIdentifier)); - System.err.println("Sending a new chat request"); - displayMessage(getChatHandle(clientId) + " -> " - + getChatHandle(targetIdentifier), message); chatField.requestFocusInWindow(); } @@ -147,7 +141,7 @@ JFrame frame = new JFrame(); ChatPanel chatPanel = new ChatPanel(); Identifier selfId = new Identifier(){}; - chatPanel.setClientId(selfId); + chatPanel.clientId = selfId; chatPanel.initialize(Arrays.asList(new Identifier[] { new Identifier(){}, new Identifier(){}, new Identifier(){}, selfId })); @@ -229,13 +223,15 @@ chatHandles.put(participants.get(i), HANDLES[i]); } } - - public void setClientId(Identifier clientId) { - this.clientId = clientId; + + public Identifier getClientId() { + if (clientId == null) { + clientId = irrigationClient.getId(); + } + return clientId; } public void setIrrigationClient(IrrigationClient client) { - setClientId(client.getId()); this.irrigationClient = client; client.getEventChannel().add(this, new EventTypeProcessor<ChatEvent>(ChatEvent.class) { public void handle(final ChatEvent chatEvent) { Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-20 02:36:40 UTC (rev 306) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-20 04:07:18 UTC (rev 307) @@ -67,7 +67,7 @@ private JButton submitTokensButton; - private ChartWindowPanelTokenBandwidth xySeriesDemo = null; + private InfrastructureEfficiencyChartPanel xySeriesDemo = null; private IrrigationClient client; @@ -625,7 +625,7 @@ private JPanel getPieChartPanel() { if (pieChartPanel == null) { pieChartPanel = new JPanel(); - xySeriesDemo = new ChartWindowPanelTokenBandwidth(client); + xySeriesDemo = new InfrastructureEfficiencyChartPanel(client); xySeriesDemo.setVisible(true); pieChart = new PieChart(); GridLayout gridLayout = new GridLayout(); @@ -654,7 +654,7 @@ System.err.println("Updating round instructions: " + roundConfiguration.getInstructions()); // if this is the first round, show the general instructions. if (roundConfiguration.isFirstRound()) { -// setInstructions(roundConfiguration.getParentConfiguration().getInitialInstructions()); + } else { instructionsBuilder.append(roundConfiguration.getInstructions()); Copied: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/InfrastructureEfficiencyChartPanel.java (from rev 306, irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChartWindowPanelTokenBandwidth.java) =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/InfrastructureEfficiencyChartPanel.java (rev 0) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/InfrastructureEfficiencyChartPanel.java 2009-10-20 04:07:18 UTC (rev 307) @@ -0,0 +1,89 @@ +package edu.asu.commons.irrigation.client; + +import java.awt.BorderLayout; +import java.awt.Dimension; + +import javax.swing.JPanel; + +import org.jfree.chart.ChartFactory; +import org.jfree.chart.ChartPanel; +import org.jfree.chart.JFreeChart; +import org.jfree.chart.plot.PlotOrientation; +import org.jfree.data.xy.XYSeries; +import org.jfree.data.xy.XYSeriesCollection; + +import edu.asu.commons.irrigation.server.GroupDataModel; + +/** + * $Id$ + * + * Presents a chart view of the infrastructure efficiency function. + * + * @author Allen Lee, Sanket Joshi + * @version $Rev$ + */ +public class InfrastructureEfficiencyChartPanel extends JPanel { + + private static final long serialVersionUID = 5555080117985336199L; + + private IrrigationClient client; + /** + * + * @param title the frame title. + */ + public InfrastructureEfficiencyChartPanel(IrrigationClient client) { + this.client = client; + setPreferredSize(new Dimension(530/2, 326/2)); + //this.setSize(screenSize.width, screenSize.height); + setName("infrastructure efficiency chart panel"); + setLayout(new BorderLayout()); + } + + public void initialize() { + add(createChartPanel(), BorderLayout.CENTER); + } + + private ChartPanel createChartPanel() { + final XYSeries actualFlowCapacitySeries = new XYSeries("Actual"); + final XYSeries potentialFlowCapacitySeries = new XYSeries("Potential"); + // final XYSeries actualFlowCapacitySeriesY = new XYSeries("Actual"); + final XYSeries initialInfrastructureEfficiencySeries = new XYSeries("Initial"); + int x,y; + GroupDataModel group = client.getClientDataModel().getGroupDataModel(); + final int infrastructureEfficiency = group.getInfrastructureEfficiency(); + final int actualFlowCapacity = group.getFlowCapacity(); + for (y = 0; y <= actualFlowCapacity; y++) { + actualFlowCapacitySeries.add(infrastructureEfficiency, y); + } + for(x =0; x<=client.getRoundConfiguration().getMaximumInfrastructureEfficiency();x++){ + y = group.calculateFlowCapacity(x); + potentialFlowCapacitySeries.add(x,y); + } + final int initialInfrastructureEfficiency = group.getInitialInfrastructureEfficiency(); + final int initialFlowCapacity = group.calculateFlowCapacity(initialInfrastructureEfficiency); + for (y = 0; y <= initialFlowCapacity; y++) { + initialInfrastructureEfficiencySeries.add(initialInfrastructureEfficiency, y); + } + + final XYSeriesCollection data = new XYSeriesCollection(); + data.addSeries(initialInfrastructureEfficiencySeries); + data.addSeries(actualFlowCapacitySeries); + data.addSeries(potentialFlowCapacitySeries); + + // data.addSeries(actualFlowCapacitySeriesY); + + final JFreeChart chart = ChartFactory.createXYLineChart( + "Total Flow Capacity", + "Infrastructure Efficiency", + "Actual Flow Capacity", + data, + PlotOrientation.VERTICAL, + true, + true, + false + ); + final ChartPanel chartPanel = new ChartPanel(chart); + chartPanel.setPreferredSize(new Dimension(500, 270)); + return chartPanel; + } +} \ No newline at end of file Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java 2009-10-20 02:36:40 UTC (rev 306) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java 2009-10-20 04:07:18 UTC (rev 307) @@ -71,14 +71,14 @@ this.channel = channel; setServerConfiguration(serverConfiguration); this.clientDispatcher = DispatcherFactory.getInstance().createClientDispatcher(channel); + initEventProcessors(); } private void initialize(Dimension screenSize) { clientDataModel = new ClientDataModel(channel, this); experimentGameWindow = new ExperimentGameWindow(this); experimentGameWindow.initialize(screenSize); - // clientGameState.setMainIrrigationGameWindow(irrigationGameWindow1); - initEventProcessors(); + connect(); } public void connect() { @@ -86,8 +86,8 @@ + " state: " + state); if (state != ClientState.UNCONNECTED) return; + id = clientDispatcher.connect(serverConfiguration.getServerAddress()); - System.err.println("Received id from server: " + id); if (id == null) { throw new RuntimeException("Null ID from Dispatcher. Server: <" + serverConfiguration.getServerAddress() + "> is probably down."); @@ -102,7 +102,6 @@ JFrame frame = new JFrame(); IrrigationClient client = new IrrigationClient(); client.initialize(defaultDimension); - client.connect(); frame.setTitle("Virtual Commons Experiment Client: " + client.id); frame.setSize(1130, 600); frame.getContentPane().add(client.getExperimentGameWindow()); Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/RoundConfiguration.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/RoundConfiguration.java 2009-10-20 02:36:40 UTC (rev 306) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/RoundConfiguration.java 2009-10-20 04:07:18 UTC (rev 307) @@ -130,14 +130,11 @@ /** * Returns true if the current round should have a communication session for - * getCommunicationDuration() seconds before the round begins. + * getChatDuration() seconds before the round begins. * * @return */ public boolean isChatEnabledBeforeRound() { - if (isPracticeRound()) { - return false; - } return getBooleanProperty("chat-enabled-before-round", true); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <al...@us...> - 2009-10-20 02:36:51
|
Revision: 306 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=306&view=rev Author: alllee Date: 2009-10-20 02:36:40 +0000 (Tue, 20 Oct 2009) Log Message: ----------- continuing to refactor GUI components. Updated the pie chart displaying token investments and the chat panel. Modified Paths: -------------- irrigation/trunk/build.xml irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChatPanel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationGamePanel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/PieChart.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/Facilitator.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/FacilitatorWindow.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/IrrigationServer.java irrigation/trunk/src/main/resources/configuration/asu-fall-2009/irrigation.xml Added Paths: ----------- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/InfrastructureUpdateEvent.java Removed Paths: ------------- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/GroupUpdateEvent.java Modified: irrigation/trunk/build.xml =================================================================== --- irrigation/trunk/build.xml 2009-10-20 00:15:43 UTC (rev 305) +++ irrigation/trunk/build.xml 2009-10-20 02:36:40 UTC (rev 306) @@ -73,7 +73,7 @@ <property name='server.class' value='edu.asu.commons.irrigation.server.IrrigationServer'/> <property name='framework.jar' value='csidex.jar'/> - <property name='dist.dir' value='dist' /> + <property name='dist.dir' value='.' /> <property name='resources.dir' value='src/main/resources'/> <property name='conf.dir' value='${resources.dir}/configuration'/> @@ -136,7 +136,7 @@ <include name='facilitator.jar'/> </fileset> <fileset dir='${lib.dir}'> - <include name='${framework.jar}'/> + <include name='*.jar'/> </fileset> <fileset dir='${resources.dir}/web'> <include name='index.html'/> @@ -195,7 +195,6 @@ <param name='main.class' value='${server.class}'/> <param name='jar.name' value='server.jar'/> </antcall> - <move file='${dist.dir}/server.jar' tofile='server.jar'/> </target> <target name='build-jar'> @@ -229,10 +228,10 @@ <target name="clean"> <delete dir="${build.dir}"/> <delete dir="${test.build.dir}"/> - <delete dir='${dist.dir}'/> <delete dir='${lib.dir}'/> <delete file='server.jar'/> - + <delete file='client.jar'/> + <delete file='facilitator.jar'/> </target> <!-- Compile project source files --> Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChatPanel.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChatPanel.java 2009-10-20 00:15:43 UTC (rev 305) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChatPanel.java 2009-10-20 02:36:40 UTC (rev 306) @@ -2,18 +2,17 @@ import java.awt.BorderLayout; import java.awt.Color; -import java.awt.Component; import java.awt.Dimension; import java.awt.Font; -import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; -import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JEditorPane; @@ -33,7 +32,6 @@ import edu.asu.commons.event.ChatEvent; import edu.asu.commons.event.ChatRequest; -import edu.asu.commons.event.EventChannel; import edu.asu.commons.event.EventTypeProcessor; import edu.asu.commons.net.Identifier; @@ -52,58 +50,65 @@ @SuppressWarnings("serial") public class ChatPanel extends JPanel { - private IrrigationClient client; + private IrrigationClient irrigationClient; - private JTextField textField; - public JTextField getJTextField(){ - if (textField == null) { - textField = new JTextField(); - } - return textField; + private Identifier clientId; + + private JScrollPane messageScrollPane; + + private JTextPane messageWindow; + + private TextEntryPanel textEntryPanel; + + private JEditorPane chatInstructionsPane; + + public ChatPanel() { + initGuiComponents(); } + + public ChatPanel(IrrigationClient irrigationClient) { + this(); + setIrrigationClient(irrigationClient); + } private class TextEntryPanel extends JPanel { private JLabel timeLeftLabel; - + private JTextField chatField; private Identifier targetIdentifier = Identifier.ALL; public TextEntryPanel() { super(); setLayout(new BorderLayout(3, 3)); - - textField.addKeyListener(new KeyAdapter() { + chatField = new JTextField(); + chatField.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent event) { - // System.err.println("event keycode is: " + - // event.getKeyCode()); - // System.err.println("vk_enter: " + KeyEvent.VK_ENTER); if (event.getKeyCode() == KeyEvent.VK_ENTER) { - sendMessage(textField); + sendMessage(); } } }); final JButton sendButton = new JButton("Send"); sendButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { - sendMessage(textField); + sendMessage(); } }); JPanel timeLeftPanel = new JPanel(); - timeLeftPanel.setLayout(new BoxLayout(timeLeftPanel, - BoxLayout.LINE_AXIS)); - timeLeftLabel = new JLabel(" 50"); + timeLeftPanel.setLayout(new BoxLayout(timeLeftPanel, BoxLayout.LINE_AXIS)); + timeLeftLabel = new JLabel("40"); timeLeftLabel.setFont(new Font("Arial", Font.BOLD, 14)); timeLeftLabel.setForeground(new Color(0x0000dd)); timeLeftPanel.add(new JLabel(" Time left: ")); timeLeftPanel.add(timeLeftLabel); - add(timeLeftPanel, BorderLayout.NORTH); - add(textField, BorderLayout.CENTER); - add(sendButton, BorderLayout.SOUTH); + add(timeLeftPanel, BorderLayout.PAGE_START); + add(chatField, BorderLayout.CENTER); + add(sendButton, BorderLayout.PAGE_END); } - private void sendMessage(JTextField textField) { - String message = textField.getText(); + private void sendMessage() { + String message = chatField.getText(); // System.err.println("message: " + message); if (message == null || "".equals(message)) { return; @@ -111,26 +116,18 @@ if (targetIdentifier == null) { return; } - textField.setText(""); - client.transmit(new ChatRequest(clientId, message, targetIdentifier)); + chatField.setText(""); + irrigationClient.transmit(new ChatRequest(clientId, message, targetIdentifier)); System.err.println("Sending a new chat request"); displayMessage(getChatHandle(clientId) + " -> " + getChatHandle(targetIdentifier), message); - textField.requestFocusInWindow(); + chatField.requestFocusInWindow(); } private void setTimeRemaining(long timeRemaining) { timeLeftLabel.setText(String.format(" %d s", timeRemaining / 1000L)); } - private void setTargetHandle(Identifier targetIdentifier) { - // this.targetIdentifier = targetIdentifier; - // if (targetIdentifier == Identifier.ALL) { - // timeLeftLabel.setText("everyone"); - // } else { - // timeLeftLabel.setText(getChatHandle(targetIdentifier)); - // } - } } private final static String HANDLE_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; @@ -143,6 +140,8 @@ "The time left for the discussion is displayed above the text field at the bottom of the screen.</p>"; private static String[] HANDLES; + + private Map<Identifier, String> chatHandles = new HashMap<Identifier, String>(); public static void main(String[] args) { JFrame frame = new JFrame(); @@ -157,25 +156,7 @@ frame.setVisible(true); } - private long timeRemaining; - private Identifier clientId; - - private JScrollPane messageScrollPane; - - private JTextPane messageWindow; - - private EventChannel channel; - - // used by the participant to select which participant to send a message to. - private JPanel participantButtonPanel; - - private List<Identifier> participants; - - private TextEntryPanel textEntryPanel; - - private JEditorPane chatInstructionsPane; - private void addStylesToMessageWindow() { StyledDocument styledDocument = messageWindow.getStyledDocument(); // and why not have something like... StyleContext.getDefaultStyle() to @@ -195,17 +176,11 @@ textEntryPanel.setTimeRemaining(timeRemaining); } - private String getChatHandle(Identifier source) { - if (source.equals(Identifier.ALL)) { + private String getChatHandle(Identifier identifier) { + if (identifier.equals(Identifier.ALL)) { return " all "; - } else { - int index = participants.indexOf(source); - if (source.equals(clientId)) { - return HANDLES[index] + "(you)"; - } - return " " + HANDLES[index] + " "; } - + return chatHandles.get(identifier); } private void initGuiComponents() { @@ -214,71 +189,19 @@ messageWindow.setEditable(false); messageScrollPane = new JScrollPane(messageWindow); addStylesToMessageWindow(); - - // set up the participant panel - participantButtonPanel = new JPanel(); - // participantButtonPanel.setLayout(new - // BoxLayout(participantButtonPanel, - // BoxLayout.PAGE_AXIS)); - participantButtonPanel.setLayout(new GridLayout(0, 1)); - participantButtonPanel.setBackground(Color.GRAY); - // JLabel selfLabel = new JLabel(getChatHandle(clientId)); - // selfLabel.setForeground(Color.ORANGE); - // selfLabel.setBackground(Color.ORANGE); - // selfLabel.setAlignmentX(Component.CENTER_ALIGNMENT); - JButton selfButton = new JButton(getChatHandle(clientId)); - selfButton.setEnabled(false); - selfButton.setAlignmentX(Component.CENTER_ALIGNMENT); - participantButtonPanel.add(selfButton); - participantButtonPanel.add(Box.createRigidArea(new Dimension(0, 15))); - for (int i = 0; i < HANDLES.length; i++) { - final Identifier targetId = participants.get(i); - if (targetId.equals(clientId)) { - continue; - } - String handle = HANDLES[i]; - JButton button = new JButton(handle); - button.setAlignmentX(Component.CENTER_ALIGNMENT); - button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - // change stuff in the messageEntryPanel - textEntryPanel.setTargetHandle(targetId); - } - }); - participantButtonPanel.add(button); - } - // special case to send a message to everyone - JButton sendAllButton = new JButton(" all "); - sendAllButton.setAlignmentX(Component.CENTER_ALIGNMENT); - sendAllButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - textEntryPanel.setTargetHandle(Identifier.ALL); - } - }); - participantButtonPanel.add(sendAllButton); - textEntryPanel = new TextEntryPanel(); - // orient the components in true lazyman fashion. - chatInstructionsPane = new JEditorPane(); chatInstructionsPane.setContentType("text/html"); chatInstructionsPane.setEditorKit(new HTMLEditorKit()); chatInstructionsPane.setEditable(false); JScrollPane chatInstructionsScrollPane = new JScrollPane(chatInstructionsPane); chatInstructionsPane.setText(CHAT_INSTRUCTIONS); - - - add(chatInstructionsScrollPane, BorderLayout.NORTH); + add(chatInstructionsScrollPane, BorderLayout.PAGE_START); add(messageScrollPane, BorderLayout.CENTER); - add(participantButtonPanel, BorderLayout.EAST); - add(textEntryPanel, BorderLayout.SOUTH); - +// add(participantButtonPanel, BorderLayout.EAST); + add(textEntryPanel, BorderLayout.PAGE_END); } - public void clear() { - participants.clear(); - } - private void displayMessage(String chatHandle, String message) { // String chatHandle = getChatHandle(source); StyledDocument document = messageWindow.getStyledDocument(); @@ -287,7 +210,8 @@ document.getStyle("bold")); document.insertString(document.getLength(), message + "\n", null); messageWindow.setCaretPosition(document.getLength()); - } catch (BadLocationException e) { + } + catch (BadLocationException e) { e.printStackTrace(); throw new RuntimeException(e); } @@ -298,36 +222,32 @@ if (HANDLES != null) { return; } - this.participants = participants; HANDLES = new String[participants.size()]; + // FIXME: shuffle handles? for (int i = HANDLES.length; --i >= 0;) { HANDLES[i] = " " + HANDLE_STRING.charAt(i) + " "; + chatHandles.put(participants.get(i), HANDLES[i]); } - // Collections.shuffle(Arrays.asList(HANDLES)); - // System.err.println("handles: " + HANDLES); + } - channel.add(this, new EventTypeProcessor<ChatEvent>(ChatEvent.class) { + public void setClientId(Identifier clientId) { + this.clientId = clientId; + } + + public void setIrrigationClient(IrrigationClient client) { + setClientId(client.getId()); + this.irrigationClient = client; + client.getEventChannel().add(this, new EventTypeProcessor<ChatEvent>(ChatEvent.class) { public void handle(final ChatEvent chatEvent) { SwingUtilities.invokeLater(new Runnable() { public void run() { displayMessage(getChatHandle(chatEvent.getSource()) + " -> " - // FIXME: either "all" or "you". + getChatHandle(chatEvent.getTarget()), chatEvent.toString()); } }); } }); - initGuiComponents(); } - public void setClientId(Identifier clientId) { - this.clientId = clientId; - } - - public void setClient(IrrigationClient client) { - setClientId(client.getId()); - this.client = client; - } - } Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-20 00:15:43 UTC (rev 305) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-20 02:36:40 UTC (rev 306) @@ -95,8 +95,6 @@ private JScrollPane tokenInstructionsScrollPane; - private int NUMBER_INSTRUCTIONS = 9; - private JLabel quizMessageLabel; private int pagesTraversed = 0; @@ -108,12 +106,15 @@ private CanalAnimationPanel canalAnimationPanel; private CardLayout cardLayout; + + private int numberOfGeneralInstructionPages; private JLabel infrastructureEfficiencyLabel = new JLabel("Current infrastructure efficiency: "); public ExperimentGameWindow(IrrigationClient client) { this.client = client; this.clientDataModel = client.getClientDataModel(); + this.numberOfGeneralInstructionPages = getServerConfiguration().getNumberOfGeneralInstructionPages(); } void initialize(Dimension screenSize) { @@ -128,7 +129,7 @@ instructionsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); instructionsScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); // create a quiz listener and then initialize the instructions. - instructionsEditorPane.setActionListener(createQuizListener(clientDataModel.getServerConfiguration())); + instructionsEditorPane.setActionListener(createQuizListener(getServerConfiguration())); instructionsEditorPane.setCaretPosition(0); setInstructions(getGeneralInstructions(0)); @@ -136,6 +137,8 @@ irrigationGamePanel = new IrrigationGamePanel(screenSize, client); addToCardLayout(irrigationGamePanel); addToCardLayout(getInvestTokensPanel()); + addToCardLayout(getChatPanel()); + addToCardLayout(getGraphPanel()); } private void addToCardLayout(Component component) { @@ -150,14 +153,13 @@ tokenInstructionsEditorPane = createInstructionsEditorPane(); tokenInstructionsScrollPane = new JScrollPane(tokenInstructionsEditorPane); investTokensPanel.add(tokenInstructionsScrollPane, BorderLayout.CENTER); - tokenInstructionsEditorPane.setText(clientDataModel.getServerConfiguration().getInvestmentInstructions()); + tokenInstructionsEditorPane.setText(getServerConfiguration().getInvestmentInstructions()); tokenInstructionsEditorPane.setCaretPosition(0); tokenInstructionsEditorPane.repaint(); investTokensPanel.add(getSubmitTokenPanel(), BorderLayout.SOUTH); investTokensPanel.add(infrastructureEfficiencyLabel, BorderLayout.NORTH); investTokensPanel.setBackground(Color.WHITE); } - updateInfrastructureEfficiencyLabel(); return investTokensPanel; } @@ -173,7 +175,6 @@ infrastructureEfficiency = group.getInfrastructureEfficiency() - roundConfiguration.getInfrastructureDegradationFactor(); } infrastructureEfficiencyLabel.setText("Current infrastructure efficiency: " + infrastructureEfficiency); - infrastructureEfficiencyLabel.repaint(); } private JPanel getSubmitTokenPanel() { @@ -206,6 +207,7 @@ instructionsNavigationPanel.add(getNextButton(), BorderLayout.LINE_END); // displays quiz messages (correct/incorrect answer). quizMessageLabel = new JLabel(); + quizMessageLabel.setHorizontalAlignment(JLabel.CENTER); instructionsNavigationPanel.add(quizMessageLabel, BorderLayout.CENTER); } return instructionsNavigationPanel; @@ -225,7 +227,6 @@ } previousButton.setEnabled(instructionNumber > 1); nextButton.setEnabled(true); - System.out.println("instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); // FIXME: get rid of hardcoded animation on page 5. Should instead // just be an animated gif or something like that. @@ -236,7 +237,7 @@ else { getInstructionsPanel().remove(getCanalAnimationPanel()); } - validate(); + getInstructionsPanel().revalidate(); } }); } @@ -255,21 +256,21 @@ if (instructionNumber >= pagesTraversed){ nextButton.setEnabled(false); } - - // getting the next instruction Number - if (instructionNumber < NUMBER_INSTRUCTIONS) { + if (instructionNumber < numberOfGeneralInstructionPages) { instructionNumber++; + setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); } - setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); +// else { +// setInstructions(clientDataModel.getRoundConfiguration().getInstructions()); +// } if(instructionNumber == 5) { getInstructionsPanel().add(getCanalAnimationPanel(), BorderLayout.PAGE_START); } else { getInstructionsPanel().remove(getCanalAnimationPanel()); } - validate(); + getInstructionsPanel().revalidate(); } - }); } @@ -291,21 +292,22 @@ * @return */ private String getGeneralInstructions(int pageNumber, int pagesTraversed) { - return clientDataModel.getServerConfiguration().getGeneralInstructions(pageNumber, pagesTraversed, clientDataModel.getPriority()); + return getServerConfiguration().getGeneralInstructions(pageNumber, pagesTraversed, clientDataModel.getPriority()); } private String getGeneralInstructions(int pageNumber) { - return clientDataModel.getServerConfiguration().getGeneralInstructions(pageNumber); + return getServerConfiguration().getGeneralInstructions(pageNumber); } + + private ServerConfiguration getServerConfiguration() { + return clientDataModel.getServerConfiguration(); + } private JTextField getInvestedTokensTextField() { if (investedTokensTextField == null) { investedTokensTextField = new JTextField(); investedTokensTextField.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent event) { - // System.err.println("event keycode is: " + - // event.getKeyCode()); - // System.err.println("vk_enter: " + KeyEvent.VK_ENTER); if (event.getKeyCode() == KeyEvent.VK_ENTER) { submitInvestedTokens(); } @@ -322,7 +324,6 @@ submitTokensButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { submitInvestedTokens(); - } }); } @@ -342,7 +343,7 @@ investedTokensTextField.setText(""); instructionsBuilder.delete(0, instructionsBuilder.length()); instructionsBuilder.append("\nPlease enter your tokens within the range 0 - 10"); - instructionsBuilder.append(clientDataModel.getServerConfiguration().getInvestmentInstructions()); + instructionsBuilder.append(getServerConfiguration().getInvestmentInstructions()); tokenInstructionsEditorPane.setText(instructionsBuilder.toString()); } } @@ -350,7 +351,7 @@ investedTokensTextField.setText(""); instructionsBuilder.delete(0, instructionsBuilder.length()); instructionsBuilder.append("\nYou only have between 0 and 10 to invest. Please choose a number between 0 and 10 and try again."); - instructionsBuilder.append(clientDataModel.getServerConfiguration().getInvestmentInstructions()); + instructionsBuilder.append(getServerConfiguration().getInvestmentInstructions()); tokenInstructionsEditorPane.setText(instructionsBuilder.toString()); } } @@ -375,42 +376,20 @@ private void addCenterComponent(Component newCenterComponent) { cardLayout.show(this, newCenterComponent.getName()); - // if (currentCenterComponent != null) { - // currentCenterComponent.setVisible(false); - // remove(currentCenterComponent); - // add(newCenterComponent, BorderLayout.CENTER); - // newCenterComponent.setVisible(true); - // invalidate(); - // validate(); - // newCenterComponent.repaint(); - // repaint(); - // } - // currentCenterComponent = newCenterComponent; revalidate(); repaint(); } public void startRound(final RoundConfiguration configuration) { - - // currentExperimentConfiguration = configuration; Runnable runnable = new Runnable() { public void run() { -// addCenterComponent(subjectWindow); + addCenterComponent(irrigationGamePanel); requestFocusInWindow(); - } }; SwingUtilities.invokeLater(runnable); } - /* - * This method could be merged somehow with the startRoundEvent. We can get - * rid of the sendContributionStatus then - */ - public void updateContributions() { - irrigationGamePanel.updateContributions(clientDataModel); - } - public void update() { irrigationGamePanel.updateClientStatus(clientDataModel); } @@ -447,6 +426,10 @@ System.err.println(message); } + /** + * FIXME: needs serious refactoring + * @param event + */ private void addDebriefingText(EndRoundEvent event) { instructionsBuilder.delete(0, instructionsBuilder.length()); @@ -515,7 +498,7 @@ "showup fee, for a grand total of $%3.2f", (float)dollarsPerToken*clientData.getTotalTokensEarned(), (float)dollarsPerToken*clientData.getTotalTokens(), - (float)dollarsPerToken*clientData.getTotalTokens() + clientDataModel.getServerConfiguration().getShowUpPayment() + (float)dollarsPerToken*clientData.getTotalTokens() + getServerConfiguration().getShowUpPayment() )); //append the added practice round instructions if(clientDataModel.getRoundConfiguration().isPracticeRound()) { @@ -523,7 +506,7 @@ "and will not count towards your actual payments"); } else if (event.isLastRound()) { - instructionsBuilder.append(clientDataModel.getServerConfiguration().getFinalInstructions()); + instructionsBuilder.append(getServerConfiguration().getFinalInstructions()); } setInstructions(instructionsBuilder.toString()); } @@ -559,63 +542,6 @@ } } } -// -// -// // iterate through expected answers -// for (Map.Entry<String, String> entry : configuration.getQuizAnswers().entrySet()) { -// // just check those questions that come in those instructions -// String questionNumber = entry.getKey(); -// String expectedAnswer = entry.getValue(); -// -// switch(instructionNumber){ -// case 1: -// if(questionNumber.equalsIgnoreCase("q1")) { -// incorrectAnswers = addIncorrectAnswerList(expectedAnswer,responses,questionNumber, incorrectAnswers); -// } -// break; -// case 2: -// if(questionNumber.equalsIgnoreCase("q2")){ -// incorrectAnswers = addIncorrectAnswerList(expectedAnswer,responses,questionNumber, incorrectAnswers); -// } -// break; -// case 3: -// if(questionNumber.equalsIgnoreCase("q3") || questionNumber.equalsIgnoreCase("q4") ) { -// incorrectAnswers = addIncorrectAnswerList(expectedAnswer,responses,questionNumber, incorrectAnswers); -// } -// break; -// case 4: -// if(questionNumber.equalsIgnoreCase("q5")) { -// incorrectAnswers = addIncorrectAnswerList(expectedAnswer,responses,questionNumber, incorrectAnswers); -// } -// break; -// -// case 5: if(questionNumber.equalsIgnoreCase("q6") || questionNumber.equalsIgnoreCase("q7") ){ -// //System.out.println("Entering the string equal"); -// incorrectAnswers = addIncorrectAnswerList(expectedAnswer,responses,questionNumber, incorrectAnswers); -// } -// break; -// -// case 6: if(questionNumber.equalsIgnoreCase("q8")){ -// //System.out.println("Entering the string equal"); -// incorrectAnswers = addIncorrectAnswerList(expectedAnswer,responses,questionNumber, incorrectAnswers); -// } -// break; -// case 7: if(questionNumber.equalsIgnoreCase("q9") || questionNumber.equalsIgnoreCase("q10") ){ -// //System.out.println("Entering the string equal"); -// incorrectAnswers = addIncorrectAnswerList(expectedAnswer,responses,questionNumber, incorrectAnswers); -// } -// break; -// -// case 8: if(questionNumber.equalsIgnoreCase("q10")){ -// //System.out.println("Entering the string equal"); -// incorrectAnswers = addIncorrectAnswerList(expectedAnswer,responses,questionNumber, incorrectAnswers); -// System.out.println("Expected question"+questionNumber); -// System.out.println("Expected Answer"+expectedAnswer); -// } -// break; -// } -// -// } printIncorrectAnswerList(incorrectAnswers); if (incorrectAnswers.isEmpty()) { nextButton.setEnabled(true); @@ -650,8 +576,6 @@ public void updateGraphDisplay(final ClientData clientData) { totalContributedTokensPerGroup = clientData.getGroupDataModel().getTotalContributedTokens(); - contributionInformationTextArea = new JTextArea(); - contributionInformationTextArea.setEditable(false); DecimalFormat df = new DecimalFormat("#.##"); final String contributionInformation = "Initial infrastructure efficiency: " + clientData.getGroupDataModel().getInitialInfrastructureEfficiency() + "%" @@ -674,33 +598,36 @@ Runnable runnable = new Runnable() { public void run() { contributionInformationTextArea.setText(contributionInformation); + pieChart.setClientData(clientData); + addCenterComponent(getGraphPanel()); } }; SwingUtilities.invokeLater(runnable); + irrigationGamePanel.updateContributions(clientDataModel); } public JPanel getGraphPanel() { if (graphPanel == null) { graphPanel = new JPanel(); + graphPanel.setName("Graph panel"); GridLayout gridLayout = new GridLayout(); gridLayout.setColumns(2); graphPanel.setLayout(gridLayout); graphPanel.add(getPieChartPanel(), null); + contributionInformationTextArea = new JTextArea(); + contributionInformationTextArea.setEditable(false); graphPanel.add(contributionInformationTextArea,null); - addCenterComponent(graphPanel); - requestFocusInWindow(); } return graphPanel; } private JPanel getPieChartPanel() { if (pieChartPanel == null) { - ClientData clientData = clientDataModel.getClientData(); pieChartPanel = new JPanel(); xySeriesDemo = new ChartWindowPanelTokenBandwidth(client); xySeriesDemo.setVisible(true); - pieChart = new PieChart(clientData.getGroupDataModel(),client); + pieChart = new PieChart(); GridLayout gridLayout = new GridLayout(); gridLayout.setRows(2); gridLayout.setColumns(1); @@ -715,15 +642,8 @@ public void updateSubmitTokenScreenDisplay() { Runnable runnable = new Runnable() { public void run() { - //mainIrrigationWindow.setup(configuration); - // reset the amount of time left in the round on food eaten - // label to the value from the configuration file. - // this is NOT dynamic; once the StartRoundEvent is fired off - // by the server no new clients can connect because the round - // has begun. - /*roundEndsOn = (configuration.getRoundTime() * 1000L) + System.currentTimeMillis(); - update();*/ addCenterComponent(getInvestTokensPanel()); + updateInfrastructureEfficiencyLabel(); getInvestedTokensTextField().requestFocusInWindow(); } }; @@ -745,8 +665,8 @@ private ChatPanel getChatPanel() { if (chatPanel == null) { - chatPanel = new ChatPanel(); - chatPanel.setClient(client); + chatPanel = new ChatPanel(client); + chatPanel.setName("Chat panel"); } return chatPanel; } @@ -759,10 +679,6 @@ ChatPanel chatPanel = getChatPanel(); chatPanel.initialize(clientDataModel.getAllClientIdentifiers()); addCenterComponent( chatPanel ); - chatPanel.getJTextField().requestFocus(); - System.err.println("Done adding chat panel..."); - //stop the animation in the instructions - } }); } Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java 2009-10-20 00:15:43 UTC (rev 305) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java 2009-10-20 02:36:40 UTC (rev 306) @@ -18,7 +18,7 @@ import edu.asu.commons.irrigation.events.CloseGateEvent; import edu.asu.commons.irrigation.events.DisplaySubmitTokenRequest; import edu.asu.commons.irrigation.events.EndRoundEvent; -import edu.asu.commons.irrigation.events.GroupUpdateEvent; +import edu.asu.commons.irrigation.events.InfrastructureUpdateEvent; import edu.asu.commons.irrigation.events.InvestedTokensEvent; import edu.asu.commons.irrigation.events.OpenGateEvent; import edu.asu.commons.irrigation.events.PauseRequest; @@ -168,12 +168,11 @@ experimentGameWindow.updateRoundInstructions(configuration); } }); - channel.add(this, new EventTypeProcessor<GroupUpdateEvent>(GroupUpdateEvent.class) { - public void handle(GroupUpdateEvent event) { + channel.add(this, new EventTypeProcessor<InfrastructureUpdateEvent>(InfrastructureUpdateEvent.class) { + public void handle(InfrastructureUpdateEvent event) { System.err.println("Received group update event: " + event); clientDataModel.setGroupDataModel(event.getGroupDataModel()); - experimentGameWindow.updateGraphDisplay(event.getClientDataMap().get(event.getId())); - experimentGameWindow.updateContributions(); + experimentGameWindow.updateGraphDisplay(event.getClientData()); } }); channel.add(this, new EventTypeProcessor<RoundStartedEvent>(RoundStartedEvent.class) { Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationGamePanel.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationGamePanel.java 2009-10-20 00:15:43 UTC (rev 305) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationGamePanel.java 2009-10-20 02:36:40 UTC (rev 306) @@ -339,9 +339,9 @@ /** * fills in the panels depending on the priority of the client */ - public void fillPanels(ClientDataModel clientGameState) { + public void fillPanels(ClientDataModel clientDataModel) { // TODO Auto-generated method stub - jPanelUpperWindow.add(getUpperPanel(clientGameState)); + jPanelUpperWindow.add(getUpperPanel(clientDataModel)); //switch(clientGameState.getPriority()){ downloadScreenPanel.add(getJPanelUpStreamWindow(),null); Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/PieChart.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/PieChart.java 2009-10-20 00:15:43 UTC (rev 305) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/PieChart.java 2009-10-20 02:36:40 UTC (rev 306) @@ -1,20 +1,16 @@ -/** - * - */ package edu.asu.commons.irrigation.client; import java.awt.Dimension; import java.awt.Font; import java.awt.Rectangle; -import java.text.AttributedString; import java.util.Map; import javax.swing.JPanel; +import javax.swing.SwingUtilities; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; -import org.jfree.chart.labels.PieSectionLabelGenerator; import org.jfree.chart.plot.PiePlot; import org.jfree.data.general.DefaultPieDataset; import org.jfree.data.general.PieDataset; @@ -24,67 +20,48 @@ import edu.asu.commons.net.Identifier; /** - * A pie chart with a custom label generator. + * Presents the group contributions as a pie chart. */ public class PieChart extends JPanel { private static final long serialVersionUID = -5382293105043214105L; - private GroupDataModel groupDataModel; - - private IrrigationClient client; + private ChartPanel chartPanel; - public PieChart(GroupDataModel groupDataModel,IrrigationClient client) { - this.groupDataModel = groupDataModel; - this.client = client; - final PieDataset dataset = createDataset(); - final JFreeChart chart = createChart(dataset); - final ChartPanel chartPanel = new ChartPanel(chart); - chartPanel.setPreferredSize(new Dimension(500, 270)); - this.add(chartPanel); - this.setBounds(new Rectangle(0,0,500,270)); + public void setClientData(final ClientData clientData) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + final PieDataset dataset = createDataset(clientData); + final JFreeChart chart = createChart(dataset); + remove(chartPanel); + chartPanel = new ChartPanel(chart); + chartPanel.setPreferredSize(new Dimension(500, 270)); + add(chartPanel); + setBounds(new Rectangle(0,0,500,270)); + } + }); } /** - * Creates a sample dataset. - * + * Creates a pie dataset out of the client * @return a sample dataset. */ - private PieDataset createDataset() { - final DefaultPieDataset dataset = new DefaultPieDataset(); + private PieDataset createDataset(ClientData clientData) { + final DefaultPieDataset defaultPieDataset = new DefaultPieDataset(); + GroupDataModel groupDataModel = clientData.getGroupDataModel(); Map<Identifier,ClientData>clientDataMap = groupDataModel.getClientDataMap(); - for(ClientData clientData : clientDataMap.values()){ - String clientPieLabel =null; - switch(clientData.getPriority()){ - case 0 : clientPieLabel = "A = "; - break; - - case 1 : clientPieLabel = "B = "; - break; - - case 2 : clientPieLabel = "C = "; - break; - - case 3 : clientPieLabel = "D = "; - break; - - case 4 : clientPieLabel = "E = "; - break; - } - if(client.getClientDataModel().getPriority() == clientData.getPriority()){ - clientPieLabel = "YOU = "; - } - clientPieLabel = clientPieLabel+new Integer(clientData.getInvestedTokens()).toString(); - dataset.setValue(clientPieLabel,new Double(clientData.getInvestedTokens())); + for (ClientData currentClientData : clientDataMap.values()) { + StringBuilder labelBuilder = new StringBuilder(); + if (currentClientData.getId().equals(clientData.getId())) { + labelBuilder.append("You"); + } + else { + labelBuilder.append(currentClientData.getPriorityAsString()); + } + labelBuilder.append(" invested ").append(currentClientData.getInvestedTokens()).append(" token(s)"); + defaultPieDataset.setValue(labelBuilder.toString(), currentClientData.getInvestedTokens()); } - /*dataset.setValue("One", new Double(43.2)); - dataset.setValue("Two", new Double(10.0)); - dataset.setValue("Three", new Double(27.5)); - dataset.setValue("Four", new Double(17.5)); - dataset.setValue("Five", new Double(11.0)); - dataset.setValue("Six", new Double(19.4)); - */ - return dataset; + return defaultPieDataset; } // **************************************************************************** @@ -125,40 +102,4 @@ } - /** - * Starting point for the demonstration application. - * - * @param args ignored. - */ - - - /** - * A custom label generator (returns null for one item as a test). - */ - static class CustomLabelGenerator implements PieSectionLabelGenerator { - - /** - * Generates a label for a pie section. - * - * @param dataset the dataset (<code>null</code> not permitted). - * @param key the section key (<code>null</code> not permitted). - * - * @return the label (possibly <code>null</code>). - */ - public String generateSectionLabel(final PieDataset dataset, final Comparable key) { - String result = null; - if (dataset != null) { - if (!key.equals("Two")) { - result = key.toString(); - } - } - return result; - } - - public AttributedString generateAttributedSectionLabel(PieDataset arg0, Comparable arg1) { - return null; - } - - } - } Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java 2009-10-20 00:15:43 UTC (rev 305) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java 2009-10-20 02:36:40 UTC (rev 306) @@ -153,5 +153,9 @@ public String getInvestmentInstructions() { return assistant.getProperty("investment-instructions"); } + + public int getNumberOfGeneralInstructionPages() { + return assistant.getIntProperty("general-instruction-pages", 8); + } } Deleted: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/GroupUpdateEvent.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/GroupUpdateEvent.java 2009-10-20 00:15:43 UTC (rev 305) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/GroupUpdateEvent.java 2009-10-20 02:36:40 UTC (rev 306) @@ -1,38 +0,0 @@ -package edu.asu.commons.irrigation.events; - -import java.util.Map; - -import edu.asu.commons.event.AbstractEvent; -import edu.asu.commons.event.ExperimentUpdateEvent; -import edu.asu.commons.irrigation.server.ClientData; -import edu.asu.commons.irrigation.server.GroupDataModel; -import edu.asu.commons.net.Identifier; - -/** - * $Id$ - * - * Event carrying the GroupDataModel and the time remaining to be sent to all participants each second. - * - * @author <a href='mailto:All...@as...'>Allen Lee</a> - * @version $Rev$ - */ -public class GroupUpdateEvent extends AbstractEvent implements ExperimentUpdateEvent { - - private static final long serialVersionUID = -8522536860601018690L; - - private final GroupDataModel groupDataModel; - - public GroupUpdateEvent(Identifier id, GroupDataModel groupDataModel) { - super(id); - this.groupDataModel = groupDataModel; - } - - public GroupDataModel getGroupDataModel() { - return groupDataModel; - } - - public Map<Identifier,ClientData> getClientDataMap(){ - return groupDataModel.getClientDataMap(); - } - -} Copied: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/InfrastructureUpdateEvent.java (from rev 298, irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/GroupUpdateEvent.java) =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/InfrastructureUpdateEvent.java (rev 0) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/InfrastructureUpdateEvent.java 2009-10-20 02:36:40 UTC (rev 306) @@ -0,0 +1,42 @@ +package edu.asu.commons.irrigation.events; + +import java.util.Map; + +import edu.asu.commons.event.AbstractEvent; +import edu.asu.commons.event.ExperimentUpdateEvent; +import edu.asu.commons.irrigation.server.ClientData; +import edu.asu.commons.irrigation.server.GroupDataModel; +import edu.asu.commons.net.Identifier; + +/** + * $Id$ + * + * Event carrying the GroupDataModel and the time remaining to be sent to all participants each second. + * + * @author <a href='mailto:All...@as...'>Allen Lee</a> + * @version $Rev$ + */ +public class InfrastructureUpdateEvent extends AbstractEvent implements ExperimentUpdateEvent { + + private static final long serialVersionUID = -8522536860601018690L; + + private final GroupDataModel groupDataModel; + + public InfrastructureUpdateEvent(Identifier id, GroupDataModel groupDataModel) { + super(id); + this.groupDataModel = groupDataModel; + } + + public GroupDataModel getGroupDataModel() { + return groupDataModel; + } + + public Map<Identifier,ClientData> getClientDataMap(){ + return groupDataModel.getClientDataMap(); + } + + public ClientData getClientData() { + return groupDataModel.getClientData(id); + } + +} Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/Facilitator.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/Facilitator.java 2009-10-20 00:15:43 UTC (rev 305) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/Facilitator.java 2009-10-20 02:36:40 UTC (rev 306) @@ -8,7 +8,6 @@ import edu.asu.commons.event.BeginExperimentRequest; import edu.asu.commons.event.BeginRoundRequest; -import edu.asu.commons.event.ConfigurationEvent; import edu.asu.commons.event.EndRoundRequest; import edu.asu.commons.event.Event; import edu.asu.commons.event.EventChannel; @@ -18,6 +17,7 @@ import edu.asu.commons.irrigation.conf.RoundConfiguration; import edu.asu.commons.irrigation.conf.ServerConfiguration; import edu.asu.commons.irrigation.events.FacilitatorEndRoundEvent; +import edu.asu.commons.irrigation.events.RegistrationEvent; import edu.asu.commons.irrigation.server.ServerDataModel; import edu.asu.commons.net.ClientDispatcher; import edu.asu.commons.net.DispatcherFactory; @@ -42,7 +42,7 @@ private ServerDataModel serverGameState; // @jve:decl-index=0: - private FacilitatorWindow irrigationFacilitatorWindow; + private FacilitatorWindow facilitatorWindow; private boolean experimentRunning = false; @@ -55,19 +55,17 @@ public Facilitator(ServerConfiguration configuration) { dispatcher = DispatcherFactory.getInstance().createClientDispatcher(channel); setConfiguration(configuration); - initializeEventProcessors(); } - - @SuppressWarnings("unchecked") + private void initializeEventProcessors() { - channel.add(this, new EventTypeProcessor<ConfigurationEvent>(ConfigurationEvent.class) { - public void handle(ConfigurationEvent configurationEvent) { - setConfiguration((ServerConfiguration) configurationEvent.getConfiguration()); + channel.add(this, new EventTypeProcessor<RegistrationEvent>(RegistrationEvent.class) { + public void handle(RegistrationEvent registrationEvent) { + facilitatorWindow.setText(registrationEvent.getRoundConfiguration().getInstructions()); } }); channel.add(this, new EventTypeProcessor<FacilitatorEndRoundEvent>(FacilitatorEndRoundEvent.class) { public void handle(FacilitatorEndRoundEvent event) { - irrigationFacilitatorWindow.endRound(event); + facilitatorWindow.endRound(event); configuration.nextRound(); } }); @@ -107,8 +105,10 @@ transmit(new FacilitatorRegistrationRequest(id)); } - void createFacilitatorWindow(Dimension dimension) { - irrigationFacilitatorWindow = new FacilitatorWindow(dimension, this); + void initialize() { + facilitatorWindow = new FacilitatorWindow(this); + facilitatorWindow.setText(configuration.getFacilitatorInstructions()); + initializeEventProcessors(); } /* @@ -121,24 +121,23 @@ public static void main(String[] args) { Runnable createGuiRunnable = new Runnable() { public void run() { - Dimension dimension = new Dimension(500, 600); + Dimension dimension = new Dimension(600, 600); Facilitator facilitator = Facilitator.getInstance(); + facilitator.initialize(); facilitator.connect(); JFrame frame = new JFrame(); frame.setTitle("Facilitator window: " + facilitator.id); - frame.setSize((int) dimension.getWidth(), (int) dimension.getHeight()); - facilitator.createFacilitatorWindow(dimension); + frame.setPreferredSize(dimension); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(facilitator.getFacilitatorWindow()); + frame.pack(); frame.setVisible(true); } }; SwingUtilities.invokeLater(createGuiRunnable); } - /* - * Send a request to server to start an experiment - */ void sendBeginExperimentRequest(){ transmit(new BeginExperimentRequest(id)); } @@ -155,7 +154,7 @@ } public FacilitatorWindow getFacilitatorWindow() { - return irrigationFacilitatorWindow; + return facilitatorWindow; } public Identifier getId(){ Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/FacilitatorWindow.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/FacilitatorWindow.java 2009-10-20 00:15:43 UTC (rev 305) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/FacilitatorWindow.java 2009-10-20 02:36:40 UTC (rev 306) @@ -1,8 +1,6 @@ package edu.asu.commons.irrigation.facilitator; import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; @@ -10,9 +8,11 @@ import java.util.TreeSet; import javax.swing.BoxLayout; +import javax.swing.GroupLayout; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; +import javax.swing.SwingUtilities; import edu.asu.commons.irrigation.events.BeginChatRoundRequest; import edu.asu.commons.irrigation.events.DisplaySubmitTokenRequest; @@ -25,8 +25,12 @@ import edu.asu.commons.util.HtmlEditorPane; /** - * @author Sanket + * $Id$ + * + * Basic facilitator interface for driving the experiment. * + * @author <a href='mailto:All...@as...'>Allen Lee</a> + * @version $Rev$ */ public class FacilitatorWindow extends JPanel { @@ -34,8 +38,6 @@ private Facilitator facilitator; - private Dimension windowDimension; - private JButton startRoundButton = null; private JButton beginChatButton; @@ -44,34 +46,36 @@ private JScrollPane scrollPane; private JButton showInstructionsButton; + + private JButton displayInvestmentButton; /** * This is the default constructor */ - public FacilitatorWindow(Dimension dimension, Facilitator facilitator) { - windowDimension = dimension; + public FacilitatorWindow(Facilitator facilitator) { this.facilitator = facilitator; - initialize(); + initGuiComponents(); } /** * * @return void */ - private void initialize() { - setSize(windowDimension); + private void initGuiComponents() { setLayout(new BorderLayout()); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS)); + buttonPanel.add(getShowInstructionsButton()); + buttonPanel.add(getBeginChatButton()); + buttonPanel.add(getDisplayInvestmentButton()); buttonPanel.add(getStartRoundButton()); - buttonPanel.add(getBeginChatButton()); - buttonPanel.add(getShowInstructionsButton()); add(buttonPanel, BorderLayout.NORTH); - JPanel informationPanel = new JPanel(); editorPane = new HtmlEditorPane(); + editorPane.setEditable(false); scrollPane = new JScrollPane(editorPane); - informationPanel.add(scrollPane); - add(informationPanel, BorderLayout.CENTER); + scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); + scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + add(scrollPane, BorderLayout.CENTER); } private JButton getShowInstructionsButton() { @@ -102,14 +106,23 @@ if (facilitator.getCurrentRoundConfiguration().isChatEnabledBeforeRound()) { facilitator.transmit(new BeginChatRoundRequest(facilitator.getId())); } - else { - facilitator.transmit(new DisplaySubmitTokenRequest(facilitator.getId())); - } } }); } return beginChatButton; } + + private JButton getDisplayInvestmentButton() { + if (displayInvestmentButton == null) { + displayInvestmentButton = new JButton("Show Investment Screen"); + displayInvestmentButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent event) { + facilitator.transmit(new DisplaySubmitTokenRequest(facilitator.getId())); + } + }); + } + return displayInvestmentButton; + } public Facilitator getFacilitator() { return facilitator; @@ -128,7 +141,6 @@ private JButton getStartRoundButton() { if (startRoundButton == null) { startRoundButton = new JButton(); - startRoundButton.setBounds(new Rectangle(180, 16, 136, 24)); startRoundButton.setText("Start Round"); startRoundButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { @@ -138,14 +150,21 @@ } return startRoundButton; } + + public void setText(final String text) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + editorPane.setText(text); + scrollPane.revalidate(); + } + }); + } /** * This method initializes Stop_Round_Button1 * * @return javax.swing.JButton */ - - public void endRound(FacilitatorEndRoundEvent event) { ServerDataModel model = event.getServerDataModel(); StringBuilder builder = new StringBuilder(); @@ -175,8 +194,7 @@ if (event.isLastRound()) { builder.append("<h2><font color='blue'>The experiment is over. Please prepare payments.</font></h2>"); } - editorPane.setText(builder.toString()); - repaint(); + setText(builder.toString()); } -} // @jve:decl-index=0:visual-constraint="48,19" +} Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/IrrigationServer.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/IrrigationServer.java 2009-10-20 00:15:43 UTC (rev 305) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/IrrigationServer.java 2009-10-20 02:36:40 UTC (rev 306) @@ -24,7 +24,7 @@ import edu.asu.commons.irrigation.events.DisplaySubmitTokenRequest; import edu.asu.commons.irrigation.events.EndRoundEvent; import edu.asu.commons.irrigation.events.FacilitatorEndRoundEvent; -import edu.asu.commons.irrigation.events.GroupUpdateEvent; +import edu.asu.commons.irrigation.events.InfrastructureUpdateEvent; import edu.asu.commons.irrigation.events.InvestedTokensEvent; import edu.asu.commons.irrigation.events.OpenGateEvent; import edu.asu.commons.irrigation.events.PauseRequest; @@ -276,8 +276,8 @@ group.calculateTotalFlowCapacity(); // iterate through all groups and send back their contribution status for (Identifier id : group.getClientDataMap().keySet()) { - GroupUpdateEvent groupUpdateEvent = new GroupUpdateEvent(id, group); - transmit(groupUpdateEvent); + InfrastructureUpdateEvent infrastructureUpdateEvent = new InfrastructureUpdateEvent(id, group); + transmit(infrastructureUpdateEvent); } } } Modified: irrigation/trunk/src/main/resources/configuration/asu-fall-2009/irrigation.xml =================================================================== --- irrigation/trunk/src/main/resources/configuration/asu-fall-2009/irrigation.xml 2009-10-20 00:15:43 UTC (rev 305) +++ irrigation/trunk/src/main/resources/configuration/asu-fall-2009/irrigation.xml 2009-10-20 02:36:40 UTC (rev 306) @@ -595,7 +595,7 @@ ]]> </entry> -<entry key="general-instructionsq9"> +<entry key="general-instructions8"> <![CDATA[ <p> We will now start with two practice rounds. This practice round will not contribute to your earnings – This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <al...@us...> - 2009-10-20 00:17:18
|
Revision: 305 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=305&view=rev Author: alllee Date: 2009-10-20 00:15:43 +0000 (Tue, 20 Oct 2009) Log Message: ----------- turning EOFExceptions into a reason to disconnect the client. Modified Paths: -------------- csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java Modified: csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java 2009-10-19 21:03:43 UTC (rev 304) +++ csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java 2009-10-20 00:15:43 UTC (rev 305) @@ -13,14 +13,11 @@ /** * $Id$ * - * Worker class that helps the Client and Server SocketDispatchers perform - * reading and writing of edu.indiana.psych.gee.event.Event-S. Reading EventS - * from the Socket is a blocking I/O operation and thus requirs its own - * dedicated thread of execution. Writes can and often do occur within a - * separate thread of execution, initiated by whatever class is manipulating - * this one. + * This class is a basic Socket-based Runnable that helps Client and Server SocketDispatchers perform + * reading and writing of Events. Will read Events from the socket via blocking I/O after this Runnable + * is start()-ed. Writes occur within caller's thread of execution. * - * @author <a href='al...@cs...'>Allen Lee</a> + * @author <a href='all...@as...'>Allen Lee</a> * @version $Revision$ */ class SocketDispatcherWorker implements Runnable { @@ -139,25 +136,26 @@ dispatcher.notifyAll(); } } - // XXX: try to recover from StreamCorruptedExceptions and - // EOFExceptions... + // XXX: try to recover from StreamCorruptedExceptions catch (StreamCorruptedException e) { e.printStackTrace(); break; } catch (EOFException e) { e.printStackTrace(); - break; + requestDisconnection(e); + // kills this thread. + stop(); } catch (IOException e) { e.printStackTrace(); requestDisconnection(e); - running = false; + stop(); } catch (ClassNotFoundException e) { e.printStackTrace(); requestDisconnection(e); - running = false; + stop(); } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <al...@us...> - 2009-10-19 21:03:50
|
Revision: 304 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=304&view=rev Author: alllee Date: 2009-10-19 21:03:43 +0000 (Mon, 19 Oct 2009) Log Message: ----------- minor hygienic changes to simplify logic, replacing boolean logic to switch on threaded handling with just a new method slot. i.e., handle(Event, boolean) changed to handleWithNewThread(Event) Modified Paths: -------------- csidex/trunk/src/main/java/edu/asu/commons/event/EventConstraintChannel.java csidex/trunk/src/main/java/edu/asu/commons/event/EventHandler.java csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeChannel.java csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeProcessor.java csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java Modified: csidex/trunk/src/main/java/edu/asu/commons/event/EventConstraintChannel.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/event/EventConstraintChannel.java 2009-10-19 20:55:44 UTC (rev 303) +++ csidex/trunk/src/main/java/edu/asu/commons/event/EventConstraintChannel.java 2009-10-19 21:03:43 UTC (rev 304) @@ -58,23 +58,18 @@ } } - public void handle(final Event event, boolean newThread) { - if (newThread) { - synchronized (eventListeners) { - for (final Map.Entry<EventHandler<Event>, EventConstraint> entry : eventListeners.entrySet()) { - if (entry.getValue().accepts(event)) { - new Thread() { - public void run() { - entry.getKey().handle(event); - } - }.start(); - } + public void handleWithNewThread(final Event event) { + synchronized (eventListeners) { + for (final Map.Entry<EventHandler<Event>, EventConstraint> entry : eventListeners.entrySet()) { + if (entry.getValue().accepts(event)) { + new Thread() { + public void run() { + entry.getKey().handle(event); + } + }.start(); } } } - else { - handle(event); - } } public void dispatch(final Event event) { Modified: csidex/trunk/src/main/java/edu/asu/commons/event/EventHandler.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/event/EventHandler.java 2009-10-19 20:55:44 UTC (rev 303) +++ csidex/trunk/src/main/java/edu/asu/commons/event/EventHandler.java 2009-10-19 21:03:43 UTC (rev 304) @@ -22,6 +22,6 @@ * @param event * @param newThread */ - public void handle(E event, boolean newThread); + public void handleWithNewThread(E event); } Modified: csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeChannel.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeChannel.java 2009-10-19 20:55:44 UTC (rev 303) +++ csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeChannel.java 2009-10-19 21:03:43 UTC (rev 304) @@ -123,18 +123,9 @@ if (event == null) return; defaultDispatcher.dispatch(event); } - - public void handle(Event event, boolean newThread) { - if (event == null) return; - if (newThread) { - threadedDispatcher.dispatch(event); - } - else { - sequentialDispatcher.dispatch(event); - } - } - public void handleInThread(Event event) { + public void handleWithNewThread(Event event) { + if (event == null) return; threadedDispatcher.dispatch(event); } Modified: csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeProcessor.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeProcessor.java 2009-10-19 20:55:44 UTC (rev 303) +++ csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeProcessor.java 2009-10-19 21:03:43 UTC (rev 304) @@ -47,7 +47,8 @@ /** * Override this method to handle in the same thread of execution invoking EventChannel.handle(someEvent); - * Otherwise, override handleInExperimentThread() to add a new command to the list. + * Otherwise, override handleInExperimentThread() to queue a new command to be processed serially by the + * experiment. */ public void handle(final E event) { experiment.schedule(new Command() { @@ -57,17 +58,12 @@ }); } - public void handle(final E event, boolean newThread) { - if (newThread) { - new Thread() { - public void run() { - handle(event); - } - }.start(); - } - else { - handle(event); - } + public void handleWithNewThread(final E event) { + new Thread() { + public void run() { + handle(event); + } + }.start(); } public void handleInExperimentThread(E event) { Modified: csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java 2009-10-19 20:55:44 UTC (rev 303) +++ csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java 2009-10-19 21:03:43 UTC (rev 304) @@ -108,7 +108,6 @@ public synchronized Event readEvent() throws IOException, ClassNotFoundException { // return SocketDispatcherWorker.readEvent(socket); - return (Event) cachedIn.readObject(); } @@ -125,7 +124,7 @@ } private void requestDisconnection(Exception exception) { - dispatcher.getLocalEventHandler().handle(new DisconnectionRequest(id, exception), true); + dispatcher.getLocalEventHandler().handleWithNewThread(new DisconnectionRequest(id, exception)); } public void run() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <al...@us...> - 2009-10-19 20:55:51
|
Revision: 303 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=303&view=rev Author: alllee Date: 2009-10-19 20:55:44 +0000 (Mon, 19 Oct 2009) Log Message: ----------- fixed stupid bug with JScrollPane not updating its scrollbars properly after instructions were set on the HtmlEditorPane view, was caused by a setPreferredSize(400, 400) call on the HtmlEditorPane. Modified Paths: -------------- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-19 19:56:28 UTC (rev 302) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-19 20:55:44 UTC (rev 303) @@ -59,7 +59,7 @@ private HtmlEditorPane instructionsEditorPane; - private JPanel tokenScreenPanel = null; + private JPanel investTokensPanel = null; private JPanel graphPanel; @@ -99,24 +99,8 @@ private JLabel quizMessageLabel; - private JLabel quizAnimationLabel = new JLabel(); - private int pagesTraversed = 0; - private JPanel animationInstructionPanel; - - private JPanel animationPanel; - - private JPanel navigationAnimationPanel; - - private JButton nextAnimationButton; - - private JButton previousAnimationButton; - - private HtmlEditorPane animationInstructionsEditorPane; - - private JScrollPane animationInstructionsScrollPane; - private JPanel pieChartPanel; private PieChart pieChart; @@ -141,7 +125,7 @@ setLayout(cardLayout); instructionsScrollPane = new JScrollPane(getInstructionsEditorPane()); - instructionsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); + instructionsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); instructionsScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); // create a quiz listener and then initialize the instructions. instructionsEditorPane.setActionListener(createQuizListener(clientDataModel.getServerConfiguration())); @@ -151,37 +135,30 @@ addToCardLayout(getInstructionsPanel()); irrigationGamePanel = new IrrigationGamePanel(screenSize, client); addToCardLayout(irrigationGamePanel); - // add any other panels that need to be switched to.. - // FIXME: see if we can simplify the number of instructions panes that Sanket has created. -// addToCardLayout(getInstructionsEditorPane()); + addToCardLayout(getInvestTokensPanel()); } private void addToCardLayout(Component component) { add(component, component.getName()); } - private JPanel getTokenScreenPanel() { - if (tokenScreenPanel == null) { - tokenScreenPanel = new JPanel(); - tokenScreenPanel.setLayout(new BorderLayout()); + private JPanel getInvestTokensPanel() { + if (investTokensPanel == null) { + investTokensPanel = new JPanel(); + investTokensPanel.setName("Invest tokens panel"); + investTokensPanel.setLayout(new BorderLayout()); tokenInstructionsEditorPane = createInstructionsEditorPane(); tokenInstructionsScrollPane = new JScrollPane(tokenInstructionsEditorPane); - tokenScreenPanel.add(tokenInstructionsScrollPane, BorderLayout.CENTER); - //setInstructions(getGeneralInstructions(11)); - // StringBuilder tokenSubmissionInstructionsBuilder = new StringBuilder("<h3>The current infrastructure efficiency is: "); - // - // tokenSubmissionInstructionsBuilder.append("% </h3>"); - // tokenSubmissionInstructionsBuilder.append( - StringBuilder tokenSubmissionInstructionsBuilder = new StringBuilder(getGeneralInstructions(11, pagesTraversed)); - tokenInstructionsEditorPane.setText(tokenSubmissionInstructionsBuilder.toString()); + investTokensPanel.add(tokenInstructionsScrollPane, BorderLayout.CENTER); + tokenInstructionsEditorPane.setText(clientDataModel.getServerConfiguration().getInvestmentInstructions()); tokenInstructionsEditorPane.setCaretPosition(0); tokenInstructionsEditorPane.repaint(); - tokenScreenPanel.add(getSubmitTokenPanel(), BorderLayout.SOUTH); - tokenScreenPanel.add(infrastructureEfficiencyLabel, BorderLayout.NORTH); - tokenScreenPanel.setBackground(Color.WHITE); + investTokensPanel.add(getSubmitTokenPanel(), BorderLayout.SOUTH); + investTokensPanel.add(infrastructureEfficiencyLabel, BorderLayout.NORTH); + investTokensPanel.setBackground(Color.WHITE); } updateInfrastructureEfficiencyLabel(); - return tokenScreenPanel; + return investTokensPanel; } public void updateInfrastructureEfficiencyLabel() { @@ -299,93 +276,6 @@ return nextButton; } - private JPanel getAnimationInstructionPanel() { - if (animationInstructionPanel == null) { - animationInstructionPanel = new JPanel(); - animationInstructionPanel.setName("Animated instruction panel"); - animationInstructionPanel.setLayout(new BorderLayout()); - animationInstructionPanel.add(getAnimationPanel(), BorderLayout.CENTER); - - animationInstructionPanel.add(getNavigationAnimationPanel(), BorderLayout.PAGE_END); - animationInstructionPanel.setBackground(Color.WHITE); - return animationInstructionPanel; - } - //System.out.println("instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); - animationInstructionsEditorPane.setText(getGeneralInstructions(instructionNumber,pagesTraversed)); - return animationInstructionPanel; - } - - - private JPanel getNavigationAnimationPanel() { - if (navigationAnimationPanel == null) { - navigationAnimationPanel = new JPanel(); - navigationAnimationPanel.setName("Navigation animation panel"); - navigationAnimationPanel.setLayout(new BorderLayout()); - navigationAnimationPanel.add(getNextAnimationButton(), BorderLayout.EAST); - navigationAnimationPanel.add(getPreviousAnimationButton(), BorderLayout.WEST); - - quizAnimationLabel.setText(""); - navigationAnimationPanel.add(quizAnimationLabel, BorderLayout.CENTER); - } - return navigationAnimationPanel; - } - - private JButton getPreviousAnimationButton() { - if (previousAnimationButton == null) { - previousAnimationButton = new JButton(); - previousAnimationButton.setText("Previous"); - previousAnimationButton.setEnabled(true); - previousAnimationButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - quizMessageLabel.setText(""); - // getting the next instruction Number - nextButton.setEnabled(true); - if (instructionNumber > 1) { - instructionNumber--; - } - previousButton.setEnabled( instructionNumber > 1 ); - setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); - addCenterComponent(getInstructionsPanel()); - } - }); - } - return previousAnimationButton; - } - - private JButton getNextAnimationButton() { - if (nextAnimationButton == null) { - nextAnimationButton = new JButton(); - nextAnimationButton.setText("Next"); - nextAnimationButton.setEnabled(false); - nextAnimationButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - quizMessageLabel.setText(""); - previousButton.setEnabled(true); - if(instructionNumber >= pagesTraversed) - nextButton.setEnabled(false); - // getting the next instruction Number - if (instructionNumber != NUMBER_INSTRUCTIONS) { - instructionNumber++; - } - System.out.println("instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); - setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); - // FIXME: horrifyingly hard coded - if(instructionNumber == 5) { - //addCenterComponent(getTokenScreenPanel()); - getInstructionsPanel().add(getCanalAnimationPanel(), BorderLayout.PAGE_START); - } - else { - getInstructionsPanel().remove(getCanalAnimationPanel()); -// addCenterComponent(getInstructionsPanel()); - } - validate(); - } - }); - } - return nextAnimationButton; - - } - private JPanel getCanalAnimationPanel() { if (canalAnimationPanel == null) { canalAnimationPanel = new CanalAnimationPanel(40); @@ -393,30 +283,6 @@ return canalAnimationPanel; } - private JPanel getAnimationPanel() { - if (animationPanel == null) { - animationPanel = new JPanel(); - animationPanel.setName("Animation panel"); - animationPanel.setLayout(new BorderLayout()); - //FIXME: Here the animation panel needs to be decided on fly - canalAnimationPanel = new CanalAnimationPanel(40); - animationPanel.add(canalAnimationPanel,BorderLayout.CENTER); - animationInstructionsEditorPane = createInstructionsEditorPane(); - animationInstructionsScrollPane = new JScrollPane(animationInstructionsEditorPane); - animationInstructionsEditorPane.setActionListener(createQuizListener(clientDataModel.getServerConfiguration())); - animationInstructionsEditorPane.setCaretPosition(0); - animationPanel.add(animationInstructionsScrollPane, BorderLayout.SOUTH); - //setInstructions(getGeneralInstructions(11)); - //System.out.println("instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); - animationInstructionsEditorPane.setText(getGeneralInstructions(instructionNumber,pagesTraversed)); - animationInstructionsEditorPane.setCaretPosition(0); - animationInstructionsEditorPane.repaint(); - animationPanel.setBackground(Color.WHITE); - } - return animationPanel; - } - - /** * This returns the string of general instructions from the irrigation.xml file * where the general instructions are stored @@ -425,7 +291,7 @@ * @return */ private String getGeneralInstructions(int pageNumber, int pagesTraversed) { - return clientDataModel.getServerConfiguration().getGeneralInstructions(pageNumber, pagesTraversed, client.getClientDataModel().getPriority()); + return clientDataModel.getServerConfiguration().getGeneralInstructions(pageNumber, pagesTraversed, clientDataModel.getPriority()); } private String getGeneralInstructions(int pageNumber) { @@ -476,7 +342,7 @@ investedTokensTextField.setText(""); instructionsBuilder.delete(0, instructionsBuilder.length()); instructionsBuilder.append("\nPlease enter your tokens within the range 0 - 10"); - instructionsBuilder.append(getGeneralInstructions(11,pagesTraversed)); + instructionsBuilder.append(clientDataModel.getServerConfiguration().getInvestmentInstructions()); tokenInstructionsEditorPane.setText(instructionsBuilder.toString()); } } @@ -484,8 +350,7 @@ investedTokensTextField.setText(""); instructionsBuilder.delete(0, instructionsBuilder.length()); instructionsBuilder.append("\nYou only have between 0 and 10 to invest. Please choose a number between 0 and 10 and try again."); - instructionsBuilder.append(getGeneralInstructions(11,pagesTraversed)); -// setInstructions(instructionsBuilder.toString()); + instructionsBuilder.append(clientDataModel.getServerConfiguration().getInvestmentInstructions()); tokenInstructionsEditorPane.setText(instructionsBuilder.toString()); } } @@ -502,7 +367,6 @@ private HtmlEditorPane createInstructionsEditorPane() { HtmlEditorPane htmlEditorPane = new HtmlEditorPane(); - htmlEditorPane.setPreferredSize(new Dimension(400, 400)); htmlEditorPane.setEditable(false); htmlEditorPane.setFont(new Font("serif", Font.PLAIN, 12)); return htmlEditorPane; @@ -522,6 +386,7 @@ // repaint(); // } // currentCenterComponent = newCenterComponent; + revalidate(); repaint(); } @@ -561,7 +426,9 @@ investedTokensTextField.setText(""); addDebriefingText(event); // generate debriefing text from data culled from the Event - addCenterComponent(instructionsEditorPane); +// addCenterComponent(instructionsEditorPane); + // FIXME: this is probably wrong. + addCenterComponent(getInstructionsPanel()); } }; try { @@ -668,135 +535,110 @@ public void run() { instructionsEditorPane.setText(instructions); instructionsEditorPane.setCaretPosition(0); - instructionsScrollPane.requestFocusInWindow(); - ExperimentGameWindow.this.repaint(); + instructionsScrollPane.revalidate(); } }); } private ActionListener createQuizListener(final ServerConfiguration configuration) { return new ActionListener() { + private Map<String, String> quizAnswers = configuration.getQuizAnswers(); public void actionPerformed(ActionEvent e){ // System.err.println("In action performed with event: " + e); FormActionEvent formEvent = (FormActionEvent) e; - Properties actualAnswers = formEvent.getData(); - System.out.println("Form data"+formEvent.getData().toString()); - // actualAnswers.list(System.err); + Properties responses = formEvent.getData(); List<String> incorrectAnswers = new ArrayList<String>(); - // iterate through expected answers - for (Map.Entry<String, String> entry : configuration.getQuizAnswers().entrySet()) { - //here just check those questions that come in those instructions - - String questionNumber = entry.getKey(); - String expectedAnswer = entry.getValue(); - - //System.out.println("Actual answer"+actualAnswers.getProperty(questionNumber)); - switch(instructionNumber){ - case 1: - if(questionNumber.equalsIgnoreCase("q1")){ - //System.out.println("Entering the string equal"); - incorrectAnswers = addIncorrectAnswerList(expectedAnswer,actualAnswers,questionNumber, incorrectAnswers); + responses.list(System.err); + for (Map.Entry<Object, Object> entry : responses.entrySet()) { + String questionNumber = (String) entry.getKey(); + if (questionNumber.charAt(0) == 'q') { + String response = (String) entry.getValue(); + String correctAnswer = quizAnswers.get(questionNumber); + if (! response.equals(correctAnswer)) { + incorrectAnswers.add(questionNumber); + } } - break; - - case 2: if(questionNumber.equalsIgnoreCase("q2")){ - //System.out.println("Entering the string equal"); - incorrectAnswers = addIncorrectAnswerList(expectedAnswer,actualAnswers,questionNumber, incorrectAnswers); - } - break; - - case 3: if(questionNumber.equalsIgnoreCase("q3") || questionNumber.equalsIgnoreCase("q4") ){ - //System.out.println("Entering the string equal"); - incorrectAnswers = addIncorrectAnswerList(expectedAnswer,actualAnswers,questionNumber, incorrectAnswers); - } - break; - - case 4: if(questionNumber.equalsIgnoreCase("q5")){ - //System.out.println("Entering the string equal"); - incorrectAnswers = addIncorrectAnswerList(expectedAnswer,actualAnswers,questionNumber, incorrectAnswers); - } - break; - - case 5: if(questionNumber.equalsIgnoreCase("q6") || questionNumber.equalsIgnoreCase("q7") ){ - //System.out.println("Entering the string equal"); - incorrectAnswers = addIncorrectAnswerList(expectedAnswer,actualAnswers,questionNumber, incorrectAnswers); - } - break; - - case 6: if(questionNumber.equalsIgnoreCase("q8")){ - //System.out.println("Entering the string equal"); - incorrectAnswers = addIncorrectAnswerList(expectedAnswer,actualAnswers,questionNumber, incorrectAnswers); - } - break; - case 7: if(questionNumber.equalsIgnoreCase("q9") || questionNumber.equalsIgnoreCase("q10") ){ - //System.out.println("Entering the string equal"); - incorrectAnswers = addIncorrectAnswerList(expectedAnswer,actualAnswers,questionNumber, incorrectAnswers); - } - break; - - case 8: if(questionNumber.equalsIgnoreCase("q11")){ - //System.out.println("Entering the string equal"); - incorrectAnswers = addIncorrectAnswerList(expectedAnswer,actualAnswers,questionNumber, incorrectAnswers); - System.out.println("Expected question"+questionNumber); - System.out.println("Expected Answer"+expectedAnswer); - } - break; - } - } +// +// +// // iterate through expected answers +// for (Map.Entry<String, String> entry : configuration.getQuizAnswers().entrySet()) { +// // just check those questions that come in those instructions +// String questionNumber = entry.getKey(); +// String expectedAnswer = entry.getValue(); +// +// switch(instructionNumber){ +// case 1: +// if(questionNumber.equalsIgnoreCase("q1")) { +// incorrectAnswers = addIncorrectAnswerList(expectedAnswer,responses,questionNumber, incorrectAnswers); +// } +// break; +// case 2: +// if(questionNumber.equalsIgnoreCase("q2")){ +// incorrectAnswers = addIncorrectAnswerList(expectedAnswer,responses,questionNumber, incorrectAnswers); +// } +// break; +// case 3: +// if(questionNumber.equalsIgnoreCase("q3") || questionNumber.equalsIgnoreCase("q4") ) { +// incorrectAnswers = addIncorrectAnswerList(expectedAnswer,responses,questionNumber, incorrectAnswers); +// } +// break; +// case 4: +// if(questionNumber.equalsIgnoreCase("q5")) { +// incorrectAnswers = addIncorrectAnswerList(expectedAnswer,responses,questionNumber, incorrectAnswers); +// } +// break; +// +// case 5: if(questionNumber.equalsIgnoreCase("q6") || questionNumber.equalsIgnoreCase("q7") ){ +// //System.out.println("Entering the string equal"); +// incorrectAnswers = addIncorrectAnswerList(expectedAnswer,responses,questionNumber, incorrectAnswers); +// } +// break; +// +// case 6: if(questionNumber.equalsIgnoreCase("q8")){ +// //System.out.println("Entering the string equal"); +// incorrectAnswers = addIncorrectAnswerList(expectedAnswer,responses,questionNumber, incorrectAnswers); +// } +// break; +// case 7: if(questionNumber.equalsIgnoreCase("q9") || questionNumber.equalsIgnoreCase("q10") ){ +// //System.out.println("Entering the string equal"); +// incorrectAnswers = addIncorrectAnswerList(expectedAnswer,responses,questionNumber, incorrectAnswers); +// } +// break; +// +// case 8: if(questionNumber.equalsIgnoreCase("q10")){ +// //System.out.println("Entering the string equal"); +// incorrectAnswers = addIncorrectAnswerList(expectedAnswer,responses,questionNumber, incorrectAnswers); +// System.out.println("Expected question"+questionNumber); +// System.out.println("Expected Answer"+expectedAnswer); +// } +// break; +// } +// +// } printIncorrectAnswerList(incorrectAnswers); if (incorrectAnswers.isEmpty()) { nextButton.setEnabled(true); - if(instructionNumber == 5){ - nextAnimationButton.setEnabled(true); - quizAnimationLabel.setForeground(Color.BLUE); - quizAnimationLabel.setText(" Congratulations, your answer is correct. You may go to the next instructions page by clicking 'Next'"); - } - pagesTraversed++; //System.out.println("quiz :instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); - if(instructionNumber == 5) { - addCenterComponent(getAnimationInstructionPanel()); - } - else { - addCenterComponent(getInstructionsPanel()); - } + addCenterComponent(getInstructionsPanel()); quizMessageLabel.setForeground(Color.BLUE); - quizMessageLabel.setText(" Congratulations, your answer is correct. You may go to the next page by clicking 'Next'"); + quizMessageLabel.setText("You answered the question(s) correctly. Please continue to the next page by clicking 'Next'"); // notify the server and also notify the participant. //StringBuilder builder = new StringBuilder(configuration.getInstructions()); //builder.append("<br><b>Congratulations!</b> You have answered all questions correctly."); //setInstructions(builder.toString()); client.transmit(new QuizCompletedEvent(client.getId(),instructionNumber)); - } else { - if(instructionNumber == 5) { - quizAnimationLabel.setForeground(Color.RED); - quizAnimationLabel.setText(" Sorry, your answer is incorrect. Please try again."); - } nextButton.setEnabled(false); quizMessageLabel.setForeground(Color.RED); - quizMessageLabel.setText(" Sorry, your answer is incorrect. Please try again."); - // FIXME: highlight the incorrect answers? - //StringBuilder builder = new StringBuilder().append(instructionsBuilder); - //builder.append("<br><b><font color='red'>You have answered some questions incorrectly. Please try again and resubmit.</font></b>"); - //setInstructions(builder.toString()); + quizMessageLabel.setText("You did not answer the question(s) correctly. Please try again."); } } - private List<String> addIncorrectAnswerList(String expectedAnswer, Properties actualAnswers, String questionNumber, List<String> incorrectAnswers) { - // TODO Auto-generated method stub - if (! expectedAnswer.equals(actualAnswers.getProperty(questionNumber)) ) { - // flag the incorrect response - incorrectAnswers.add(questionNumber); - } - return incorrectAnswers; - } - private void printIncorrectAnswerList(List<String> incorrectAnswers) { - // TODO Auto-generated method stub System.out.println("Size of the incorrect answers is :"+incorrectAnswers.size()); for(int i=0;i<incorrectAnswers.size();i++){ System.out.println("Incorrect Answers :"+incorrectAnswers.get(i)); @@ -810,10 +652,8 @@ totalContributedTokensPerGroup = clientData.getGroupDataModel().getTotalContributedTokens(); contributionInformationTextArea = new JTextArea(); contributionInformationTextArea.setEditable(false); - - // adding the Contribution Status Information to the Text Area DecimalFormat df = new DecimalFormat("#.##"); - String contributionInformation = + final String contributionInformation = "Initial infrastructure efficiency: " + clientData.getGroupDataModel().getInitialInfrastructureEfficiency() + "%" + "\n\nInitial flow capacity: " + clientData.getGroupDataModel().getInitialFlowCapacity() + " cubic feet per second " + "\n\nActual infrastructure efficiency: " + clientData.getGroupDataModel().getInfrastructureEfficiency() + "%" @@ -830,11 +670,10 @@ + " cubic feet per second"; - contributionInformationTextArea.setText(contributionInformation); Runnable runnable = new Runnable() { public void run() { - + contributionInformationTextArea.setText(contributionInformation); } }; @@ -884,7 +723,7 @@ // has begun. /*roundEndsOn = (configuration.getRoundTime() * 1000L) + System.currentTimeMillis(); update();*/ - addCenterComponent(getTokenScreenPanel()); + addCenterComponent(getInvestTokensPanel()); getInvestedTokensTextField().requestFocusInWindow(); } }; @@ -937,7 +776,7 @@ final long timeRemaining = endTime - System.currentTimeMillis(); if (timeRemaining < 0) { sleep(); - addCenterComponent(getTokenScreenPanel()); + addCenterComponent(getInvestTokensPanel()); getInvestedTokensTextField().requestFocusInWindow(); timer.stop(); timer = null; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <al...@us...> - 2009-10-19 19:56:40
|
Revision: 302 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=302&view=rev Author: alllee Date: 2009-10-19 19:56:28 +0000 (Mon, 19 Oct 2009) Log Message: ----------- fixing some bugs related to threading of the event channel and connection management. Here's what the flow of the bug looks like: 1. client breaks connection 2. server doesn't realize that the client has broken the connection until it tries to write to that socket 3. transmitting an event to all clients used to occur in a single thread of execution. 4. while transmitting the event (say a ShowInstructionsRequest), a DisconnectionRequest bubbles up out of the csidex framework. 5. Since the event is asking to be handled in the same thread of execution, it still has acquired the same locks necessary to modify the clients map. So the disconnection request modifies the clients map while we are iterating through the clients map. Hence, a ConcurrentModificationException occurs. 6. Server dies, everyone goes home. The fix for this is to make sure that all DisconnectionRequests get handled in a separate thread execution so that thread will block while trying to acquire a lock on the clients map. Perhaps a better fix for this is just to by default always run each event handler in a separate thread of execution but for performance sake we have been avoiding that. So now there is an additional boolean parameter in EventHandler.handle() that allows you to specify whether or not you want to run each handler in a separate thread of execution. Modified Paths: -------------- csidex/trunk/src/main/java/edu/asu/commons/event/AbstractEvent.java csidex/trunk/src/main/java/edu/asu/commons/event/EventConstraintChannel.java csidex/trunk/src/main/java/edu/asu/commons/event/EventHandler.java csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeChannel.java csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeProcessor.java csidex/trunk/src/main/java/edu/asu/commons/net/AbstractServerDispatcher.java csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java Modified: csidex/trunk/src/main/java/edu/asu/commons/event/AbstractEvent.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/event/AbstractEvent.java 2009-10-19 18:58:17 UTC (rev 301) +++ csidex/trunk/src/main/java/edu/asu/commons/event/AbstractEvent.java 2009-10-19 19:56:28 UTC (rev 302) @@ -16,9 +16,9 @@ private final static long serialVersionUID = -3443360054002127621L; - protected final Identifier id; + protected Identifier id; protected long creationTime; - private final String message; + protected String message; public AbstractEvent() { this(Identifier.NULL); Modified: csidex/trunk/src/main/java/edu/asu/commons/event/EventConstraintChannel.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/event/EventConstraintChannel.java 2009-10-19 18:58:17 UTC (rev 301) +++ csidex/trunk/src/main/java/edu/asu/commons/event/EventConstraintChannel.java 2009-10-19 19:56:28 UTC (rev 302) @@ -39,8 +39,8 @@ /** * Adds an event to the EventChannel which then propagates the event to - * all interested subscribers. EventHandler.handle(Event) is invoked in a separate - * thread of execution. + * all interested subscribers. EventHandler.handle(Event) is invoked in a + * single separate thread of execution. * * @param event The event to distribute via this EventChannel. */ @@ -58,6 +58,25 @@ } } + public void handle(final Event event, boolean newThread) { + if (newThread) { + synchronized (eventListeners) { + for (final Map.Entry<EventHandler<Event>, EventConstraint> entry : eventListeners.entrySet()) { + if (entry.getValue().accepts(event)) { + new Thread() { + public void run() { + entry.getKey().handle(event); + } + }.start(); + } + } + } + } + else { + handle(event); + } + } + public void dispatch(final Event event) { handle(event); } Modified: csidex/trunk/src/main/java/edu/asu/commons/event/EventHandler.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/event/EventHandler.java 2009-10-19 18:58:17 UTC (rev 301) +++ csidex/trunk/src/main/java/edu/asu/commons/event/EventHandler.java 2009-10-19 19:56:28 UTC (rev 302) @@ -17,4 +17,11 @@ */ public void handle(E event); + /** + * Handles the given Event in a new thread of execution. + * @param event + * @param newThread + */ + public void handle(E event, boolean newThread); + } Modified: csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeChannel.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeChannel.java 2009-10-19 18:58:17 UTC (rev 301) +++ csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeChannel.java 2009-10-19 19:56:28 UTC (rev 302) @@ -19,6 +19,9 @@ new HashMap<Object, List<EventProcessor>>(); private final EventDispatcher defaultDispatcher; + + private final ThreadedDispatcher threadedDispatcher = new ThreadedDispatcher(); + private final SequentialDispatcher sequentialDispatcher = new SequentialDispatcher(); public final static EventTypeChannel INSTANCE = new EventTypeChannel(); @@ -32,10 +35,10 @@ public EventTypeChannel(boolean shouldThread) { if (shouldThread) { - defaultDispatcher = new ThreadedDispatcher(); + defaultDispatcher = threadedDispatcher; } else { - defaultDispatcher = new SequentialDispatcher(); + defaultDispatcher = sequentialDispatcher; } } @@ -120,9 +123,19 @@ if (event == null) return; defaultDispatcher.dispatch(event); } + + public void handle(Event event, boolean newThread) { + if (event == null) return; + if (newThread) { + threadedDispatcher.dispatch(event); + } + else { + sequentialDispatcher.dispatch(event); + } + } public void handleInThread(Event event) { - new ThreadedDispatcher().dispatch(event); + threadedDispatcher.dispatch(event); } public void dispatch(Event event) { @@ -156,13 +169,35 @@ } } - private class ThreadedDispatcher extends SequentialDispatcher { + private class ThreadedDispatcher implements EventDispatcher { public void dispatch(final Event event) { - new Thread() { - public void run() { - ThreadedDispatcher.super.dispatch(event); + final Class<? extends Event> eventClass = event.getClass(); + // first check handlers that want this and only this event type. + synchronized (equalTypesEventProcessorMap) { + List<EventProcessor> handlers = equalTypesEventProcessorMap.get(eventClass); + if (handlers != null) { + for (final EventProcessor<Event> handler: handlers) { + new Thread() { + public void run() { + handler.handle(event); + } + }.start(); + } } - }.start(); + } + // next, check to see if this event should be processed by the subtype processors. + synchronized (acceptsSubtypesEventProcessors) { + for (final EventProcessor<Event> handler: acceptsSubtypesEventProcessors) { + if (handler.getEventClass().isInstance(event)) { + new Thread() { + public void run() { + handler.handle(event); + } + }.start(); + } + } + } + } } } Modified: csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeProcessor.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeProcessor.java 2009-10-19 18:58:17 UTC (rev 301) +++ csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeProcessor.java 2009-10-19 19:56:28 UTC (rev 302) @@ -57,6 +57,19 @@ }); } + public void handle(final E event, boolean newThread) { + if (newThread) { + new Thread() { + public void run() { + handle(event); + } + }.start(); + } + else { + handle(event); + } + } + public void handleInExperimentThread(E event) { throw new UnsupportedOperationException("Override handleInExperimentThread and make sure you do NOT override handle(E) if you want to use single-threaded event handling."); } Modified: csidex/trunk/src/main/java/edu/asu/commons/net/AbstractServerDispatcher.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/net/AbstractServerDispatcher.java 2009-10-19 18:58:17 UTC (rev 301) +++ csidex/trunk/src/main/java/edu/asu/commons/net/AbstractServerDispatcher.java 2009-10-19 19:56:28 UTC (rev 302) @@ -104,18 +104,26 @@ logger.info(getClass() + " listening on port:" + port); try { bind(port); - listening = true; - while ( listening ) { - processIncomingConnections(); - // disconnect any pending disconnected clients and so on. - performConnectionMaintenance(); - } } catch (IOException e) { e.printStackTrace(); - logger.severe("unrecoverable IOException: " + e); + logger.severe(String.format("Couldn't bind to port %d due to exception [%s] - shutting down.", port, e)); shutdown(); + return; } + listening = true; + while ( listening ) { + try { + processIncomingConnections(); + // disconnect any pending disconnected clients + performConnectionMaintenance(); + } + catch (IOException e) { + e.printStackTrace(); + logger.severe("IO Exception while processing incoming connections: " + e); + } + + } } }; } Modified: csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java 2009-10-19 18:58:17 UTC (rev 301) +++ csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java 2009-10-19 19:56:28 UTC (rev 302) @@ -75,7 +75,6 @@ public void write(Event event) { try { - // FIXME: consider caching the object output stream? synchronized (socket) { // ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); // out.writeObject(event); @@ -126,7 +125,7 @@ } private void requestDisconnection(Exception exception) { - dispatcher.getLocalEventHandler().handle(new DisconnectionRequest(id, exception)); + dispatcher.getLocalEventHandler().handle(new DisconnectionRequest(id, exception), true); } public void run() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <al...@us...> - 2009-10-19 18:58:27
|
Revision: 301 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=301&view=rev Author: alllee Date: 2009-10-19 18:58:17 +0000 (Mon, 19 Oct 2009) Log Message: ----------- finished adding the rest of the general instructions, still need to fill in screenshots. More refactoring on the client GUI as well, general instructions are almost complete. Modified Paths: -------------- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ClientDataModel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/RegistrationEvent.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/FacilitatorWindow.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/IrrigationServer.java irrigation/trunk/src/main/resources/configuration/asu-fall-2009/irrigation.xml Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ClientDataModel.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ClientDataModel.java 2009-10-17 22:23:23 UTC (rev 300) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ClientDataModel.java 2009-10-19 18:58:17 UTC (rev 301) @@ -1,6 +1,3 @@ -/** - * - */ package edu.asu.commons.irrigation.client; import java.util.ArrayList; @@ -32,13 +29,15 @@ private GroupDataModel groupDataModel; private IrrigationClient client; - + + private ServerConfiguration serverConfiguration; private RoundConfiguration roundConfiguration; private int timeLeft = 0; public ClientDataModel(EventChannel channel, IrrigationClient client) { this.client = client; + this.serverConfiguration = client.getServerConfiguration(); } public ClientData getClientData() { @@ -85,12 +84,11 @@ } public ServerConfiguration getServerConfiguration() { - return roundConfiguration.getParentConfiguration(); + return serverConfiguration; } public void setGroupDataModel(GroupDataModel groupDataModel) { this.groupDataModel = groupDataModel; - setRoundConfiguration(groupDataModel.getRoundConfiguration()); } public GroupDataModel getGroupDataModel() { Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-17 22:23:23 UTC (rev 300) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-19 18:58:17 UTC (rev 301) @@ -41,6 +41,8 @@ * $Id$ * * The root experiment window placed in the client's JFrame. + * + * FIXME: refactor this class. * * @author <a href='mailto:All...@as...'>Allen Lee</a> * @version $Rev$ @@ -50,6 +52,8 @@ private static final long serialVersionUID = -5636795631355367711L; private ClientDataModel clientDataModel; + + private ChatPanel chatPanel; private JScrollPane instructionsScrollPane; @@ -249,7 +253,7 @@ // FIXME: get rid of hardcoded animation on page 5. Should instead // just be an animated gif or something like that. // should be more like "if instructions.hasAnimation()" - if(instructionNumber == 5) { + if (instructionNumber == 5) { getInstructionsPanel().add(getCanalAnimationPanel(), BorderLayout.PAGE_START); } else { @@ -421,12 +425,11 @@ * @return */ private String getGeneralInstructions(int pageNumber, int pagesTraversed) { - return clientDataModel.getServerConfiguration().getGeneralInstructions(pageNumber, pagesTraversed, client.getClientDataModel().getPriority()); } private String getGeneralInstructions(int pageNumber) { - return client.getServerConfiguration().getGeneralInstructions(pageNumber); + return clientDataModel.getServerConfiguration().getGeneralInstructions(pageNumber); } private JTextField getInvestedTokensTextField() { @@ -645,7 +648,7 @@ "showup fee, for a grand total of $%3.2f", (float)dollarsPerToken*clientData.getTotalTokensEarned(), (float)dollarsPerToken*clientData.getTotalTokens(), - (float)dollarsPerToken*clientData.getTotalTokens() + client.getServerConfiguration().getShowUpPayment() + (float)dollarsPerToken*clientData.getTotalTokens() + clientDataModel.getServerConfiguration().getShowUpPayment() )); //append the added practice round instructions if(clientDataModel.getRoundConfiguration().isPracticeRound()) { @@ -665,7 +668,8 @@ public void run() { instructionsEditorPane.setText(instructions); instructionsEditorPane.setCaretPosition(0); - instructionsScrollPane.requestFocusInWindow(); + instructionsScrollPane.requestFocusInWindow(); + ExperimentGameWindow.this.repaint(); } }); } @@ -900,7 +904,6 @@ addCenterComponent(getInstructionsPanel()); } - private ChatPanel chatPanel; private ChatPanel getChatPanel() { if (chatPanel == null) { chatPanel = new ChatPanel(); Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java 2009-10-17 22:23:23 UTC (rev 300) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java 2009-10-19 18:58:17 UTC (rev 301) @@ -69,7 +69,7 @@ public IrrigationClient(EventChannel channel, ServerConfiguration serverConfiguration) { this.channel = channel; - this.serverConfiguration = serverConfiguration; + setServerConfiguration(serverConfiguration); this.clientDispatcher = DispatcherFactory.getInstance().createClientDispatcher(channel); } @@ -158,9 +158,12 @@ } private void initEventProcessors() { + // registration events are sent before the start of each round and contain the configuration + // for that round, including all instructions, parameters, for that round. channel.add(this, new EventTypeProcessor<RegistrationEvent>(RegistrationEvent.class) { public void handle(RegistrationEvent event) { RoundConfiguration configuration = event.getRoundConfiguration(); + clientDataModel.setGroupDataModel(event.getClientData().getGroupDataModel()); clientDataModel.setRoundConfiguration(configuration); experimentGameWindow.updateRoundInstructions(configuration); } @@ -224,7 +227,7 @@ public ServerConfiguration getServerConfiguration() { return serverConfiguration; } - + public void setServerConfiguration(ServerConfiguration serverConfiguration) { this.serverConfiguration = serverConfiguration; } Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java 2009-10-17 22:23:23 UTC (rev 300) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java 2009-10-19 18:58:17 UTC (rev 301) @@ -65,10 +65,9 @@ } /** - * getting the general welcome instructions + * Returns the appropriate general instructions text, performing logic for adding + * positions and quizzes. * - * FIXME: Refactor this method. - * * @param instructionPageNumber * @param pagesTraversed * @return @@ -150,5 +149,9 @@ public String getFinalInstructions() { return assistant.getProperty("final-instructions", "<b>The experiment is now over. Thanks for participating!</b>"); } + + public String getInvestmentInstructions() { + return assistant.getProperty("investment-instructions"); + } } Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/RegistrationEvent.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/RegistrationEvent.java 2009-10-17 22:23:23 UTC (rev 300) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/RegistrationEvent.java 2009-10-19 18:58:17 UTC (rev 301) @@ -17,15 +17,25 @@ private RoundConfiguration roundConfiguration; private final ClientData clientData; - public RegistrationEvent(Identifier target, RoundConfiguration configuration) { - this(target, configuration, null); + /** + * Constructor used by the facilitator, which doesn't need any ClientData objects. + * + * @param id + * @param roundConfiguration + */ + public RegistrationEvent(Identifier id, RoundConfiguration roundConfiguration) { + this(id, roundConfiguration, null); } - public RegistrationEvent(Identifier target, RoundConfiguration roundConfiguration, ClientData clientData) { - super(target, roundConfiguration.getInstructions()); - this.roundConfiguration = roundConfiguration; + public RegistrationEvent(Identifier id, RoundConfiguration roundConfiguration, ClientData clientData) { + super(id, roundConfiguration.getInstructions()); this.clientData = clientData; } + + public RegistrationEvent(ClientData clientData, RoundConfiguration roundConfiguration) { + this(clientData.getId(), roundConfiguration, clientData); + this.roundConfiguration = roundConfiguration; + } public RoundConfiguration getRoundConfiguration() { return roundConfiguration; Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/FacilitatorWindow.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/FacilitatorWindow.java 2009-10-17 22:23:23 UTC (rev 300) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/FacilitatorWindow.java 2009-10-19 18:58:17 UTC (rev 301) @@ -1,6 +1,3 @@ -/** - * - */ package edu.asu.commons.irrigation.facilitator; import java.awt.BorderLayout; @@ -33,13 +30,12 @@ */ public class FacilitatorWindow extends JPanel { + private static final long serialVersionUID = 3607885359444962888L; + private Facilitator facilitator; private Dimension windowDimension; - private static final long serialVersionUID = 1L; - - private JButton startRoundButton = null; private JButton beginChatButton; @@ -47,7 +43,7 @@ private HtmlEditorPane editorPane; private JScrollPane scrollPane; - private JButton enableInstructionButton; + private JButton showInstructionsButton; /** * This is the default constructor */ @@ -58,15 +54,7 @@ initialize(); } - /* - public IrrigationFacilitatorWindow(){ - super(); - initialize(); - } - */ - /** - * This method initializes this * * @return void */ @@ -77,7 +65,7 @@ buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS)); buttonPanel.add(getStartRoundButton()); buttonPanel.add(getBeginChatButton()); - buttonPanel.add(getEnableInstructionButton()); + buttonPanel.add(getShowInstructionsButton()); add(buttonPanel, BorderLayout.NORTH); JPanel informationPanel = new JPanel(); editorPane = new HtmlEditorPane(); @@ -86,18 +74,17 @@ add(informationPanel, BorderLayout.CENTER); } - private JButton getEnableInstructionButton() { - // TODO Auto-generated method stub - if (enableInstructionButton == null) { - enableInstructionButton = new JButton("Enable Instruction"); - enableInstructionButton.addActionListener(new ActionListener() { + private JButton getShowInstructionsButton() { + if (showInstructionsButton == null) { + showInstructionsButton = new JButton("Show Instructions"); + showInstructionsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { - enableInstructionButton.setEnabled(false); +// enableInstructionButton.setEnabled(false); facilitator.transmit(new ShowInstructionsRequest(facilitator.getId())); } }); } - return enableInstructionButton; + return showInstructionsButton; } /** @@ -124,7 +111,7 @@ return beginChatButton; } - public Facilitator getFacilitator(){ + public Facilitator getFacilitator() { return facilitator; } @@ -143,9 +130,8 @@ startRoundButton = new JButton(); startRoundButton.setBounds(new Rectangle(180, 16, 136, 24)); startRoundButton.setText("Start Round"); - startRoundButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed() + startRoundButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { facilitator.sendBeginRoundRequest(); } }); Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/IrrigationServer.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/IrrigationServer.java 2009-10-17 22:23:23 UTC (rev 300) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/IrrigationServer.java 2009-10-19 18:58:17 UTC (rev 301) @@ -186,13 +186,13 @@ clients.put(identifier, clientData); serverDataModel.addClient(clientData); } - transmit(new RegistrationEvent(clientData.getId(), getRoundConfiguration(), clientData)); + transmit(new RegistrationEvent(clientData, getRoundConfiguration())); } }); addEventProcessor(new EventTypeProcessor<DisconnectionRequest>(DisconnectionRequest.class) { @Override public void handle(DisconnectionRequest request) { - getLogger().warning("irrigation server is disconnecting: " + request); + getLogger().warning("irrigation server handling disconnection request: " + request); Identifier disconnectedClientId = request.getId(); synchronized (clients) { clients.remove(disconnectedClientId); @@ -239,8 +239,8 @@ addEventProcessor(new EventTypeProcessor<QuizCompletedEvent>(QuizCompletedEvent.class) { @Override public void handle(QuizCompletedEvent event) { - getLogger().info("Quiz Completed Event:"+event.getId()+" : instruction Number"+event.getInstructionNumber()); numberOfCompletedQuizzes++; + getLogger().info("Completed quizzes: " + numberOfCompletedQuizzes); if(numberOfCompletedQuizzes == clients.size()*8){ getLogger().info("Everyone has finished reading the general instructions successfully"); } @@ -392,9 +392,11 @@ // need to send instructions //Send the end round event to the facilitator //Send the end round event to all the clients - for (ClientData data : clients.values()) { - data.award(); - transmit(new EndRoundEvent(data.getId(), data.getGroupDataModel(), getConfiguration().isLastRound())); + synchronized (clients) { + for (ClientData data : clients.values()) { + data.award(); + transmit(new EndRoundEvent(data.getId(), data.getGroupDataModel(), getConfiguration().isLastRound())); + } } transmit(new FacilitatorEndRoundEvent(facilitatorId, serverDataModel)); @@ -406,13 +408,15 @@ private void cleanupRound() { // reset client data values - for (ClientData clientData: clients.values()) { - if (getConfiguration().getCurrentParameters().isPracticeRound()) { - clientData.resetAllTokens(); + synchronized (clients) { + for (ClientData clientData: clients.values()) { + if (getConfiguration().getCurrentParameters().isPracticeRound()) { + clientData.resetAllTokens(); + } + else { + clientData.reset(); + } } - else { - clientData.reset(); - } } submittedClients = 0; persister.clear(); @@ -425,19 +429,21 @@ RoundConfiguration nextRoundConfiguration = getConfiguration().nextRound(); serverDataModel.setRoundConfiguration(nextRoundConfiguration); // set up the next round - if (nextRoundConfiguration.shouldRandomizeGroup()) { - serverDataModel.clear(); - List<ClientData> clientDataList = new ArrayList<ClientData>(clients.values()); - // randomize the client data list - Collections.shuffle(clientDataList); - // re-add each the clients to the server data model - for (ClientData data: clientDataList) { - serverDataModel.addClient(data); + synchronized (clients) { + if (nextRoundConfiguration.shouldRandomizeGroup()) { + serverDataModel.clear(); + List<ClientData> clientDataList = new ArrayList<ClientData>(clients.values()); + // randomize the client data list + Collections.shuffle(clientDataList); + // re-add each the clients to the server data model + for (ClientData data: clientDataList) { + serverDataModel.addClient(data); + } + } + // send registration events to all participants. + for (ClientData data: clients.values()) { + transmit(new RegistrationEvent(data, nextRoundConfiguration)); } - } - // send registration events to all participants. - for (ClientData data: clients.values()) { - transmit(new RegistrationEvent(data.getId(), nextRoundConfiguration, data)); } // send new round configuration to the facilitator transmit(new RegistrationEvent(facilitatorId, nextRoundConfiguration)); Modified: irrigation/trunk/src/main/resources/configuration/asu-fall-2009/irrigation.xml =================================================================== --- irrigation/trunk/src/main/resources/configuration/asu-fall-2009/irrigation.xml 2009-10-17 22:23:23 UTC (rev 300) +++ irrigation/trunk/src/main/resources/configuration/asu-fall-2009/irrigation.xml 2009-10-19 18:58:17 UTC (rev 301) @@ -32,7 +32,7 @@ <entry key="wait-for-participants">true</entry> <entry key="number-of-rounds">22</entry> -<entry key="undisrupted-bandwidth">true</entry> +<entry key="undisrupted-flow-required">true</entry> <entry key="q1">4</entry> <entry key="q2">identity</entry> @@ -41,12 +41,37 @@ <entry key="q5">4</entry> <entry key="q6">5</entry> <entry key="q7">25</entry> -<entry key="q8">4</entry> -<entry key="q9">25</entry> -<entry key="q10">30</entry> -<entry key="q11">1.50</entry> +<entry key="q8">7</entry> +<entry key="q9">19</entry> +<entry key="q10">1.50</entry> +<entry key='final-instructions'> +<![CDATA[ +<p> +The experiment is almost over. We have a brief survey for you to fill out while the +facilitator prepares your payments. When the facilitator has finished preparing +payments and you have all completed your surveys your computer number will be +called. You can then go next door to receive your payment. For privacy reasons we +must pay you one at a time. +</p> +<p> +Thanks for participating! +</p> +]]> +</entry> + +<entry key="initial-instructions"> +<![CDATA[ +<h3>Welcome</h3> +<p> +Please be patient while the experimental environment is set up. +<b>Please do not close this window or open any other windows.</b> +</p> +]]> +</entry> + + <entry key="facilitator-instructions"> <![CDATA[ <h3>Facilitator Instructions</h3> @@ -125,18 +150,27 @@ <entry key="general-instructions2"> <![CDATA[ <h3>Chat</h3> -<p>Each round will start with a chat period of 40 seconds where you can send text -messages to the other participants. You may discuss any aspect of the exercise. -<b>However</b>, you are <b>not allowed</b> to promise the other participants +<p>Before each round you will have a chat period of 40 seconds where you can send +text messages to the other participants. You may discuss any aspect of the exercise +with two important exceptions: +</p> +<ol> +<li>You are <b>not allowed</b> to promise the other participants side-payments or threaten them with any consequence after the experiment is -finished. You are also <b>not allowed</b> to reveal your real identity. We will be -monitoring the chat traffic. If we see any member of a group violating the rules, -we will have to remove that <b>entire group</b> from the experiment room. That -group will have to wait until the entire experiment is finished to receive -their payment.<br><br> - +finished. +</li> +<li>You are <b>not allowed to reveal your real identity</b>.</li> +</ol> +<p> +We will be monitoring the chat traffic. If we detect any violation of these rules, +we will have to remove <b>all members of the group where the violation occurred</b> +from the experiment. That group will have to wait until the entire experiment is +finished to receive their payment. +</p> +<p> You will see a text box appear on your screen when a chat period starts. The amount of time left in the chat period will be shown at the <b>top left of the screen</b>.<br> +</p> ]]> </entry> @@ -160,20 +194,20 @@ <![CDATA[ <h3>Creating Irrigation Infrastructure</h3> <p> -At the beginning of each round you and each other participant will be given 10 -tokens. You must then decide what to do with these tokens. You may decide to invest -in the irrigation infrastructure or to keep the tokens. If you keep the tokens you -will earn at a minimum 10 tokens X 5 cents = $0.50 for each round. If you do this -every round after twenty rounds you will end up with at least $10 (plus any crops -that you may be able to grow as we will discuss later). Your total earnings for -participating in the experiment would then be at least $10 plus your show-up fee of -$5, for a grand total of at least $15. +After the chat period ends you and each other participant will be given 10 tokens. +You must then decide what to do with these tokens. You may decide to invest in the +irrigation infrastructure or to keep the tokens. If you keep the tokens you will +earn at a minimum 10 tokens X 5 cents = $0.50 for each round. If you do this every +round after twenty rounds you will end up with at least $10 (plus any crops that you +may be able to grow as we will discuss later). Your total earnings for +participating in the experiment would then be at least $10 plus your show-up payment +of $5, for a grand total of at least $15. </p> <p> On the other hand, if you invest some of your tokens in the irrigation infrastructure, you may be able to earn more than this amount by growing crops. If -the irrigation infrastructure is operating at near maximum capacity you can grow a -large crop and earn $1.50 each round. If you grow crops you can roughly triple your +the irrigation infrastructure is operating at near maximum capacity you can earn +close to $1.50 each round. Thus if you grow crops you can roughly triple your earnings compared to doing nothing. The actual earnings depend on the decisions you and the other participants in your group make in terms of investment and when to grow crops. @@ -238,7 +272,7 @@ <th>Water delivery (cubic feet per second)</th> </thead> <tr> -<td> ≤ 45</td><td>0</td> +<td>≤ 45</td><td>0</td> </tr> <tr> <td>46-51</td><td>5</td> @@ -350,9 +384,12 @@ <entry key="general-instructions5"> <![CDATA[ <h3>Positions A,B,C,D and E</h3> -<p> The animation above illustrates how water flows to each player when their gates are opened and closed. When a player opens -their gate, the black line will rotate to a vertical position, allowing water (represented by white balls) to flow to them. -Note that the available bandwidth downstream of a player with an open port is reduced (illustrated by narrowing of the canal). +<p> +The animation above illustrates how water flows to each player when their gates are +opened and closed. When a player opens their gate, the black line will rotate to a +vertical position, allowing water (represented by white dots) to flow to them. Note +that the water available downstream of a player with an open port is reduced, +illustrated by a narrowing of the canal. </p> <p> Access to water depends on your position as shown in the window. Water originates @@ -361,24 +398,21 @@ participant A is then available to be used by participant B. Water not used by participants A and B is then available for C. Water not used by participants A, B and C is available for D. Finally, water not used by participants A, B, C and D is -available for E. You can only start growing a crop if you have water available to -your position. If water runs out during the growing period of the crop, the partial -grown crop is lost, and you need to start from scratch again. Water can run out if, -for example, one or more people upstream from your position open their gates. <b>You -can only grow a crop successfully when you have access to water for a number of -seconds without disruptions.</b> +available for E. </p> <p> -Assume that the total irrigation capacity available is 40 cfps. If player A opens -their gate, they will take 25 cfps from the canal, leaving 15 cfps for B and -everyone else downstream. If A does not open the gate however, then a total of 40 -cfps is left for B and everyone else downstream. +You can only get water to your field if you have water available to your position. +Suppose that the total irrigation capacity available is 40 cfps and 40 cfps of water +is available. If player A opens their gate they will consume 25 cfps of water and 15 +cfps is left for B. Suppose on the other hand, A does not open the gate, then a +total of 40 cfps is left for B, allowing B to extract water at the maximum rate of +25 cfps. </p> <p> -As another example, suppose that the canal system has been allowed to deteriorate so -that the total irrigation capacity available is 20 cfps. While player A's gate is -open, no water is available for B. If A is NOT using water, 20 cfps is available -for B. +As another example, suppose that the canal system has been allowed to deteriorate +so that the total irrigation capacity available is 20 cfps. While player A’s gate is +open, no water is available for B. If A is NOT using water, 20 cfps is available for +B. </p> ]]> </entry> @@ -388,14 +422,23 @@ <br><br> To continue to the next page, please answer the following question:<br> <form> -What is the minimum time to deliver 500 cubic feet to your field when your maximum -water flow capacity is available? +Suppose the irrigation efficiency is between 71 and 80% so that the canal flow +capacity is 30 cfps. If A opens their gate and diverts water at 25 cfps what is the +available water flow for B? <br> -<input type="radio" name="q6" value="12.5">12.5 seconds<br> -<input type="radio" name="q6" value="20">20 seconds<br> -<input type="radio" name="q6" value="25">25 seconds<br> -<input type="radio" name="q6" value="50">50 seconds<br> +<input type="radio" name="q6" value="30">30 cfps<br> +<input type="radio" name="q6" value="25">25 cfps<br> +<input type="radio" name="q6" value="15">15 cfps<br> +<input type="radio" name="q6" value="5">5 cfps<br> <br><br> +If the canal flow capacity available is 25 cfps and A,B,C and D are not using water, +what is the available water for E? +<br> +<input type="radio" name="q7" value="40">40 cfps<br> +<input type="radio" name="q7" value="25">25 cfps<br> +<input type="radio" name="q7" value="15">15 cfps<br> +<input type="radio" name="q7" value="0">0 cfps<br> + <input type="submit" name="submit" value="Submit"> <br><br> </form> @@ -405,21 +448,88 @@ <entry key="general-instructions6"> <![CDATA[ <h3>How to grow crops</h3> -<p>To start growing crops, click on one of the boxes labeled "Grow this crop".<br> <p> -<img src = "http://sod19.asu.edu/irrigation/images/fileScreenShotNew.JPG"><br> +To start growing crops, click on the yellow button labeled "open gate". +This will open your irrigation gate and allow water to flow to your field if it is +available. The text on the button will change to "close gate" - if +you would like to close the gate and stop extracting water from the canal, just +click on the yellow button again. Your gate will close and the text on the button +will change back to "open gate". </p> -The crop receiving water will turn red. When the crop is successfully grown and -harvested it the box will turn green. If water becomes unavailable for a period of -5 seconds after starting to grow a crop, the crop will be lost and you will have to -click the button again to re-irrigate that crop. -<br> -The percentage of the water needed for the crop at any point in time is indicated by the progress bar <br> -<img src = "http://sod19.asu.edu/irrigation/images/fileProgressBarScreenShot.JPG"><br> <p> -You cannot grow multiple crops at the same time. -<img src = "http://sod19.asu.edu/irrigation/images/pauseButtonScreenShot.JPG"><br> +The amount of water units (cubic feet) your field has received is shown on the +screen, as well as the resulting amount of tokens earned from growing a crop. +The number of tokens earned in each round depends on how much water you have +diverted to your field. If you receive less than 150 cubic feet (cf) the crop has +not received enough water to grow a crop and you will thus not receive any tokens. +The maximum earnings are received when between 500 cf and 549 cf are diverted to +your field. If more than 549 cf water is diverted to your field, this will +negatively affect the growth of the crop (i.e. overwatering) and less tokens will be +earned. In the table below you can see the amount of tokens earned for amount of +water applied to your field. </p> +<b>Table 2</b>: Earnings resulting from the amount of water applied to your field. + +<table border="1" cellspacing="2" cellpadding="2"> +<thead> +<th>Water units received (cubic feet)</th> +<th>Tokens earned</th> +</thead> +<tr> +<td>< 150</td><td>0</td> +</tr> +<tr> +<td>150-199</td><td>1</td> +</tr> +<tr> +<td>200-249</td><td>4</td> +</tr> +<tr> +<td>250-299</td><td>10</td> +</tr> +<tr> +<td>300-349</td><td>15</td> +</tr> +<tr> +<td>350-399</td><td>18</td> +</tr> +<tr> +<td>400-499</td><td>19</td> +</tr> +<tr> +<td>500-549</td><td>20</td> +</tr> +<tr> +<td>550-649</td><td>19</td> +</tr> +<tr> +<td>650-699</td><td>18</td> +</tr> +<tr> +<td>700-749</td><td>15</td> +</tr> +<tr> +<td>750-799</td><td>10</td> +</tr> +<tr> +<td>800-849</td><td>4</td> +</tr> +<tr> +<td>850-899</td><td>1</td> +</tr> +<tr> +<td>> 899</td><td>0</td> +</tr> +</table> + +Your earnings at the end of the round depend on your investment and the number of +tokens received for the crop. For example, suppose you invest 6 out of the 10 +tokens you are endowed with at the start of the round and you receive 333 cubic feet +of water. Your total earnings will be the amount of tokens leftover from your +initial endowment (10 - 6) plus the tokens you earned from your crop (15 tokens for +333 cubic feet of water, see Table 2). The total number of tokens earned is 19 +($0.85 since each token is $0.05). + ]]> </entry> @@ -428,12 +538,20 @@ <br><br> To continue to the next page, please answer the following question:<br> <form> -If there are 4 green boxes and one red box, how many crops have you grown and harvested successfully?<br> -<input type="radio" name="q8" value="1">1<br> +If you invest 7 of the 10 tokens you started with, and you put 202 cf of water on +your field, what is the total number of tokens you will have earned for that round? +<input type="radio" name="q8" value="3">3<br> <input type="radio" name="q8" value="4">4<br> -<input type="radio" name="q8" value="5">5<br> -<input type="radio" name="q8" value="10">10<br> +<input type="radio" name="q8" value="7">7<br> +<input type="radio" name="q8" value="13">13<br> <br><br> +If you invest all 10 tokens you start with, and you put 555 cf of water on your +field, what is the total number of tokens your will have earned for that round? +<input type="radio" name="q9" value="10">10<br> +<input type="radio" name="q9" value="19">19<br> +<input type="radio" name="q9" value="20">20<br> +<input type="radio" name="q9" value="29">29<br> +<br><br> <input type="submit" name="submit" value="Submit"> </form> ]]> @@ -441,44 +559,20 @@ <entry key="general-instructions7"> <![CDATA[ -<h3>Earnings</h3> -<p>The number of tokens earned in each round depends on how many crops have been grown and harvested in that round. -The earnings reflect the net profit of growing crops, taking into account the costs -of fertilization, labor, and equipment. The first few crops you grow don't generate -any net profit in terms of tokens earned because your costs must be covered first. -You must have grown at last two crops before you cover your fixed costs and begin to -generate tokens as shown in the following graph. -</p> +<h3>Scores</h3> +<p> +The total number of tokens collected during a round is shown on the screen with the +message: +<br><br> +Total tokens earned this round: 0 +<br><br> +This the total of tokens not invested in irrigation structure plus additional +tokens earned by growing a crop. <br> -<img src = "http://sod19.asu.edu/irrigation/images/fileTokenGraphScreenShot.JPG"><br> -<p> -The amount of tokens earned by growing crops files can also be represented as the following table. -</p> -<table border="1" cellspacing="2" cellpadding="2"> -<tr> - <td>Number of crops grown</td> - <td>0</td> - <td>1</td> - <td>2</td> - <td>3</td> - <td>4</td> - <td>5</td> -</tr> -<tr> - <td>Tokens earned</td> - <td>0</td> - <td>0</td> - <td>6</td> - <td>22</td> - <td>28</td> - <td>30</td> -</tr> -</table> -Your earnings at the end of the round depend on your investment and the number of crops grown. -Recall that you get 10 tokens to start with. Suppose you invest 6 tokens in the irrigation -infrastructure and you grow 4 crops. You would have earned 28 tokens from your -crops, added to your leftover tokens, i.e., 28 + (10-6) = 32 tokens. Each token is -worth 5 cents, translating to an actual dollar amount of $1.60.<br> +You will also see the scores of the other participants summarized on the screen. +Finally, you will see the water flow capacity of each player at any given moment, as +illustrated in the figure below. + ]]> </entry> @@ -488,85 +582,50 @@ <br><br> To continue to the next page, please answer the following question:<br> <form> -If you invest 7 tokens out of the 10 tokens you start with, and you grow 3 crops, how many total tokens would you have earned that round? +Each token is worth 5 cents, thus if you collected 30 tokens in a round you earned: <br> -<input type="radio" name="q9" value="3">3<br> -<input type="radio" name="q9" value="7">7<br> -<input type="radio" name="q9" value="22">22<br> -<input type="radio" name="q9" value="25">25<br> +<input type="radio" name="q10" value=".15">$0.15<br> +<input type="radio" name="q10" value=".50">$0.50<br> +<input type="radio" name="q10" value="1.50">$1.50<br> +<input type="radio" name="q10" value="2.50">$2.50<br> <br><br> - -If you invest 10 tokens out of the 10 tokens you start with, and you grow 5 crops, how many total tokens would you have earned that round? -<br> -<input type="radio" name="q10" value="10">10<br> -<input type="radio" name="q10" value="20">20<br> -<input type="radio" name="q10" value="25">25<br> -<input type="radio" name="q10" value="30">30<br> -<br><br> <input type="submit" name="submit" value="Submit"> <br><br> </form> ]]> </entry> -<entry key="general-instructions8"> +<entry key="general-instructionsq9"> <![CDATA[ -<h3>Scores</h3> -<p>The total number of tokens collected during the experiment is shown as:<br> <p> -<img src = "http://sod19.asu.edu/irrigation/images/tokensCollectedScreenShot.JPG"><br> +We will now start with two practice rounds. This practice round will not contribute to your earnings – +it is intended to acquaint you with the functioning of the exercise environment. </p> -This is the total of tokens not invested in irrigation infrastructure plus the -additional tokens you've earned by growing crops<br> -You can see the scores of the other participants summarized on the screen. You can -also see the percentage of each player's water being used at any given moment, -as illustrated in the figure below. <p> -<img src = "http://sod19.asu.edu/irrigation/images/scoreScreenShotNew.JPG"><br> +You will first chat via text with other participants in your group for 40 seconds, +then decide how much you wish to invest in irrigation infrastructure +maintenance. After all investment decisions have been made you will begin the +actual round and make real-time decisions on when to open your gates and irrigate +your fields. </p> -]]> -</entry> - -<entry key="general-instructionsq8"> -<![CDATA[ -<br><br> -To continue to the next page, please answer the following question:<br> -<form> -Each token is worth 5 cents. If you collected 30 tokens in a round you would have earned:<br> -<input type="radio" name="q11" value="0.15">0.15<br> -<input type="radio" name="q11" value="0.50">0.50<br> -<input type="radio" name="q11" value="1.50">1.50<br> -<input type="radio" name="q11" value="2.50">2.50<br> -<br><br> -<input type="submit" name="submit" value="Submit"> -</form> -]]> -</entry> - -<entry key="general-instructionsq9"> -<![CDATA[ -We will now start with two practice rounds. This practice round will not contribute to your earnings – -it is intended to acquaint you with the functioning of the exercise environment.<br><br> - +<p> If you have any questions feel free to raise your hand and to ask your question. <b>Do you have any questions so far?</b> +</p> ]]> </entry> -<entry key="general-instructions-undisruptedBandwidth"> +<entry key="undisrupted-flow-instructions"> <![CDATA[ -<br> -You can only start downloading a file if you have bandwidth available at your position. If the bandwidth connection -is broken during the downloading of a file, the downloaded part of the file is lost, and you need to start from scratch -again to download this file. The bandwidth connection can be broken if, for example, one or more people to the left of -your position starts downloading files, using up the all available bandwidth. Only when you have continuous access to -bandwidth without disruptions for a length of time sufficient to download an entire file can you download a file -successfully. +<p> +If the flow of water is disrupted while your gate is open your crop growing progress +will be halted. +</p> ]]> </entry> -<entry key="general-instructions11"> +<entry key="investment-instructions"> <![CDATA[ <h3>Invest tokens in the irrigation infrastructure</h3> <p> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: Kalin J. <kj...@as...> - 2009-10-18 20:35:46
|
I haven't been able to make any changes that improved the program today. It seems that the list of locations is somehow not being passed down the list of elements anymore. I have not been able to dynamically get the list of locations from server. Signing off at 13:30pm (2.5hr) On Sun, Oct 18, 2009 at 11:03 AM, Kalin Jonas <kj...@as...> wrote: > Working from home at 11:00am > I'm working on receiving the round from server, currently > > > On Sat, Oct 17, 2009 at 4:17 PM, Kalin Jonas <kj...@as...> wrote: > >> I have tested the program with three, four, and five students at a time, >> and have not been seeing the error that used to pop up. >> I'm looking into the code for getting the round, and trying to fix that so >> that it stops making the errors pop up. >> signing out for the day at 16:00pm (3hr) >> >> >> On Sat, Oct 17, 2009 at 1:12 PM, Kalin Jonas <kj...@as...> wrote: >> >>> I'm logging in from home today at 13:00pm (slept in) >>> I will be checking to see if the problem is solved with >>> DayByDayDecisions. >>> I notice that I am still not getting information windows from the server >>> properly. >>> >>> >>> On Fri, Oct 16, 2009 at 2:49 PM, Kalin Jonas <kj...@as...> wrote: >>> >>>> I have located the source of the error that seema finally sent me a >>>> screenshot of. I have put a check into the program so that it doesn't just >>>> try and load information from an empty arraylist. I'm not sure why it would >>>> try, so I will have to look into that when i have time. >>>> Right now I check out at 14:45 (3.75hr) for class. >>>> >>>> >>>> On Fri, Oct 16, 2009 at 11:23 AM, Allen Lee <All...@as...> wrote: >>>> >>>>> Kalin, you need to be a little more clear about what it is you're >>>>> doing. >>>>> >>>>> On Thu, Oct 15, 2009 at 5:35 PM, Kalin Jonas <kj...@as...> wrote: >>>>> > checking out at 4:45 >>>>> > I'm not 100% sure where the problem is >>>>> > >>>>> > On Thu, Oct 15, 2009 at 3:43 PM, Kalin Jonas <kj...@as...> wrote: >>>>> >> >>>>> >> Working from home at 3:45 >>>>> > >>>>> > >>>>> > >>>>> ------------------------------------------------------------------------------ >>>>> > Come build with us! The BlackBerry(R) Developer Conference in SF, CA >>>>> > is the only developer event you need to attend this year. Jumpstart >>>>> your >>>>> > developing skills, take BlackBerry mobile applications to market and >>>>> stay >>>>> > ahead of the curve. Join us from November 9 - 12, 2009. Register now! >>>>> > http://p.sf.net/sfu/devconference >>>>> > _______________________________________________ >>>>> > Virtualcommons-svn mailing list >>>>> > Vir...@li... >>>>> > https://lists.sourceforge.net/lists/listinfo/virtualcommons-svn >>>>> > >>>>> > >>>>> >>>>> >>>>> >>>>> -- >>>>> Allen Lee >>>>> Center for the Study of Institutional Diversity [http://csid.asu.edu] >>>>> Arizona State University | P.O. Box 872402 | Tempe, Arizona 85287-2402 >>>>> Office: 480.727.0401 | Fax: 480.965.7671 >>>>> >>>> >>>> >>> >> > |
From: Kalin J. <kj...@as...> - 2009-10-18 18:03:44
|
Working from home at 11:00am I'm working on receiving the round from server, currently On Sat, Oct 17, 2009 at 4:17 PM, Kalin Jonas <kj...@as...> wrote: > I have tested the program with three, four, and five students at a time, > and have not been seeing the error that used to pop up. > I'm looking into the code for getting the round, and trying to fix that so > that it stops making the errors pop up. > signing out for the day at 16:00pm (3hr) > > > On Sat, Oct 17, 2009 at 1:12 PM, Kalin Jonas <kj...@as...> wrote: > >> I'm logging in from home today at 13:00pm (slept in) >> I will be checking to see if the problem is solved with DayByDayDecisions. >> I notice that I am still not getting information windows from the server >> properly. >> >> >> On Fri, Oct 16, 2009 at 2:49 PM, Kalin Jonas <kj...@as...> wrote: >> >>> I have located the source of the error that seema finally sent me a >>> screenshot of. I have put a check into the program so that it doesn't just >>> try and load information from an empty arraylist. I'm not sure why it would >>> try, so I will have to look into that when i have time. >>> Right now I check out at 14:45 (3.75hr) for class. >>> >>> >>> On Fri, Oct 16, 2009 at 11:23 AM, Allen Lee <All...@as...> wrote: >>> >>>> Kalin, you need to be a little more clear about what it is you're doing. >>>> >>>> On Thu, Oct 15, 2009 at 5:35 PM, Kalin Jonas <kj...@as...> wrote: >>>> > checking out at 4:45 >>>> > I'm not 100% sure where the problem is >>>> > >>>> > On Thu, Oct 15, 2009 at 3:43 PM, Kalin Jonas <kj...@as...> wrote: >>>> >> >>>> >> Working from home at 3:45 >>>> > >>>> > >>>> > >>>> ------------------------------------------------------------------------------ >>>> > Come build with us! The BlackBerry(R) Developer Conference in SF, CA >>>> > is the only developer event you need to attend this year. Jumpstart >>>> your >>>> > developing skills, take BlackBerry mobile applications to market and >>>> stay >>>> > ahead of the curve. Join us from November 9 - 12, 2009. Register now! >>>> > http://p.sf.net/sfu/devconference >>>> > _______________________________________________ >>>> > Virtualcommons-svn mailing list >>>> > Vir...@li... >>>> > https://lists.sourceforge.net/lists/listinfo/virtualcommons-svn >>>> > >>>> > >>>> >>>> >>>> >>>> -- >>>> Allen Lee >>>> Center for the Study of Institutional Diversity [http://csid.asu.edu] >>>> Arizona State University | P.O. Box 872402 | Tempe, Arizona 85287-2402 >>>> Office: 480.727.0401 | Fax: 480.965.7671 >>>> >>> >>> >> > |
From: Kalin J. <kj...@as...> - 2009-10-17 23:17:40
|
I have tested the program with three, four, and five students at a time, and have not been seeing the error that used to pop up. I'm looking into the code for getting the round, and trying to fix that so that it stops making the errors pop up. signing out for the day at 16:00pm (3hr) On Sat, Oct 17, 2009 at 1:12 PM, Kalin Jonas <kj...@as...> wrote: > I'm logging in from home today at 13:00pm (slept in) > I will be checking to see if the problem is solved with DayByDayDecisions. > I notice that I am still not getting information windows from the server > properly. > > > On Fri, Oct 16, 2009 at 2:49 PM, Kalin Jonas <kj...@as...> wrote: > >> I have located the source of the error that seema finally sent me a >> screenshot of. I have put a check into the program so that it doesn't just >> try and load information from an empty arraylist. I'm not sure why it would >> try, so I will have to look into that when i have time. >> Right now I check out at 14:45 (3.75hr) for class. >> >> >> On Fri, Oct 16, 2009 at 11:23 AM, Allen Lee <All...@as...> wrote: >> >>> Kalin, you need to be a little more clear about what it is you're doing. >>> >>> On Thu, Oct 15, 2009 at 5:35 PM, Kalin Jonas <kj...@as...> wrote: >>> > checking out at 4:45 >>> > I'm not 100% sure where the problem is >>> > >>> > On Thu, Oct 15, 2009 at 3:43 PM, Kalin Jonas <kj...@as...> wrote: >>> >> >>> >> Working from home at 3:45 >>> > >>> > >>> > >>> ------------------------------------------------------------------------------ >>> > Come build with us! The BlackBerry(R) Developer Conference in SF, CA >>> > is the only developer event you need to attend this year. Jumpstart >>> your >>> > developing skills, take BlackBerry mobile applications to market and >>> stay >>> > ahead of the curve. Join us from November 9 - 12, 2009. Register now! >>> > http://p.sf.net/sfu/devconference >>> > _______________________________________________ >>> > Virtualcommons-svn mailing list >>> > Vir...@li... >>> > https://lists.sourceforge.net/lists/listinfo/virtualcommons-svn >>> > >>> > >>> >>> >>> >>> -- >>> Allen Lee >>> Center for the Study of Institutional Diversity [http://csid.asu.edu] >>> Arizona State University | P.O. Box 872402 | Tempe, Arizona 85287-2402 >>> Office: 480.727.0401 | Fax: 480.965.7671 >>> >> >> > |
From: <al...@us...> - 2009-10-17 22:23:31
|
Revision: 300 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=300&view=rev Author: alllee Date: 2009-10-17 22:23:23 +0000 (Sat, 17 Oct 2009) Log Message: ----------- minor hygiene, referring to client data model instead of client primarily Modified Paths: -------------- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ClientDataModel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ClientDataModel.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ClientDataModel.java 2009-10-16 23:02:53 UTC (rev 299) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ClientDataModel.java 2009-10-17 22:23:23 UTC (rev 300) @@ -10,6 +10,7 @@ import edu.asu.commons.event.EventChannel; import edu.asu.commons.experiment.DataModel; import edu.asu.commons.irrigation.conf.RoundConfiguration; +import edu.asu.commons.irrigation.conf.ServerConfiguration; import edu.asu.commons.irrigation.events.ClientUpdateEvent; import edu.asu.commons.irrigation.events.RoundStartedEvent; import edu.asu.commons.irrigation.server.ClientData; @@ -34,8 +35,6 @@ private RoundConfiguration roundConfiguration; - private int priority = 0; - private int timeLeft = 0; public ClientDataModel(EventChannel channel, IrrigationClient client) { @@ -60,15 +59,8 @@ setTimeLeft( (int) (getRoundConfiguration().getRoundDuration().getDelta() / 1000L) ); } - /** - * Setting priority for this client. - */ - public void setPriority(int priority){ - this.priority = priority; - } - public int getPriority(){ - return priority; + return getClientData().getPriority(); } public void update(ClientUpdateEvent clientUpdateEvent) { @@ -92,6 +84,10 @@ this.roundConfiguration = roundConfiguration; } + public ServerConfiguration getServerConfiguration() { + return roundConfiguration.getParentConfiguration(); + } + public void setGroupDataModel(GroupDataModel groupDataModel) { this.groupDataModel = groupDataModel; setRoundConfiguration(groupDataModel.getRoundConfiguration()); Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-16 23:02:53 UTC (rev 299) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-17 22:23:23 UTC (rev 300) @@ -140,7 +140,7 @@ instructionsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); instructionsScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); // create a quiz listener and then initialize the instructions. - instructionsEditorPane.setActionListener(createQuizListener(client.getServerConfiguration())); + instructionsEditorPane.setActionListener(createQuizListener(clientDataModel.getServerConfiguration())); instructionsEditorPane.setCaretPosition(0); setInstructions(getGeneralInstructions(0)); @@ -181,14 +181,14 @@ } public void updateInfrastructureEfficiencyLabel() { - GroupDataModel group = client.getClientDataModel().getGroupDataModel(); - RoundConfiguration roundConfiguration = client.getRoundConfiguration(); + GroupDataModel group = clientDataModel.getGroupDataModel(); + RoundConfiguration roundConfiguration = clientDataModel.getRoundConfiguration(); int infrastructureEfficiency = 0; if (roundConfiguration.isPracticeRound() || roundConfiguration.isFirstRound()) { infrastructureEfficiency = roundConfiguration.getInitialInfrastructureEfficiency(); } else { - System.err.println("group was not null, efficiency is: " + group.getInfrastructureEfficiency() + " degrading by " + client.getRoundConfiguration().getInfrastructureDegradationFactor()); + System.err.println("group was not null, efficiency is: " + group.getInfrastructureEfficiency() + " degrading by " + clientDataModel.getRoundConfiguration().getInfrastructureDegradationFactor()); infrastructureEfficiency = group.getInfrastructureEfficiency() - roundConfiguration.getInfrastructureDegradationFactor(); } infrastructureEfficiencyLabel.setText("Current infrastructure efficiency: " + infrastructureEfficiency); @@ -399,7 +399,7 @@ animationPanel.add(canalAnimationPanel,BorderLayout.CENTER); animationInstructionsEditorPane = createInstructionsEditorPane(); animationInstructionsScrollPane = new JScrollPane(animationInstructionsEditorPane); - animationInstructionsEditorPane.setActionListener(createQuizListener(client.getServerConfiguration())); + animationInstructionsEditorPane.setActionListener(createQuizListener(clientDataModel.getServerConfiguration())); animationInstructionsEditorPane.setCaretPosition(0); animationPanel.add(animationInstructionsScrollPane, BorderLayout.SOUTH); //setInstructions(getGeneralInstructions(11)); @@ -421,7 +421,8 @@ * @return */ private String getGeneralInstructions(int pageNumber, int pagesTraversed) { - return client.getServerConfiguration().getGeneralInstructions(pageNumber, pagesTraversed, client.getClientDataModel().getPriority()); + + return clientDataModel.getServerConfiguration().getGeneralInstructions(pageNumber, pagesTraversed, client.getClientDataModel().getPriority()); } private String getGeneralInstructions(int pageNumber) { @@ -623,11 +624,11 @@ allClientData[3].getTotalTokensEarned(), allClientData[4].getTotalTokensEarned(), - (float)allClientData[0].getRoundConfiguration().getDollarsPerToken()*allClientData[0].getTotalTokensEarned(), - (float)allClientData[1].getRoundConfiguration().getDollarsPerToken()*allClientData[1].getTotalTokensEarned(), - (float)allClientData[2].getRoundConfiguration().getDollarsPerToken()*allClientData[2].getTotalTokensEarned(), - (float)allClientData[3].getRoundConfiguration().getDollarsPerToken()*allClientData[3].getTotalTokensEarned(), - (float)allClientData[4].getRoundConfiguration().getDollarsPerToken()*allClientData[4].getTotalTokensEarned() + (float)dollarsPerToken*allClientData[0].getTotalTokensEarned(), + (float)dollarsPerToken*allClientData[1].getTotalTokensEarned(), + (float)dollarsPerToken*allClientData[2].getTotalTokensEarned(), + (float)dollarsPerToken*allClientData[3].getTotalTokensEarned(), + (float)dollarsPerToken*allClientData[4].getTotalTokensEarned() /* event.getClientData().getContributedTokens(),otherClientData.getContributedTokens(), @@ -647,12 +648,12 @@ (float)dollarsPerToken*clientData.getTotalTokens() + client.getServerConfiguration().getShowUpPayment() )); //append the added practice round instructions - if(client.getRoundConfiguration().isPracticeRound()) { + if(clientDataModel.getRoundConfiguration().isPracticeRound()) { instructionsBuilder.append(" However, this is a practice round and the earnings mentioned are only for illustrative purposes " + "and will not count towards your actual payments"); } else if (event.isLastRound()) { - instructionsBuilder.append(client.getServerConfiguration().getFinalInstructions()); + instructionsBuilder.append(clientDataModel.getServerConfiguration().getFinalInstructions()); } setInstructions(instructionsBuilder.toString()); } @@ -669,7 +670,6 @@ }); } - private ActionListener createQuizListener(final ServerConfiguration configuration) { return new ActionListener() { public void actionPerformed(ActionEvent e){ @@ -816,13 +816,13 @@ + "\n\nActual total flow capacity: " + df.format(clientData.getGroupDataModel().getMaximumAvailableFlowCapacity()) + " cubic feet per second \n\n" + "\n\nMaximum tokens that could have been contributed: " - + client.getRoundConfiguration().getMaximumTotalInvestedTokens() + + clientDataModel.getRoundConfiguration().getMaximumTotalInvestedTokens() + "\n\nTotal tokens contributed: " + totalContributedTokensPerGroup + "\n\nYour token contribution: " + clientData.getInvestedTokens() + "\n\nTotal flow capacity that could have been generated: " - + client.getRoundConfiguration().getMaximumCanalFlowCapacity() + + clientDataModel.getRoundConfiguration().getMaximumCanalFlowCapacity() + " cubic feet per second"; @@ -853,7 +853,7 @@ private JPanel getPieChartPanel() { if (pieChartPanel == null) { - ClientData clientData = client.getClientDataModel().getClientData(); + ClientData clientData = clientDataModel.getClientData(); pieChartPanel = new JPanel(); xySeriesDemo = new ChartWindowPanelTokenBandwidth(client); xySeriesDemo.setVisible(true); Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java 2009-10-16 23:02:53 UTC (rev 299) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java 2009-10-17 22:23:23 UTC (rev 300) @@ -161,7 +161,7 @@ channel.add(this, new EventTypeProcessor<RegistrationEvent>(RegistrationEvent.class) { public void handle(RegistrationEvent event) { RoundConfiguration configuration = event.getRoundConfiguration(); - setRoundConfiguration(configuration); + clientDataModel.setRoundConfiguration(configuration); experimentGameWindow.updateRoundInstructions(configuration); } }); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: Kalin J. <kj...@as...> - 2009-10-17 20:13:00
|
I'm logging in from home today at 13:00pm (slept in) I will be checking to see if the problem is solved with DayByDayDecisions. I notice that I am still not getting information windows from the server properly. On Fri, Oct 16, 2009 at 2:49 PM, Kalin Jonas <kj...@as...> wrote: > I have located the source of the error that seema finally sent me a > screenshot of. I have put a check into the program so that it doesn't just > try and load information from an empty arraylist. I'm not sure why it would > try, so I will have to look into that when i have time. > Right now I check out at 14:45 (3.75hr) for class. > > > On Fri, Oct 16, 2009 at 11:23 AM, Allen Lee <All...@as...> wrote: > >> Kalin, you need to be a little more clear about what it is you're doing. >> >> On Thu, Oct 15, 2009 at 5:35 PM, Kalin Jonas <kj...@as...> wrote: >> > checking out at 4:45 >> > I'm not 100% sure where the problem is >> > >> > On Thu, Oct 15, 2009 at 3:43 PM, Kalin Jonas <kj...@as...> wrote: >> >> >> >> Working from home at 3:45 >> > >> > >> > >> ------------------------------------------------------------------------------ >> > Come build with us! The BlackBerry(R) Developer Conference in SF, CA >> > is the only developer event you need to attend this year. Jumpstart your >> > developing skills, take BlackBerry mobile applications to market and >> stay >> > ahead of the curve. Join us from November 9 - 12, 2009. Register now! >> > http://p.sf.net/sfu/devconference >> > _______________________________________________ >> > Virtualcommons-svn mailing list >> > Vir...@li... >> > https://lists.sourceforge.net/lists/listinfo/virtualcommons-svn >> > >> > >> >> >> >> -- >> Allen Lee >> Center for the Study of Institutional Diversity [http://csid.asu.edu] >> Arizona State University | P.O. Box 872402 | Tempe, Arizona 85287-2402 >> Office: 480.727.0401 | Fax: 480.965.7671 >> > > |
From: <al...@us...> - 2009-10-16 23:03:08
|
Revision: 299 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=299&view=rev Author: alllee Date: 2009-10-16 23:02:53 +0000 (Fri, 16 Oct 2009) Log Message: ----------- Still cleaning up the initial stages of the experiment, namely the instructions and quiz pages. Next up is to properly deal with the actual experiment interface. Modified Paths: -------------- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalAnimationPanel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChartWindowPanelTokenBandwidth.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationGamePanel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/PieChart.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/RoundConfiguration.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/ClientData.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/GroupDataModel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/IrrigationServer.java Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalAnimationPanel.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalAnimationPanel.java 2009-10-15 00:12:05 UTC (rev 298) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalAnimationPanel.java 2009-10-16 23:02:53 UTC (rev 299) @@ -1,6 +1,7 @@ package edu.asu.commons.irrigation.client; import java.awt.Color; +import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagLayout; @@ -18,100 +19,75 @@ * * FIXME: needs heavy refactoring. * - * @author Sanket + * @author Sanket Joshi + * @author Allen Lee * @version $Rev$ */ public class CanalAnimationPanel extends JPanel { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 2049547253093489218L; - /** - * This is the default constructor - */ - private int x1UpStream; + //private IrrigationClientGameState clientGameState; - private int y1UpStream; + //////////////////animation logic parameters////////////////////////////// + private Timer timer; - private int x2UpStream = 420; + private final int DELAY = 20; - private int y2UpStream = 100; + private Ball balls[]; - private int y2DownStream = 100; + private int BALLCOUNT = 500; - private int x2DownStream = 950; + private Gate gate[] = new Gate[6]; - private int y1DownStream; + private int gateHeight = 20; - private int x1DownStream; + Random generator = new Random(); - private Graphics2D graphics2D; + private boolean enableBallAnimation = true; - private boolean flagDownStream = false; + private double totalContributedBandwidth; - private boolean flagUpStream = false; - - //private IrrigationClientGameState clientGameState; - - //////////////////animation logic parameters////////////////////////////// - private Timer timer; - - private final int DELAY = 20; + private long prev_time; - private Ball balls[]; - - private int BALLCOUNT = 500; - - private Gate gate[] = new Gate[6]; + private int gateCount = 0; - private int gateHeight = 20; - - Random generator = new Random(); + //////////////////////////////////////////////////////////////////////////// - private boolean enableBallAnimation = true; + public CanalAnimationPanel(double totalContributedBandwidth) { + super(); + this.totalContributedBandwidth = totalContributedBandwidth; + initialize(); + } - private double totalContributedBandwidth; + /** + * + * @return void + */ + private void initialize() { + this.setPreferredSize(new Dimension(1098,150)); + this.setLayout(new GridBagLayout()); + this.setBackground(Color.white); + //initializing the constructor for Gates + for(int i=0;i<6;i++){ + gate[i] = new Gate(totalContributedBandwidth,i); + //System.out.println("Gate "+i+"x : "+gate[i].getX()+"y : "+gate[i].getY()); + } - private long prev_time; + initializexy(); - private int gateCount = 0; + timer = new Timer(DELAY, new ReboundListener()); // setup the Timer to do an action + // every DELAY times. + prev_time = System.currentTimeMillis(); + timer.start(); // starts the timer. + } - //////////////////////////////////////////////////////////////////////////// + private void gateReboundListener(){ - public CanalAnimationPanel(double totalContributedBandwidth) { - super(); - this.totalContributedBandwidth = totalContributedBandwidth; - initialize(); - } - - /** - * This method initializes this - * - * @return void - */ - private void initialize() { - this.setSize(1098,150); - this.setLayout(new GridBagLayout()); - this.setBackground(Color.white); - //initializing the constructor for Gates - for(int i=0;i<6;i++){ - gate[i] = new Gate(totalContributedBandwidth,i); - //System.out.println("Gate "+i+"x : "+gate[i].getX()+"y : "+gate[i].getY()); - } - - initializexy(); - - timer = new Timer(DELAY, new ReboundListener()); // setup the Timer to do an action - // every DELAY times. - prev_time = System.currentTimeMillis(); - timer.start(); // starts the timer. - } - - private void gateReboundListener(){ - - openGates(gateCount ); - if(!(gateCount == 0)) - closeGates(gateCount-1); - /*if(!gate[0].isOpenGate() && flagDownStream == false){ + openGates(gateCount ); + if(!(gateCount == 0)) + closeGates(gateCount-1); + /*if(!gate[0].isOpenGate() && flagDownStream == false){ System.out.println("Opening gates"); closeGates(0); openGates(1); @@ -132,435 +108,396 @@ closeGates(0); //closeGates(1); } -*/} - - + */} - protected void paintComponent(Graphics graphics){ - updateGUI(); - super.paintComponent(graphics); // needed! - Graphics2D graphics2D = (Graphics2D)graphics; - this.graphics2D = graphics2D; - this.graphics2D.setColor(Color.BLUE); - this.graphics2D.fillRect(0,0,100,100); - //draw the other gates - for(int i=0;i<5;i++){ - this.graphics2D.setColor(Color.BLUE); - this.graphics2D.fillRect(gate[i].getX(), gate[i].getY(), gate[i].getWidth(),gate[i].getHeight()); - this.graphics2D.fillRect(gate[i].getOpeningsX(), gate[i].getOpeningsY(),gate[i].getOpeningsWidth(), - gate[i].getOpeningsHeight()); - this.graphics2D.setColor(Color.BLACK); - this.graphics2D.drawLine(gate[i].getx1(),gate[i].gety1(),gate[i].getx2(),gate[i].gety2()); - } - this.graphics2D.setColor(Color.BLUE); - this.graphics2D.fillRect(gate[5].getX(), gate[5].getY(),10,gate[5].getHeight()); - //System.out.println("Gate :"+5+" X: "+gate[5].getX()+" Y :"+gate[5].getY()); - - //////////////////////Animation Logic//////////////////////////// - if(enableBallAnimation == true) - { - graphics.setColor(Color.white); - int ballCounter = 0; - for(int i=0;i<BALLCOUNT;i++){ - /*if(!(balls[i].isInServer == false && clientGameState.getGroupDataModel().getMaximumAvailableBandwidth() == 0)){ - if(!(flagDownStream == true && flagUpStream == true && balls[i].x >= 950)) - if(!(flagUpStream == true && clientGameState.getGroupDataModel().getMaximumAvailableBandwidth() <=25 && balls[i].x >=420)){ - if(flagUpStream == true && balls[i].x >=420 && clientGameState.getGroupDataModel().getMaximumAvailableBandwidth() >=25 ){ - if(!(flagDownStream == false && balls[i].y >= 80)) - graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); - } - else{ - - graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); // paints a whole new circle, with changing coords - - } - - } - - } - */ - //System.out.println("ball sposition x :"+balls[i].x+" y:"+balls[i].y); - //get the position information of the ball. and then recheck the condition for height. - if((balls[i].getPosition() == 1)||(balls[i].getPosition() == 2) || (balls[i].getPosition()==3) - || (balls[i].getPosition() == 4) || (balls[i].getPosition() == 5)){ - if(!((!gate[balls[i].getPosition()-1].isOpenGate())&& balls[i].getY() >= (gate[balls[i].getPosition()-1].getY()+gate[balls[i].getPosition()-1].getHeight()))) - graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); - - - } - else{ - if(balls[i].getPosition() != 0){ - if(gate[balls[i].getPosition() - 6].getHeight() != 0) - graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); - } - else{ - graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); - } - } - } - } - - } - - - - private void updateGUI() { - // TODO Auto-generated method stub - for(int i=1;i<6;i++){ - if(gate[i-1].isOpenGate()){ - if(!(gate[i-1].getHeight() - gateHeight < 0)){ - gate[i].setHeight(gate[i-1].getHeight() - gateHeight ); - } - else{ - gate[i].setHeight(0); - } - } - else{ - gate[i].setHeight(gate[i-1].getHeight()); - - } - //order matters here - if(!(i == 5)){ - gate[i].setOpeningsHeight((totalContributedBandwidth*0.8) - - gate[i].getHeight()); - gate[i].setOpeningsY(gate[i].getOpeningsHeight() - 50); - - //opening the lid logic - if(gate[i].isOpenGate()){ - gate[i].setx1(gate[i].getx2()); - if(!(gate[i].gety2()- gate[i].getGateWidth() < gate[i].getY())) - gate[i].sety1(gate[i].gety2()- gate[i].getGateWidth()); - else - gate[i].sety1(gate[i].getOpeningsY()); - } - else{ - gate[i].setx1(gate[i].getdefaultx1()); - gate[i].sety1(gate[i].getdefaulty1()); - } - - if(gate[0].isOpenGate()){ - gate[0].setx1(gate[0].getx2()); - if(!(gate[0].gety2()- gate[0].getGateWidth() < gate[0].getY())) - gate[0].sety1(gate[0].gety2()- gate[0].getGateWidth()); - else - gate[0].sety1(gate[0].getY()); - } - else{ - gate[0].setx1(gate[0].getdefaultx1()); - gate[0].sety1(gate[0].getdefaulty1()); - } - - } - } - } + protected void paintComponent(Graphics graphics){ + updateGUI(); + super.paintComponent(graphics); // needed! + Graphics2D graphics2D = (Graphics2D)graphics; + graphics2D = graphics2D; + graphics2D.setColor(Color.BLUE); + graphics2D.fillRect(0,0,100,100); + //draw the other gates + for(int i=0;i<5;i++){ + graphics2D.setColor(Color.BLUE); + graphics2D.fillRect(gate[i].getX(), gate[i].getY(), gate[i].getWidth(),gate[i].getHeight()); + graphics2D.fillRect(gate[i].getOpeningsX(), gate[i].getOpeningsY(),gate[i].getOpeningsWidth(), + gate[i].getOpeningsHeight()); + graphics2D.setColor(Color.BLACK); + graphics2D.drawLine(gate[i].getx1(),gate[i].gety1(),gate[i].getx2(),gate[i].gety2()); + } - /* - * initialize the Balls - */ - private void initializexy() { - // TODO Auto-generated method stub - balls = new Ball[BALLCOUNT]; - if(balls == null){ - System.out.println("Ball is null"); - } - - for(int i=0;i<BALLCOUNT;i++){ - balls[i] = new Ball(generator); - - } - } + graphics2D.setColor(Color.BLUE); + graphics2D.fillRect(gate[5].getX(), gate[5].getY(),10,gate[5].getHeight()); - // this is the private class the Timer will look at every DELAY seconds - private class ReboundListener implements ActionListener{ - Random generator = new Random(); - public void actionPerformed(ActionEvent e) { - if((System.currentTimeMillis() - prev_time) > 5000){ - //System.out.println("Change the time"); - prev_time = System.currentTimeMillis(); - gateCount++; - if(gateCount > 4) - gateCount = 0; - gateReboundListener(); - } - for(int i=0;i<BALLCOUNT;i++){ - //updateGUI(); - balls[i].x += balls[i].moveX; - balls[i].y += balls[i].moveY; - process(i); - - } - repaint(); - } - } + //////////////////////Animation Logic//////////////////////////// + // FIXME: good lord, refactor this. + if (enableBallAnimation) { + graphics.setColor(Color.white); + for(int i=0;i<BALLCOUNT;i++){ + //get the position information of the ball. and then recheck the condition for height. + if((balls[i].getPosition() == 1)||(balls[i].getPosition() == 2) || (balls[i].getPosition()==3) + || (balls[i].getPosition() == 4) || (balls[i].getPosition() == 5)){ + if(!((!gate[balls[i].getPosition()-1].isOpenGate())&& balls[i].getY() >= (gate[balls[i].getPosition()-1].getY()+gate[balls[i].getPosition()-1].getHeight()))) + graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); + } + else { + if(balls[i].getPosition() != 0){ + if(gate[balls[i].getPosition() - 6].getHeight() != 0) { + graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); + } + } + else { + graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); + } + } + } + } - /* - * This will process the balls according to their position - */ - private void process(int i){ - // TODO Auto-generated method stub - - switch(balls[i].getPosition()){ - - case 0: if((balls[i].x >= (100 - 20) && balls[i].x <= 100) && (balls[i].y >= 100-(int)(totalContributedBandwidth*0.8) && + } + + + + private void updateGUI() { + for(int i=1;i<6;i++){ + if(gate[i-1].isOpenGate()){ + if(!(gate[i-1].getHeight() - gateHeight < 0)){ + gate[i].setHeight(gate[i-1].getHeight() - gateHeight ); + + } + else{ + gate[i].setHeight(0); + } + } + else{ + gate[i].setHeight(gate[i-1].getHeight()); + + } + //order matters here + if(!(i == 5)){ + gate[i].setOpeningsHeight((totalContributedBandwidth*0.8) + - gate[i].getHeight()); + gate[i].setOpeningsY(gate[i].getOpeningsHeight() - 50); + + //opening the lid logic + if(gate[i].isOpenGate()){ + gate[i].setx1(gate[i].getx2()); + if(!(gate[i].gety2()- gate[i].getGateWidth() < gate[i].getY())) + gate[i].sety1(gate[i].gety2()- gate[i].getGateWidth()); + else + gate[i].sety1(gate[i].getOpeningsY()); + } + else{ + gate[i].setx1(gate[i].getdefaultx1()); + gate[i].sety1(gate[i].getdefaulty1()); + } + + if(gate[0].isOpenGate()){ + gate[0].setx1(gate[0].getx2()); + if(!(gate[0].gety2()- gate[0].getGateWidth() < gate[0].getY())) + gate[0].sety1(gate[0].gety2()- gate[0].getGateWidth()); + else + gate[0].sety1(gate[0].getY()); + } + else{ + gate[0].setx1(gate[0].getdefaultx1()); + gate[0].sety1(gate[0].getdefaulty1()); + } + + } + } + } + + /* + * initialize the Balls + */ + private void initializexy() { + balls = new Ball[BALLCOUNT]; + if(balls == null){ + System.out.println("Ball is null"); + } + + for(int i=0;i<BALLCOUNT;i++){ + balls[i] = new Ball(generator); + + } + } + + // this is the private class the Timer will look at every DELAY seconds + private class ReboundListener implements ActionListener { + public void actionPerformed(ActionEvent e) { + if((System.currentTimeMillis() - prev_time) > 5000){ + //System.out.println("Change the time"); + prev_time = System.currentTimeMillis(); + gateCount++; + if(gateCount > 4) + gateCount = 0; + gateReboundListener(); + } + for(int i=0;i<BALLCOUNT;i++){ + //updateGUI(); + balls[i].x += balls[i].moveX; + balls[i].y += balls[i].moveY; + process(i); + + } + repaint(); + } + } + + /* + * This will process the balls according to their position + */ + private void process(int i){ + switch(balls[i].getPosition()) { + + case 0: + if((balls[i].x >= (100 - 20) && balls[i].x <= 100) + && (balls[i].y >= 100-(int)(totalContributedBandwidth*0.8) + && balls[i].y <= 100)) + { + balls[i].setPosition(1); + setBounds(i); + } + //still in server + else { + setBounds(i); + if(balls[i].x <= balls[i].xBOUNDSLOWER || balls[i].x >= balls[i].xBOUNDSUPPER-balls[i].getBallSize()){ + balls[i].moveX = balls[i].moveX * -1; + } + if(balls[i].y <= balls[i].yBOUNDSLOWER || balls[i].y >= balls[i].yBOUNDSUPPER-balls[i].getBallSize()) + balls[i].moveY = balls[i].moveY * -1; + } + break; + + case 1: /*if(gate[0].isOpenGate() && (balls[i].x >= 400 && balls[i].x <= 420) && (balls[i].y >= 80 && balls[i].y <= 100)){ - balls[i].setPosition(1); - setBounds(i); - } - //still in server - else{ - setBounds(i); - if(balls[i].x <= balls[i].xBOUNDSLOWER || balls[i].x >= balls[i].xBOUNDSUPPER-balls[i].getBallSize()){ - balls[i].moveX = balls[i].moveX * -1; - } - if(balls[i].y <= balls[i].yBOUNDSLOWER || balls[i].y >= balls[i].yBOUNDSUPPER-balls[i].getBallSize()) - balls[i].moveY = balls[i].moveY * -1; - } - break; - - case 1: /*if(gate[0].isOpenGate() && (balls[i].x >= 400 && balls[i].x <= 420) && (balls[i].y >= 80 && - balls[i].y <= 100)){ - */ if(gate[0].isOpenGate() && (balls[i].x >= gate[0].getOpeningsX() && balls[i].x <= (gate[0].getOpeningsX()+20)) - && (balls[i].y >= 80 && balls[i].y <= 100)){ - balls[i].setPosition(7); - //directly pass in the information - setBounds(i); - /*System.out.println("X upper :"+balls[i].xBOUNDSUPPER+" Y Upper :"+balls[i].yBOUNDSUPPER + */ if(gate[0].isOpenGate() && (balls[i].x >= gate[0].getOpeningsX() && balls[i].x <= (gate[0].getOpeningsX()+20)) + && (balls[i].y >= 80 && balls[i].y <= 100)){ + balls[i].setPosition(7); + //directly pass in the information + setBounds(i); + /*System.out.println("X upper :"+balls[i].xBOUNDSUPPER+" Y Upper :"+balls[i].yBOUNDSUPPER +" X Lower"+balls[i].xBOUNDSLOWER+" X Upper"+balls[i].xBOUNDSUPPER);*/ - /* balls[i].xBOUNDSUPPER = 420; + /* balls[i].xBOUNDSUPPER = 420; balls[i].xBOUNDSLOWER = 400; balls[i].yBOUNDSUPPER = 150; balls[i].yBOUNDSLOWER = 80; balls[i].moveX = 0; balls[i].moveY = 3;*/ - } - else{ - setBounds(i); - /*System.out.println("X upper :"+balls[i].xBOUNDSUPPER+" Y Upper :"+balls[i].yBOUNDSUPPER + } + else{ + setBounds(i); + /*System.out.println("X upper :"+balls[i].xBOUNDSUPPER+" Y Upper :"+balls[i].yBOUNDSUPPER +" X Lower"+balls[i].xBOUNDSLOWER+" X Upper"+balls[i].xBOUNDSUPPER); - */ - if(balls[i].getX() > balls[i].xBOUNDSUPPER){ - balls[i].setPosition(2); - } - if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ - balls[i].moveY = balls[i].moveY*-1; - } - } - - break; - - case 2: if(gate[1].isOpenGate() && (balls[i].x >= gate[1].getOpeningsX() && balls[i].x <= (gate[1].getOpeningsX()+20)) - && (balls[i].y >= 80 && balls[i].y <= 100)){ - balls[i].setPosition(8); - //directly pass in the information - setBounds(i); - /* balls[i].xBOUNDSUPPER = 420; + */ + if(balls[i].getX() > balls[i].xBOUNDSUPPER){ + balls[i].setPosition(2); + } + if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ + balls[i].moveY = balls[i].moveY*-1; + } + } + + break; + + case 2: if(gate[1].isOpenGate() && (balls[i].x >= gate[1].getOpeningsX() && balls[i].x <= (gate[1].getOpeningsX()+20)) + && (balls[i].y >= 80 && balls[i].y <= 100)){ + balls[i].setPosition(8); + //directly pass in the information + setBounds(i); + /* balls[i].xBOUNDSUPPER = 420; balls[i].xBOUNDSLOWER = 400; balls[i].yBOUNDSUPPER = 150; balls[i].yBOUNDSLOWER = 80; balls[i].moveX = 0; balls[i].moveY = 3;*/ - } - else{ - setBounds(i); - if(balls[i].getX() > balls[i].xBOUNDSUPPER){ - balls[i].setPosition(3); - } - if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ - balls[i].moveY = balls[i].moveY*-1; - } - } - break; - - - case 3: if(gate[2].isOpenGate() && (balls[i].x >= gate[2].getOpeningsX() && balls[i].x <= (gate[2].getOpeningsX()+20)) - && (balls[i].y >= 80 && balls[i].y <= 100)){ - balls[i].setPosition(9); - //directly pass in the information - setBounds(i); - /* balls[i].xBOUNDSUPPER = 420; + } + else{ + setBounds(i); + if(balls[i].getX() > balls[i].xBOUNDSUPPER){ + balls[i].setPosition(3); + } + if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ + balls[i].moveY = balls[i].moveY*-1; + } + } + break; + + + case 3: if(gate[2].isOpenGate() && (balls[i].x >= gate[2].getOpeningsX() && balls[i].x <= (gate[2].getOpeningsX()+20)) + && (balls[i].y >= 80 && balls[i].y <= 100)){ + balls[i].setPosition(9); + //directly pass in the information + setBounds(i); + /* balls[i].xBOUNDSUPPER = 420; balls[i].xBOUNDSLOWER = 400; balls[i].yBOUNDSUPPER = 150; balls[i].yBOUNDSLOWER = 80; balls[i].moveX = 0; balls[i].moveY = 3;*/ - } - else{ - setBounds(i); - if(balls[i].getX() > balls[i].xBOUNDSUPPER){ - balls[i].setPosition(4); - } - if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ - balls[i].moveY = balls[i].moveY*-1; - } - } - break; - - case 4: if(gate[3].isOpenGate() && (balls[i].x >= gate[3].getOpeningsX() && balls[i].x <= (gate[3].getOpeningsX()+20)) - && (balls[i].y >= 80 && balls[i].y <= 100)){ - balls[i].setPosition(10); - //directly pass in the information - setBounds(i); - /* balls[i].xBOUNDSUPPER = 420; + } + else{ + setBounds(i); + if(balls[i].getX() > balls[i].xBOUNDSUPPER){ + balls[i].setPosition(4); + } + if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ + balls[i].moveY = balls[i].moveY*-1; + } + } + break; + + case 4: if(gate[3].isOpenGate() && (balls[i].x >= gate[3].getOpeningsX() && balls[i].x <= (gate[3].getOpeningsX()+20)) + && (balls[i].y >= 80 && balls[i].y <= 100)){ + balls[i].setPosition(10); + //directly pass in the information + setBounds(i); + /* balls[i].xBOUNDSUPPER = 420; balls[i].xBOUNDSLOWER = 400; balls[i].yBOUNDSUPPER = 150; balls[i].yBOUNDSLOWER = 80; balls[i].moveX = 0; balls[i].moveY = 3;*/ - } - else{ - setBounds(i); - if(balls[i].getX() > balls[i].xBOUNDSUPPER){ - balls[i].setPosition(5); - } - if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ - balls[i].moveY = balls[i].moveY*-1; - } - } - break; - - case 5: if(gate[4].isOpenGate() && (balls[i].x >= gate[4].getOpeningsX() && balls[i].x <= (gate[4].getOpeningsX()+20)) - && (balls[i].y >= 80 && balls[i].y <= 100)){ - balls[i].setPosition(11); - //directly pass in the information - setBounds(i); - /* balls[i].xBOUNDSUPPER = 420; + } + else{ + setBounds(i); + if(balls[i].getX() > balls[i].xBOUNDSUPPER){ + balls[i].setPosition(5); + } + if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ + balls[i].moveY = balls[i].moveY*-1; + } + } + break; + + case 5: if(gate[4].isOpenGate() && (balls[i].x >= gate[4].getOpeningsX() && balls[i].x <= (gate[4].getOpeningsX()+20)) + && (balls[i].y >= 80 && balls[i].y <= 100)){ + balls[i].setPosition(11); + //directly pass in the information + setBounds(i); + /* balls[i].xBOUNDSUPPER = 420; balls[i].xBOUNDSLOWER = 400; balls[i].yBOUNDSUPPER = 150; balls[i].yBOUNDSLOWER = 80; balls[i].moveX = 0; balls[i].moveY = 3;*/ - } - else{ - setBounds(i); - if(balls[i].getX() > balls[i].xBOUNDSUPPER){ - balls[i].setPosition(6); - } - if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ - balls[i].moveY = balls[i].moveY*-1; - } - } - break; - - case 6: setBounds(i); - if(balls[i].getX() > balls[i].xBOUNDSUPPER){ - /*balls[i].setX(generator.nextInt(100)); + } + else{ + setBounds(i); + if(balls[i].getX() > balls[i].xBOUNDSUPPER){ + balls[i].setPosition(6); + } + if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ + balls[i].moveY = balls[i].moveY*-1; + } + } + break; + + case 6: setBounds(i); + if(balls[i].getX() > balls[i].xBOUNDSUPPER){ + /*balls[i].setX(generator.nextInt(100)); balls[i].setY(100 - gate[0].getHeight()+ generator.nextInt(gate[0].getHeight())); balls[i].setPosition(0); setBounds(i);*/ - setBallinServer(i); - } - - if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ - balls[i].moveY = balls[i].moveY*-1; - } - break; - } - - if((balls[i].getPosition() == 11) || (balls[i].getPosition() == 7) || (balls[i].getPosition() == 8) - || (balls[i].getPosition() == 9) || (balls[i].getPosition() == 10)){ - if(balls[i].getY() >= 150){ - /*balls[i].setX(generator.nextInt(100)); + setBallInTank(i); + } + + if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ + balls[i].moveY = balls[i].moveY*-1; + } + break; + } + + if((balls[i].getPosition() == 11) || (balls[i].getPosition() == 7) || (balls[i].getPosition() == 8) + || (balls[i].getPosition() == 9) || (balls[i].getPosition() == 10)){ + if(balls[i].getY() >= 150){ + /*balls[i].setX(generator.nextInt(100)); balls[i].setY(100 - gate[0].getHeight()+ generator.nextInt(gate[0].getHeight())); //balls[i].setY(generator.nextInt(100)); balls[i].setPosition(0); setBounds(i); - */ - setBallinServer(i); - } - else{ - setBounds(i); - //System.out.println("X upper :"+balls[i].xBOUNDSUPPER+" Y Upper :"+balls[i].yBOUNDSUPPER - //+" X Lower"+balls[i].xBOUNDSLOWER+" X Upper"+balls[i].xBOUNDSUPPER); - } - } - } + */ + setBallInTank(i); + } + else{ + setBounds(i); + //System.out.println("X upper :"+balls[i].xBOUNDSUPPER+" Y Upper :"+balls[i].yBOUNDSUPPER + //+" X Lower"+balls[i].xBOUNDSLOWER+" X Upper"+balls[i].xBOUNDSUPPER); + } + } + } - private void setBallinServer(int i) { - // TODO Auto-generated method stub - generator.setSeed(i*(i+1)); - balls[i].setX(generator.nextInt(100)); - balls[i].setY(generator.nextInt(100)); - - //balls[i].setY(100 - gate[0].getHeight()+ generator.nextInt(gate[0].getHeight())); - balls[i].setPosition(0); - if(balls[i].moveX == 0) - balls[i].moveX = generator.nextInt(15); - setBounds(i); - } + private void setBallInTank(int i) { + // FIXME: is this supposed to be a random seed? + generator.setSeed(i*(i+1)); + balls[i].setX(generator.nextInt(100)); + balls[i].setY(generator.nextInt(100)); - private void setBounds(int ballIndex) { - // TODO Auto-generated method stub - //ball is in the server - if(balls[ballIndex].getPosition() == 0){ - balls[ballIndex].xBOUNDSUPPER = 100; - balls[ballIndex].xBOUNDSLOWER = 0; - balls[ballIndex].yBOUNDSUPPER = 100; - balls[ballIndex].yBOUNDSLOWER = 0; - //balls[ballIndex].moveX = generator.nextInt(6); - //balls[ballIndex].moveY = generator.nextInt(6); - //balls[ballIndex].moveX = 3; - //balls[ballIndex].moveY = 3; - } - else{ - if((balls[ballIndex].getPosition() == 1)||(balls[ballIndex].getPosition() == 2) || (balls[ballIndex].getPosition()==3) - || (balls[ballIndex].getPosition() == 4) || (balls[ballIndex].getPosition() == 5)||(balls[ballIndex].getPosition() == 6)){ - - balls[ballIndex].xBOUNDSUPPER = gate[balls[ballIndex].getPosition() - 1].getX()+gate[balls[ballIndex].getPosition() - 1].getWidth(); - balls[ballIndex].xBOUNDSLOWER = gate[balls[ballIndex].getPosition() - 1].getX(); - balls[ballIndex].yBOUNDSUPPER = gate[balls[ballIndex].getPosition() - 1].getY()/*+gate[balls[ballIndex].getPosition() - 1].getHeight()*/; - balls[ballIndex].yBOUNDSLOWER = gate[balls[ballIndex].getPosition() - 1].getY(); - //balls[ballIndex].moveX = 3; - //balls[ballIndex].moveY = 3; - - } - //the ball is in one of the openings - else{ - balls[ballIndex].xBOUNDSUPPER = gate[balls[ballIndex].getPosition() - 7].getOpeningsX()+gate[balls[ballIndex].getPosition() - 7].getGateWidth(); - balls[ballIndex].xBOUNDSLOWER = gate[balls[ballIndex].getPosition() - 7].getOpeningsX(); - balls[ballIndex].yBOUNDSUPPER = gate[balls[ballIndex].getPosition() - 7].getOpeningsY()+gate[balls[ballIndex].getPosition() - 7].getOpeningsHeight(); - balls[ballIndex].yBOUNDSLOWER = gate[balls[ballIndex].getPosition() - 7].getOpeningsY(); - balls[ballIndex].moveX = 0; - balls[ballIndex].moveY = 3; - } - } - } + //balls[i].setY(100 - gate[0].getHeight()+ generator.nextInt(gate[0].getHeight())); + balls[i].setPosition(0); + if(balls[i].moveX == 0) { + balls[i].moveX = generator.nextInt(15); + } + setBounds(i); + } - public void openGates(int priority) { - // TODO Auto-generated method stub - - gate[priority].setGateOpen(true); - - //set the height of all the canal panls depending on the state of the game - paintComponent(graphics2D); - } + private void setBounds(int ballIndex) { + // ball is in the server + if(balls[ballIndex].getPosition() == 0){ + balls[ballIndex].xBOUNDSUPPER = 100; + balls[ballIndex].xBOUNDSLOWER = 0; + balls[ballIndex].yBOUNDSUPPER = 100; + balls[ballIndex].yBOUNDSLOWER = 0; + //balls[ballIndex].moveX = generator.nextInt(6); + //balls[ballIndex].moveY = generator.nextInt(6); + //balls[ballIndex].moveX = 3; + //balls[ballIndex].moveY = 3; + } + else{ + if((balls[ballIndex].getPosition() == 1)||(balls[ballIndex].getPosition() == 2) || (balls[ballIndex].getPosition()==3) + || (balls[ballIndex].getPosition() == 4) || (balls[ballIndex].getPosition() == 5)||(balls[ballIndex].getPosition() == 6)){ - public void closeGates(int priority) { - // TODO Auto-generated method stub - gate[priority].setGateOpen(false); - gate[priority].setx1(gate[priority].getdefaultx1()); - gate[priority].sety1(gate[priority].getdefaulty1()); - /*if(!(priority == 0)) - gate[priority].setHeight(gate[priority-1].getHeight());*/ - paintComponent(graphics2D); - } + balls[ballIndex].xBOUNDSUPPER = gate[balls[ballIndex].getPosition() - 1].getX()+gate[balls[ballIndex].getPosition() - 1].getWidth(); + balls[ballIndex].xBOUNDSLOWER = gate[balls[ballIndex].getPosition() - 1].getX(); + balls[ballIndex].yBOUNDSUPPER = gate[balls[ballIndex].getPosition() - 1].getY()/*+gate[balls[ballIndex].getPosition() - 1].getHeight()*/; + balls[ballIndex].yBOUNDSLOWER = gate[balls[ballIndex].getPosition() - 1].getY(); + //balls[ballIndex].moveX = 3; + //balls[ballIndex].moveY = 3; - public void endRound() { - // TODO Auto-generated method stub - flagDownStream = false; - flagDownStream = false; + } + //the ball is in one of the openings + else{ + balls[ballIndex].xBOUNDSUPPER = gate[balls[ballIndex].getPosition() - 7].getOpeningsX()+gate[balls[ballIndex].getPosition() - 7].getGateWidth(); + balls[ballIndex].xBOUNDSLOWER = gate[balls[ballIndex].getPosition() - 7].getOpeningsX(); + balls[ballIndex].yBOUNDSUPPER = gate[balls[ballIndex].getPosition() - 7].getOpeningsY()+gate[balls[ballIndex].getPosition() - 7].getOpeningsHeight(); + balls[ballIndex].yBOUNDSLOWER = gate[balls[ballIndex].getPosition() - 7].getOpeningsY(); + balls[ballIndex].moveX = 0; + balls[ballIndex].moveY = 3; + } + } + } - x2UpStream = 420; + public void openGates(int priority) { + gate[priority].setGateOpen(true); + // set the height of all the canal panels depending on the state of the game + repaint(); + } - y2UpStream = 100; + public void closeGates(int priority) { + gate[priority].setGateOpen(false); + gate[priority].setx1(gate[priority].getdefaultx1()); + gate[priority].sety1(gate[priority].getdefaulty1()); + /*if(!(priority == 0)) + gate[priority].setHeight(gate[priority-1].getHeight());*/ + repaint(); + } - y2DownStream = 100; - - x2DownStream = 950; - - initializexy(); - } + public void endRound() { + initializexy(); + } } Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChartWindowPanelTokenBandwidth.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChartWindowPanelTokenBandwidth.java 2009-10-15 00:12:05 UTC (rev 298) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChartWindowPanelTokenBandwidth.java 2009-10-16 23:02:53 UTC (rev 299) @@ -1,45 +1,3 @@ - -/* =========================================================== - * JFreeChart : a free chart library for the Java(tm) platform - * =========================================================== - * - * (C) Copyright 2000-2004, by Object Refinery Limited and Contributors. - * - * Project Info: http://www.jfree.org/jfreechart/index.html - * - * This library is free software; you can redistribute it and/or modify it under the terms - * of the GNU Lesser General Public License as published by the Free Software Foundation; - * either version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License along with this - * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * ----------------- - * XYSeriesDemo.java - * ----------------- - * (C) Copyright 2002-2004, by Object Refinery Limited and Contributors. - * - * Original Author: David Gilbert (for Object Refinery Limited); - * Contributor(s): -; - * - * $Id$ - * - * Changes - * ------- - * 08-Apr-2002 : Version 1 (DG); - * 11-Jun-2002 : Inserted value out of order to see that it works (DG); - * 11-Oct-2002 : Fixed issues reported by Checkstyle (DG); - * - */ - package edu.asu.commons.irrigation.client; import java.awt.CardLayout; @@ -57,140 +15,117 @@ import edu.asu.commons.irrigation.server.GroupDataModel; - /** - * A simple demo showing a dataset created using the {@link XYSeriesCollection} class. + * $Id$ + * * + * @author Sanket Joshi + * @version $Rev$ */ -//public class XYSeriesDemo extends ApplicationFrame { +public class ChartWindowPanelTokenBandwidth extends JPanel { - public class ChartWindowPanelTokenBandwidth extends JPanel { + private static final long serialVersionUID = 5555080117985336199L; - /** - * - */ - private static final long serialVersionUID = 5555080117985336199L; + private int numberofFilesDownloaded = 10; - private int numberofFilesDownloaded = 10; + private Dimension screenSize; - private Dimension screenSize; + private JPanel jPanel; - private JPanel jPanel; - - private IrrigationClient client; + private IrrigationClient client; - + /** * A demonstration application showing an XY series containing a null value. * * @param title the frame title. */ public ChartWindowPanelTokenBandwidth(IrrigationClient client) { - - //super(title); - this.client = client; - initialize(); + this.client = client; + initialize(); } - public void initialize() { - // TODO Auto-generated method stub - this.setLayout(new CardLayout()); - this.setSize(new Dimension(530/2, 326/2)); - //this.setSize(screenSize.width, screenSize.height); - this.add(getJPanel(), getJPanel().getName()); - repaint(); + public void initialize() { + this.setLayout(new CardLayout()); + this.setSize(new Dimension(530/2, 326/2)); + //this.setSize(screenSize.width, screenSize.height); + this.add(getJPanel(), getJPanel().getName()); + repaint(); - } + } - /** - * This method initializes jPanel - * - * @return javax.swing.JPanel - */ - private JPanel getJPanel() { - if (jPanel == null) { - jPanel = new JPanel(); - GridLayout gridLayout = new GridLayout(); - gridLayout.setColumns(2); - jPanel.setLayout(gridLayout); - jPanel.add(getChartPanel()); - //jPanel.add(getchartPanel1()); - jPanel.setName("jPanel"); - } - return jPanel; - } + /** + * This method initializes jPanel + * + * @return javax.swing.JPanel + */ + private JPanel getJPanel() { + if (jPanel == null) { + jPanel = new JPanel(); + GridLayout gridLayout = new GridLayout(); + gridLayout.setColumns(2); + jPanel.setLayout(gridLayout); + jPanel.add(getChartPanel()); + //jPanel.add(getchartPanel1()); + jPanel.setName("jPanel"); + } + return jPanel; + } - private ChartPanel getChartPanel() { - // TODO Auto-generated method stub - final XYSeries actualFlowCapacitySeries = new XYSeries("Actual"); - final XYSeries potentialFlowCapacitySeries = new XYSeries("Potential"); -// final XYSeries actualFlowCapacitySeriesY = new XYSeries("Actual"); - final XYSeries initialInfrastructureEfficiencySeries = new XYSeries("Initial"); - int x,y; - GroupDataModel group = client.getClientDataModel().getGroupDataModel(); - final int infrastructureEfficiency = group.getInfrastructureEfficiency(); - final int actualFlowCapacity = group.getFlowCapacity(); - for(y = 0; y <= actualFlowCapacity; y++) { - actualFlowCapacitySeries.add(infrastructureEfficiency, y); - } - for(x =0; x<=client.getRoundConfiguration().getMaximumInfrastructureEfficiency();x++){ - y = group.calculateFlowCapacity(x); - potentialFlowCapacitySeries.add(x,y); - } - final int initialInfrastructureEfficiency = group.getInitialInfrastructureEfficiency(); - final int initialFlowCapacity = group.calculateFlowCapacity(initialInfrastructureEfficiency); - for (y = 0; y <= initialFlowCapacity; y++) { - initialInfrastructureEfficiencySeries.add(initialInfrastructureEfficiency, y); - } + private ChartPanel getChartPanel() { + // TODO Auto-generated method stub + final XYSeries actualFlowCapacitySeries = new XYSeries("Actual"); + final XYSeries potentialFlowCapacitySeries = new XYSeries("Potential"); + // final XYSeries actualFlowCapacitySeriesY = new XYSeries("Actual"); + final XYSeries initialInfrastructureEfficiencySeries = new XYSeries("Initial"); + int x,y; + GroupDataModel group = client.getClientDataModel().getGroupDataModel(); + final int infrastructureEfficiency = group.getInfrastructureEfficiency(); + final int actualFlowCapacity = group.getFlowCapacity(); + for(y = 0; y <= actualFlowCapacity; y++) { + actualFlowCapacitySeries.add(infrastructureEfficiency, y); + } + for(x =0; x<=client.getRoundConfiguration().getMaximumInfrastructureEfficiency();x++){ + y = group.calculateFlowCapacity(x); + potentialFlowCapacitySeries.add(x,y); + } + final int initialInfrastructureEfficiency = group.getInitialInfrastructureEfficiency(); + final int initialFlowCapacity = group.calculateFlowCapacity(initialInfrastructureEfficiency); + for (y = 0; y <= initialFlowCapacity; y++) { + initialInfrastructureEfficiencySeries.add(initialInfrastructureEfficiency, y); + } -// for(y = 0; y <= actualFlowCapacity; y++) { -// actualFlowCapacitySeriesY.add(infrastructureEfficiency,y); -// } - repaint(); + // for(y = 0; y <= actualFlowCapacity; y++) { + // actualFlowCapacitySeriesY.add(infrastructureEfficiency,y); + // } - final XYSeriesCollection data = new XYSeriesCollection(); - data.addSeries(initialInfrastructureEfficiencySeries); - data.addSeries(actualFlowCapacitySeries); - data.addSeries(potentialFlowCapacitySeries); + final XYSeriesCollection data = new XYSeriesCollection(); + data.addSeries(initialInfrastructureEfficiencySeries); + data.addSeries(actualFlowCapacitySeries); + data.addSeries(potentialFlowCapacitySeries); -// data.addSeries(actualFlowCapacitySeriesY); + // data.addSeries(actualFlowCapacitySeriesY); - final JFreeChart chart = ChartFactory.createXYLineChart( - "Total Flow Capacity", - "Infrastructure Efficiency", - "Actual Flow Capacity", - data, - PlotOrientation.VERTICAL, - true, - true, - false - ); - final ChartPanel chartPanel = new ChartPanel(chart); - //chartPanel.chartProgress(arg0) - chartPanel.setLayout(new CardLayout()); - chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); - //setContentPane(chartPanel); - return chartPanel; - //y=4*x; - } - // **************************************************************************** - // * JFREECHART DEVELOPER GUIDE * - // * The JFreeChart Developer Guide, written by David Gilbert, is available * - // * to purchase from Object Refinery Limited: * - // * * - // * http://www.object-refinery.com/jfreechart/guide.html * - // * * - // * Sales are used to provide funding for the JFreeChart project - please * - // * support us so that we can continue developing free software. * - // **************************************************************************** - - /** - * Starting point for the demonstration application. - * - * @param args ignored. - */ - - } \ No newline at end of file + final JFreeChart chart = ChartFactory.createXYLineChart( + "Total Flow Capacity", + "Infrastructure Efficiency", + "Actual Flow Capacity", + data, + PlotOrientation.VERTICAL, + true, + true, + false + ); + final ChartPanel chartPanel = new ChartPanel(chart); + //chartPanel.chartProgress(arg0) + chartPanel.setLayout(new CardLayout()); + chartPanel.setPreferredSize(new Dimension(500, 270)); + repaint(); + //setContentPane(chartPanel); + return chartPanel; + //y=4*x; + } +} \ No newline at end of file Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-15 00:12:05 UTC (rev 298) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-16 23:02:53 UTC (rev 299) @@ -9,10 +9,11 @@ import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; import java.lang.reflect.InvocationTargetException; import java.text.DecimalFormat; import java.util.ArrayList; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; @@ -58,7 +59,7 @@ private JPanel graphPanel; - private JTextField tokenEntryTextField; + private JTextField investedTokensTextField; private JButton submitTokensButton; @@ -72,7 +73,7 @@ private int totalContributedTokensPerGroup; - private JTextArea contributionStatusInformationjTextArea; + private JTextArea contributionInformationTextArea; private JButton nextButton; @@ -92,7 +93,7 @@ private int NUMBER_INSTRUCTIONS = 9; - private JLabel quizLabel; + private JLabel quizMessageLabel; private JLabel quizAnimationLabel = new JLabel(); @@ -112,26 +113,22 @@ private JScrollPane animationInstructionsScrollPane; - private JPanel chartPanel; + private JPanel pieChartPanel; private PieChart pieChart; - public ClientData clientData; - private CanalAnimationPanel canalAnimationPanel; private CardLayout cardLayout; private JLabel infrastructureEfficiencyLabel = new JLabel("Current infrastructure efficiency: "); - public ExperimentGameWindow(Dimension screenSize, IrrigationClient client) { + public ExperimentGameWindow(IrrigationClient client) { this.client = client; this.clientDataModel = client.getClientDataModel(); - // FIXME: set the actual screen size dimensions after this JPanel has - // been initialized... - // this.screenSize = getParent().getSize(); - // feed subject view the available screen size so that - // it can adjust appropriately when given a board size + } + + void initialize(Dimension screenSize) { initGuiComponents(screenSize); } @@ -150,7 +147,7 @@ addToCardLayout(getInstructionsPanel()); irrigationGamePanel = new IrrigationGamePanel(screenSize, client); addToCardLayout(irrigationGamePanel); - // add any other panels that need to be switched out. + // add any other panels that need to be switched to.. // FIXME: see if we can simplify the number of instructions panes that Sanket has created. // addToCardLayout(getInstructionsEditorPane()); } @@ -202,7 +199,7 @@ if (submitTokenPanel == null) { submitTokenPanel = new JPanel(); submitTokenPanel.setLayout(new BorderLayout()); - submitTokenPanel.add(getTokenEntryTextField(), BorderLayout.CENTER); + submitTokenPanel.add(getInvestedTokensTextField(), BorderLayout.CENTER); submitTokenPanel.add(getSubmitTokensButton(), BorderLayout.EAST); return submitTokenPanel; } @@ -218,52 +215,78 @@ instructionsPanel.add(getInstructionsNavigationPanel(), BorderLayout.PAGE_END); } return instructionsPanel; - } - + private JPanel getInstructionsNavigationPanel() { if (instructionsNavigationPanel == null) { instructionsNavigationPanel = new JPanel(); instructionsNavigationPanel.setLayout(new BorderLayout()); instructionsNavigationPanel.add(getPreviousButton(), BorderLayout.LINE_START); instructionsNavigationPanel.add(getNextButton(), BorderLayout.LINE_END); - // this is just to add spacing I think. - quizLabel = new JLabel(); - instructionsNavigationPanel.add(quizLabel, BorderLayout.CENTER); + // displays quiz messages (correct/incorrect answer). + quizMessageLabel = new JLabel(); + instructionsNavigationPanel.add(quizMessageLabel, BorderLayout.CENTER); } return instructionsNavigationPanel; } + private JButton getPreviousButton() { + if (previousButton == null) { + previousButton = new JButton(); + previousButton.setText("Previous"); + previousButton.setEnabled(false); + previousButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + quizMessageLabel.setText(""); + // getting the next instruction Number + if (instructionNumber > 1) { + instructionNumber--; + } + previousButton.setEnabled(instructionNumber > 1); + nextButton.setEnabled(true); + System.out.println("instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); + setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); + // FIXME: get rid of hardcoded animation on page 5. Should instead + // just be an animated gif or something like that. + // should be more like "if instructions.hasAnimation()" + if(instructionNumber == 5) { + getInstructionsPanel().add(getCanalAnimationPanel(), BorderLayout.PAGE_START); + } + else { + getInstructionsPanel().remove(getCanalAnimationPanel()); + } + validate(); + } + }); + } + return previousButton; + } + private JButton getNextButton() { if (nextButton == null) { nextButton = new JButton(); nextButton.setText("Next"); nextButton.setEnabled(false); - nextButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - quizLabel.setText(""); - + nextButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + quizMessageLabel.setText(""); previousButton.setEnabled(true); - if(instructionNumber >= pagesTraversed){ + if (instructionNumber >= pagesTraversed){ nextButton.setEnabled(false); } // getting the next instruction Number - if (instructionNumber == NUMBER_INSTRUCTIONS) { - - } - else + if (instructionNumber < NUMBER_INSTRUCTIONS) { instructionNumber++; - System.out.println("instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); + } setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); - if(instructionNumber == 5){ - quizAnimationLabel.setText(""); - addCenterComponent(getAnimationInstructionPane()); - //addCenterComponent(getTokenScreenPanel()); + if(instructionNumber == 5) { + getInstructionsPanel().add(getCanalAnimationPanel(), BorderLayout.PAGE_START); } else { - addCenterComponent(getInstructionsPanel()); + getInstructionsPanel().remove(getCanalAnimationPanel()); } + validate(); } }); @@ -272,14 +295,14 @@ return nextButton; } - private JPanel getAnimationInstructionPane() { + private JPanel getAnimationInstructionPanel() { if (animationInstructionPanel == null) { animationInstructionPanel = new JPanel(); animationInstructionPanel.setName("Animated instruction panel"); animationInstructionPanel.setLayout(new BorderLayout()); - animationInstructionPanel.add(getAnimationPane(), BorderLayout.CENTER); + animationInstructionPanel.add(getAnimationPanel(), BorderLayout.CENTER); - animationInstructionPanel.add(getNavigationAnimationPanel(), BorderLayout.SOUTH); + animationInstructionPanel.add(getNavigationAnimationPanel(), BorderLayout.PAGE_END); animationInstructionPanel.setBackground(Color.WHITE); return animationInstructionPanel; } @@ -291,8 +314,8 @@ private JPanel getNavigationAnimationPanel() { if (navigationAnimationPanel == null) { - navigationAnimationPanel = new JPanel(); + navigationAnimationPanel.setName("Navigation animation panel"); navigationAnimationPanel.setLayout(new BorderLayout()); navigationAnimationPanel.add(getNextAnimationButton(), BorderLayout.EAST); navigationAnimationPanel.add(getPreviousAnimationButton(), BorderLayout.WEST); @@ -310,7 +333,7 @@ previousAnimationButton.setEnabled(true); previousAnimationButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { - quizLabel.setText(""); + quizMessageLabel.setText(""); // getting the next instruction Number nextButton.setEnabled(true); if (instructionNumber > 1) { @@ -332,7 +355,7 @@ nextAnimationButton.setEnabled(false); nextAnimationButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - quizLabel.setText(""); + quizMessageLabel.setText(""); previousButton.setEnabled(true); if(instructionNumber >= pagesTraversed) nextButton.setEnabled(false); @@ -342,26 +365,36 @@ } System.out.println("instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); - if(instructionNumber == 5){ - addCenterComponent(getAnimationInstructionPane()); + // FIXME: horrifyingly hard coded + if(instructionNumber == 5) { //addCenterComponent(getTokenScreenPanel()); + getInstructionsPanel().add(getCanalAnimationPanel(), BorderLayout.PAGE_START); } else { - addCenterComponent(getInstructionsPanel()); + getInstructionsPanel().remove(getCanalAnimationPanel()); +// addCenterComponent(getInstructionsPanel()); } + validate(); } }); } return nextAnimationButton; } + + private JPanel getCanalAnimationPanel() { + if (canalAnimationPanel == null) { + canalAnimationPanel = new CanalAnimationPanel(40); + } + return canalAnimationPanel; + } - private JPanel getAnimationPane() { + private JPanel getAnimationPanel() { if (animationPanel == null) { animationPanel = new JPanel(); + animationPanel.setName("Animation panel"); animationPanel.setLayout(new BorderLayout()); //FIXME: Here the animation panel needs to be decided on fly - //canalPanelAnimation = new CanalPanelAnimation(40); canalAnimationPanel = new CanalAnimationPanel(40); animationPanel.add(canalAnimationPanel,BorderLayout.CENTER); animationInstructionsEditorPane = createInstructionsEditorPane(); @@ -375,42 +408,10 @@ animationInstructionsEditorPane.setCaretPosition(0); animationInstructionsEditorPane.repaint(); animationPanel.setBackground(Color.WHITE); - return animationPanel; } - return animationPanel; } - private JButton getPreviousButton() { - if (previousButton == null) { - previousButton = new JButton(); - previousButton.setText("Previous"); - previousButton.setEnabled(false); - previousButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - quizLabel.setText(""); - // getting the next instruction Number - nextButton.setEnabled(true); - if (instructionNumber !=... [truncated message content] |
From: Kalin J. <kj...@as...> - 2009-10-16 21:49:17
|
I have located the source of the error that seema finally sent me a screenshot of. I have put a check into the program so that it doesn't just try and load information from an empty arraylist. I'm not sure why it would try, so I will have to look into that when i have time. Right now I check out at 14:45 (3.75hr) for class. On Fri, Oct 16, 2009 at 11:23 AM, Allen Lee <All...@as...> wrote: > Kalin, you need to be a little more clear about what it is you're doing. > > On Thu, Oct 15, 2009 at 5:35 PM, Kalin Jonas <kj...@as...> wrote: > > checking out at 4:45 > > I'm not 100% sure where the problem is > > > > On Thu, Oct 15, 2009 at 3:43 PM, Kalin Jonas <kj...@as...> wrote: > >> > >> Working from home at 3:45 > > > > > > > ------------------------------------------------------------------------------ > > Come build with us! The BlackBerry(R) Developer Conference in SF, CA > > is the only developer event you need to attend this year. Jumpstart your > > developing skills, take BlackBerry mobile applications to market and stay > > ahead of the curve. Join us from November 9 - 12, 2009. Register now! > > http://p.sf.net/sfu/devconference > > _______________________________________________ > > Virtualcommons-svn mailing list > > Vir...@li... > > https://lists.sourceforge.net/lists/listinfo/virtualcommons-svn > > > > > > > > -- > Allen Lee > Center for the Study of Institutional Diversity [http://csid.asu.edu] > Arizona State University | P.O. Box 872402 | Tempe, Arizona 85287-2402 > Office: 480.727.0401 | Fax: 480.965.7671 > |
From: Kalin J. <kj...@as...> - 2009-10-16 18:16:10
|
working at home again at 11:00 am. I have been having coughing fits more often today, and I'd rather not spread so many germs at work. On Thu, Oct 15, 2009 at 5:35 PM, Kalin Jonas <kj...@as...> wrote: > checking out at 4:45 > I'm not 100% sure where the problem is > > > On Thu, Oct 15, 2009 at 3:43 PM, Kalin Jonas <kj...@as...> wrote: > >> Working from home at 3:45 >> > > |
From: Kalin J. <kj...@as...> - 2009-10-16 00:36:00
|
checking out at 4:45 I'm not 100% sure where the problem is On Thu, Oct 15, 2009 at 3:43 PM, Kalin Jonas <kj...@as...> wrote: > Working from home at 3:45 > |
From: Kalin J. <kj...@as...> - 2009-10-15 22:43:40
|
Working from home at 3:45 |
From: <al...@us...> - 2009-10-15 00:15:18
|
Revision: 298 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=298&view=rev Author: alllee Date: 2009-10-15 00:12:05 +0000 (Thu, 15 Oct 2009) Log Message: ----------- initial general instructions appears to work with new CardLayout. Modified Paths: -------------- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationGamePanel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-14 22:10:26 UTC (rev 297) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-15 00:12:05 UTC (rev 298) @@ -58,7 +58,7 @@ private JPanel graphPanel; - private JTextField enterTokens; + private JTextField tokenEntryTextField; private JButton submitTokensButton; @@ -147,15 +147,18 @@ instructionsEditorPane.setCaretPosition(0); setInstructions(getGeneralInstructions(0)); - add(getInstructionsPanel(), getInstructionsPanel().getName()); + addToCardLayout(getInstructionsPanel()); irrigationGamePanel = new IrrigationGamePanel(screenSize, client); - add(irrigationGamePanel, irrigationGamePanel.getName()); + addToCardLayout(irrigationGamePanel); // add any other panels that need to be switched out. // FIXME: see if we can simplify the number of instructions panes that Sanket has created. - add(getInstructionsEditorPane()); +// addToCardLayout(getInstructionsEditorPane()); } + + private void addToCardLayout(Component component) { + add(component, component.getName()); + } - private JPanel getTokenScreenPanel() { if (tokenScreenPanel == null) { tokenScreenPanel = new JPanel(); @@ -199,7 +202,7 @@ if (submitTokenPanel == null) { submitTokenPanel = new JPanel(); submitTokenPanel.setLayout(new BorderLayout()); - submitTokenPanel.add(getEnterTokens(), BorderLayout.CENTER); + submitTokenPanel.add(getTokenEntryTextField(), BorderLayout.CENTER); submitTokenPanel.add(getSubmitTokensButton(), BorderLayout.EAST); return submitTokenPanel; } @@ -222,8 +225,8 @@ if (instructionsNavigationPanel == null) { instructionsNavigationPanel = new JPanel(); instructionsNavigationPanel.setLayout(new BorderLayout()); - instructionsNavigationPanel.add(getNextButton(), BorderLayout.LINE_START); - instructionsNavigationPanel.add(getPreviousButton(), BorderLayout.LINE_END); + instructionsNavigationPanel.add(getPreviousButton(), BorderLayout.LINE_START); + instructionsNavigationPanel.add(getNextButton(), BorderLayout.LINE_END); // this is just to add spacing I think. quizLabel = new JLabel(); instructionsNavigationPanel.add(quizLabel, BorderLayout.CENTER); @@ -310,21 +313,14 @@ quizLabel.setText(""); // getting the next instruction Number nextButton.setEnabled(true); - if (instructionNumber == 1) { - - } else + if (instructionNumber > 1) { instructionNumber--; - if(instructionNumber > 1) - previousButton.setEnabled(true); - else - previousButton.setEnabled(false); - System.out.println("instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); + } + previousButton.setEnabled( instructionNumber > 1 ); setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); addCenterComponent(getInstructionsPanel()); } }); - return previousAnimationButton; - } return previousAnimationButton; } @@ -334,10 +330,8 @@ nextAnimationButton = new JButton(); nextAnimationButton.setText("Next"); nextAnimationButton.setEnabled(false); - nextAnimationButton.addActionListener(new java.awt.event.ActionListener() { - - - public void actionPerformed(java.awt.event.ActionEvent e) { + nextAnimationButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { quizLabel.setText(""); previousButton.setEnabled(true); if(instructionNumber >= pagesTraversed) @@ -352,12 +346,11 @@ addCenterComponent(getAnimationInstructionPane()); //addCenterComponent(getTokenScreenPanel()); } - else + else { addCenterComponent(getInstructionsPanel()); + } } - }); - } return nextAnimationButton; @@ -398,47 +391,35 @@ quizLabel.setText(""); // getting the next instruction Number nextButton.setEnabled(true); - if (instructionNumber == 1) { - - } else + if (instructionNumber != 1) { instructionNumber--; - if(instructionNumber > 1) - previousButton.setEnabled(true); - else - previousButton.setEnabled(false); + } + previousButton.setEnabled(instructionNumber > 1); System.out.println("instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); - if(instructionNumber == 5){ + if(instructionNumber == 5) { quizAnimationLabel.setText(""); nextAnimationButton.setEnabled(true); addCenterComponent(getAnimationInstructionPane()); //addCenterComponent(getTokenScreenPanel()); } - else + else { addCenterComponent(getInstructionsPanel()); + } } }); - return previousButton; - } return previousButton; } /** - * This returns the string of general instructions from the round0.xml files + * This returns the string of general instructions from the irrigation.xml file * where the general instructions are stored * @param pagesTraversed * * @return */ private String getGeneralInstructions(int pageNumber, int pagesTraversed) { - /*if(pageNumber == 2){ - if(client.getClientGameState().getPriority()== 0) - return client.getServerConfiguration().getGeneralInstructions(20); - else - return client.getServerConfiguration().getGeneralInstructions(21); - }*/ - return client.getServerConfiguration().getGeneralInstructions(pageNumber,pagesTraversed, client.getClientDataModel().getPriority()); } @@ -447,17 +428,11 @@ return client.getServerConfiguration().getGeneralInstructions(pageNumber); } - private JTextField getEnterTokens() { - if (enterTokens == null) { - enterTokens = new JTextField(); - enterTokens.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent event) { - submitInvestedTokens(); - } - }); + private JTextField getTokenEntryTextField() { + if (tokenEntryTextField == null) { + tokenEntryTextField = new JTextField(); } - - return enterTokens; + return tokenEntryTextField; } private JButton getSubmitTokensButton() { @@ -470,31 +445,29 @@ submitInvestedTokens(); } catch(NumberFormatException e1){ - enterTokens.setText(""); + tokenEntryTextField.setText(""); instructionsBuilder.delete(0, instructionsBuilder.length()); - instructionsBuilder.append("\nPlease Enter your tokens within the range 0 -10"); + instructionsBuilder.append("\nYou only have between 0 and 10 to invest. Please choose a number between 0 and 10 and try again."); instructionsBuilder.append(getGeneralInstructions(11,pagesTraversed)); +// setInstructions(instructionsBuilder.toString()); tokenInstructionsEditorPane.setText(instructionsBuilder.toString()); } } - - }); - return submitTokensButton; } return submitTokensButton; } private void submitInvestedTokens() throws NumberFormatException { - int token = Integer.parseInt(enterTokens.getText()); + int token = Integer.parseInt(tokenEntryTextField.getText()); // validating token range if (token >= 0 && token <= 10) { client.transmitTokenContributed(token); - updateInstructions("Please wait while the server computes your total flow capacity based on your group's total token contribution investment."); + setInstructions("Please wait while the server computes your total flow capacity based on your group's total token contribution investment."); addCenterComponent(getInstructionsEditorPane()); } else { - enterTokens.setText(""); + tokenEntryTextField.setText(""); instructionsBuilder.delete(0, instructionsBuilder.length()); instructionsBuilder.append("\nPlease Enter your tokens within the range 0 - 10"); instructionsBuilder.append(getGeneralInstructions(11,pagesTraversed)); @@ -505,10 +478,9 @@ // /////////////////////////////////////////////////////////////////////////////////////////////////////////// private HtmlEditorPane getInstructionsEditorPane() { - // JEditorPane pane = new JEditorPane("text/html", - // "Costly Sanctioning Experiment"); if (instructionsEditorPane == null) { instructionsEditorPane = createInstructionsEditorPane(); + instructionsEditorPane.setName("Instructions editor pane"); } return instructionsEditorPane; } @@ -522,8 +494,6 @@ } - - private void addCenterComponent(Component newCenterComponent) { cardLayout.show(this, newCenterComponent.getName()); // if (currentCenterComponent != null) { @@ -537,6 +507,7 @@ // repaint(); // } // currentCenterComponent = newCenterComponent; + repaint(); } public void startRound(final RoundConfiguration configuration) { @@ -572,7 +543,7 @@ irrigationGamePanel.endRound(); Runnable runnable = new Runnable() { public void run() { - enterTokens.setText(""); + tokenEntryTextField.setText(""); addDebriefingText(event); // generate debriefing text from data culled from the Event addCenterComponent(instructionsEditorPane); @@ -671,13 +642,12 @@ setInstructions(instructionsBuilder.toString()); if (event.isLastRound()) { - instructionsBuilder - .append(String - .format( + instructionsBuilder.append( + String.format( "<p><b>The experiment is now almost over. There is a survey" - + " for you to fill out" - + " while the facilitator prepares your earnings. When the facilitator is ready " - + "and you have completed the survey, your computer number will be called. You will then go to " + + " for you to fill out while the facilitator prepares your earnings. " + + " When the facilitator is ready and you have completed the survey, " + + "your computer number will be called. You will then go to " + "the room next door to receive payment.</b></p>", event.getId())); setInstructions(instructionsBuilder.toString()); @@ -700,12 +670,15 @@ } // adding the instructions into the instruction Panel - private void setInstructions(String s) { - instructionsEditorPane.setText(s); - instructionsEditorPane.setCaretPosition(0); - invalidate(); - validate(); - instructionsScrollPane.requestFocusInWindow(); + private void setInstructions(final String instructions) { + System.err.println("Setting instructions: " + instructions); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + instructionsEditorPane.setText(instructions); + instructionsEditorPane.setCaretPosition(0); + instructionsScrollPane.requestFocusInWindow(); + } + }); } @@ -840,13 +813,6 @@ } - public void updateInstructions(final String s) { - // setting the initial instructions - // FIXME: endRound should do the addCenterComponent(..) - //addCenterComponent(instructionsEditorPane); - setInstructions(s); - } - public void updateGraphDisplay(final ClientData clientData) { // TODO Auto-generated method stub this.clientData = clientData; @@ -893,7 +859,6 @@ } private JPanel getChartPanel(ClientData clientData) { - // TODO Auto-generated method stub chartPanel = new JPanel(); xySeriesDemo = new ChartWindowPanelTokenBandwidth( @@ -924,16 +889,23 @@ /*roundEndsOn = (configuration.getRoundTime() * 1000L) + System.currentTimeMillis(); update();*/ addCenterComponent(getTokenScreenPanel()); - getEnterTokens().requestFocusInWindow(); + getTokenEntryTextField().requestFocusInWindow(); } }; SwingUtilities.invokeLater(runnable); } - public void updateRoundInstructions(String instructions, int priority) { - instructionsBuilder.append(instructions); - updateInstructions(instructionsBuilder.toString()); - addCenterComponent(instructionsEditorPane); + public void updateRoundInstructions(RoundConfiguration roundConfiguration) { + System.err.println("Updating round instructions: " + roundConfiguration.getInstructions()); + // if this is the first round, show the general instructions. + if (roundConfiguration.isFirstRound()) { +// setInstructions(roundConfiguration.getParentConfiguration().getInitialInstructions()); + } + else { + instructionsBuilder.append(roundConfiguration.getInstructions()); + setInstructions(instructionsBuilder.toString()); + } + addCenterComponent(getInstructionsPanel()); } private ChatPanel chatPanel; @@ -971,7 +943,7 @@ if (timeRemaining < 0) { sleep(); addCenterComponent(getTokenScreenPanel()); - getEnterTokens().requestFocusInWindow(); + getTokenEntryTextField().requestFocusInWindow(); timer.stop(); timer = null; } @@ -981,7 +953,6 @@ } private void sleep() { - // TODO Auto-generated method stub long prevTime = System.currentTimeMillis(); while((System.currentTimeMillis() - prevTime) < 5000) { //System.out.println("Prev "+prevTime); @@ -996,7 +967,6 @@ } public void enableInstructions() { - // TODO Auto-generated method stub setInstructions(getGeneralInstructions(1,pagesTraversed)); addCenterComponent(getInstructionsPanel()); Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java 2009-10-14 22:10:26 UTC (rev 297) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java 2009-10-15 00:12:05 UTC (rev 298) @@ -64,18 +64,17 @@ Map<Identifier, ClientData> updatedClientDataMap = new LinkedHashMap<Identifier, ClientData>(); - private IrrigationClient(Dimension screenSize) { - this(EventChannelFactory.create(), screenSize, new ServerConfiguration()); + private IrrigationClient() { + this(EventChannelFactory.create(), new ServerConfiguration()); } - public IrrigationClient(EventChannel channel, Dimension screenSize, - ServerConfiguration configuration) { + public IrrigationClient(EventChannel channel, ServerConfiguration serverConfiguration) { this.channel = channel; - this.serverConfiguration = configuration; - // moved this line down to the connect so that we get a new instance - // of a dispatcher every time we connect - - clientDispatcher = DispatcherFactory.getInstance().createClientDispatcher(channel); + this.serverConfiguration = serverConfiguration; + this.clientDispatcher = DispatcherFactory.getInstance().createClientDispatcher(channel); + } + + private void initialize(Dimension screenSize) { clientDataModel = new ClientDataModel(channel, this); experimentGameWindow = new ExperimentGameWindow(screenSize, this); // clientGameState.setMainIrrigationGameWindow(irrigationGameWindow1); @@ -101,7 +100,8 @@ public void run() { Dimension defaultDimension = new Dimension(500, 500); JFrame frame = new JFrame(); - IrrigationClient client = new IrrigationClient(defaultDimension); + IrrigationClient client = new IrrigationClient(); + client.initialize(defaultDimension); client.connect(); frame.setTitle("Client Window: " + client.id); frame.setSize(1130, 600); @@ -162,12 +162,7 @@ public void handle(RegistrationEvent event) { RoundConfiguration configuration = event.getRoundConfiguration(); setRoundConfiguration(configuration); - int priority = event.getClientData().getPriority(); - clientDataModel.setPriority(priority); - // FIXME: display priority - if (! configuration.isPracticeRound() || configuration.isSecondPracticeRound()) { - experimentGameWindow.updateRoundInstructions(configuration.getInstructions(),priority); - } + experimentGameWindow.updateRoundInstructions(configuration); } }); channel.add(this, new EventTypeProcessor<GroupUpdateEvent>(GroupUpdateEvent.class) { @@ -219,8 +214,7 @@ } public RoundConfiguration getRoundConfiguration() { - - return clientDataModel.getRoundConfiguration(); + return clientDataModel.getRoundConfiguration(); } public void setRoundConfiguration(RoundConfiguration roundConfiguration) { Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationGamePanel.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationGamePanel.java 2009-10-14 22:10:26 UTC (rev 297) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationGamePanel.java 2009-10-15 00:12:05 UTC (rev 298) @@ -26,12 +26,12 @@ */ public class IrrigationGamePanel extends JPanel { - public IrrigationGameWindow controlPanel; + private static final long serialVersionUID = -3878952269498777014L; + + public IrrigationGameWindow controlPanel; public CanalPanel upperPanel; - private static final long serialVersionUID = 1L; - private JPanel jPanelMain = null; //this contains the CanalPanel private JPanel jPanelUpperWindow = null; Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java 2009-10-14 22:10:26 UTC (rev 297) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java 2009-10-15 00:12:05 UTC (rev 298) @@ -147,6 +147,10 @@ public double getShowUpPayment() { return assistant.getDoubleProperty("showup-payment", 5.0d); } + + public String getInitialInstructions() { + return assistant.getProperty("initial-instructions"); + } public Map<String, String> getQuizAnswers() { //System.out.println("I am in the beginning of getquiz"); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <al...@us...> - 2009-10-14 22:10:34
|
Revision: 297 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=297&view=rev Author: alllee Date: 2009-10-14 22:10:26 +0000 (Wed, 14 Oct 2009) Log Message: ----------- starting to simplify/disentangle the irrigation experiment's GUI code. Modified Paths: -------------- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalPanel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChartWindowPanelTokenBandwidth.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/Gate.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationGameWindow.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/MiddleScorePanel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/MiddleWindowPanel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/PieChart.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ScoreBoxPanel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/RoundStartedEvent.java Added Paths: ----------- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ClientDataModel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationGamePanel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/SummaryPanel.java Removed Paths: ------------- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ActivitySummaryPanel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ActivitySummaryPanelNew.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClientGameState.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/MainIrrigationGameWindow.java Deleted: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ActivitySummaryPanel.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ActivitySummaryPanel.java 2009-10-13 17:09:51 UTC (rev 296) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ActivitySummaryPanel.java 2009-10-14 22:10:26 UTC (rev 297) @@ -1,132 +0,0 @@ -/** - * - */ -package edu.asu.commons.irrigation.client; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.GridLayout; - -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.SwingUtilities; - -import edu.asu.commons.irrigation.server.ClientData; - -/** - * @author Sanket - * - */ -public class ActivitySummaryPanel extends JPanel { - - /** - * - */ - private static final long serialVersionUID = -2400441194759984763L; - private JLabel currentBandwidthTextjLabel = null; - private JLabel filesDownloadedjLabel = null; - private JLabel filesDownloadedTextjLabel = null; - private JLabel tokensCollectedjLabel = null; - private JLabel currentBandwidthjLabel = null; - private JLabel tokensCollectedTextjLabel = null; - - private JLabel positionjLabel = null; - private JLabel positionTextjLabel = null; - - private ClientData clientData; // @jve:decl-index=0: - /** - * This method initializes - * - */ - public ActivitySummaryPanel(int i) { - super(); - initialize(i); - } - - /** - * This method initializes this - * - */ - private void initialize(int i) { - tokensCollectedTextjLabel = new JLabel(); - tokensCollectedTextjLabel.setText(""); - currentBandwidthjLabel = new JLabel(); - currentBandwidthjLabel.setText("Current Flow Capacity:"); - tokensCollectedjLabel = new JLabel(); - tokensCollectedjLabel.setText("Tokens Collected:"); - filesDownloadedTextjLabel = new JLabel(); - filesDownloadedTextjLabel.setText(""); - filesDownloadedjLabel = new JLabel(); - filesDownloadedjLabel.setText("Crops Grown:"); - currentBandwidthTextjLabel = new JLabel(); - currentBandwidthTextjLabel.setText(""); - - positionjLabel = new JLabel(); - positionjLabel.setText("Position :"); - - positionTextjLabel = new JLabel(); - positionTextjLabel.setText(""); - - GridLayout gridLayout = new GridLayout(); - gridLayout.setRows(4); - gridLayout.setColumns(2); - this.setLayout(gridLayout); - this.setSize(new Dimension(430,126)); - switch(i) - { - case 0: this.setBackground(Color.PINK); - break; - - case 1: this.setBackground(Color.GREEN); - break; - - case 2: this.setBackground(Color.WHITE); - break; - - case 3: this.setBackground(Color.CYAN); - break; - - case 4: this.setBackground(Color.YELLOW); - break; - } - this.add(positionjLabel, null); - this.add(positionTextjLabel, null); - this.add(currentBandwidthjLabel, null); - this.add(currentBandwidthTextjLabel, null); - this.add(filesDownloadedjLabel, null); - this.add(filesDownloadedTextjLabel, null); - this.add(tokensCollectedjLabel, null); - this.add(tokensCollectedTextjLabel, null); - } - - public void update(ClientData data) { - this.clientData = data; - // TODO Auto-generated method stub - //System.out.println("Client Data Prioriity"+clientData.getPriority()+"Avaiable bandwidth"+ - //clientData.getAvailableBandwidth()); - - Runnable createGuiRunnable = new Runnable(){ - public void run() { - //System.out.println("In the UPdate facilitator"); - positionTextjLabel.setText(new Integer(clientData.getPriority()).toString()); - tokensCollectedTextjLabel.setText(new Integer(clientData.getTotalTokensEarned()).toString()); - if(clientData.getAvailableFlowCapacity() > 25){ - currentBandwidthTextjLabel.setText(new Double(25).toString()); - } - else - currentBandwidthTextjLabel.setText(new Double(clientData.getAvailableFlowCapacity()).toString()); - filesDownloadedTextjLabel.setText(new Integer(clientData.getCropsGrown()).toString()); - } - }; - SwingUtilities.invokeLater(createGuiRunnable); - } - - public void endRound() { - // TODO Auto-generated method stub - currentBandwidthTextjLabel.setText(""); - filesDownloadedTextjLabel.setText(""); - tokensCollectedTextjLabel.setText(""); - - } - -} // @jve:decl-index=0:visual-constraint="10,10" Deleted: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ActivitySummaryPanelNew.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ActivitySummaryPanelNew.java 2009-10-13 17:09:51 UTC (rev 296) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ActivitySummaryPanelNew.java 2009-10-14 22:10:26 UTC (rev 297) @@ -1,221 +0,0 @@ -/** - * - */ -package edu.asu.commons.irrigation.client; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Rectangle; -import java.util.LinkedHashMap; -import java.util.Map; - -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JProgressBar; - -import edu.asu.commons.irrigation.server.ClientData; - - -/** - * @author Sanket - * - */ -public class ActivitySummaryPanelNew extends JPanel { - - /** - * - */ - private static final long serialVersionUID = 2393688647176774993L; - - //create three Maps for every parameter - Map<Integer,JProgressBar>availableBandwidthMap = new LinkedHashMap<Integer, JProgressBar>(); - Map<Integer, JLabel>filesDownLoadedMap = new LinkedHashMap<Integer, JLabel>(); - Map<Integer, JLabel>tokensCollectedMap = new LinkedHashMap<Integer, JLabel>(); - - JLabel labelA; - - JLabel labelB; - - JLabel labelC; - - JLabel labelD; - - JLabel labelE; - - JLabel titleLabel[] = new JLabel[3]; - - //private int NUMBER_OF_PARTICIPANTS_PERGROUP = 2; - - private int parameterIndex; - - IrrigationClient client; // @jve:decl-index=0: - - public ActivitySummaryPanelNew(int parameterIndex, IrrigationClient client) { - // TODO Auto-generated constructor stub - super(); - initialize(parameterIndex,client); - } - - private void initialize(int parameterIndex,IrrigationClient client) { - // TODO Auto-generated method stub - this.parameterIndex = parameterIndex; - - this.client = client; - - this.setLayout(null); - /*else{ - GridLayout gridLayout = new GridLayout(); - gridLayout.setColumns(1); - gridLayout.setRows(5); - this.setLayout(gridLayout); - }*/ - //add the parameters depending on the parameter Index - //initialize Labels - - for(int i=0;i<client.getRoundConfiguration().getClientsPerGroup();i++){ - System.out.println("I reach here"); - switch(i){ - case 0 :labelA = new JLabel(); - labelA.setBounds(new Rectangle(0,30+15*(i+i),25,15)); - if(client.getClientGameState().getPriority() == i){ - labelA.setText("YOU"); - } - else - labelA.setText("A"); - this.add(labelA); - break; - - case 1: labelB = new JLabel(); - labelB.setBounds(new Rectangle(0,30+15*(i+i),25,15)); - if(client.getClientGameState().getPriority() == i){ - labelB.setText("YOU"); - } - else - labelB.setText("B"); - this.add(labelB); - break; - - case 2: labelC = new JLabel(); - labelC.setBounds(new Rectangle(0,30+15*(i+i),25,15)); - if(client.getClientGameState().getPriority() == i){ - labelC.setText("YOU"); - } - else - labelC.setText("C"); - this.add(labelC); - break; - - case 3: labelD = new JLabel(); - labelD.setBounds(new Rectangle(0,30+15*(i+i),25,15)); - if(client.getClientGameState().getPriority() == i){ - labelD.setText("YOU"); - } - else - labelD.setText("D"); - this.add(labelD); - break; - - case 4: labelE = new JLabel(); - labelE.setBounds(new Rectangle(0,30+15*(i+i),25,15)); - if(client.getClientGameState().getPriority() == i){ - labelE.setText("YOU"); - } - else - labelE.setText("E"); - this.add(labelE); - break; - } - } - switch(parameterIndex){ - - case 0 : //add the progress Bbar - this.setBackground(Color.PINK); - titleLabel[0] = new JLabel(); - titleLabel[0].setText("Available Flow Capacity"); - titleLabel[0].setBounds(new Rectangle(60,5,200,20)); - this.add(titleLabel[0],null); - for(int i=0;i<client.getRoundConfiguration().getClientsPerGroup();i++){ - JProgressBar availableBandwidthProgressBar = new JProgressBar(); - availableBandwidthProgressBar.setMaximum(25); - availableBandwidthProgressBar.setBounds(new Rectangle(40,30+15*(i+i),150,15)); - availableBandwidthProgressBar.setStringPainted(true); - if(i == client.getClientGameState().getPriority()){ - availableBandwidthProgressBar.setForeground(Color.ORANGE); - } - else - availableBandwidthProgressBar.setForeground(new Color(51, 153, 255)); - availableBandwidthProgressBar.setBackground(Color.white); - availableBandwidthProgressBar.setValue(25); - this.add(availableBandwidthProgressBar); - availableBandwidthMap.put(new Integer(i), availableBandwidthProgressBar); - } - break; - - case 1 : //add the number of files downloaded - this.setBackground(Color.WHITE); - titleLabel[1] = new JLabel(); - titleLabel[1].setText("Crops Grown"); - titleLabel[1].setBounds(new Rectangle(60,5,200,20)); - this.add(titleLabel[1],null); - for(int i=0;i<client.getRoundConfiguration().getClientsPerGroup();i++){ - JLabel filesDownLoaded = new JLabel(); - filesDownLoaded.setFont(new Font("Serif", Font.BOLD, 14)); - if(i == client.getClientGameState().getPriority()){ - filesDownLoaded.setForeground(Color.ORANGE); - } - else - filesDownLoaded.setForeground(new Color(51,153,255)); - filesDownLoaded.setBounds(new Rectangle(132,30+15*(i+i),100,15)); - this.add(filesDownLoaded); - filesDownLoaded.setText(""); - filesDownLoadedMap.put(new Integer(i),filesDownLoaded); - } - break; - - case 2: //add the number of tokens collected - this.setBackground(Color.WHITE); - titleLabel[2] = new JLabel(); - titleLabel[2].setText("Tokens Collected"); - titleLabel[2].setBounds(new Rectangle(60,5,200,20)); - this.add(titleLabel[2],null); - for(int i=0;i<client.getRoundConfiguration().getClientsPerGroup();i++){ - JLabel tokensCollected = new JLabel(); - tokensCollected.setFont(new Font("Comic Sans MS", Font.BOLD, 14)); - if(i == client.getClientGameState().getPriority()){ - tokensCollected.setForeground(Color.ORANGE); - } - else - tokensCollected.setForeground(new Color(51,153,255)); - tokensCollected.setBounds(new Rectangle(132,30+15*(i+i),100,15)); - this.add(tokensCollected); - tokensCollected.setText(""); - tokensCollectedMap.put(new Integer(i),tokensCollected); - } - break; - } - } - - public void update(ClientData clientData) { - // TODO Auto-generated method stub - switch(parameterIndex){ - case 0 : - availableBandwidthMap.get(new Integer(clientData.getPriority())).setValue((int) clientData.getAvailableFlowCapacity()); - break; - - case 1: - filesDownLoadedMap.get(new Integer(clientData.getPriority())).setText(new Integer(clientData.getCropsGrown()).toString()); - break; - - case 2: - tokensCollectedMap.get(new Integer(clientData.getPriority())).setText(new Integer(clientData.getTotalTokensEarned()).toString()); - break; - } - } - - //implement this Later on - public void endRound() { - // TODO Auto-generated method stub - //implement this later on. - } - -} Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalPanel.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalPanel.java 2009-10-13 17:09:51 UTC (rev 296) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalPanel.java 2009-10-14 22:10:26 UTC (rev 297) @@ -65,7 +65,7 @@ private double totalContributedBandwidth; - private IrrigationClientGameState clientGameState; + private ClientDataModel clientGameState; private int numberofGates = 6; @@ -79,7 +79,7 @@ //////////////////////////////////////////////////////////////////////////// - public CanalPanel(IrrigationClientGameState clientGameState) { + public CanalPanel(ClientDataModel clientGameState) { super(); //when totalContributed bandwidth = 1.0, you dont see the canal line this.totalContributedBandwidth = clientGameState.getGroupDataModel().getMaximumAvailableFlowCapacity(); Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChartWindowPanelTokenBandwidth.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChartWindowPanelTokenBandwidth.java 2009-10-13 17:09:51 UTC (rev 296) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ChartWindowPanelTokenBandwidth.java 2009-10-14 22:10:26 UTC (rev 297) @@ -130,7 +130,7 @@ // final XYSeries actualFlowCapacitySeriesY = new XYSeries("Actual"); final XYSeries initialInfrastructureEfficiencySeries = new XYSeries("Initial"); int x,y; - GroupDataModel group = client.getClientGameState().getGroupDataModel(); + GroupDataModel group = client.getClientDataModel().getGroupDataModel(); final int infrastructureEfficiency = group.getInfrastructureEfficiency(); final int actualFlowCapacity = group.getFlowCapacity(); for(y = 0; y <= actualFlowCapacity; y++) { Copied: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ClientDataModel.java (from rev 296, irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClientGameState.java) =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ClientDataModel.java (rev 0) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ClientDataModel.java 2009-10-14 22:10:26 UTC (rev 297) @@ -0,0 +1,109 @@ +/** + * + */ +package edu.asu.commons.irrigation.client; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import edu.asu.commons.event.EventChannel; +import edu.asu.commons.experiment.DataModel; +import edu.asu.commons.irrigation.conf.RoundConfiguration; +import edu.asu.commons.irrigation.events.ClientUpdateEvent; +import edu.asu.commons.irrigation.events.RoundStartedEvent; +import edu.asu.commons.irrigation.server.ClientData; +import edu.asu.commons.irrigation.server.GroupDataModel; +import edu.asu.commons.net.Identifier; + +/** + * $Id$ + * + * The client side data model, simply wraps a GroupDataModel. + * + * @author <a href='mailto:All...@as...'>Allen Lee</a> + * @version $Rev$ + */ +public class ClientDataModel implements DataModel<RoundConfiguration> { + + private static final long serialVersionUID = -3424256672940188027L; + + private GroupDataModel groupDataModel; + + private IrrigationClient client; + + private RoundConfiguration roundConfiguration; + + private int priority = 0; + + private int timeLeft = 0; + + public ClientDataModel(EventChannel channel, IrrigationClient client) { + this.client = client; + } + + public ClientData getClientData() { + return groupDataModel.getClientData( getId() ); + } + + public Identifier getId() { + return client.getId(); + } + + public List<Identifier> getAllClientIdentifiers() { + return new ArrayList<Identifier>(groupDataModel.getClientIdentifiers()); + } + + public synchronized void initialize(RoundStartedEvent event) { + groupDataModel.clear(); + setGroupDataModel(event.getGroupDataModel()); + setTimeLeft( (int) (getRoundConfiguration().getRoundDuration().getDelta() / 1000L) ); + } + + /** + * Setting priority for this client. + */ + public void setPriority(int priority){ + this.priority = priority; + } + + public int getPriority(){ + return priority; + } + + public void update(ClientUpdateEvent clientUpdateEvent) { + setGroupDataModel(clientUpdateEvent.getGroupDataModel()); + setTimeLeft(clientUpdateEvent.getTimeLeft()); + } + + public void setTimeLeft(int timeLeft) { + this.timeLeft = timeLeft; + } + + public int getTimeLeft() { + return timeLeft; + } + + public RoundConfiguration getRoundConfiguration() { + return roundConfiguration; + } + + public void setRoundConfiguration(RoundConfiguration roundConfiguration) { + this.roundConfiguration = roundConfiguration; + } + + public void setGroupDataModel(GroupDataModel groupDataModel) { + this.groupDataModel = groupDataModel; + setRoundConfiguration(groupDataModel.getRoundConfiguration()); + } + + public GroupDataModel getGroupDataModel() { + return groupDataModel; + } + + public Map<Identifier, ClientData> getClientDataMap() { + return groupDataModel.getClientDataMap(); + } + + +} Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-13 17:09:51 UTC (rev 296) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-14 22:10:26 UTC (rev 297) @@ -1,6 +1,7 @@ package edu.asu.commons.irrigation.client; import java.awt.BorderLayout; +import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; @@ -25,7 +26,6 @@ import javax.swing.SwingUtilities; import javax.swing.Timer; -import edu.asu.commons.event.EventChannel; import edu.asu.commons.irrigation.conf.RoundConfiguration; import edu.asu.commons.irrigation.conf.ServerConfiguration; import edu.asu.commons.irrigation.events.EndRoundEvent; @@ -39,6 +39,7 @@ /** * $Id$ * + * The root experiment window placed in the client's JFrame. * * @author <a href='mailto:All...@as...'>Allen Lee</a> * @version $Rev$ @@ -47,16 +48,12 @@ private static final long serialVersionUID = -5636795631355367711L; - private IrrigationClientGameState state; + private ClientDataModel clientDataModel; - private Component currentCenterComponent; - private JScrollPane instructionsScrollPane; private HtmlEditorPane instructionsEditorPane; - private JPanel subjectWindow; - private JPanel tokenScreenPanel = null; private JPanel graphPanel; @@ -69,9 +66,9 @@ private IrrigationClient client; - private MainIrrigationGameWindow mainIrrigationWindow; + private IrrigationGamePanel irrigationGamePanel; - private StringBuilder instructionsBuilder = new StringBuilder(); // @jve:decl-index=0: + private StringBuilder instructionsBuilder = new StringBuilder(); private int totalContributedTokensPerGroup; @@ -79,104 +76,98 @@ private JButton nextButton; - private JPanel navigationPane; + private JPanel instructionsNavigationPanel; private JButton previousButton; - private JPanel welcomeInstructionsPane; + private JPanel instructionsPanel; private int instructionNumber = 1; private JPanel submitTokenPanel; - private EventChannel channel; + private HtmlEditorPane tokenInstructionsEditorPane; - private HtmlEditorPane tokenInstructionsEditorPane; + private JScrollPane tokenInstructionsScrollPane; - private JScrollPane tokenInstructionsScrollPane; + private int NUMBER_INSTRUCTIONS = 9; - private int NUMBER_INSTRUCTIONS = 9; + private JLabel quizLabel; - private JLabel quizLabel; - - private JLabel quizAnimationLabel = new JLabel(); - - private int pagesTraversed = 0; + private JLabel quizAnimationLabel = new JLabel(); - private JPanel animationInstructionPanel; + private int pagesTraversed = 0; - private JPanel animationPanel; - - private JPanel navigationAnimationPanel; + private JPanel animationInstructionPanel; - private JButton nextAnimationButton; + private JPanel animationPanel; - private JButton previousAnimationButton; + private JPanel navigationAnimationPanel; - private HtmlEditorPane animationInstructionsEditorPane; + private JButton nextAnimationButton; - private JScrollPane animationInstructionsScrollPane; + private JButton previousAnimationButton; - private JPanel chartPanel; + private HtmlEditorPane animationInstructionsEditorPane; - private PieChart pieChart; + private JScrollPane animationInstructionsScrollPane; - public ClientData clientData; + private JPanel chartPanel; - private CanalAnimationPanel canalPanelAnimationNew; + private PieChart pieChart; + public ClientData clientData; + + private CanalAnimationPanel canalAnimationPanel; + + private CardLayout cardLayout; + + private JLabel infrastructureEfficiencyLabel = new JLabel("Current infrastructure efficiency: "); + public ExperimentGameWindow(Dimension screenSize, IrrigationClient client) { this.client = client; - this.state = client.getClientGameState(); + this.clientDataModel = client.getClientDataModel(); // FIXME: set the actual screen size dimensions after this JPanel has // been initialized... // this.screenSize = getParent().getSize(); - this.channel = client.getEventChannel(); // feed subject view the available screen size so that // it can adjust appropriately when given a board size - mainIrrigationWindow = new MainIrrigationGameWindow(screenSize, client); - initGuiComponents(); + initGuiComponents(screenSize); } - private void initGuiComponents() { - setLayout(new BorderLayout()); - instructionsEditorPane = createInstructionsEditorPane(); - instructionsScrollPane = new JScrollPane(instructionsEditorPane); + private void initGuiComponents(Dimension screenSize) { + cardLayout = new CardLayout(); + setLayout(cardLayout); + + instructionsScrollPane = new JScrollPane(getInstructionsEditorPane()); instructionsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); instructionsScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - // getting the initial general instructions + // create a quiz listener and then initialize the instructions. instructionsEditorPane.setActionListener(createQuizListener(client.getServerConfiguration())); instructionsEditorPane.setCaretPosition(0); setInstructions(getGeneralInstructions(0)); - addCenterComponent(getWelcomeInstructionsPane()); - add(getWelcomeInstructionsPane(), BorderLayout.CENTER); - /*setInstructions(getGeneralInstructions(1)); - currentCenterComponent = WelcomeInstructionPane; - *///currentCenterComponent = getWelcomeInstructionPane(); - // setup the Subject Window, add the experiment view - subjectWindow = new JPanel(new BorderLayout(4, 4)); - subjectWindow.setBackground(Color.WHITE); - subjectWindow.setForeground(Color.BLACK); - subjectWindow.add(mainIrrigationWindow, BorderLayout.CENTER); - // setup the SubmitToken View, add the Submit token View - setBackground(Color.WHITE); + + add(getInstructionsPanel(), getInstructionsPanel().getName()); + irrigationGamePanel = new IrrigationGamePanel(screenSize, client); + add(irrigationGamePanel, irrigationGamePanel.getName()); + // add any other panels that need to be switched out. + // FIXME: see if we can simplify the number of instructions panes that Sanket has created. + add(getInstructionsEditorPane()); } - private JLabel infrastructureEfficiencyLabel = new JLabel("Current infrastructure efficiency: "); - - private JPanel getTokenScreenPanel() { + private JPanel getTokenScreenPanel() { if (tokenScreenPanel == null) { - tokenScreenPanel = new JPanel(); + tokenScreenPanel = new JPanel(); tokenScreenPanel.setLayout(new BorderLayout()); tokenInstructionsEditorPane = createInstructionsEditorPane(); tokenInstructionsScrollPane = new JScrollPane(tokenInstructionsEditorPane); tokenScreenPanel.add(tokenInstructionsScrollPane, BorderLayout.CENTER); //setInstructions(getGeneralInstructions(11)); -// StringBuilder tokenSubmissionInstructionsBuilder = new StringBuilder("<h3>The current infrastructure efficiency is: "); -// -// tokenSubmissionInstructionsBuilder.append("% </h3>"); -// tokenSubmissionInstructionsBuilder.append( + // StringBuilder tokenSubmissionInstructionsBuilder = new StringBuilder("<h3>The current infrastructure efficiency is: "); + // + // tokenSubmissionInstructionsBuilder.append("% </h3>"); + // tokenSubmissionInstructionsBuilder.append( StringBuilder tokenSubmissionInstructionsBuilder = new StringBuilder(getGeneralInstructions(11, pagesTraversed)); tokenInstructionsEditorPane.setText(tokenSubmissionInstructionsBuilder.toString()); tokenInstructionsEditorPane.setCaretPosition(0); @@ -188,22 +179,22 @@ updateInfrastructureEfficiencyLabel(); return tokenScreenPanel; } - - public void updateInfrastructureEfficiencyLabel() { - GroupDataModel group = client.getClientGameState().getGroupDataModel(); - RoundConfiguration roundConfiguration = client.getRoundConfiguration(); - int infrastructureEfficiency = 0; - if (roundConfiguration.isPracticeRound() || roundConfiguration.isFirstRound()) { - infrastructureEfficiency = roundConfiguration.getInitialInfrastructureEfficiency(); - } - else { - System.err.println("group was not null, efficiency is: " + group.getInfrastructureEfficiency() + " degrading by " + client.getRoundConfiguration().getInfrastructureDegradationFactor()); - infrastructureEfficiency = group.getInfrastructureEfficiency() - roundConfiguration.getInfrastructureDegradationFactor(); - } - infrastructureEfficiencyLabel.setText("Current infrastructure efficiency: " + infrastructureEfficiency); - infrastructureEfficiencyLabel.repaint(); - } + public void updateInfrastructureEfficiencyLabel() { + GroupDataModel group = client.getClientDataModel().getGroupDataModel(); + RoundConfiguration roundConfiguration = client.getRoundConfiguration(); + int infrastructureEfficiency = 0; + if (roundConfiguration.isPracticeRound() || roundConfiguration.isFirstRound()) { + infrastructureEfficiency = roundConfiguration.getInitialInfrastructureEfficiency(); + } + else { + System.err.println("group was not null, efficiency is: " + group.getInfrastructureEfficiency() + " degrading by " + client.getRoundConfiguration().getInfrastructureDegradationFactor()); + infrastructureEfficiency = group.getInfrastructureEfficiency() - roundConfiguration.getInfrastructureDegradationFactor(); + } + infrastructureEfficiencyLabel.setText("Current infrastructure efficiency: " + infrastructureEfficiency); + infrastructureEfficiencyLabel.repaint(); + } + private JPanel getSubmitTokenPanel() { if (submitTokenPanel == null) { submitTokenPanel = new JPanel(); @@ -215,27 +206,29 @@ return submitTokenPanel; } - private JPanel getWelcomeInstructionsPane() { - if (welcomeInstructionsPane == null) { - welcomeInstructionsPane = new JPanel(); - welcomeInstructionsPane.setLayout(new BorderLayout()); - welcomeInstructionsPane.add(instructionsScrollPane, BorderLayout.CENTER); - welcomeInstructionsPane.add(getNavigationButtonPane(), BorderLayout.SOUTH); - } - return welcomeInstructionsPane; + private JPanel getInstructionsPanel() { + if (instructionsPanel == null) { + instructionsPanel = new JPanel(); + instructionsPanel.setName("General instructions panel"); + instructionsPanel.setLayout(new BorderLayout()); + instructionsPanel.add(instructionsScrollPane, BorderLayout.CENTER); + instructionsPanel.add(getInstructionsNavigationPanel(), BorderLayout.PAGE_END); + } + return instructionsPanel; } - private JPanel getNavigationButtonPane() { - if (navigationPane == null) { - navigationPane = new JPanel(); - navigationPane.setLayout(new BorderLayout()); - navigationPane.add(getNextButton(), BorderLayout.EAST); - navigationPane.add(getPreviousButton(), BorderLayout.WEST); + private JPanel getInstructionsNavigationPanel() { + if (instructionsNavigationPanel == null) { + instructionsNavigationPanel = new JPanel(); + instructionsNavigationPanel.setLayout(new BorderLayout()); + instructionsNavigationPanel.add(getNextButton(), BorderLayout.LINE_START); + instructionsNavigationPanel.add(getPreviousButton(), BorderLayout.LINE_END); + // this is just to add spacing I think. quizLabel = new JLabel(); - navigationPane.add(quizLabel, BorderLayout.CENTER); + instructionsNavigationPanel.add(quizLabel, BorderLayout.CENTER); } - return navigationPane; + return instructionsNavigationPanel; } private JButton getNextButton() { @@ -244,15 +237,15 @@ nextButton.setText("Next"); nextButton.setEnabled(false); nextButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - quizLabel.setText(""); - - previousButton.setEnabled(true); - if(instructionNumber >= pagesTraversed){ - nextButton.setEnabled(false); - } - - // getting the next instruction Number + public void actionPerformed(java.awt.event.ActionEvent e) { + quizLabel.setText(""); + + previousButton.setEnabled(true); + if(instructionNumber >= pagesTraversed){ + nextButton.setEnabled(false); + } + + // getting the next instruction Number if (instructionNumber == NUMBER_INSTRUCTIONS) { } @@ -261,122 +254,123 @@ System.out.println("instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); if(instructionNumber == 5){ - quizAnimationLabel.setText(""); - addCenterComponent(getAnimationInstructionPane()); - //addCenterComponent(getTokenScreenPanel()); + quizAnimationLabel.setText(""); + addCenterComponent(getAnimationInstructionPane()); + //addCenterComponent(getTokenScreenPanel()); } else { - addCenterComponent(getWelcomeInstructionsPane()); + addCenterComponent(getInstructionsPanel()); } } - + }); } return nextButton; } - private JPanel getAnimationInstructionPane() { + private JPanel getAnimationInstructionPane() { if (animationInstructionPanel == null) { - animationInstructionPanel = new JPanel(); + animationInstructionPanel = new JPanel(); + animationInstructionPanel.setName("Animated instruction panel"); animationInstructionPanel.setLayout(new BorderLayout()); - animationInstructionPanel.add(getAnimationPane(), BorderLayout.CENTER); - + animationInstructionPanel.add(getAnimationPane(), BorderLayout.CENTER); + animationInstructionPanel.add(getNavigationAnimationPanel(), BorderLayout.SOUTH); animationInstructionPanel.setBackground(Color.WHITE); return animationInstructionPanel; } //System.out.println("instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); animationInstructionsEditorPane.setText(getGeneralInstructions(instructionNumber,pagesTraversed)); - return animationInstructionPanel; - } - - + return animationInstructionPanel; + } + + private JPanel getNavigationAnimationPanel() { if (navigationAnimationPanel == null) { - + navigationAnimationPanel = new JPanel(); navigationAnimationPanel.setLayout(new BorderLayout()); navigationAnimationPanel.add(getNextAnimationButton(), BorderLayout.EAST); navigationAnimationPanel.add(getPreviousAnimationButton(), BorderLayout.WEST); - + quizAnimationLabel.setText(""); navigationAnimationPanel.add(quizAnimationLabel, BorderLayout.CENTER); } return navigationAnimationPanel; - } + } - private JButton getPreviousAnimationButton() { - if (previousAnimationButton == null) { - previousAnimationButton = new JButton(); - previousAnimationButton.setText("Previous"); - previousAnimationButton.setEnabled(true); - previousAnimationButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - quizLabel.setText(""); - // getting the next instruction Number - nextButton.setEnabled(true); - if (instructionNumber == 1) { - - } else - instructionNumber--; - if(instructionNumber > 1) - previousButton.setEnabled(true); - else - previousButton.setEnabled(false); - System.out.println("instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); - setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); - addCenterComponent(getWelcomeInstructionsPane()); - } - }); - return previousAnimationButton; + private JButton getPreviousAnimationButton() { + if (previousAnimationButton == null) { + previousAnimationButton = new JButton(); + previousAnimationButton.setText("Previous"); + previousAnimationButton.setEnabled(true); + previousAnimationButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent e) { + quizLabel.setText(""); + // getting the next instruction Number + nextButton.setEnabled(true); + if (instructionNumber == 1) { - } - return previousAnimationButton; - } + } else + instructionNumber--; + if(instructionNumber > 1) + previousButton.setEnabled(true); + else + previousButton.setEnabled(false); + System.out.println("instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); + setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); + addCenterComponent(getInstructionsPanel()); + } + }); + return previousAnimationButton; - private JButton getNextAnimationButton() { - if (nextAnimationButton == null) { - nextAnimationButton = new JButton(); - nextAnimationButton.setText("Next"); - nextAnimationButton.setEnabled(false); - nextAnimationButton.addActionListener(new java.awt.event.ActionListener() { - + } + return previousAnimationButton; + } - public void actionPerformed(java.awt.event.ActionEvent e) { - quizLabel.setText(""); - previousButton.setEnabled(true); - if(instructionNumber >= pagesTraversed) - nextButton.setEnabled(false); - // getting the next instruction Number - if (instructionNumber != NUMBER_INSTRUCTIONS) { - instructionNumber++; - } - System.out.println("instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); - setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); - if(instructionNumber == 5){ - addCenterComponent(getAnimationInstructionPane()); - //addCenterComponent(getTokenScreenPanel()); - } - else - addCenterComponent(getWelcomeInstructionsPane()); - } - - }); + private JButton getNextAnimationButton() { + if (nextAnimationButton == null) { + nextAnimationButton = new JButton(); + nextAnimationButton.setText("Next"); + nextAnimationButton.setEnabled(false); + nextAnimationButton.addActionListener(new java.awt.event.ActionListener() { - } - return nextAnimationButton; - - } - private JPanel getAnimationPane() { + public void actionPerformed(java.awt.event.ActionEvent e) { + quizLabel.setText(""); + previousButton.setEnabled(true); + if(instructionNumber >= pagesTraversed) + nextButton.setEnabled(false); + // getting the next instruction Number + if (instructionNumber != NUMBER_INSTRUCTIONS) { + instructionNumber++; + } + System.out.println("instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); + setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); + if(instructionNumber == 5){ + addCenterComponent(getAnimationInstructionPane()); + //addCenterComponent(getTokenScreenPanel()); + } + else + addCenterComponent(getInstructionsPanel()); + } + + }); + + } + return nextAnimationButton; + + } + + private JPanel getAnimationPane() { if (animationPanel == null) { - animationPanel = new JPanel(); - animationPanel.setLayout(new BorderLayout()); - //FIXME: Here the animation panel needs to be decided on fly - //canalPanelAnimation = new CanalPanelAnimation(40); - canalPanelAnimationNew = new CanalAnimationPanel(40); - animationPanel.add(canalPanelAnimationNew,BorderLayout.CENTER); + animationPanel = new JPanel(); + animationPanel.setLayout(new BorderLayout()); + //FIXME: Here the animation panel needs to be decided on fly + //canalPanelAnimation = new CanalPanelAnimation(40); + canalAnimationPanel = new CanalAnimationPanel(40); + animationPanel.add(canalAnimationPanel,BorderLayout.CENTER); animationInstructionsEditorPane = createInstructionsEditorPane(); animationInstructionsScrollPane = new JScrollPane(animationInstructionsEditorPane); animationInstructionsEditorPane.setActionListener(createQuizListener(client.getServerConfiguration())); @@ -390,38 +384,38 @@ animationPanel.setBackground(Color.WHITE); return animationPanel; } - + return animationPanel; - } + } - private JButton getPreviousButton() { + private JButton getPreviousButton() { if (previousButton == null) { previousButton = new JButton(); previousButton.setText("Previous"); previousButton.setEnabled(false); previousButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { - quizLabel.setText(""); + quizLabel.setText(""); // getting the next instruction Number - nextButton.setEnabled(true); + nextButton.setEnabled(true); if (instructionNumber == 1) { - + } else instructionNumber--; if(instructionNumber > 1) - previousButton.setEnabled(true); + previousButton.setEnabled(true); else - previousButton.setEnabled(false); + previousButton.setEnabled(false); System.out.println("instruction number : "+instructionNumber+" pages traversed"+pagesTraversed); setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); if(instructionNumber == 5){ - quizAnimationLabel.setText(""); - nextAnimationButton.setEnabled(true); - addCenterComponent(getAnimationInstructionPane()); - //addCenterComponent(getTokenScreenPanel()); + quizAnimationLabel.setText(""); + nextAnimationButton.setEnabled(true); + addCenterComponent(getAnimationInstructionPane()); + //addCenterComponent(getTokenScreenPanel()); } else - addCenterComponent(getWelcomeInstructionsPane()); + addCenterComponent(getInstructionsPanel()); } }); return previousButton; @@ -438,31 +432,31 @@ * @return */ private String getGeneralInstructions(int pageNumber, int pagesTraversed) { - /*if(pageNumber == 2){ + /*if(pageNumber == 2){ if(client.getClientGameState().getPriority()== 0) return client.getServerConfiguration().getGeneralInstructions(20); else return client.getServerConfiguration().getGeneralInstructions(21); }*/ - + return client.getServerConfiguration().getGeneralInstructions(pageNumber,pagesTraversed, - client.getClientGameState().getPriority()); + client.getClientDataModel().getPriority()); } - + private String getGeneralInstructions(int pageNumber) { - return client.getServerConfiguration().getGeneralInstructions(pageNumber); - } + return client.getServerConfiguration().getGeneralInstructions(pageNumber); + } private JTextField getEnterTokens() { if (enterTokens == null) { enterTokens = new JTextField(); enterTokens.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent event) { - submitInvestedTokens(); - } + public void actionPerformed(ActionEvent event) { + submitInvestedTokens(); + } }); } - + return enterTokens; } @@ -473,15 +467,15 @@ submitTokensButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { try{ - submitInvestedTokens(); + submitInvestedTokens(); } - catch(NumberFormatException e1){ - enterTokens.setText(""); + catch(NumberFormatException e1){ + enterTokens.setText(""); instructionsBuilder.delete(0, instructionsBuilder.length()); instructionsBuilder.append("\nPlease Enter your tokens within the range 0 -10"); instructionsBuilder.append(getGeneralInstructions(11,pagesTraversed)); tokenInstructionsEditorPane.setText(instructionsBuilder.toString()); - } + } } @@ -490,18 +484,14 @@ } return submitTokensButton; } - + private void submitInvestedTokens() throws NumberFormatException { - int token = Integer.parseInt(enterTokens.getText()); - // validating token range + int token = Integer.parseInt(enterTokens.getText()); + // validating token range if (token >= 0 && token <= 10) { - client.transmitTokenContributed(token); + client.transmitTokenContributed(token); updateInstructions("Please wait while the server computes your total flow capacity based on your group's total token contribution investment."); - addCenterComponent(instructionsEditorPane); - - /* setInstructions(getGeneralInstructions(instructionNumber,pagesTraversed)); - addCenterComponent(getWelcomeInstructionPane());*/ - + addCenterComponent(getInstructionsEditorPane()); } else { enterTokens.setText(""); @@ -514,30 +504,39 @@ // /////////////////////////////////////////////////////////////////////////////////////////////////////////// - private HtmlEditorPane createInstructionsEditorPane() { + private HtmlEditorPane getInstructionsEditorPane() { // JEditorPane pane = new JEditorPane("text/html", // "Costly Sanctioning Experiment"); - final HtmlEditorPane htmlPane = new HtmlEditorPane(); - htmlPane.setPreferredSize(new Dimension(400, 400)); - htmlPane.setEditable(false); - htmlPane.setFont(new Font("serif", Font.PLAIN, 12)); - return htmlPane; + if (instructionsEditorPane == null) { + instructionsEditorPane = createInstructionsEditorPane(); + } + return instructionsEditorPane; } - + private HtmlEditorPane createInstructionsEditorPane() { + HtmlEditorPane htmlEditorPane = new HtmlEditorPane(); + htmlEditorPane.setPreferredSize(new Dimension(400, 400)); + htmlEditorPane.setEditable(false); + htmlEditorPane.setFont(new Font("serif", Font.PLAIN, 12)); + return htmlEditorPane; + } + + + private void addCenterComponent(Component newCenterComponent) { - if (currentCenterComponent != null) { - currentCenterComponent.setVisible(false); - remove(currentCenterComponent); - add(newCenterComponent, BorderLayout.CENTER); - newCenterComponent.setVisible(true); - invalidate(); - validate(); - newCenterComponent.repaint(); - repaint(); - } - currentCenterComponent = newCenterComponent; + cardLayout.show(this, newCenterComponent.getName()); + // if (currentCenterComponent != null) { + // currentCenterComponent.setVisible(false); + // remove(currentCenterComponent); + // add(newCenterComponent, BorderLayout.CENTER); + // newCenterComponent.setVisible(true); + // invalidate(); + // validate(); + // newCenterComponent.repaint(); + // repaint(); + // } + // currentCenterComponent = newCenterComponent; } public void startRound(final RoundConfiguration configuration) { @@ -545,9 +544,9 @@ // currentExperimentConfiguration = configuration; Runnable runnable = new Runnable() { public void run() { - addCenterComponent(subjectWindow); +// addCenterComponent(subjectWindow); requestFocusInWindow(); - + } }; SwingUtilities.invokeLater(runnable); @@ -558,11 +557,11 @@ * rid of the sendContributionStatus then */ public void updateContributions() { - mainIrrigationWindow.updateContributions(state); + irrigationGamePanel.updateContributions(clientDataModel); } public void update() { - mainIrrigationWindow.updateClientStatus(state); + irrigationGamePanel.updateClientStatus(clientDataModel); } /* @@ -570,8 +569,7 @@ * instructionsScrollPane with the debreifing information */ public void updateEndRoundEvent(final EndRoundEvent event) { - // TODO Auto-generated method stub - mainIrrigationWindow.updateEndRoundEvent(); + irrigationGamePanel.endRound(); Runnable runnable = new Runnable() { public void run() { enterTokens.setText(""); @@ -598,58 +596,58 @@ private void addDebriefingText(EndRoundEvent event) { instructionsBuilder.delete(0, instructionsBuilder.length()); - + Map<Identifier,ClientData>clientDataMap = event.getClientDataMap(); - + //create a map of clientData based on priority as the index structure Map<Integer,ClientData>clientDataMapIndexInteger = new LinkedHashMap<Integer,ClientData>(); - - String position = "Your Position is :"; - position = position+mapClientPosition(client.getClientGameState().getPriority()); + + String position = "Your position is :"; + position = position+mapClientPosition(client.getClientDataModel().getPriority()); for(ClientData clientData : clientDataMap.values()){ - clientDataMapIndexInteger.put(new Integer(clientData.getPriority()), clientData); + clientDataMapIndexInteger.put(new Integer(clientData.getPriority()), clientData); } // FIXME: this is horrendous instructionsBuilder.append(String.format( - position+ - "<table><thead><th></th><th></th><th>A</th><th></th><th>B</th><th></th><th>C</th><th></th><th>D</th><th></th><th>E</th></thead><tbody>"+ - "<tr><td>A Initial endowment</td><td></td><td>10</td><td></td><td>10</td><td></td><td>10</td><td></td><td>10</td><td></td><td>10</td></tr>"+ - "<tr><td>B Infrastructure investment</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td></tr>"+ - "<tr><td>C Kept endowment (A - B)</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td></tr>"+ - "<tr><td>D Return from growing crops</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td></tr>"+ - "<tr><td>E Total tokens earned in last round(D+C)</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td></tr>"+ - "<tr><td>F Total dollars earned in this round (E*0.1$)</td><td></td><td>%3.2f</td><td></td><td>%3.2f</td><td></td><td>%3.2f</td><td></td><td>%3.2f</td><td></td><td>%3.2f</td></tr>", - clientDataMapIndexInteger.get(new Integer(0)).getContributedTokens(), - clientDataMapIndexInteger.get(new Integer(1)).getContributedTokens(), - clientDataMapIndexInteger.get(new Integer(2)).getContributedTokens(), - clientDataMapIndexInteger.get(new Integer(3)).getContributedTokens(), - clientDataMapIndexInteger.get(new Integer(4)).getContributedTokens(), - - 10 - clientDataMapIndexInteger.get(new Integer(0)).getContributedTokens(), - 10 - clientDataMapIndexInteger.get(new Integer(1)).getContributedTokens(), - 10 - clientDataMapIndexInteger.get(new Integer(2)).getContributedTokens(), - 10 - clientDataMapIndexInteger.get(new Integer(3)).getContributedTokens(), - 10 - clientDataMapIndexInteger.get(new Integer(4)).getContributedTokens(), - - clientDataMapIndexInteger.get(new Integer(0)).getTotalTokensEarned() - (10 - clientDataMapIndexInteger.get(new Integer(0)).getContributedTokens()), - clientDataMapIndexInteger.get(new Integer(1)).getTotalTokensEarned() - (10 - clientDataMapIndexInteger.get(new Integer(1)).getContributedTokens()), - clientDataMapIndexInteger.get(new Integer(2)).getTotalTokensEarned() - (10 - clientDataMapIndexInteger.get(new Integer(2)).getContributedTokens()), - clientDataMapIndexInteger.get(new Integer(3)).getTotalTokensEarned() - (10 - clientDataMapIndexInteger.get(new Integer(3)).getContributedTokens()), - clientDataMapIndexInteger.get(new Integer(4)).getTotalTokensEarned() - (10 - clientDataMapIndexInteger.get(new Integer(4)).getContributedTokens()), - - clientDataMapIndexInteger.get(new Integer(0)).getTotalTokensEarned(), - clientDataMapIndexInteger.get(new Integer(1)).getTotalTokensEarned(), - clientDataMapIndexInteger.get(new Integer(2)).getTotalTokensEarned(), - clientDataMapIndexInteger.get(new Integer(3)).getTotalTokensEarned(), - clientDataMapIndexInteger.get(new Integer(4)).getTotalTokensEarned(), - - (float)clientDataMapIndexInteger.get(new Integer(0)).getRoundConfiguration().getDollarsPerToken()*clientDataMapIndexInteger.get(new Integer(0)).getTotalTokensEarned(), - (float)clientDataMapIndexInteger.get(new Integer(1)).getRoundConfiguration().getDollarsPerToken()*clientDataMapIndexInteger.get(new Integer(1)).getTotalTokensEarned(), - (float)clientDataMapIndexInteger.get(new Integer(2)).getRoundConfiguration().getDollarsPerToken()*clientDataMapIndexInteger.get(new Integer(2)).getTotalTokensEarned(), - (float)clientDataMapIndexInteger.get(new Integer(3)).getRoundConfiguration().getDollarsPerToken()*clientDataMapIndexInteger.get(new Integer(3)).getTotalTokensEarned(), - (float)clientDataMapIndexInteger.get(new Integer(4)).getRoundConfiguration().getDollarsPerToken()*clientDataMapIndexInteger.get(new Integer(4)).getTotalTokensEarned() - - /* + position+ + "<table><thead><th></th><th></th><th>A</th><th></th><th>B</th><th></th><th>C</th><th></th><th>D</th><th></th><th>E</th></thead><tbody>"+ + "<tr><td>A Initial endowment</td><td></td><td>10</td><td></td><td>10</td><td></td><td>10</td><td></td><td>10</td><td></td><td>10</td></tr>"+ + "<tr><td>B Infrastructure investment</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td></tr>"+ + "<tr><td>C Kept endowment (A - B)</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td></tr>"+ + "<tr><td>D Return from growing crops</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td></tr>"+ + "<tr><td>E Total tokens earned in last round(D+C)</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td><td></td><td>%d</td></tr>"+ + "<tr><td>F Total dollars earned in this round (E*0.1$)</td><td></td><td>%3.2f</td><td></td><td>%3.2f</td><td></td><td>%3.2f</td><td></td><td>%3.2f</td><td></td><td>%3.2f</td></tr>", + clientDataMapIndexInteger.get(new Integer(0)).getContributedTokens(), + clientDataMapIndexInteger.get(new Integer(1)).getContributedTokens(), + clientDataMapIndexInteger.get(new Integer(2)).getContributedTokens(), + clientDataMapIndexInteger.get(new Integer(3)).getContributedTokens(), + clientDataMapIndexInteger.get(new Integer(4)).getContributedTokens(), + + 10 - clientDataMapIndexInteger.get(new Integer(0)).getContributedTokens(), + 10 - clientDataMapIndexInteger.get(new Integer(1)).getContributedTokens(), + 10 - clientDataMapIndexInteger.get(new Integer(2)).getContributedTokens(), + 10 - clientDataMapIndexInteger.get(new Integer(3)).getContributedTokens(), + 10 - clientDataMapIndexInteger.get(new Integer(4)).getContributedTokens(), + + clientDataMapIndexInteger.get(new Integer(0)).getTotalTokensEarned() - (10 - clientDataMapIndexInteger.get(new Integer(0)).getContributedTokens()), + clientDataMapIndexInteger.get(new Integer(1)).getTotalTokensEarned() - (10 - clientDataMapIndexInteger.get(new Integer(1)).getContributedTokens()), + clientDataMapIndexInteger.get(new Integer(2)).getTotalTokensEarned() - (10 - clientDataMapIndexInteger.get(new Integer(2)).getContributedTokens()), + clientDataMapIndexInteger.get(new Integer(3)).getTotalTokensEarned() - (10 - clientDataMapIndexInteger.get(new Integer(3)).getContributedTokens()), + clientDataMapIndexInteger.get(new Integer(4)).getTotalTokensEarned() - (10 - clientDataMapIndexInteger.get(new Integer(4)).getContributedTokens()), + + clientDataMapIndexInteger.get(new Integer(0)).getTotalTokensEarned(), + clientDataMapIndexInteger.get(new Integer(1)).getTotalTokensEarned(), + clientDataMapIndexInteger.get(new Integer(2)).getTotalTokensEarned(), + clientDataMapIndexInteger.get(new Integer(3)).getTotalTokensEarned(), + clientDataMapIndexInteger.get(new Integer(4)).getTotalTokensEarned(), + + (float)clientDataMapIndexInteger.g... [truncated message content] |
From: <al...@us...> - 2009-10-13 17:10:03
|
Revision: 296 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=296&view=rev Author: alllee Date: 2009-10-13 17:09:51 +0000 (Tue, 13 Oct 2009) Log Message: ----------- adding cached SocketDispatcherWorker that uses cached Object(Input|Output)Streams instead of recreating them each time. Should probably create a subtype of both that uses either and make it configurable. Modified Paths: -------------- csidex/trunk/src/main/java/edu/asu/commons/event/AbstractEvent.java csidex/trunk/src/main/java/edu/asu/commons/event/AbstractPersistableEvent.java csidex/trunk/src/main/java/edu/asu/commons/experiment/AbstractExperiment.java csidex/trunk/src/main/java/edu/asu/commons/experiment/StateMachine.java csidex/trunk/src/main/java/edu/asu/commons/net/ClientSocketDispatcher.java csidex/trunk/src/main/java/edu/asu/commons/net/DispatcherFactory.java csidex/trunk/src/main/java/edu/asu/commons/net/ServerSocketDispatcher.java csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java csidex/trunk/src/main/java/edu/asu/commons/util/Duration.java Modified: csidex/trunk/src/main/java/edu/asu/commons/event/AbstractEvent.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/event/AbstractEvent.java 2009-10-13 17:09:24 UTC (rev 295) +++ csidex/trunk/src/main/java/edu/asu/commons/event/AbstractEvent.java 2009-10-13 17:09:51 UTC (rev 296) @@ -16,7 +16,7 @@ private final static long serialVersionUID = -3443360054002127621L; - protected Identifier id; + protected final Identifier id; protected long creationTime; private final String message; @@ -34,9 +34,7 @@ "a null Identifier"); } this.id = id; - // FIXME: switch to System.currentTimeNanos() once we become Java 1.5 - // compliant. - this.creationTime = System.currentTimeMillis(); + this.creationTime = System.nanoTime(); this.message = message; } @@ -46,10 +44,15 @@ public Identifier getId() { return id; } + + public String getMessage() { + return message; + } public String toString() { if (message == null) { - return getClass() + " id [" + id + "], creation time [ " + creationTime + "]"; + return String.format("%s - id: %s, created on %d", getClass(), id, creationTime); +// return getClass() + " id [" + id + "], creation time [ " + creationTime + "]"; } return message; } Modified: csidex/trunk/src/main/java/edu/asu/commons/event/AbstractPersistableEvent.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/event/AbstractPersistableEvent.java 2009-10-13 17:09:24 UTC (rev 295) +++ csidex/trunk/src/main/java/edu/asu/commons/event/AbstractPersistableEvent.java 2009-10-13 17:09:51 UTC (rev 296) @@ -7,7 +7,7 @@ * $Id$ * * Base class that provides uniqueness with respect to the time-ordered stream - * of Events originating from a single place. + * of Events originating from a single place. * * @author <a href='mailto:All...@as...'>Allen Lee</a> * @version $Revision$ @@ -51,6 +51,6 @@ } public final void timestamp() { - super.creationTime = System.currentTimeMillis(); + super.creationTime = System.nanoTime(); } } Modified: csidex/trunk/src/main/java/edu/asu/commons/experiment/AbstractExperiment.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/experiment/AbstractExperiment.java 2009-10-13 17:09:24 UTC (rev 295) +++ csidex/trunk/src/main/java/edu/asu/commons/experiment/AbstractExperiment.java 2009-10-13 17:09:51 UTC (rev 296) @@ -37,19 +37,6 @@ private final List<Command> commands = new LinkedList<Command>(); private Thread serverThread; -// private final Thread eventHandlingThread = new Thread() { -// public void run() { -// while ( isRunning() ) { -// synchronized (commands) { -// for (Iterator<Command> iterator = commands.iterator(); iterator.hasNext(); ) { -// iterator.next().execute(); -// iterator.remove(); -// } -// } -// AbstractExperiment.sleep(50); -// } -// } -// }; private boolean running; Modified: csidex/trunk/src/main/java/edu/asu/commons/experiment/StateMachine.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/experiment/StateMachine.java 2009-10-13 17:09:24 UTC (rev 295) +++ csidex/trunk/src/main/java/edu/asu/commons/experiment/StateMachine.java 2009-10-13 17:09:51 UTC (rev 296) @@ -5,7 +5,7 @@ /** * $Id$ * - * Very basic experiment state machine. + * Basic experiment state machine. * * @author <a href='mailto:All...@as...'>Allen Lee</a> * @version $Revision$ @@ -13,4 +13,5 @@ public interface StateMachine { public void initialize(); public void execute(Dispatcher dispatcher); +// public void execute(); } \ No newline at end of file Modified: csidex/trunk/src/main/java/edu/asu/commons/net/ClientSocketDispatcher.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/net/ClientSocketDispatcher.java 2009-10-13 17:09:24 UTC (rev 295) +++ csidex/trunk/src/main/java/edu/asu/commons/net/ClientSocketDispatcher.java 2009-10-13 17:09:51 UTC (rev 296) @@ -47,13 +47,14 @@ Socket socket = new Socket(); socket.connect(inetSocketAddress); // block while we wait for the ServerSocketDispatcher to assign an - // Identifier to us. - Event event = SocketDispatcherWorker.readEvent(socket); + // Identifier to us. The construction of an ObjectInputStream blocks. + worker = new SocketDispatcherWorker(this, socket); + ConnectionEvent event = (ConnectionEvent) worker.readEvent(); assert event instanceof ConnectionEvent; Identifier id = event.getId(); - worker = new SocketDispatcherWorker(this, id, socket); + worker.setId(id); worker.start(); - getLocalEventHandler().handle((ConnectionEvent) event); + getLocalEventHandler().handle(event); return id; } catch (IOException e) { Modified: csidex/trunk/src/main/java/edu/asu/commons/net/DispatcherFactory.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/net/DispatcherFactory.java 2009-10-13 17:09:24 UTC (rev 295) +++ csidex/trunk/src/main/java/edu/asu/commons/net/DispatcherFactory.java 2009-10-13 17:09:51 UTC (rev 296) @@ -23,8 +23,8 @@ } public ClientDispatcher createClientDispatcher(EventChannel channel) { -// return new ClientSocketDispatcher(channel); - return new NioDispatcher(channel, 1); + return new ClientSocketDispatcher(channel); +// return new NioDispatcher(channel, 1); } public ServerDispatcher createServerDispatcher(EventChannel channel) { @@ -32,7 +32,7 @@ } public ServerDispatcher createServerDispatcher(EventChannel channel, int workerPoolSize) { - return new NioDispatcher(channel, workerPoolSize); -// return new ServerSocketDispatcher(channel, workerPoolSize); +// return new NioDispatcher(channel, workerPoolSize); + return new ServerSocketDispatcher(channel, workerPoolSize); } } Modified: csidex/trunk/src/main/java/edu/asu/commons/net/ServerSocketDispatcher.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/net/ServerSocketDispatcher.java 2009-10-13 17:09:24 UTC (rev 295) +++ csidex/trunk/src/main/java/edu/asu/commons/net/ServerSocketDispatcher.java 2009-10-13 17:09:51 UTC (rev 296) @@ -91,8 +91,7 @@ return; } Identifier id = new SocketIdentifier(incoming); - // FIXME: consider pooling socket connections - SocketDispatcherWorker worker = new SocketDispatcherWorker(this, id, incoming); + SocketDispatcherWorker worker = new SocketDispatcherWorker(this, incoming, id); // immediately write a ConnectionEvent to the incoming connection. ConnectionEvent event = new ConnectionEvent(id); worker.write(event); Modified: csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java 2009-10-13 17:09:24 UTC (rev 295) +++ csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java 2009-10-13 17:09:51 UTC (rev 296) @@ -27,13 +27,22 @@ private final Dispatcher dispatcher; private final Socket socket; - private final Identifier id; + private Identifier id; private Thread workerThread; private boolean running; + private ObjectOutputStream cachedOut; + private ObjectInputStream cachedIn; - protected SocketDispatcherWorker(Dispatcher dispatcher, Identifier id, Socket socket) throws IOException { + protected SocketDispatcherWorker(Dispatcher dispatcher, Socket socket) throws IOException { this.dispatcher = dispatcher; this.socket = socket; + cachedOut = new ObjectOutputStream(socket.getOutputStream()); + cachedOut.flush(); + cachedIn = new ObjectInputStream(socket.getInputStream()); + } + + protected SocketDispatcherWorker(Dispatcher dispatcher, Socket socket, Identifier id) throws IOException { + this(dispatcher, socket); this.id = id; } @@ -68,9 +77,12 @@ try { // FIXME: consider caching the object output stream? synchronized (socket) { - ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); - out.writeObject(event); - out.flush(); +// ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); +// out.writeObject(event); +// out.flush(); + cachedOut.reset(); + cachedOut.writeObject(event); + cachedOut.flush(); } // XXX: don't close() the stream. It closes the wrapped Socket // output stream and essentially fubars the socket. @@ -96,7 +108,9 @@ } public synchronized Event readEvent() throws IOException, ClassNotFoundException { - return SocketDispatcherWorker.readEvent(socket); +// return SocketDispatcherWorker.readEvent(socket); + + return (Event) cachedIn.readObject(); } public Socket getSocket() { @@ -117,10 +131,12 @@ public void run() { try { +// cachedIn = new ObjectInputStream(socket.getInputStream()); while ( isRunning() ) { // try to read Events from the socket try { - dispatcher.getLocalEventHandler().handle( readEvent(socket) ); + dispatcher.getLocalEventHandler().handle( readEvent() ); + // wake up all threads waiting on the dispatcher.. synchronized (dispatcher) { dispatcher.notifyAll(); } @@ -153,4 +169,12 @@ requestDisconnection(e); } } + + /** + * Should only be invoked by the client after receiving its Identifier from the server. + * @param id + */ + void setId(Identifier id) { + this.id = id; + } } Modified: csidex/trunk/src/main/java/edu/asu/commons/util/Duration.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/util/Duration.java 2009-10-13 17:09:24 UTC (rev 295) +++ csidex/trunk/src/main/java/edu/asu/commons/util/Duration.java 2009-10-13 17:09:51 UTC (rev 296) @@ -8,7 +8,7 @@ * * Inspired/derived from the timeandmoney.sf.net project's API. * - * @author <a href='al...@cs...'>Allen Lee</a> + * @author <a href='all...@as...'>Allen Lee</a> * @version $Revision$ */ public class Duration implements Serializable { @@ -17,6 +17,7 @@ // FIXME: what's a better name for the amount of time a duration is supposed // to take up? TimeAndMoney uses 'quantity' I believe. + // Delta is always specified in milliseconds. private final long delta; // number of times this Duration has been restart()-ed. private long startCount = 0; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <al...@us...> - 2009-10-13 17:09:34
|
Revision: 295 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=295&view=rev Author: alllee Date: 2009-10-13 17:09:24 +0000 (Tue, 13 Oct 2009) Log Message: ----------- more refactoring, switching to use csidex snapshot, renaming some class files for consistency across the foraging experiment, and removing dead code. Modified Paths: -------------- irrigation/trunk/ivy.xml irrigation/trunk/ivysettings.xml irrigation/trunk/pom.xml irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClientGameState.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationGameWindow.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/MainIrrigationGameWindow.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/RoundConfiguration.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/ClientUpdateEvent.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/FacilitatorEndRoundEvent.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/Facilitator.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/FacilitatorWindow.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/ClientData.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/GroupDataModel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/IrrigationPersister.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/IrrigationServer.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/ServerDataModel.java irrigation/trunk/src/main/resources/configuration/asu-fall-2009/irrigation.xml Added Paths: ----------- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalAnimationPanel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/BeginChatRoundRequest.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/GroupUpdateEvent.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/PauseRequest.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/ShowInstructionsRequest.java Removed Paths: ------------- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalPanelAnimation.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalPanelAnimationNew.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/BeginCommunicationRequest.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/InstructionEnableRequest.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/PauseEvent.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/SendContributionStatusEvent.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/events/SendFileProgressEvent.java Modified: irrigation/trunk/ivy.xml =================================================================== --- irrigation/trunk/ivy.xml 2009-10-12 22:05:11 UTC (rev 294) +++ irrigation/trunk/ivy.xml 2009-10-13 17:09:24 UTC (rev 295) @@ -6,7 +6,7 @@ <info organisation="edu.asu.commons" module="irrigation"/> <dependencies> <dependency org="junit" name="junit" rev="latest.integration"/> - <dependency org="edu.asu.commons" name="csidex" rev="latest.integration"/> + <dependency org="edu.asu.commons" name="csidex" rev="0.2-SNAPSHOT"/> <dependency org="jfree" name="jfreechart" rev="1.0.13"/> <dependency org="jfree" name="jcommon" rev="1.0.16"/> </dependencies> Modified: irrigation/trunk/ivysettings.xml =================================================================== --- irrigation/trunk/ivysettings.xml 2009-10-12 22:05:11 UTC (rev 294) +++ irrigation/trunk/ivysettings.xml 2009-10-13 17:09:24 UTC (rev 295) @@ -12,6 +12,7 @@ <ivy pattern='${local-m2-pattern}.pom' /> <artifact pattern='${local-m2-pattern}.[ext]'/> </filesystem> + <ibiblio name='commons-archiva' m2compatible='true' root='http://dev.commons.asu.edu/archiva/repository/snapshots'/> <ibiblio name='commons-archiva' m2compatible='true' root='http://dev.commons.asu.edu/archiva/repository/internal'/> <ibiblio name='tdar-archiva' m2compatible='true' root='http://dev.tdar.org/archiva/repository/internal'/> </chain> Modified: irrigation/trunk/pom.xml =================================================================== --- irrigation/trunk/pom.xml 2009-10-12 22:05:11 UTC (rev 294) +++ irrigation/trunk/pom.xml 2009-10-13 17:09:24 UTC (rev 295) @@ -44,7 +44,7 @@ <dependency> <groupId>edu.asu.commons</groupId> <artifactId>csidex</artifactId> - <version>0.2.1</version> + <version>0.2-SNAPSHOT</version> </dependency> <dependency> <groupId>jfree</groupId> Copied: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalAnimationPanel.java (from rev 291, irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalPanelAnimationNew.java) =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalAnimationPanel.java (rev 0) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalAnimationPanel.java 2009-10-13 17:09:24 UTC (rev 295) @@ -0,0 +1,566 @@ +package edu.asu.commons.irrigation.client; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GridBagLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Random; + +import javax.swing.JPanel; +import javax.swing.Timer; + +/** + * $Id$ + * + * The animation for the irrigation canal. + * + * FIXME: needs heavy refactoring. + * + * @author Sanket + * @version $Rev$ + */ +public class CanalAnimationPanel extends JPanel { + + private static final long serialVersionUID = 1L; + + /** + * This is the default constructor + */ + private int x1UpStream; + + private int y1UpStream; + + private int x2UpStream = 420; + + private int y2UpStream = 100; + + private int y2DownStream = 100; + + private int x2DownStream = 950; + + private int y1DownStream; + + private int x1DownStream; + + private Graphics2D graphics2D; + + private boolean flagDownStream = false; + + private boolean flagUpStream = false; + + //private IrrigationClientGameState clientGameState; + + //////////////////animation logic parameters////////////////////////////// + private Timer timer; + + private final int DELAY = 20; + + private Ball balls[]; + + private int BALLCOUNT = 500; + + private Gate gate[] = new Gate[6]; + + private int gateHeight = 20; + + Random generator = new Random(); + + private boolean enableBallAnimation = true; + + private double totalContributedBandwidth; + + private long prev_time; + + private int gateCount = 0; + + //////////////////////////////////////////////////////////////////////////// + + public CanalAnimationPanel(double totalContributedBandwidth) { + super(); + this.totalContributedBandwidth = totalContributedBandwidth; + initialize(); + } + + /** + * This method initializes this + * + * @return void + */ + private void initialize() { + this.setSize(1098,150); + this.setLayout(new GridBagLayout()); + this.setBackground(Color.white); + //initializing the constructor for Gates + for(int i=0;i<6;i++){ + gate[i] = new Gate(totalContributedBandwidth,i); + //System.out.println("Gate "+i+"x : "+gate[i].getX()+"y : "+gate[i].getY()); + } + + initializexy(); + + timer = new Timer(DELAY, new ReboundListener()); // setup the Timer to do an action + // every DELAY times. + prev_time = System.currentTimeMillis(); + timer.start(); // starts the timer. + } + + private void gateReboundListener(){ + + openGates(gateCount ); + if(!(gateCount == 0)) + closeGates(gateCount-1); + /*if(!gate[0].isOpenGate() && flagDownStream == false){ + System.out.println("Opening gates"); + closeGates(0); + openGates(1); + } + else + if(flagUpStream == false && flagDownStream == true) + { + openGates(0); + } + else + if(flagUpStream == true && flagDownStream == true) + { + closeGates(1); + //openGates(1); + } + else + if(flagUpStream == true && flagDownStream == false){ + closeGates(0); + //closeGates(1); + } +*/} + + + + protected void paintComponent(Graphics graphics){ + updateGUI(); + super.paintComponent(graphics); // needed! + Graphics2D graphics2D = (Graphics2D)graphics; + this.graphics2D = graphics2D; + this.graphics2D.setColor(Color.BLUE); + this.graphics2D.fillRect(0,0,100,100); + //draw the other gates + for(int i=0;i<5;i++){ + this.graphics2D.setColor(Color.BLUE); + this.graphics2D.fillRect(gate[i].getX(), gate[i].getY(), gate[i].getWidth(),gate[i].getHeight()); + this.graphics2D.fillRect(gate[i].getOpeningsX(), gate[i].getOpeningsY(),gate[i].getOpeningsWidth(), + gate[i].getOpeningsHeight()); + this.graphics2D.setColor(Color.BLACK); + this.graphics2D.drawLine(gate[i].getx1(),gate[i].gety1(),gate[i].getx2(),gate[i].gety2()); + } + + this.graphics2D.setColor(Color.BLUE); + this.graphics2D.fillRect(gate[5].getX(), gate[5].getY(),10,gate[5].getHeight()); + //System.out.println("Gate :"+5+" X: "+gate[5].getX()+" Y :"+gate[5].getY()); + + //////////////////////Animation Logic//////////////////////////// + if(enableBallAnimation == true) + { + graphics.setColor(Color.white); + int ballCounter = 0; + for(int i=0;i<BALLCOUNT;i++){ + /*if(!(balls[i].isInServer == false && clientGameState.getGroupDataModel().getMaximumAvailableBandwidth() == 0)){ + if(!(flagDownStream == true && flagUpStream == true && balls[i].x >= 950)) + if(!(flagUpStream == true && clientGameState.getGroupDataModel().getMaximumAvailableBandwidth() <=25 && balls[i].x >=420)){ + if(flagUpStream == true && balls[i].x >=420 && clientGameState.getGroupDataModel().getMaximumAvailableBandwidth() >=25 ){ + if(!(flagDownStream == false && balls[i].y >= 80)) + graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); + } + else{ + + graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); // paints a whole new circle, with changing coords + + } + + } + + } + */ + //System.out.println("ball sposition x :"+balls[i].x+" y:"+balls[i].y); + //get the position information of the ball. and then recheck the condition for height. + if((balls[i].getPosition() == 1)||(balls[i].getPosition() == 2) || (balls[i].getPosition()==3) + || (balls[i].getPosition() == 4) || (balls[i].getPosition() == 5)){ + if(!((!gate[balls[i].getPosition()-1].isOpenGate())&& balls[i].getY() >= (gate[balls[i].getPosition()-1].getY()+gate[balls[i].getPosition()-1].getHeight()))) + graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); + + + } + else{ + if(balls[i].getPosition() != 0){ + if(gate[balls[i].getPosition() - 6].getHeight() != 0) + graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); + } + else{ + graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); + } + } + } + } + + } + + + + private void updateGUI() { + // TODO Auto-generated method stub + for(int i=1;i<6;i++){ + if(gate[i-1].isOpenGate()){ + if(!(gate[i-1].getHeight() - gateHeight < 0)){ + gate[i].setHeight(gate[i-1].getHeight() - gateHeight ); + + } + else{ + gate[i].setHeight(0); + } + } + else{ + gate[i].setHeight(gate[i-1].getHeight()); + + } + //order matters here + if(!(i == 5)){ + gate[i].setOpeningsHeight((totalContributedBandwidth*0.8) + - gate[i].getHeight()); + gate[i].setOpeningsY(gate[i].getOpeningsHeight() - 50); + + //opening the lid logic + if(gate[i].isOpenGate()){ + gate[i].setx1(gate[i].getx2()); + if(!(gate[i].gety2()- gate[i].getGateWidth() < gate[i].getY())) + gate[i].sety1(gate[i].gety2()- gate[i].getGateWidth()); + else + gate[i].sety1(gate[i].getOpeningsY()); + } + else{ + gate[i].setx1(gate[i].getdefaultx1()); + gate[i].sety1(gate[i].getdefaulty1()); + } + + if(gate[0].isOpenGate()){ + gate[0].setx1(gate[0].getx2()); + if(!(gate[0].gety2()- gate[0].getGateWidth() < gate[0].getY())) + gate[0].sety1(gate[0].gety2()- gate[0].getGateWidth()); + else + gate[0].sety1(gate[0].getY()); + } + else{ + gate[0].setx1(gate[0].getdefaultx1()); + gate[0].sety1(gate[0].getdefaulty1()); + } + + } + } + } + + /* + * initialize the Balls + */ + private void initializexy() { + // TODO Auto-generated method stub + balls = new Ball[BALLCOUNT]; + if(balls == null){ + System.out.println("Ball is null"); + } + + for(int i=0;i<BALLCOUNT;i++){ + balls[i] = new Ball(generator); + + } + } + + // this is the private class the Timer will look at every DELAY seconds + private class ReboundListener implements ActionListener{ + Random generator = new Random(); + public void actionPerformed(ActionEvent e) { + if((System.currentTimeMillis() - prev_time) > 5000){ + //System.out.println("Change the time"); + prev_time = System.currentTimeMillis(); + gateCount++; + if(gateCount > 4) + gateCount = 0; + gateReboundListener(); + } + for(int i=0;i<BALLCOUNT;i++){ + //updateGUI(); + balls[i].x += balls[i].moveX; + balls[i].y += balls[i].moveY; + process(i); + + } + repaint(); + } + } + + /* + * This will process the balls according to their position + */ + private void process(int i){ + // TODO Auto-generated method stub + + switch(balls[i].getPosition()){ + + case 0: if((balls[i].x >= (100 - 20) && balls[i].x <= 100) && (balls[i].y >= 100-(int)(totalContributedBandwidth*0.8) && + balls[i].y <= 100)){ + balls[i].setPosition(1); + setBounds(i); + } + //still in server + else{ + setBounds(i); + if(balls[i].x <= balls[i].xBOUNDSLOWER || balls[i].x >= balls[i].xBOUNDSUPPER-balls[i].getBallSize()){ + balls[i].moveX = balls[i].moveX * -1; + } + if(balls[i].y <= balls[i].yBOUNDSLOWER || balls[i].y >= balls[i].yBOUNDSUPPER-balls[i].getBallSize()) + balls[i].moveY = balls[i].moveY * -1; + } + break; + + case 1: /*if(gate[0].isOpenGate() && (balls[i].x >= 400 && balls[i].x <= 420) && (balls[i].y >= 80 && + balls[i].y <= 100)){ + */ if(gate[0].isOpenGate() && (balls[i].x >= gate[0].getOpeningsX() && balls[i].x <= (gate[0].getOpeningsX()+20)) + && (balls[i].y >= 80 && balls[i].y <= 100)){ + balls[i].setPosition(7); + //directly pass in the information + setBounds(i); + /*System.out.println("X upper :"+balls[i].xBOUNDSUPPER+" Y Upper :"+balls[i].yBOUNDSUPPER + +" X Lower"+balls[i].xBOUNDSLOWER+" X Upper"+balls[i].xBOUNDSUPPER);*/ + /* balls[i].xBOUNDSUPPER = 420; + balls[i].xBOUNDSLOWER = 400; + balls[i].yBOUNDSUPPER = 150; + balls[i].yBOUNDSLOWER = 80; + balls[i].moveX = 0; + balls[i].moveY = 3;*/ + } + else{ + setBounds(i); + /*System.out.println("X upper :"+balls[i].xBOUNDSUPPER+" Y Upper :"+balls[i].yBOUNDSUPPER + +" X Lower"+balls[i].xBOUNDSLOWER+" X Upper"+balls[i].xBOUNDSUPPER); + */ + if(balls[i].getX() > balls[i].xBOUNDSUPPER){ + balls[i].setPosition(2); + } + if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ + balls[i].moveY = balls[i].moveY*-1; + } + } + + break; + + case 2: if(gate[1].isOpenGate() && (balls[i].x >= gate[1].getOpeningsX() && balls[i].x <= (gate[1].getOpeningsX()+20)) + && (balls[i].y >= 80 && balls[i].y <= 100)){ + balls[i].setPosition(8); + //directly pass in the information + setBounds(i); + /* balls[i].xBOUNDSUPPER = 420; + balls[i].xBOUNDSLOWER = 400; + balls[i].yBOUNDSUPPER = 150; + balls[i].yBOUNDSLOWER = 80; + balls[i].moveX = 0; + balls[i].moveY = 3;*/ + } + else{ + setBounds(i); + if(balls[i].getX() > balls[i].xBOUNDSUPPER){ + balls[i].setPosition(3); + } + if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ + balls[i].moveY = balls[i].moveY*-1; + } + } + break; + + + case 3: if(gate[2].isOpenGate() && (balls[i].x >= gate[2].getOpeningsX() && balls[i].x <= (gate[2].getOpeningsX()+20)) + && (balls[i].y >= 80 && balls[i].y <= 100)){ + balls[i].setPosition(9); + //directly pass in the information + setBounds(i); + /* balls[i].xBOUNDSUPPER = 420; + balls[i].xBOUNDSLOWER = 400; + balls[i].yBOUNDSUPPER = 150; + balls[i].yBOUNDSLOWER = 80; + balls[i].moveX = 0; + balls[i].moveY = 3;*/ + } + else{ + setBounds(i); + if(balls[i].getX() > balls[i].xBOUNDSUPPER){ + balls[i].setPosition(4); + } + if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ + balls[i].moveY = balls[i].moveY*-1; + } + } + break; + + case 4: if(gate[3].isOpenGate() && (balls[i].x >= gate[3].getOpeningsX() && balls[i].x <= (gate[3].getOpeningsX()+20)) + && (balls[i].y >= 80 && balls[i].y <= 100)){ + balls[i].setPosition(10); + //directly pass in the information + setBounds(i); + /* balls[i].xBOUNDSUPPER = 420; + balls[i].xBOUNDSLOWER = 400; + balls[i].yBOUNDSUPPER = 150; + balls[i].yBOUNDSLOWER = 80; + balls[i].moveX = 0; + balls[i].moveY = 3;*/ + } + else{ + setBounds(i); + if(balls[i].getX() > balls[i].xBOUNDSUPPER){ + balls[i].setPosition(5); + } + if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ + balls[i].moveY = balls[i].moveY*-1; + } + } + break; + + case 5: if(gate[4].isOpenGate() && (balls[i].x >= gate[4].getOpeningsX() && balls[i].x <= (gate[4].getOpeningsX()+20)) + && (balls[i].y >= 80 && balls[i].y <= 100)){ + balls[i].setPosition(11); + //directly pass in the information + setBounds(i); + /* balls[i].xBOUNDSUPPER = 420; + balls[i].xBOUNDSLOWER = 400; + balls[i].yBOUNDSUPPER = 150; + balls[i].yBOUNDSLOWER = 80; + balls[i].moveX = 0; + balls[i].moveY = 3;*/ + } + else{ + setBounds(i); + if(balls[i].getX() > balls[i].xBOUNDSUPPER){ + balls[i].setPosition(6); + } + if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ + balls[i].moveY = balls[i].moveY*-1; + } + } + break; + + case 6: setBounds(i); + if(balls[i].getX() > balls[i].xBOUNDSUPPER){ + /*balls[i].setX(generator.nextInt(100)); + balls[i].setY(100 - gate[0].getHeight()+ generator.nextInt(gate[0].getHeight())); + balls[i].setPosition(0); + setBounds(i);*/ + setBallinServer(i); + } + + if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ + balls[i].moveY = balls[i].moveY*-1; + } + break; + } + + if((balls[i].getPosition() == 11) || (balls[i].getPosition() == 7) || (balls[i].getPosition() == 8) + || (balls[i].getPosition() == 9) || (balls[i].getPosition() == 10)){ + if(balls[i].getY() >= 150){ + /*balls[i].setX(generator.nextInt(100)); + balls[i].setY(100 - gate[0].getHeight()+ generator.nextInt(gate[0].getHeight())); + //balls[i].setY(generator.nextInt(100)); + balls[i].setPosition(0); + setBounds(i); + */ + setBallinServer(i); + } + else{ + setBounds(i); + //System.out.println("X upper :"+balls[i].xBOUNDSUPPER+" Y Upper :"+balls[i].yBOUNDSUPPER + //+" X Lower"+balls[i].xBOUNDSLOWER+" X Upper"+balls[i].xBOUNDSUPPER); + } + } + } + + + private void setBallinServer(int i) { + // TODO Auto-generated method stub + generator.setSeed(i*(i+1)); + balls[i].setX(generator.nextInt(100)); + balls[i].setY(generator.nextInt(100)); + + //balls[i].setY(100 - gate[0].getHeight()+ generator.nextInt(gate[0].getHeight())); + balls[i].setPosition(0); + if(balls[i].moveX == 0) + balls[i].moveX = generator.nextInt(15); + setBounds(i); + } + + private void setBounds(int ballIndex) { + // TODO Auto-generated method stub + //ball is in the server + if(balls[ballIndex].getPosition() == 0){ + balls[ballIndex].xBOUNDSUPPER = 100; + balls[ballIndex].xBOUNDSLOWER = 0; + balls[ballIndex].yBOUNDSUPPER = 100; + balls[ballIndex].yBOUNDSLOWER = 0; + //balls[ballIndex].moveX = generator.nextInt(6); + //balls[ballIndex].moveY = generator.nextInt(6); + //balls[ballIndex].moveX = 3; + //balls[ballIndex].moveY = 3; + } + else{ + if((balls[ballIndex].getPosition() == 1)||(balls[ballIndex].getPosition() == 2) || (balls[ballIndex].getPosition()==3) + || (balls[ballIndex].getPosition() == 4) || (balls[ballIndex].getPosition() == 5)||(balls[ballIndex].getPosition() == 6)){ + + balls[ballIndex].xBOUNDSUPPER = gate[balls[ballIndex].getPosition() - 1].getX()+gate[balls[ballIndex].getPosition() - 1].getWidth(); + balls[ballIndex].xBOUNDSLOWER = gate[balls[ballIndex].getPosition() - 1].getX(); + balls[ballIndex].yBOUNDSUPPER = gate[balls[ballIndex].getPosition() - 1].getY()/*+gate[balls[ballIndex].getPosition() - 1].getHeight()*/; + balls[ballIndex].yBOUNDSLOWER = gate[balls[ballIndex].getPosition() - 1].getY(); + //balls[ballIndex].moveX = 3; + //balls[ballIndex].moveY = 3; + + } + //the ball is in one of the openings + else{ + balls[ballIndex].xBOUNDSUPPER = gate[balls[ballIndex].getPosition() - 7].getOpeningsX()+gate[balls[ballIndex].getPosition() - 7].getGateWidth(); + balls[ballIndex].xBOUNDSLOWER = gate[balls[ballIndex].getPosition() - 7].getOpeningsX(); + balls[ballIndex].yBOUNDSUPPER = gate[balls[ballIndex].getPosition() - 7].getOpeningsY()+gate[balls[ballIndex].getPosition() - 7].getOpeningsHeight(); + balls[ballIndex].yBOUNDSLOWER = gate[balls[ballIndex].getPosition() - 7].getOpeningsY(); + balls[ballIndex].moveX = 0; + balls[ballIndex].moveY = 3; + } + } + } + + public void openGates(int priority) { + // TODO Auto-generated method stub + + gate[priority].setGateOpen(true); + + //set the height of all the canal panls depending on the state of the game + paintComponent(graphics2D); + } + + public void closeGates(int priority) { + // TODO Auto-generated method stub + gate[priority].setGateOpen(false); + gate[priority].setx1(gate[priority].getdefaultx1()); + gate[priority].sety1(gate[priority].getdefaulty1()); + /*if(!(priority == 0)) + gate[priority].setHeight(gate[priority-1].getHeight());*/ + paintComponent(graphics2D); + } + + public void endRound() { + // TODO Auto-generated method stub + flagDownStream = false; + flagDownStream = false; + + x2UpStream = 420; + + y2UpStream = 100; + + y2DownStream = 100; + + x2DownStream = 950; + + initializexy(); + } +} + Deleted: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalPanelAnimation.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalPanelAnimation.java 2009-10-12 22:05:11 UTC (rev 294) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalPanelAnimation.java 2009-10-13 17:09:24 UTC (rev 295) @@ -1,422 +0,0 @@ -/** - * - */ -package edu.asu.commons.irrigation.client; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Random; - -import javax.swing.JPanel; -import javax.swing.Timer; - - - -/** - * @author Sanket - * - */ -public class CanalPanelAnimation extends JPanel{ - - private static final long serialVersionUID = 1L; - - /** - * This is the default constructor - */ - private int x1UpStream; - - private int y1UpStream; - - private int x2UpStream = 420; - - private int y2UpStream = 100; - - private int y2DownStream = 100; - - private int x2DownStream = 950; - - private int y1DownStream; - - private int x1DownStream; - - private Graphics2D graphics2D; - - private boolean flagDownStream = false; - - private boolean flagUpStream = false; - - private double totalContributedBandwidth; - - //////////////////animation logic parameters////////////////////////////// - private Timer timer; - - private final int DELAY = 20; - - private Ball balls[]; - - private int BALLCOUNT = 500; - - private long prev_time; - - //////////////////////////////////////////////////////////////////////////// - - public CanalPanelAnimation(double totalContributedBandwidth) { - super(); - this.totalContributedBandwidth = totalContributedBandwidth; - initialize(); - } - - /** - * This method initializes this - * - * @return void - */ - private void initialize() { - this.setSize(1098,150); - this.setLayout(new GridBagLayout()); - this.setBackground(Color.white); - - initializexy(); - - timer = new Timer(DELAY, new ReboundListener()); // setup the Timer to do an action - // every DELAY times. - prev_time = System.currentTimeMillis(); - timer.start(); // starts the timer. - - } - - private void gateReboundListener(){ - - if(flagUpStream == false && flagDownStream == false){ - System.out.println("Opening gates"); - closeGates(0); - openGates(1); - } - else - if(flagUpStream == false && flagDownStream == true) - { - openGates(0); - } - else - if(flagUpStream == true && flagDownStream == true) - { - closeGates(1); - //openGates(1); - } - else - if(flagUpStream == true && flagDownStream == false){ - closeGates(0); - //closeGates(1); - } -} - - protected void paintComponent(Graphics graphics){ - super.paintComponent(graphics); // needed! - Graphics2D graphics2D = (Graphics2D)graphics; - this.graphics2D = graphics2D; - //this.graphics2D.setColor(new Color(186,226,237)); - this.graphics2D.setColor(Color.BLUE); - this.graphics2D.fillRect(0,0,100,100); - //graphics2D.fillRoundRect(5,25,100,100,10,10); - //this.graphics2D.setColor(new Color(186,226,237)); - if((int)(totalContributedBandwidth) == 1) - this.graphics2D.fillRect(0, 100 - 2,420,2); - else - /*this.graphics2D.fillRect(0, 100-(int)(totalContributedBandwidth*0.8),1093, (int)(totalContributedBandwidth*0.8)); - this.graphics2D.fillRect(400, 100, 20, 50); - this.graphics2D.fillRect(930, 100, 20, 50); - */ - - this.graphics2D.fillRect(0, 100-(int)(totalContributedBandwidth*0.8),420, (int)(totalContributedBandwidth*0.8)); - if(flagUpStream == true){ - this.graphics2D.fillRect(420, 100-(int)(totalContributedBandwidth*0.8),(950-420), (int)(totalContributedBandwidth*0.8)-20); - //here if downstream is alsoo open, dont show the remaining part - if(flagDownStream == false) - this.graphics2D.fillRect(950, 100-(int)(totalContributedBandwidth*0.8),(1093-950), (int)(totalContributedBandwidth*0.8)-20); - else - this.graphics2D.fillRect(950, 100-(int)(totalContributedBandwidth*0.8),0,0); - - this.graphics2D.fillRect(930,100 - 20, 20, 50+20); - - } - - else{ - this.graphics2D.fillRect(420, 100-(int)(totalContributedBandwidth*0.8),(950-420), (int)(totalContributedBandwidth*0.8)); - if(flagDownStream == false) - this.graphics2D.fillRect(950, 100-(int)(totalContributedBandwidth*0.8),(1093-950), (int)(totalContributedBandwidth*0.8)); - else{ - if(totalContributedBandwidth <= 25){ - this.graphics2D.fillRect(950, 100-(int)(totalContributedBandwidth*0.8),0,0); - } - else - this.graphics2D.fillRect(950, 100-(int)(totalContributedBandwidth*0.8),(1093-950), (int)(totalContributedBandwidth*0.8)-20); - } - - this.graphics2D.fillRect(930, 100, 20, 50); - } - - this.graphics2D.fillRect(400, 100, 20, 50); - - this.graphics2D.setColor(Color.BLACK); - if(flagUpStream == false){ - x1UpStream = x2UpStream - 20; - y1UpStream = y2UpStream; - //resetting the position of downstream gate - //y2DownStream = y2DownStream + 20; - if(y2DownStream == 100-20) - y2DownStream = 100; - } - if(flagDownStream == false){ - x1DownStream = x2DownStream - 20; - y1DownStream = y2DownStream; - } - drawLid(x1UpStream,y1UpStream,x2UpStream,y2UpStream); - drawLid(x1DownStream,y1DownStream,x2DownStream,y2DownStream); - - //////////////////////Animation Logic//////////////////////////// - graphics.setColor(Color.white); - int ballCounter = 0; - for(int i=0;i<BALLCOUNT;i++){ - if(!(balls[i].isInServer == false && totalContributedBandwidth == 0)){ - if(!(flagDownStream == true && flagUpStream == true && balls[i].x >= 950)) - if(!(flagUpStream == true && totalContributedBandwidth <=25 && balls[i].x >=420)){ - if(flagUpStream == true && balls[i].x >=420 && totalContributedBandwidth >=25 ){ - if(!(flagDownStream == false && balls[i].y >= 80)) - //if(ballCounter < 20){ - graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); - //ballCounter++; - //} - } - else{ - - graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); // paints a whole new circle, with changing coords - - } - - } - - } - } - } - - private void initializexy() { - // TODO Auto-generated method stub - balls = new Ball[BALLCOUNT]; - if(balls == null){ - System.out.println("Ball is null"); - } - for(int i=0;i<BALLCOUNT;i++){ - Random generator = new Random(); - balls[i] = new Ball(generator); - if(balls[i] == null){ - System.out.println("Ball i is null"); - } - } - Random generator = new Random(); - System.out.println("Here it fails"); - balls[0].x = 40; - balls[0].y = 50; - - for(int i=1;i<BALLCOUNT;i++){ - balls[i].x = generator.nextInt(100); - balls[i].y = generator.nextInt(100); - balls[i].xBOUNDSUPPER = 100; - balls[i].yBOUNDSUPPER = 100; - balls[i].xBOUNDSLOWER = 0; - balls[i].yBOUNDSLOWER = 0; - balls[i].moveX = generator.nextInt(6); - balls[i].moveY = generator.nextInt(6); - balls[i].isInServer = true; - balls[i].isInSecondCanal = false; - balls[i].isInFirstCanal = false; - } - } - - // this is the private class the Timer will look at every DELAY seconds - private class ReboundListener implements ActionListener{ - Random generator = new Random(); - public void actionPerformed(ActionEvent e) { - if((System.currentTimeMillis() - prev_time) > 5000){ - System.out.println("Change the time"); - prev_time = System.currentTimeMillis(); - gateReboundListener(); - } - for(int i=0;i<BALLCOUNT;i++){ - balls[i].x += balls[i].moveX; - balls[i].y += balls[i].moveY; - - if(balls[i].isInServer == true){ - if((balls[i].x >= (100-20) && balls[i].x <= 100) && (balls[i].y >= 100-(int)(totalContributedBandwidth*0.8) && - balls[i].y <= 100)){ - balls[i].isInServer = false; - balls[i].moveX = 3; - balls[i].moveY = 3; - balls[i].xBOUNDSUPPER = 1093; - balls[i].xBOUNDSLOWER = 0; - balls[i].yBOUNDSUPPER = 100; - balls[i].yBOUNDSLOWER = 100-(int)(totalContributedBandwidth*0.8); - } - else{ - if(balls[i].x <= balls[i].xBOUNDSLOWER || balls[i].x >= balls[i].xBOUNDSUPPER-balls[i].getBallSize()){ - balls[i].moveX = balls[i].moveX * -1; - } - if(balls[i].y <= balls[i].yBOUNDSLOWER || balls[i].y >= balls[i].yBOUNDSUPPER-balls[i].getBallSize()) - balls[i].moveY = balls[i].moveY * -1; - } - } - //within the canal - else{ - // the upstream gate is open - if(flagUpStream == true){ - if((balls[i].x >= 400 && balls[i].x <= 420) && (balls[i].y >= 80 && balls[i].y <= 100)){ - balls[i].isInFirstCanal = true; - balls[i].xBOUNDSUPPER = 420; - balls[i].xBOUNDSLOWER = 400; - balls[i].yBOUNDSUPPER = 150; - balls[i].yBOUNDSLOWER = 80; - balls[i].moveX = 0; - balls[i].moveY = 3; - } - if(balls[i].isInFirstCanal == true) - if(balls[i].y <= balls[i].yBOUNDSLOWER || balls[i].y >= balls[i].yBOUNDSUPPER){ - balls[i].x = generator.nextInt(100); - balls[i].y = generator.nextInt(100); - balls[i].isInServer = true; - balls[i].isInFirstCanal = false; - balls[i].moveX = 3; - balls[i].moveY = 3; - balls[i].xBOUNDSUPPER = 100; - balls[i].xBOUNDSLOWER = 0; - balls[i].yBOUNDSUPPER = 100; - balls[i].yBOUNDSLOWER = 0; - } - if(balls[i].x <= balls[i].xBOUNDSLOWER || balls[i].x >= balls[i].xBOUNDSUPPER-balls[i].getBallSize()) - balls[i].moveX = balls[i].moveX * -1; - } - - if(flagDownStream == true){ - int yUpperBound; - if(flagUpStream == true){ - yUpperBound = 100 - (int)((totalContributedBandwidth)*0.8); - } - else - yUpperBound = 80; - if((balls[i].x >= 930 && balls[i].x <= 950) && (balls[i].y >= yUpperBound && balls[i].y <= 100)){ - balls[i].isInSecondCanal = true; - balls[i].xBOUNDSUPPER = 950; - balls[i].xBOUNDSLOWER = 930; - balls[i].yBOUNDSUPPER = 150; - balls[i].yBOUNDSLOWER = 80; - balls[i].moveX = 0; - balls[i].moveY = 3; - } - if(balls[i].isInSecondCanal == true) - if(balls[i].y <= balls[i].yBOUNDSLOWER || balls[i].y >= balls[i].yBOUNDSUPPER){ - balls[i].x = generator.nextInt(100); - balls[i].y = generator.nextInt(100); - balls[i].isInServer = true; - balls[i].isInSecondCanal = false; - balls[i].xBOUNDSUPPER = 100; - balls[i].xBOUNDSLOWER = 0; - balls[i].yBOUNDSUPPER = 100; - balls[i].yBOUNDSLOWER = 0; - balls[i].moveX =3; - balls[i].moveY =3; - } - if(balls[i].x <= balls[i].xBOUNDSLOWER || balls[i].x >= balls[i].xBOUNDSUPPER-balls[i].getBallSize()) - balls[i].moveX = balls[i].moveX * -1; - } - - //ball goes out of the scope of the canal - if(balls[i].isInFirstCanal == false && balls[i].isInSecondCanal == false){ - if(balls[i].x <= balls[i].xBOUNDSLOWER || balls[i].x >= balls[i].xBOUNDSUPPER-balls[i].getBallSize()){ - balls[i].x = generator.nextInt(100); - balls[i].y = generator.nextInt(100); - balls[i].moveX = 3; - balls[i].isInServer = true; - balls[i].xBOUNDSUPPER = 100; - balls[i].xBOUNDSLOWER = 0; - balls[i].yBOUNDSUPPER = 100; - balls[i].yBOUNDSLOWER = 0; - } - if(balls[i].y <= balls[i].yBOUNDSLOWER || balls[i].y >= balls[i].yBOUNDSUPPER-balls[i].getBallSize()) - balls[i].moveY = balls[i].moveY * -1; - } - } - } - repaint(); - } - } - - private void drawLid(int x1, int y1, int x2, int y2) { - // TODO Auto-generated method stub - graphics2D.drawLine(x1,y1,x2,y2); - } - - public void openGates(int priority) { - // TODO Auto-generated method stub - switch(priority){ - case 0 : x1UpStream = x2UpStream; - if(totalContributedBandwidth < 25){ - y1UpStream = y2UpStream - (int)(totalContributedBandwidth*0.8); - } - else{ - y1UpStream = y2UpStream - 20; - //changing the position of downstream gate - //y2DownStream = y2DownStream - 20; - - } - if(y2DownStream == 100) - y2DownStream = y2DownStream - 20; - flagUpStream = true; - break; - - case 1 : x1DownStream = x2DownStream; - if(totalContributedBandwidth < 25){ - y1DownStream = y2DownStream - (int)(totalContributedBandwidth*0.8); - //for the new animation - //y2DownStream = y1DownStream; - } - else - y1DownStream = y2DownStream - 20; - if(y1DownStream < (100-totalContributedBandwidth*0.8)){ - y1DownStream = y2DownStream - (int)(totalContributedBandwidth*0.8 - 20); - } - flagDownStream = true; - break; - - } - paintComponent(graphics2D); - } - - public void closeGates(int priority) { - // TODO Auto-generated method stub - switch (priority){ - case 0 : flagUpStream = false; - break; - - case 1 : flagDownStream = false; - break; - } - } - - public void endRound() { - // TODO Auto-generated method stub - flagDownStream = false; - flagDownStream = false; - totalContributedBandwidth = 0; - x2UpStream = 420; - - y2UpStream = 100; - - y2DownStream = 100; - - x2DownStream = 950; - - initializexy(); - } -} Deleted: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalPanelAnimationNew.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalPanelAnimationNew.java 2009-10-12 22:05:11 UTC (rev 294) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/CanalPanelAnimationNew.java 2009-10-13 17:09:24 UTC (rev 295) @@ -1,560 +0,0 @@ -package edu.asu.commons.irrigation.client; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Random; - -import javax.swing.JPanel; -import javax.swing.Timer; - -/** - * @author Sanket - * - */ -public class CanalPanelAnimationNew extends JPanel { - - private static final long serialVersionUID = 1L; - - /** - * This is the default constructor - */ - private int x1UpStream; - - private int y1UpStream; - - private int x2UpStream = 420; - - private int y2UpStream = 100; - - private int y2DownStream = 100; - - private int x2DownStream = 950; - - private int y1DownStream; - - private int x1DownStream; - - private Graphics2D graphics2D; - - private boolean flagDownStream = false; - - private boolean flagUpStream = false; - - //private IrrigationClientGameState clientGameState; - - //////////////////animation logic parameters////////////////////////////// - private Timer timer; - - private final int DELAY = 20; - - private Ball balls[]; - - private int BALLCOUNT = 500; - - private Gate gate[] = new Gate[6]; - - private int gateHeight = 20; - - Random generator = new Random(); - - private boolean enableBallAnimation = true; - - private double totalContributedBandwidth; - - private long prev_time; - - private int gateCount = 0; - - //////////////////////////////////////////////////////////////////////////// - - public CanalPanelAnimationNew(double totalContributedBandwidth) { - super(); - this.totalContributedBandwidth = totalContributedBandwidth; - initialize(); - } - - /** - * This method initializes this - * - * @return void - */ - private void initialize() { - this.setSize(1098,150); - this.setLayout(new GridBagLayout()); - this.setBackground(Color.white); - //initializing the constructor for Gates - for(int i=0;i<6;i++){ - gate[i] = new Gate(totalContributedBandwidth,i); - //System.out.println("Gate "+i+"x : "+gate[i].getX()+"y : "+gate[i].getY()); - } - - initializexy(); - - timer = new Timer(DELAY, new ReboundListener()); // setup the Timer to do an action - // every DELAY times. - prev_time = System.currentTimeMillis(); - timer.start(); // starts the timer. - } - - private void gateReboundListener(){ - - openGates(gateCount ); - if(!(gateCount == 0)) - closeGates(gateCount-1); - /*if(!gate[0].isOpenGate() && flagDownStream == false){ - System.out.println("Opening gates"); - closeGates(0); - openGates(1); - } - else - if(flagUpStream == false && flagDownStream == true) - { - openGates(0); - } - else - if(flagUpStream == true && flagDownStream == true) - { - closeGates(1); - //openGates(1); - } - else - if(flagUpStream == true && flagDownStream == false){ - closeGates(0); - //closeGates(1); - } -*/} - - - - protected void paintComponent(Graphics graphics){ - updateGUI(); - super.paintComponent(graphics); // needed! - Graphics2D graphics2D = (Graphics2D)graphics; - this.graphics2D = graphics2D; - this.graphics2D.setColor(Color.BLUE); - this.graphics2D.fillRect(0,0,100,100); - //draw the other gates - for(int i=0;i<5;i++){ - this.graphics2D.setColor(Color.BLUE); - this.graphics2D.fillRect(gate[i].getX(), gate[i].getY(), gate[i].getWidth(),gate[i].getHeight()); - this.graphics2D.fillRect(gate[i].getOpeningsX(), gate[i].getOpeningsY(),gate[i].getOpeningsWidth(), - gate[i].getOpeningsHeight()); - this.graphics2D.setColor(Color.BLACK); - this.graphics2D.drawLine(gate[i].getx1(),gate[i].gety1(),gate[i].getx2(),gate[i].gety2()); - } - - this.graphics2D.setColor(Color.BLUE); - this.graphics2D.fillRect(gate[5].getX(), gate[5].getY(),10,gate[5].getHeight()); - //System.out.println("Gate :"+5+" X: "+gate[5].getX()+" Y :"+gate[5].getY()); - - //////////////////////Animation Logic//////////////////////////// - if(enableBallAnimation == true) - { - graphics.setColor(Color.white); - int ballCounter = 0; - for(int i=0;i<BALLCOUNT;i++){ - /*if(!(balls[i].isInServer == false && clientGameState.getGroupDataModel().getMaximumAvailableBandwidth() == 0)){ - if(!(flagDownStream == true && flagUpStream == true && balls[i].x >= 950)) - if(!(flagUpStream == true && clientGameState.getGroupDataModel().getMaximumAvailableBandwidth() <=25 && balls[i].x >=420)){ - if(flagUpStream == true && balls[i].x >=420 && clientGameState.getGroupDataModel().getMaximumAvailableBandwidth() >=25 ){ - if(!(flagDownStream == false && balls[i].y >= 80)) - graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); - } - else{ - - graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); // paints a whole new circle, with changing coords - - } - - } - - } - */ - //System.out.println("ball sposition x :"+balls[i].x+" y:"+balls[i].y); - //get the position information of the ball. and then recheck the condition for height. - if((balls[i].getPosition() == 1)||(balls[i].getPosition() == 2) || (balls[i].getPosition()==3) - || (balls[i].getPosition() == 4) || (balls[i].getPosition() == 5)){ - if(!((!gate[balls[i].getPosition()-1].isOpenGate())&& balls[i].getY() >= (gate[balls[i].getPosition()-1].getY()+gate[balls[i].getPosition()-1].getHeight()))) - graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); - - - } - else{ - if(balls[i].getPosition() != 0){ - if(gate[balls[i].getPosition() - 6].getHeight() != 0) - graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); - } - else{ - graphics.fillOval(balls[i].x,balls[i].y,balls[i].getBallSize(), balls[i].getBallSize()); - } - } - } - } - - } - - - - private void updateGUI() { - // TODO Auto-generated method stub - for(int i=1;i<6;i++){ - if(gate[i-1].isOpenGate()){ - if(!(gate[i-1].getHeight() - gateHeight < 0)){ - gate[i].setHeight(gate[i-1].getHeight() - gateHeight ); - - } - else{ - gate[i].setHeight(0); - } - } - else{ - gate[i].setHeight(gate[i-1].getHeight()); - - } - //order matters here - if(!(i == 5)){ - gate[i].setOpeningsHeight((totalContributedBandwidth*0.8) - - gate[i].getHeight()); - gate[i].setOpeningsY(gate[i].getOpeningsHeight() - 50); - - //opening the lid logic - if(gate[i].isOpenGate()){ - gate[i].setx1(gate[i].getx2()); - if(!(gate[i].gety2()- gate[i].getGateWidth() < gate[i].getY())) - gate[i].sety1(gate[i].gety2()- gate[i].getGateWidth()); - else - gate[i].sety1(gate[i].getOpeningsY()); - } - else{ - gate[i].setx1(gate[i].getdefaultx1()); - gate[i].sety1(gate[i].getdefaulty1()); - } - - if(gate[0].isOpenGate()){ - gate[0].setx1(gate[0].getx2()); - if(!(gate[0].gety2()- gate[0].getGateWidth() < gate[0].getY())) - gate[0].sety1(gate[0].gety2()- gate[0].getGateWidth()); - else - gate[0].sety1(gate[0].getY()); - } - else{ - gate[0].setx1(gate[0].getdefaultx1()); - gate[0].sety1(gate[0].getdefaulty1()); - } - - } - } - } - - /* - * initialize the Balls - */ - private void initializexy() { - // TODO Auto-generated method stub - balls = new Ball[BALLCOUNT]; - if(balls == null){ - System.out.println("Ball is null"); - } - - for(int i=0;i<BALLCOUNT;i++){ - balls[i] = new Ball(generator); - - } - } - - // this is the private class the Timer will look at every DELAY seconds - private class ReboundListener implements ActionListener{ - Random generator = new Random(); - public void actionPerformed(ActionEvent e) { - if((System.currentTimeMillis() - prev_time) > 5000){ - //System.out.println("Change the time"); - prev_time = System.currentTimeMillis(); - gateCount++; - if(gateCount > 4) - gateCount = 0; - gateReboundListener(); - } - for(int i=0;i<BALLCOUNT;i++){ - //updateGUI(); - balls[i].x += balls[i].moveX; - balls[i].y += balls[i].moveY; - process(i); - - } - repaint(); - } - } - - /* - * This will process the balls according to their position - */ - private void process(int i){ - // TODO Auto-generated method stub - - switch(balls[i].getPosition()){ - - case 0: if((balls[i].x >= (100 - 20) && balls[i].x <= 100) && (balls[i].y >= 100-(int)(totalContributedBandwidth*0.8) && - balls[i].y <= 100)){ - balls[i].setPosition(1); - setBounds(i); - } - //still in server - else{ - setBounds(i); - if(balls[i].x <= balls[i].xBOUNDSLOWER || balls[i].x >= balls[i].xBOUNDSUPPER-balls[i].getBallSize()){ - balls[i].moveX = balls[i].moveX * -1; - } - if(balls[i].y <= balls[i].yBOUNDSLOWER || balls[i].y >= balls[i].yBOUNDSUPPER-balls[i].getBallSize()) - balls[i].moveY = balls[i].moveY * -1; - } - break; - - case 1: /*if(gate[0].isOpenGate() && (balls[i].x >= 400 && balls[i].x <= 420) && (balls[i].y >= 80 && - balls[i].y <= 100)){ - */ if(gate[0].isOpenGate() && (balls[i].x >= gate[0].getOpeningsX() && balls[i].x <= (gate[0].getOpeningsX()+20)) - && (balls[i].y >= 80 && balls[i].y <= 100)){ - balls[i].setPosition(7); - //directly pass in the information - setBounds(i); - /*System.out.println("X upper :"+balls[i].xBOUNDSUPPER+" Y Upper :"+balls[i].yBOUNDSUPPER - +" X Lower"+balls[i].xBOUNDSLOWER+" X Upper"+balls[i].xBOUNDSUPPER);*/ - /* balls[i].xBOUNDSUPPER = 420; - balls[i].xBOUNDSLOWER = 400; - balls[i].yBOUNDSUPPER = 150; - balls[i].yBOUNDSLOWER = 80; - balls[i].moveX = 0; - balls[i].moveY = 3;*/ - } - else{ - setBounds(i); - /*System.out.println("X upper :"+balls[i].xBOUNDSUPPER+" Y Upper :"+balls[i].yBOUNDSUPPER - +" X Lower"+balls[i].xBOUNDSLOWER+" X Upper"+balls[i].xBOUNDSUPPER); - */ - if(balls[i].getX() > balls[i].xBOUNDSUPPER){ - balls[i].setPosition(2); - } - if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ - balls[i].moveY = balls[i].moveY*-1; - } - } - - break; - - case 2: if(gate[1].isOpenGate() && (balls[i].x >= gate[1].getOpeningsX() && balls[i].x <= (gate[1].getOpeningsX()+20)) - && (balls[i].y >= 80 && balls[i].y <= 100)){ - balls[i].setPosition(8); - //directly pass in the information - setBounds(i); - /* balls[i].xBOUNDSUPPER = 420; - balls[i].xBOUNDSLOWER = 400; - balls[i].yBOUNDSUPPER = 150; - balls[i].yBOUNDSLOWER = 80; - balls[i].moveX = 0; - balls[i].moveY = 3;*/ - } - else{ - setBounds(i); - if(balls[i].getX() > balls[i].xBOUNDSUPPER){ - balls[i].setPosition(3); - } - if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ - balls[i].moveY = balls[i].moveY*-1; - } - } - break; - - - case 3: if(gate[2].isOpenGate() && (balls[i].x >= gate[2].getOpeningsX() && balls[i].x <= (gate[2].getOpeningsX()+20)) - && (balls[i].y >= 80 && balls[i].y <= 100)){ - balls[i].setPosition(9); - //directly pass in the information - setBounds(i); - /* balls[i].xBOUNDSUPPER = 420; - balls[i].xBOUNDSLOWER = 400; - balls[i].yBOUNDSUPPER = 150; - balls[i].yBOUNDSLOWER = 80; - balls[i].moveX = 0; - balls[i].moveY = 3;*/ - } - else{ - setBounds(i); - if(balls[i].getX() > balls[i].xBOUNDSUPPER){ - balls[i].setPosition(4); - } - if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ - balls[i].moveY = balls[i].moveY*-1; - } - } - break; - - case 4: if(gate[3].isOpenGate() && (balls[i].x >= gate[3].getOpeningsX() && balls[i].x <= (gate[3].getOpeningsX()+20)) - && (balls[i].y >= 80 && balls[i].y <= 100)){ - balls[i].setPosition(10); - //directly pass in the information - setBounds(i); - /* balls[i].xBOUNDSUPPER = 420; - balls[i].xBOUNDSLOWER = 400; - balls[i].yBOUNDSUPPER = 150; - balls[i].yBOUNDSLOWER = 80; - balls[i].moveX = 0; - balls[i].moveY = 3;*/ - } - else{ - setBounds(i); - if(balls[i].getX() > balls[i].xBOUNDSUPPER){ - balls[i].setPosition(5); - } - if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ - balls[i].moveY = balls[i].moveY*-1; - } - } - break; - - case 5: if(gate[4].isOpenGate() && (balls[i].x >= gate[4].getOpeningsX() && balls[i].x <= (gate[4].getOpeningsX()+20)) - && (balls[i].y >= 80 && balls[i].y <= 100)){ - balls[i].setPosition(11); - //directly pass in the information - setBounds(i); - /* balls[i].xBOUNDSUPPER = 420; - balls[i].xBOUNDSLOWER = 400; - balls[i].yBOUNDSUPPER = 150; - balls[i].yBOUNDSLOWER = 80; - balls[i].moveX = 0; - balls[i].moveY = 3;*/ - } - else{ - setBounds(i); - if(balls[i].getX() > balls[i].xBOUNDSUPPER){ - balls[i].setPosition(6); - } - if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ - balls[i].moveY = balls[i].moveY*-1; - } - } - break; - - case 6: setBounds(i); - if(balls[i].getX() > balls[i].xBOUNDSUPPER){ - /*balls[i].setX(generator.nextInt(100)); - balls[i].setY(100 - gate[0].getHeight()+ generator.nextInt(gate[0].getHeight())); - balls[i].setPosition(0); - setBounds(i);*/ - setBallinServer(i); - } - - if(balls[i].getY() >= balls[i].yBOUNDSUPPER - balls[i].getBallSize() || balls[i].getY() <= balls[i].yBOUNDSLOWER){ - balls[i].moveY = balls[i].moveY*-1; - } - break; - } - - if((balls[i].getPosition() == 11) || (balls[i].getPosition() == 7) || (balls[i].getPosition() == 8) - || (balls[i].getPosition() == 9) || (balls[i].getPosition() == 10)){ - if(balls[i].getY() >= 150){ - /*balls[i].setX(generator.nextInt(100)); - balls[i].setY(100 - gate[0].getHeight()+ generator.nextInt(gate[0].getHeight())); - //balls[i].setY(generator.nextInt(100)); - balls[i].setPosition(0); - setBounds(i); - */ - setBallinServer(i); - } - else{ - setBounds(i); - //System.out.println("X upper :"+balls[i].xBOUNDSUPPER+" Y Upper :"+balls[i].yBOUNDSUPPER - //+" X Lower"+balls[i].xBOUNDSLOWER+" X Upper"+balls[i].xBOUNDSUPPER); - } - } - } - - - private void setBallinServer(int i) { - // TODO Auto-generated method stub - generator.setSeed(i*(i+1)); - balls[i].setX(generator.nextInt(100)); - balls[i].setY(generator.nextInt(100)); - - //balls[i].setY(100 - gate[0].getHeight()+ generator.nextInt(gate[0].getHeight())); - balls[i].setPosition(0); - if(balls[i].moveX == 0) - balls[i].moveX = generator.nextInt(15); - setBounds(i); - } - - private void setBounds(int ballIndex) { - // TODO Auto-generated method stub - //ball is in the server - if(balls[ballIndex].getPosition() == 0){ - balls[ballIndex].xBOUNDSUPPER = 100; - balls[ballIndex].xBOUNDSLOWER = 0; - balls[ballIndex].yBOUNDSUPPER = 100; - balls[ballIndex].yBOUNDSLOWER = 0; - //balls[ballIndex].moveX = generator.nextInt(6); - //balls[ballIndex].moveY = generator.nextInt(6); - //balls[ballIndex].moveX = 3; - //balls[ballIndex].moveY = 3; - } - else{ - if((balls[ballIndex].getPosition() == 1)||(balls[ballIndex].getPosition() == 2) || (balls[ballIndex].getPosition()==3) - || (balls[ballIndex].getPosition() == 4) || (balls[ballIndex].getPosition() == 5)||(balls[ballIndex].getPosition() == 6)){ - - balls[ballIndex].xBOUNDSUPPER = gate[balls[ballIndex].getPosition() - 1].getX()+gate[balls[ballIndex].getPosition() - 1].getWidth(); - balls[ballIndex].xBOUNDSLOWER = gate[balls[ballIndex].getPosition() - 1].getX(); - balls[ballIndex].yBOUNDSUPPER = gate[balls[ballIndex].getPosition() - 1].getY()/*+gate[balls[ballIndex].getPosition() - 1].getHeight()*/; - balls[ballIndex].yBOUNDSLOWER = gate[balls[ballIndex].getPosition() - 1].getY(); - //balls[ballIndex].moveX = 3; - //balls[ballIndex].moveY = 3; - - } - //the ball is in one of the openings - else{ - balls[ballIndex].xBOUNDSUPPER = gate[balls[ballIndex].getPosition() - 7].getOpeningsX()+gate[balls[ballIndex].getPosition() - 7].getGateWidth(); - balls[ballIndex].xBOUNDSLOWER = gate[balls[ballIndex].getPosition() - 7].getOpeningsX(); - balls[ballIndex].yBOUNDSUPPER = gate[balls[ballIndex].getPosition() - 7].getOpeningsY()+gate[balls[ballIndex].getPosition() - 7].getOpeningsHeight(); - balls[ballIndex].yBOUNDSLOWER = gate[balls[ballIndex].getPosition() - 7].getOpeningsY(); - balls[ballIndex].moveX = 0; - balls[ballIndex].moveY = 3; - } - } - } - - public void openGates(int priority) { - // TODO Auto-generated method stub - - gate[priority].setGateOpen(true); - - //set the height of all the canal panls depending on the state of the game - paintComponent(graphics2D); - } - - public void closeGates(int priority) { - // TODO Auto-generated method stub - gate[priority].setGateOpen(false); - gate[priority].setx1(gate[priority].getdefaultx1()); - gate[priority].sety1(gate[priority].getdefaulty1()); - /*if(!(priority == 0)) - gate[priority].setHeight(gate[priority-1].getHeight());*/ - paintComponent(graphics2D); - } - - public void endRound() { - // TODO Auto-generated method stub - flagDownStream = false; - flagDownStream = false; - - x2UpStream = 420; - - y2UpStream = 100; - - y2DownStream = 100; - - x2DownStream = 950; - - initializexy(); - } -} - Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-12 22:05:11 UTC (rev 294) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/ExperimentGameWindow.java 2009-10-13 17:09:24 UTC (rev 295) @@ -123,7 +123,7 @@ public ClientData clientData; - private CanalPanelAnimationNew canalPanelAnimationNew; + private CanalAnimationPanel canalPanelAnimationNew; public ExperimentGameWindow(Dimension screenSize, IrrigationClient client) { this.client = client; @@ -375,7 +375,7 @@ animationPanel.setLayout(new BorderLayout()); //FIXME: Here the animation panel needs to be decided on fly //canalPanelAnimation = new CanalPanelAnimation(40); - canalPanelAnimationNew = new CanalPanelAnimationNew(40); + canalPanelAnimationNew = new CanalAnimationPanel(40); animationPanel.add(canalPanelAnimationNew,BorderLayout.CENTER); animationInstructionsEditorPane = createInstructionsEditorPane(); animationInstructionsScrollPane = new JScrollPane(animationInstructionsEditorPane); @@ -557,12 +557,12 @@ * This method could be merged somehow with the startRoundEvent. We can get * rid of the sendContributionStatus then */ - public void updateSendContributionStatus() { - mainIrrigationWindow.updateSendContributionStatus(state); + public void updateContributions() { + mainIrrigationWindow.updateContributions(state); } - public void updateSendFileProgress() { - mainIrrigationWindow.updateSendFileProgress(state); + public void update() { + mainIrrigationWindow.updateClientStatus(state); } /* Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java 2009-10-12 22:05:11 UTC (rev 294) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/client/IrrigationClient.java 2009-10-13 17:09:24 UTC (rev 295) @@ -17,18 +17,18 @@ import edu.asu.commons.event.EventTypeProcessor; import edu.asu.commons.irrigation.conf.RoundConfiguration; import edu.asu.commons.irrigation.conf.ServerConfiguration; -import edu.asu.commons.irrigation.events.BeginCommunicationRequest; +import edu.asu.commons.irrigation.events.BeginChatRoundRequest; +import edu.asu.commons.irrigation.events.ClientUpdateEvent; +import edu.asu.commons.irrigation.events.CloseGateEvent; import edu.asu.commons.irrigation.events.DisplaySubmitTokenRequest; import edu.asu.commons.irrigation.events.EndRoundEvent; -import edu.asu.commons.irrigation.events.OpenGateEvent; -import edu.asu.commons.irrigation.events.InstructionEnableRequest; +import edu.asu.commons.irrigation.events.GroupUpdateEvent; import edu.asu.commons.irrigation.events.InvestedTokensEvent; +import edu.asu.commons.irrigation.events.OpenGateEvent; +import edu.asu.commons.irrigation.events.PauseRequest; import edu.asu.commons.irrigation.events.RegistrationEvent; import edu.asu.commons.irrigation.events.RoundStartedEvent; -import edu.asu.commons.irrigation.events.SendContributionStatusEvent; -import edu.asu.commons.irrigation.events.SendFileProgressEvent; -import edu.asu.commons.irrigation.events.PauseEvent; -import edu.asu.commons.irrigation.events.CloseGateEvent; +import edu.asu.commons.irrigation.events.ShowInstructionsRequest; import edu.asu.commons.irrigation.server.ClientData; import edu.asu.commons.net.ClientDispatcher; import edu.asu.commons.net.DispatcherFactory; @@ -152,7 +152,7 @@ * * @param fileNo */ - public void openGate(String fileNo) { + public void openGate() { OpenGateEvent openGateEvent = new OpenGateEvent(getId()); transmit(openGateEvent); } @@ -163,10 +163,9 @@ transmit(closeGateEvent); } - public void startPause(String fileNo) { - PauseEvent startPausedEvent = new PauseEvent(getId()); - startPausedEvent.setFileNumber(fileNo); - transmit(startPausedEvent); + public void pause() { + PauseRequest pauseRequest = new PauseRequest(getId()); + transmit(pauseRequest); } public void transmit(Event event) { @@ -189,11 +188,12 @@ } } }); - channel.add(this, new EventTypeProcessor<SendContributionStatusEvent>(SendContributionStat... [truncated message content] |
From: <see...@us...> - 2009-10-12 22:05:19
|
Revision: 294 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=294&view=rev Author: seematalele Date: 2009-10-12 22:05:11 +0000 (Mon, 12 Oct 2009) Log Message: ----------- Created Interface PushData.java which provides mechanism for callback, when block timer is over. Able to sent blocks to the clients (Checked using Alert.Show messages in StartGame.swf). Currently the timer is set is 5 sec. (in sendBlock() method of MessageHandler class). Timer thread is created. This thread sleeps for 1 sec. sendblock checks after 1 sec if time for block is over or not. Problems: FisheryExperimentShell is still giving an error for DayByDayDecisionsC.mxml at 178 line. Need to resolve this issue Modified Paths: -------------- mentalmodels/trunk/flex/src/StartGame.mxml mentalmodels/trunk/flex/src/custom/FisheryExperimentCore.mxml mentalmodels/trunk/src/main/java/edu/asu/commons/mme/service/GameService.java mentalmodels/trunk/src/main/java/edu/asu/commons/mme/service/RoundService.java mentalmodels/trunk/src/main/java/edu/asu/commons/mme/service/StartGame.java mentalmodels/trunk/src/main/java/edu/asu/commons/mme/service/StudentService.java mentalmodels/trunk/src/main/java/edu/asu/commons/mme/utility/MessageHandler.java Added Paths: ----------- mentalmodels/trunk/src/main/java/edu/asu/commons/mme/utility/PushData.java mentalmodels/trunk/src/main/java/edu/asu/commons/mme/utility/Timer.java Modified: mentalmodels/trunk/flex/src/StartGame.mxml =================================================================== --- mentalmodels/trunk/flex/src/StartGame.mxml 2009-10-10 01:18:43 UTC (rev 293) +++ mentalmodels/trunk/flex/src/StartGame.mxml 2009-10-12 22:05:11 UTC (rev 294) @@ -28,7 +28,7 @@ <mx:VBox id="responsesContent"/> </mx:VBox> - <mx:RemoteObject id="startupService" destination="startupService" fault="faultHandler(event)"> + <mx:RemoteObject id="gameService" destination="gameService" fault="faultHandler(event)"> <mx:method name="createGame" result="gameObjectResultHandler(event)"/> <mx:method name="startGame"/> </mx:RemoteObject> @@ -55,6 +55,7 @@ import mx.messaging.events.MessageFaultEvent; import mx.messaging.FlexClient; import mx.messaging.messages.AsyncMessage; + import mx.collections.ArrayCollection; import mx.logging.*; import mx.logging.targets.*; @@ -111,15 +112,12 @@ gameObject.money = stpMoney.value; gameObject.gameCode = txtDescription.text; gameObject.timestamp = new Date(); - - startupService.createGame(gameObject); + + gameService.createGame(gameObject); /* var message:AsyncMessage = new AsyncMessage(); message.body = "got gameObject" + gameObject.description; producer.send(message); Alert.show("message is send"); */ - - - } public function start():void { @@ -127,7 +125,7 @@ /*consumer.subscribe(); Alert.show("subscribed to destination: " + consumer.destination);*/ - startupService.startGame(game); + gameService.startGame(game); //consumer.subtopic = "hello3"; } @@ -163,15 +161,23 @@ private function messageHandler(event:MessageEvent):void { //Alert.show("message from server came.."); - var block:actionscript.Block = event.message.body as actionscript.Block; + if(event.message.body as actionscript.Block) + { + var block:actionscript.Block = event.message.body as actionscript.Block; //Alert.show("String came from server is: " + block.id + " " + block.description); - if(block == null) + if(block == null) + { + Alert.show("Game is over!!"); + } + else + Alert.show("Block from server is : " + block.description); + } + else if(event.message.body as ArrayCollection) { - Alert.show("Game is over!!"); + Alert.show("something else "); } - else - Alert.show("Block from server is : " + block.description); + } ]]> Modified: mentalmodels/trunk/flex/src/custom/FisheryExperimentCore.mxml =================================================================== --- mentalmodels/trunk/flex/src/custom/FisheryExperimentCore.mxml 2009-10-10 01:18:43 UTC (rev 293) +++ mentalmodels/trunk/flex/src/custom/FisheryExperimentCore.mxml 2009-10-12 22:05:11 UTC (rev 294) @@ -57,7 +57,7 @@ </mx:HBox> - <mx:RemoteObject id="startupService" destination="startupService" fault="faultHandler(event)"> + <mx:RemoteObject id="studentService" destination="studentService" fault="faultHandler(event)"> <mx:method name="createStudent" result="studentResultHandler(event)"/> </mx:RemoteObject> <mx:RemoteObject id="answeringService" destination="answeringService" fault="faultHandler(event)"> @@ -127,7 +127,30 @@ private function messageHandler(event:MessageEvent):void { - setBlock(event.message.body as actionscript.Block); + var msg:IMessage; + + if(event.message.body as actionscript.Block) + { + setBlock(event.message.body as actionscript.Block); + } + else if(event.message.body as ArrayCollection) + { + var students:ArrayCollection = new ArrayCollection(); + students = ArrayCollection(event.message.body); + Alert.show("Student size is: " + students.length); + if(students.length !=0) + { + for(var i:int = 0; i< students.length; i++) + { + if(actionscript.Student(students.getItemAt(i)).id == studentObject.id) + { + studentObject.group = actionscript.Student(students.getItemAt(i)).group; + studentObject.studentNo = actionscript.Student(students.getItemAt(i)).studentNo; + } + } + } + Alert.show("Current Student Information is: " + "\n"+studentObject.id +"\n"+studentObject.gameCode+"\n"+studentObject.studentNo); + } } private function blockResultHandler(event:ResultEvent):void { @@ -472,7 +495,7 @@ newStudent.semester = (obj as SocioDemographicPage).getSemester(); newStudent.gameCode = (obj as SocioDemographicPage).getGameCode(); - startupService.createStudent(newStudent); + studentService.createStudent(newStudent); currentState = "wait"; btnBack.enabled = btnForward.enabled = btnReset.enabled = true; Modified: mentalmodels/trunk/src/main/java/edu/asu/commons/mme/service/GameService.java =================================================================== --- mentalmodels/trunk/src/main/java/edu/asu/commons/mme/service/GameService.java 2009-10-10 01:18:43 UTC (rev 293) +++ mentalmodels/trunk/src/main/java/edu/asu/commons/mme/service/GameService.java 2009-10-12 22:05:11 UTC (rev 294) @@ -35,12 +35,10 @@ import edu.asu.commons.mme.entity.Round; import edu.asu.commons.mme.entity.Student; import edu.asu.commons.mme.utility.MessageHandler; -import flex.messaging.MessageBroker; -import flex.messaging.messages.AsyncMessage; -import flex.messaging.util.UUIDUtils; +import edu.asu.commons.mme.utility.PushData; @Transactional -public class GameService extends Service.Base<Game, HibernateGameDao>{ +public class GameService extends Service.Base<Game, HibernateGameDao> implements PushData{ private HibernateModuleDao moduleDao; @@ -54,8 +52,14 @@ private HibernateLocationDao locationDao; private int blockSeqNo; + + private RoundService roundService; - private RoundService roundService; + MessageHandler msgHandler; + + public GameService() + { + } public GameConfig createGameConfig(GameConfig gameConfig) { @@ -131,66 +135,67 @@ public void startGame(Game game) { assignGroups(game); -/* getRoundService().setGame(game); - getRoundService().run(); -*/ + getLogger().debug("system has assigned groups. "); + pushBlock(game); + } + + + private void pushBlock(Game game) { Game newGameState = null; Block block = null; boolean running = false; getLogger().info("game start is: " + game.getId()); newGameState = getDao().find(game.getId()); - MessageHandler msgHandler = new MessageHandler(); + //FIXME: Do not know if this is a right way, I do not think because it will create refrecne to message handler for every block + msgHandler = new MessageHandler(this); msgHandler.setDestination("mme"); msgHandler.setSubtopic(getGameCode(newGameState)); - int noOfBlocks = getNumberOfBlock(game); - + //int noOfBlocks = getNumberOfBlock(game); + int i=0; try { - while (i<noOfBlocks) { - + //while (i<noOfBlocks) { i++; newGameState = getBlock(game); game = newGameState; if(newGameState == null) { - msgHandler.send(null); + getLogger().debug("game state is null..."); + msgHandler.sendBlock(null, null); } else { + getLogger().debug("game state is NOT null..."); block = newGameState.getCurrentBlock(); - msgHandler.send(block); + msgHandler.sendBlock(block,newGameState); } - if(block.getDescription().equalsIgnoreCase("Day-by-day decisions game")) - { - //start day by day decision - //getDayBydayDecisionService(). + /*if(block.getDescription().equalsIgnoreCase("Day-by-day decisions game")) + { + //start day by day decision + //getDayBydayDecisionService(). - } - else if (block.getDescription().equalsIgnoreCase("Communication")) - { - //start communication round + } + else if (block.getDescription().equalsIgnoreCase("Communication")) + { + //start communication round - } - //get the timer for the block - Integer timer = getTimerforBlock(block); - //start the timer for the block sent - - //for testing purpose 5000 is given as an argument - Thread.sleep(10000); - if(block == null) - { - running = false; - } - } - }catch (InterruptedException e) { + }*/ + //} + }catch (Exception e) { + getLogger().debug(e); } } - + public void pushNextData(Game game) { + // TODO Auto-generated method stub + pushBlock(game); + + } private int getNumberOfBlock(Game game) { // TODO Auto-generated method stub + + //game.getGameConfig() - //game.getGameConfig() return 0; } @@ -203,8 +208,6 @@ Game game = getDao().find(currentGame.getId()); try{ //getLogger().debug("In the assigngroups." + game.getId()); - - students = getStudentDao().findAllByProperty("game", game); //getLogger().debug("test student object is : " + students.size()); @@ -261,7 +264,7 @@ getLogger().debug("size of 5 : " + noOfGroupsWithSize5); */ - int groupNo = 0; + int startGroupNo = 0; //assign every student a number and group if(!students.isEmpty()) @@ -269,25 +272,25 @@ if(noOfGroupsWithSize5 > 0) { - for(Student student5:assignGroupstoStudents(5,noOfGroupsWithSize5,students,groupNo)) + for(Student student5:assignGroupstoStudents(5,noOfGroupsWithSize5,students,startGroupNo)) studentWithGroupsAssigned.add(student5); //getLogger().debug("student size after 5 is: " + students.size()); getLogger().debug("student with groups assigned: " + studentWithGroupsAssigned.size()); } - groupNo = noOfGroupsWithSize5; + startGroupNo = noOfGroupsWithSize5; if(noOfGroupsWithSize4 > 0) { - for(Student student4:assignGroupstoStudents(4,noOfGroupsWithSize4,students,groupNo)) + for(Student student4:assignGroupstoStudents(4,noOfGroupsWithSize4,students,startGroupNo)) studentWithGroupsAssigned.add(student4); //getLogger().debug("student size after 4 is: " + students.size()); getLogger().debug("student with groups assigned: " + studentWithGroupsAssigned.size()); } - groupNo = noOfGroupsWithSize5 + noOfGroupsWithSize4; + startGroupNo = noOfGroupsWithSize5 + noOfGroupsWithSize4; if(noOfGroupsWithSize3 > 0) { - for(Student student3:assignGroupstoStudents(3,noOfGroupsWithSize3,students,groupNo)) + for(Student student3:assignGroupstoStudents(3,noOfGroupsWithSize3,students,startGroupNo)) studentWithGroupsAssigned.add(student3); //getLogger().debug("student size after 3 is: " + students.size()); getLogger().debug("student with groups assigned: " + studentWithGroupsAssigned.size()); @@ -321,7 +324,7 @@ System.out.println("Students size is: " + studentWithGroupsAssigned.size()); msgBroker.routeMessageToService(msg, null);*/ - MessageHandler msgHandler = new MessageHandler(); + msgHandler = new MessageHandler(null); msgHandler.setDestination("mme"); msgHandler.setSubtopic(game.getGameCode()); /*for(Student student: studentWithGroupsAssigned) @@ -937,7 +940,7 @@ boolean flag = false; List<Block> blocks = new ArrayList<Block>(); - getLogger().debug("in iscurrentmodulefinished"); + //getLogger().debug("in iscurrentmodulefinished"); if(currentBlock == null) { flag = true; @@ -987,11 +990,11 @@ return newGame; } - public Integer getTimerforBlock(Block block) + /*public Integer getTimerforBlock(Block block) { return block.getDuration(); - } + }*/ /*public Block getCurrentBlock() { //FIXEME: game id 1 is hard coded, it should be dynamic @@ -1115,4 +1118,9 @@ public RoundService getRoundService() { return roundService; } + + + + + } Modified: mentalmodels/trunk/src/main/java/edu/asu/commons/mme/service/RoundService.java =================================================================== --- mentalmodels/trunk/src/main/java/edu/asu/commons/mme/service/RoundService.java 2009-10-10 01:18:43 UTC (rev 293) +++ mentalmodels/trunk/src/main/java/edu/asu/commons/mme/service/RoundService.java 2009-10-12 22:05:11 UTC (rev 294) @@ -775,7 +775,7 @@ boolean running = false; getLogger().info("game start is: " + game.getId()); newGameState = getGameDao().find(game.getId()); - MessageHandler msgHandler = new MessageHandler(); + MessageHandler msgHandler = new MessageHandler(null); msgHandler.setDestination("mme"); msgHandler.setSubtopic(getGameCode(newGameState)); Modified: mentalmodels/trunk/src/main/java/edu/asu/commons/mme/service/StartGame.java =================================================================== --- mentalmodels/trunk/src/main/java/edu/asu/commons/mme/service/StartGame.java 2009-10-10 01:18:43 UTC (rev 293) +++ mentalmodels/trunk/src/main/java/edu/asu/commons/mme/service/StartGame.java 2009-10-12 22:05:11 UTC (rev 294) @@ -58,7 +58,7 @@ public List<Student> assignGroups(Game game) { List<Student> students = null; - students = studentService.assignGroups(game); + // students = studentService.assignGroups(game); if(students != null) { MessageBroker msgBroker = MessageBroker.getMessageBroker("_messageBroker"); Modified: mentalmodels/trunk/src/main/java/edu/asu/commons/mme/service/StudentService.java =================================================================== --- mentalmodels/trunk/src/main/java/edu/asu/commons/mme/service/StudentService.java 2009-10-10 01:18:43 UTC (rev 293) +++ mentalmodels/trunk/src/main/java/edu/asu/commons/mme/service/StudentService.java 2009-10-12 22:05:11 UTC (rev 294) @@ -10,7 +10,6 @@ import edu.asu.commons.mme.dao.HibernateGroupDao; import edu.asu.commons.mme.dao.HibernateStudentDao; import edu.asu.commons.mme.entity.Game; -import edu.asu.commons.mme.entity.Group; import edu.asu.commons.mme.entity.Student; /** @@ -79,157 +78,6 @@ return false; } - - public List<Student> assignGroups(Game game) - { - //createGroup(1); - List<Student> studentWithGroupsAssigned = new ArrayList<Student>(); - List<Student> students = new ArrayList<Student>(); - try{ - getLogger().debug("In the assigngroups." + game.getId()); - - students = getDao().findAllByProperty("game", game); - - //getLogger().debug("test student object is : " + students.size()); - if(students.size() > 1) - { - //write an algorithm to form groups - int totalStudents = students.size(); - int noOfGroupsWithSize3=0; - int noOfGroupsWithSize4=0; - int noOfGroupsWithSize5=0; - int x; - - - //no of groups - noOfGroupsWithSize5=((int)(totalStudents/5)); - - - x= totalStudents%5; - - /* if(x==0) - { - totalGroups=groupSize5; - } - else*/ - if(x==1) - { - noOfGroupsWithSize5=noOfGroupsWithSize5 - 1; - noOfGroupsWithSize3=2; - // totalGroups=groupSize5 + groupSize3; - } - - else if(x==2) - { - noOfGroupsWithSize5=noOfGroupsWithSize5-1; - noOfGroupsWithSize4=1; - noOfGroupsWithSize3=1; - // totalGroups=groupSize5 + groupSize3 + groupSize4; - } - else if(x==3) - { - noOfGroupsWithSize3=1; - // totalGroups=groupSize3 + groupSize5; - } - - else if(x==4) - { - noOfGroupsWithSize4=1; - // totalGroups=groupSize4 + groupSize5; - } - - - //getLogger().debug("size of 4 : " + noOfGroupsWithSize4); - //getLogger().debug("size of 3 : " + noOfGroupsWithSize3); - //getLogger().debug("size of 5 : " + noOfGroupsWithSize5); - - int groupNo = 0; - //assign every student a number and group - if(!students.isEmpty()) - { - if(noOfGroupsWithSize5 > 0) - { - studentWithGroupsAssigned.addAll(assignGroupstoStudents(5,noOfGroupsWithSize5,students,groupNo)); - //getLogger().debug("student size after 5 is: " + students.size()); - //getLogger().debug("student with groups assigned: " + studentWithGroupsAssigned.size()); - } - groupNo = noOfGroupsWithSize5; - if(noOfGroupsWithSize4 > 0) - { - studentWithGroupsAssigned.addAll(assignGroupstoStudents(4,noOfGroupsWithSize4,students,groupNo)); - //getLogger().debug("student size after 4 is: " + students.size()); - //getLogger().debug("student with groups assigned: " + studentWithGroupsAssigned.size()); - } - groupNo = noOfGroupsWithSize5 + noOfGroupsWithSize4; - if(noOfGroupsWithSize3 > 0) - { - studentWithGroupsAssigned.addAll(assignGroupstoStudents(3,noOfGroupsWithSize3,students,groupNo)); - //getLogger().debug("student size after 3 is: " + students.size()); - //getLogger().debug("student with groups assigned: " + studentWithGroupsAssigned.size()); - } - } - } - getLogger().debug("Final student with groups assigned: " + studentWithGroupsAssigned.size()); - }catch(Exception e) - { - getLogger().error(e); - } - return studentWithGroupsAssigned; - - } - - private List<Student> assignGroupstoStudents(int groupSize, int noOfGroups,List<Student> students,int groupNo) { - // TODO Auto-generated method stub - Student student = new Student(); - List<Student> studentWithGroupsAssigned = new ArrayList<Student>(); - getLogger().debug("group size is : "+groupSize + " and group number is : "+ groupNo); - - for(int counter = 0; counter < noOfGroups; counter++) - { - //create group - Group grp = new Group(); - - grp.setNumber(++groupNo); - groupDao.save(grp); - - getLogger().info("Group is created with id: " + grp.getId()); - int studentNo = 1; - int j = 0; - for(int i = 0; i <= groupSize-1 ; i++) - { - //get a student from a list - student = students.get(0); - getLogger().debug("i is: " + i +"student id is : "+student.getId()); - if(student.getGroup() == null) - { - //assign student no and group to each student - getLogger().debug("group assigned is : " + grp.getId()); - student.setStudentNo(studentNo); - student.setGroup(grp); - getDao().save(student); - studentNo++; - initializeStudent(student); - studentWithGroupsAssigned.add(student); - students.remove(0); - } - j++; - } - } - return students; - } - - public Group createGroup(int groupNo) - { - Group grp = new Group(); - grp.setNumber(groupNo); - groupDao.save(grp); - getLogger().info("Group is created with id: " + grp.getId()); - return grp; - } - /*public HibernateGroupDao getGroupDao() { - return groupDao; - }*/ - public void setGroupDao(HibernateGroupDao groupDao) { this.groupDao = groupDao; } Modified: mentalmodels/trunk/src/main/java/edu/asu/commons/mme/utility/MessageHandler.java =================================================================== --- mentalmodels/trunk/src/main/java/edu/asu/commons/mme/utility/MessageHandler.java 2009-10-10 01:18:43 UTC (rev 293) +++ mentalmodels/trunk/src/main/java/edu/asu/commons/mme/utility/MessageHandler.java 2009-10-12 22:05:11 UTC (rev 294) @@ -1,17 +1,25 @@ package edu.asu.commons.mme.utility; +import org.apache.log4j.Logger; import edu.asu.commons.mme.entity.Block; +import edu.asu.commons.mme.entity.Game; +import edu.asu.commons.mme.service.GameService; import edu.asu.commons.mme.service.StartGame; import flex.messaging.MessageBroker; import flex.messaging.messages.AcknowledgeMessage; import flex.messaging.messages.AsyncMessage; import flex.messaging.util.UUIDUtils; -import org.apache.log4j.Logger; public class MessageHandler { - + private static Logger logger = Logger.getLogger(StartGame.class); + + private PushData pushData; + public MessageHandler(PushData pushData) { + // TODO Auto-generated constructor stub + this.pushData = pushData; + } private String destination; public String getDestination() { @@ -34,7 +42,7 @@ public void send(Object message) { - + MessageBroker msgBroker = MessageBroker.getMessageBroker("_messageBroker"); String clientID = UUIDUtils.createUUID(); @@ -51,28 +59,48 @@ System.out.println("Students size is: " + message); AcknowledgeMessage ack = msgBroker.routeMessageToService(msg, null); - logger.info("Ack received from client for message " + msg + "is : " + ack); + /*logger.info("Ack received from client for message " + msg + "is : " + ack);*/ } - - public void sendBlock(Block block) + + public void sendBlock(Block block, Game game) { MessageBroker msgBroker = MessageBroker.getMessageBroker("_messageBroker"); String clientID = UUIDUtils.createUUID(); AsyncMessage msg = new AsyncMessage(); msg.setDestination(destination); - //String msgDestination = game.getGameCode(); msg.setHeader("DSSubtopic", subtopic); msg.setClientId(clientID); msg.setMessageId(UUIDUtils.createUUID()); msg.setTimestamp(System.currentTimeMillis()); - msg.setBody(block); - System.out.println("Message broker is: "+ msgBroker); - //System.out.println("Students size is: " + message); + AcknowledgeMessage ack = msgBroker.routeMessageToService(msg, null); + if(block!=null) + { + //int duration = block.getDuration(); + + int duration = 5; + Timer timer = new Timer(); + Long startTime = System.currentTimeMillis()/1000; + System.out.println("Started time is : " + System.currentTimeMillis()/1000); - AcknowledgeMessage ack = msgBroker.routeMessageToService(msg, null); + while((startTime + duration) > System.currentTimeMillis()/1000) + { + + System.out.println("Still Running..." + System.currentTimeMillis()/1000); + timer.run(); + } + System.out.println("Stop timer..." + System.currentTimeMillis()/1000); + pushData.pushNextData(game); + } + else + { + System.out.println("Game is Over..." + msg); + } + + + /*AcknowledgeMessage ack = msgBroker.routeMessageToService(msg, null); logger.info("Ack received from client for message " + msg + "is : " + ack); - + */ } } Added: mentalmodels/trunk/src/main/java/edu/asu/commons/mme/utility/PushData.java =================================================================== --- mentalmodels/trunk/src/main/java/edu/asu/commons/mme/utility/PushData.java (rev 0) +++ mentalmodels/trunk/src/main/java/edu/asu/commons/mme/utility/PushData.java 2009-10-12 22:05:11 UTC (rev 294) @@ -0,0 +1,8 @@ +package edu.asu.commons.mme.utility; + +import edu.asu.commons.mme.entity.Game; + +public interface PushData { + + public void pushNextData(Game game); +} Added: mentalmodels/trunk/src/main/java/edu/asu/commons/mme/utility/Timer.java =================================================================== --- mentalmodels/trunk/src/main/java/edu/asu/commons/mme/utility/Timer.java (rev 0) +++ mentalmodels/trunk/src/main/java/edu/asu/commons/mme/utility/Timer.java 2009-10-12 22:05:11 UTC (rev 294) @@ -0,0 +1,21 @@ +package edu.asu.commons.mme.utility; + +public class Timer implements Runnable { + + public Timer() + { + + } + + public void run() { + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <al...@us...> - 2009-10-10 01:18:49
|
Revision: 293 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=293&view=rev Author: alllee Date: 2009-10-10 01:18:43 +0000 (Sat, 10 Oct 2009) Log Message: ----------- minor hygiene, adding getDefaultRoundDuration() method that can be overridden by subtypes of ExperimentRoundParameters, and working on improving connection management. Modified Paths: -------------- csidex/trunk/src/main/java/edu/asu/commons/conf/ExperimentRoundParameters.java csidex/trunk/src/main/java/edu/asu/commons/event/AbstractPersistableEvent.java csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeChannel.java csidex/trunk/src/main/java/edu/asu/commons/experiment/AbstractExperiment.java csidex/trunk/src/main/java/edu/asu/commons/experiment/Persister.java csidex/trunk/src/main/java/edu/asu/commons/net/NioDispatcher.java csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java csidex/trunk/src/main/java/edu/asu/commons/net/event/DisconnectionRequest.java Modified: csidex/trunk/src/main/java/edu/asu/commons/conf/ExperimentRoundParameters.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/conf/ExperimentRoundParameters.java 2009-10-10 01:16:33 UTC (rev 292) +++ csidex/trunk/src/main/java/edu/asu/commons/conf/ExperimentRoundParameters.java 2009-10-10 01:18:43 UTC (rev 293) @@ -15,7 +15,7 @@ * @author <a href='al...@cs...'>Allen Lee</a> * @version $Revision$ */ - +@SuppressWarnings("unchecked") public interface ExperimentRoundParameters<T extends ExperimentConfiguration> extends Serializable { public String getInstructions(); @@ -73,8 +73,16 @@ } public Duration getRoundDuration() { - return Duration.create(assistant.getIntProperty("duration", 240)); + return Duration.create(assistant.getIntProperty("duration", getDefaultRoundDuration())); } + + /** + * Override to set up a different default round duration. + * @return + */ + protected int getDefaultRoundDuration() { + return 240; + } public void setParentConfiguration(E parentConfiguration) { this.parentConfiguration = parentConfiguration; Modified: csidex/trunk/src/main/java/edu/asu/commons/event/AbstractPersistableEvent.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/event/AbstractPersistableEvent.java 2009-10-10 01:16:33 UTC (rev 292) +++ csidex/trunk/src/main/java/edu/asu/commons/event/AbstractPersistableEvent.java 2009-10-10 01:18:43 UTC (rev 293) @@ -15,6 +15,8 @@ public abstract class AbstractPersistableEvent extends AbstractEvent implements PersistableEvent, Comparable<AbstractPersistableEvent> { + private static final long serialVersionUID = -8335415577272927846L; + private static long classCounter = 0; private final long ordinal; Modified: csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeChannel.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeChannel.java 2009-10-10 01:16:33 UTC (rev 292) +++ csidex/trunk/src/main/java/edu/asu/commons/event/EventTypeChannel.java 2009-10-10 01:18:43 UTC (rev 293) @@ -72,6 +72,10 @@ public <E extends Event> void subscribe(EventProcessor<E> handler) { add(handler); } + + public <E extends Event> boolean unsubscribe(EventProcessor<E> handler) { + return remove(handler); + } public <E extends Event> boolean remove(EventProcessor<E> handler) { synchronized (acceptsSubtypesEventProcessors) { @@ -99,10 +103,6 @@ } } - public <E extends Event> boolean unsubscribe(EventProcessor<E> handler) { - return remove(handler); - } - int getNumberOfOwners() { return owners.size(); } @@ -136,6 +136,7 @@ private class SequentialDispatcher implements EventDispatcher { public void dispatch(Event event) { final Class<? extends Event> eventClass = event.getClass(); + // first check handlers that want this and only this event type. synchronized (equalTypesEventProcessorMap) { List<EventProcessor> handlers = equalTypesEventProcessorMap.get(eventClass); if (handlers != null) { @@ -144,6 +145,7 @@ } } } + // next, check to see if this event should be processed by the subtype processors. synchronized (acceptsSubtypesEventProcessors) { for (final EventProcessor<Event> handler: acceptsSubtypesEventProcessors) { if (handler.getEventClass().isInstance(event)) { @@ -154,7 +156,6 @@ } } - // FIXME: turn into decorator pattern by having an EventDispatcher delegate? Only if there's less code? private class ThreadedDispatcher extends SequentialDispatcher { public void dispatch(final Event event) { new Thread() { Modified: csidex/trunk/src/main/java/edu/asu/commons/experiment/AbstractExperiment.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/experiment/AbstractExperiment.java 2009-10-10 01:16:33 UTC (rev 292) +++ csidex/trunk/src/main/java/edu/asu/commons/experiment/AbstractExperiment.java 2009-10-10 01:18:43 UTC (rev 293) @@ -143,6 +143,12 @@ return channel; } + /** + * Subtypes should always use this to add an event processor in lieu of talking with the event channel + * directly, as it ensures that the command queue can be used. + * + * @param processor + */ protected void addEventProcessor(EventTypeProcessor<? extends Event> processor) { processor.setExperiment(this); channel.add(this, processor); @@ -183,7 +189,7 @@ } catch (Exception exception) { getLogger().severe("Attempting to recover from exception: " + exception); - getLogger().throwing(getClass().getName(), "experimentThread.run()", exception); + getLogger().throwing(getClass().getName(), "experimentServerThread.run()", exception); exception.printStackTrace(); continue; } Modified: csidex/trunk/src/main/java/edu/asu/commons/experiment/Persister.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/experiment/Persister.java 2009-10-10 01:16:33 UTC (rev 292) +++ csidex/trunk/src/main/java/edu/asu/commons/experiment/Persister.java 2009-10-10 01:18:43 UTC (rev 293) @@ -58,7 +58,7 @@ private R roundConfiguration; private final SortedSet<PersistableEvent> actions; - private final SortedSet<ChatRequest> chats; + private final SortedSet<ChatRequest> chatRequests; private String experimentSaveDirectory; private String persistenceDirectory; private EventChannel channel; @@ -74,7 +74,7 @@ public Persister(T experimentConfiguration) { this.persistenceDirectory = experimentConfiguration.getPersistenceDirectory(); this.actions = new TreeSet<PersistableEvent>(); - this.chats = new TreeSet<ChatRequest>(); + this.chatRequests = new TreeSet<ChatRequest>(); // initialize persister with first round parameters SimpleDateFormat simpleDateFormat = new SimpleDateFormat(ROUND_SAVE_DIRECTORY_FORMAT); this.experimentSaveDirectory = simpleDateFormat.format(new Date()); @@ -145,11 +145,18 @@ } } + public void clearChatData() { + chatRequests.clear(); + } + public void store(ChatRequest request) { request.timestamp(); - // FIXME: this is inefficient, but chat data shouldn't be too huge.. should it? - synchronized (chats) { - chats.add(request); + // FIXME: right now all cumulative chat requests are stored in each round file. Should either + // switch to one set of chats per round, or a single chat file, as in the chatLogger. There + // is some difficulty in figuring out when exactly to clear out all the old chat requests in a + // flexible manner. Could probably do it when the BeginCommunicationRequest is handled, actually. + synchronized (chatRequests) { + chatRequests.add(request); } chatLogger.log(Level.ALL, String.format("%s, %s, %s, %s", @@ -200,7 +207,6 @@ */ private static void processSaveDirectory(File directory, List<SaveFileProcessor> processors) { try { -// ExperimentConfiguration experimentConfiguration = restoreExperimentConfiguration(directory, DEFAULT_EXPERIMENT_CONFIGURATION_FILE); int numberOfRounds = restoreExperimentConfiguration(directory).getAllParameters().size(); for (int roundNumber = 0; roundNumber < numberOfRounds; roundNumber++) { SavedRoundData savedRoundData = restoreSavedRoundData(directory, roundNumber); @@ -256,7 +262,6 @@ } } } - public final <E extends DataModel<R>> void persist(E serverDataModel) { save(serverDataModel); @@ -371,8 +376,8 @@ synchronized (actions) { oos.writeObject(actions); } - synchronized (chats) { - oos.writeObject(chats); + synchronized (chatRequests) { + oos.writeObject(chatRequests); } oos.flush(); } Modified: csidex/trunk/src/main/java/edu/asu/commons/net/NioDispatcher.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/net/NioDispatcher.java 2009-10-10 01:16:33 UTC (rev 292) +++ csidex/trunk/src/main/java/edu/asu/commons/net/NioDispatcher.java 2009-10-10 01:18:43 UTC (rev 293) @@ -21,7 +21,6 @@ import edu.asu.commons.event.EventChannel; import edu.asu.commons.net.event.ConnectionEvent; import edu.asu.commons.net.event.DisconnectionEvent; -import edu.asu.commons.util.Duration; /** @@ -52,7 +51,7 @@ // either a single NioDispatcherWorker or an aggregate WorkerPool that // constructs NioDispatcherWorkers. private Worker<SocketChannel> worker; - + // we need to maintain a mapping between Identifiers -> SocketChannel as // well as SocketChannel -> Identifier due to the way nio inherently // works; when data is incoming across the network the Selector is woken @@ -129,7 +128,6 @@ private Identifier readConnectionEvent(SocketChannel connection) throws IOException { InputStream in = connection.socket().getInputStream(); // read past the int header - in.read(); in.read(); in.read(); in.read(); ObjectInputStream ois = new ObjectInputStream(in); try { @@ -137,9 +135,8 @@ return event.getId(); } catch (Exception e) { - e.printStackTrace(); + throw new RuntimeException("Could not read connection event", e); } - return null; } private void addMapping(Identifier id, SocketChannel channel) { @@ -448,6 +445,12 @@ public Identifier process(SocketChannel incoming) { synchronized (channels) { + try { + selector.selectNow(); + } + catch (IOException exception) { + exception.printStackTrace(); + } channels.add(incoming); } synchronized (incoming) { @@ -526,20 +529,22 @@ { SocketChannel incoming = iter.next(); iter.remove(); - try { - incoming.configureBlocking(false); - incoming.register(selector, SelectionKey.OP_READ); - } - catch (IOException e) { - // recoverable, incoming connection was broken, - // just ignore it and move on. - e.printStackTrace(); - continue; - } - finally { - synchronized (incoming) { - incoming.notifyAll(); + if (incoming.isOpen()) { + try { + incoming.configureBlocking(false); + incoming.register(selector, SelectionKey.OP_READ); } + catch (IOException e) { + // recoverable, incoming connection was broken, + // just ignore it and move on. + e.printStackTrace(); + continue; + } + finally { + synchronized (incoming) { + incoming.notifyAll(); + } + } } } } Modified: csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java 2009-10-10 01:16:33 UTC (rev 292) +++ csidex/trunk/src/main/java/edu/asu/commons/net/SocketDispatcherWorker.java 2009-10-10 01:18:43 UTC (rev 293) @@ -142,14 +142,15 @@ } catch (ClassNotFoundException e) { e.printStackTrace(); + requestDisconnection(e); running = false; } } - } catch (Exception e) { + // runtime unhandled exception. e.printStackTrace(); - dispatcher.getLocalEventHandler().handle(new DisconnectionRequest(id, e)); + requestDisconnection(e); } } } Modified: csidex/trunk/src/main/java/edu/asu/commons/net/event/DisconnectionRequest.java =================================================================== --- csidex/trunk/src/main/java/edu/asu/commons/net/event/DisconnectionRequest.java 2009-10-10 01:16:33 UTC (rev 292) +++ csidex/trunk/src/main/java/edu/asu/commons/net/event/DisconnectionRequest.java 2009-10-10 01:18:43 UTC (rev 293) @@ -31,4 +31,8 @@ public Exception getException() { return exception; } + + public String toString() { + return "Disconnecting id " + id + " due to exception: " + exception; + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <al...@us...> - 2009-10-10 01:16:40
|
Revision: 292 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=292&view=rev Author: alllee Date: 2009-10-10 01:16:33 +0000 (Sat, 10 Oct 2009) Log Message: ----------- minor hygiene, tracking down connection event errors when a client disconnects. Modified Paths: -------------- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/Facilitator.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/ClientData.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/GroupDataModel.java irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/IrrigationServer.java Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java 2009-10-09 06:26:41 UTC (rev 291) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/conf/ServerConfiguration.java 2009-10-10 01:16:33 UTC (rev 292) @@ -141,9 +141,7 @@ // } public boolean isUndisruptedBandwidth(){ - if(assistant.getBooleanProperty("undisrupted-bandwidth")== true) - return true; - return false; + return assistant.getBooleanProperty("undisruptedBandwidth", false); } public double getShowUpPayment() { Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/Facilitator.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/Facilitator.java 2009-10-09 06:26:41 UTC (rev 291) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/facilitator/Facilitator.java 2009-10-10 01:16:33 UTC (rev 292) @@ -29,34 +29,34 @@ */ public class Facilitator { - private final static Facilitator INSTANCE = new Facilitator(); - - private Identifier id; // @jve:decl-index=0: + private final static Facilitator INSTANCE = new Facilitator(); - private ClientDispatcher dispatcher; - - private ServerConfiguration configuration; - - private ServerDataModel serverGameState; // @jve:decl-index=0: - - private FacilitatorWindow irrigationFacilitatorWindow; - - private boolean stopExperiment = false; - - private boolean experimentRunning = false; - + private Identifier id; // @jve:decl-index=0: + + private ClientDispatcher dispatcher; + + private ServerConfiguration configuration; + + private ServerDataModel serverGameState; // @jve:decl-index=0: + + private FacilitatorWindow irrigationFacilitatorWindow; + + private boolean stopExperiment = false; + + private boolean experimentRunning = false; + private final EventTypeChannel channel = new EventTypeChannel(); - - private Facilitator() { + + private Facilitator() { this(new ServerConfiguration()); } - + public Facilitator(ServerConfiguration configuration) { dispatcher = DispatcherFactory.getInstance().createClientDispatcher(channel); setConfiguration(configuration); initializeEventProcessors(); } - + @SuppressWarnings("unchecked") private void initializeEventProcessors() { channel.add(new EventTypeProcessor<ConfigurationEvent>(ConfigurationEvent.class) { @@ -66,7 +66,7 @@ }); channel.add(new EventTypeProcessor<FacilitatorEndRoundEvent>(FacilitatorEndRoundEvent.class) { public void handle(FacilitatorEndRoundEvent event) { -// serverGameState = null; + // serverGameState = null; irrigationFacilitatorWindow.endRound(event); configuration.nextRound(); } @@ -76,7 +76,7 @@ public static Facilitator getInstance(){ return INSTANCE; } - + public void setConfiguration(ServerConfiguration configuration) { if (configuration == null) { System.err.println("attempt to setConfiguration with null, ignoring"); @@ -86,11 +86,11 @@ this.configuration = configuration; } } - - /** - * @param args - */ - + + /** + * @param args + */ + /* * Connects facilitator to the server and registers with the server as a facilitator. * @@ -101,124 +101,118 @@ public void connect() { connect(configuration.getServerAddress()); } - + public void connect(InetSocketAddress address) { id = dispatcher.connect(address); if (id != null) { - transmit(new FacilitatorRegistrationRequest(id)); + transmit(new FacilitatorRegistrationRequest(id)); } - + } - + void createFacilitatorWindow(Dimension dimension) { irrigationFacilitatorWindow = new FacilitatorWindow(dimension, this); - //if (id == null) { - // configure for unconnected functionality - // facilitatorWindow.configureForReplay(); - //} } - + /* * Sends requests to the server */ public void transmit(Event event) { dispatcher.transmit(event); } - + public static void main(String[] args) { - - Runnable createGuiRunnable = new Runnable(){ - public void run() { - // TODO Auto-generated method stub - Dimension dimension = new Dimension(500, 600); - Facilitator facilitator = Facilitator.getInstance(); - facilitator.connect(); - JFrame frame = new JFrame(); - frame.setTitle("Facilitator window: " + facilitator.id); - frame.setSize((int) dimension.getWidth(), (int) dimension.getHeight()); - facilitator.createFacilitatorWindow(dimension); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - frame.getContentPane().add(facilitator.getFacilitatorWindow()); - frame.setVisible(true); + Runnable createGuiRunnable = new Runnable(){ + public void run() { + Dimension dimension = new Dimension(500, 600); + Facilitator facilitator = Facilitator.getInstance(); + facilitator.connect(); + JFrame frame = new JFrame(); + frame.setTitle("Facilitator window: " + facilitator.id); + frame.setSize((int) dimension.getWidth(), (int) dimension.getHeight()); + facilitator.createFacilitatorWindow(dimension); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().add(facilitator.getFacilitatorWindow()); + frame.setVisible(true); } - }; - SwingUtilities.invokeLater(createGuiRunnable); - } + }; + SwingUtilities.invokeLater(createGuiRunnable); + } - public void accept(Identifier id, Object event) { - // TODO Auto-generated method stub - if (event instanceof ConfigurationEvent) { - ConfigurationEvent configEvent = (ConfigurationEvent) event; - setConfiguration((ServerConfiguration)configEvent.getConfiguration()); - } - else if(event instanceof ServerGameStateEvent){ - ServerGameStateEvent serverGameStateEvent = (ServerGameStateEvent)event; - if (!stopExperiment) { - if (serverGameState == null) { - System.err.println("about to display game.."); - experimentRunning = true; - // FIXME: could use configuration from this event... serverGameStateEvent.getServerGameState().getConfiguration(); - serverGameState = serverGameStateEvent.getServerGameState(); - /** - * Here I need to display Game..this goes to the facilitator window. - */ - //facilitatorWindow.displayGame(); - } - else { - // synchronous updates - serverGameState = serverGameStateEvent.getServerGameState(); - } - } - //facilitatorWindow.updateWindow(serverGameStateEvent.getTimeLeft()); - } - else if (event instanceof FacilitatorEndRoundEvent){ - FacilitatorEndRoundEvent endRoundEvent = (FacilitatorEndRoundEvent)event; - serverGameState = null; - /** - * This method goes to facilitator widow. - */ - //facilitatorWindow.endRound(endRoundEvent); - } - - } + // public void accept(Identifier id, Object event) { + // // TODO Auto-generated method stub + // if (event instanceof ConfigurationEvent) { + // ConfigurationEvent configEvent = (ConfigurationEvent) event; + // setConfiguration((ServerConfiguration)configEvent.getConfiguration()); + // } + // else if(event instanceof ServerGameStateEvent){ + // ServerGameStateEvent serverGameStateEvent = (ServerGameStateEvent)event; + // if (!stopExperiment) { + // if (serverGameState == null) { + // System.err.println("about to display game.."); + // experimentRunning = true; + // // FIXME: could use configuration from this event... serverGameStateEvent.getServerGameState().getConfiguration(); + // serverGameState = serverGameStateEvent.getServerGameState(); + // /** + // * Here I need to display Game..this goes to the facilitator window. + // */ + // //facilitatorWindow.displayGame(); + // } + // else { + // // synchronous updates + // serverGameState = serverGameStateEvent.getServerGameState(); + // } + // } + // //facilitatorWindow.updateWindow(serverGameStateEvent.getTimeLeft()); + // } + // else if (event instanceof FacilitatorEndRoundEvent){ + // FacilitatorEndRoundEvent endRoundEvent = (FacilitatorEndRoundEvent)event; + // serverGameState = null; + // /** + // * This method goes to facilitator widow. + // */ + // //facilitatorWindow.endRound(endRoundEvent); + // } + // + // } - /* + /* * Send a request to server to start an experiment */ void sendBeginExperimentRequest(){ - System.out.println("I am in sendBeginExperiment"); - transmit(new BeginExperimentRequest(id)); - //sendBeginRoundRequest(); - stopExperiment = false; - } - - /* + System.out.println("I am in sendBeginExperiment"); + transmit(new BeginExperimentRequest(id)); + //sendBeginRoundRequest(); + stopExperiment = false; + } + + /* * Send a request to start a round */ public void sendBeginRoundRequest() { transmit(new BeginRoundRequest(id)); } - -// /* -// * Send a request to stop an experiment -// */ -// -// public void sendStopExperimentRequest() { -// transmit(new EndExperimentRequest(id)); -// endExperiment(); -// } - -// public void endExperiment() { -// configuration.resetExperimentRoundConfiguration(); -// serverGameState = null; -// stopExperiment = true; -// experimentRunning = false; -// //facilitatorWindow.updateMenuItems(); -// } + + // /* + // * Send a request to stop an experiment + // */ + // + // public void sendStopExperimentRequest() { + // transmit(new EndExperimentRequest(id)); + // endExperiment(); + // } + + // public void endExperiment() { + // configuration.resetExperimentRoundConfiguration(); + // serverGameState = null; + // stopExperiment = true; + // experimentRunning = false; + // //facilitatorWindow.updateMenuItems(); + // } /* * Send a request to stop a round */ - + public void sendEndRoundRequest() { transmit(new EndRoundRequest(id)); } @@ -228,31 +222,31 @@ public void sendSetConfigRequest() { dispatcher.transmit(new ConfigurationEvent(id, getConfiguration())); } - + public FacilitatorWindow getFacilitatorWindow() { return irrigationFacilitatorWindow; } - + public Identifier getIdentifier(){ - return id; + return id; } public ServerDataModel getServerGameState(){ - return serverGameState; + return serverGameState; } - + public ServerConfiguration getConfiguration(){ - return configuration; + return configuration; } - + public boolean isExperimentRunning(){ - return experimentRunning; + return experimentRunning; } - - public RoundConfiguration getCurrentRoundConfiguration() { + + public RoundConfiguration getCurrentRoundConfiguration() { return configuration.getCurrentParameters(); } - + public void setServerGameState(ServerDataModel serverGameState) { this.serverGameState = serverGameState; } Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/ClientData.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/ClientData.java 2009-10-09 06:26:41 UTC (rev 291) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/ClientData.java 2009-10-10 01:16:33 UTC (rev 292) @@ -219,12 +219,12 @@ * This would initialize the clientData before the start of each download. * */ - public void init(double availableBandwidth) { + public void init(double availableFlowCapacity) { resetFileInformation(); //maximumDeliveryBandwidth = getRoundConfiguration().getBtmax()/getRoundConfiguration().getClientsPerGroup(); maximumIndividualFlowCapacity = getRoundConfiguration().getMaximumIndividualFlowCapacity(); //currentBandwidth = totalContributedBandwidth; - this.availableFlowCapacity = availableBandwidth; + this.availableFlowCapacity = availableFlowCapacity; } private void resetFileInformation() { Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/GroupDataModel.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/GroupDataModel.java 2009-10-09 06:26:41 UTC (rev 291) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/GroupDataModel.java 2009-10-10 01:16:33 UTC (rev 292) @@ -141,12 +141,12 @@ } /** - * The main transfer function that maps the number of tokens generated to the Bandwidth Bi + * This function maps flow capacity to infrastructure efficiency. Returns an int representing + * the flow capacity given the infrastructure efficiency. * this needs to be designed. * @param totalTokens * @return */ - public int calculateFlowCapacity(final int infrastructureEfficiency) { if (infrastructureEfficiency <= 45) { return 0; @@ -190,7 +190,6 @@ currentlyAvailableFlowCapacity = maximumAvailableFlowCapacity; } - public void allocateFlowCapacity(ClientData clientData) { if (currentlyAvailableFlowCapacity >= clientData.getMaximumIndividualFlowCapacity()) { currentlyAvailableFlowCapacity -= clientData.getMaximumIndividualFlowCapacity(); Modified: irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/IrrigationServer.java =================================================================== --- irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/IrrigationServer.java 2009-10-09 06:26:41 UTC (rev 291) +++ irrigation/trunk/src/main/java/edu/asu/commons/irrigation/server/IrrigationServer.java 2009-10-10 01:16:33 UTC (rev 292) @@ -19,22 +19,23 @@ import edu.asu.commons.irrigation.conf.RoundConfiguration; import edu.asu.commons.irrigation.conf.ServerConfiguration; import edu.asu.commons.irrigation.events.BeginCommunicationRequest; +import edu.asu.commons.irrigation.events.CloseGateEvent; import edu.asu.commons.irrigation.events.DisplaySubmitTokenRequest; import edu.asu.commons.irrigation.events.EndRoundEvent; import edu.asu.commons.irrigation.events.FacilitatorEndRoundEvent; -import edu.asu.commons.irrigation.events.OpenGateEvent; import edu.asu.commons.irrigation.events.InstructionEnableRequest; import edu.asu.commons.irrigation.events.InvestedTokensEvent; +import edu.asu.commons.irrigation.events.OpenGateEvent; +import edu.asu.commons.irrigation.events.PauseEvent; import edu.asu.commons.irrigation.events.QuizCompletedEvent; import edu.asu.commons.irrigation.events.RegistrationEvent; import edu.asu.commons.irrigation.events.RoundStartedEvent; import edu.asu.commons.irrigation.events.SendContributionStatusEvent; import edu.asu.commons.irrigation.events.SendFileProgressEvent; -import edu.asu.commons.irrigation.events.PauseEvent; -import edu.asu.commons.irrigation.events.CloseGateEvent; import edu.asu.commons.net.Dispatcher; import edu.asu.commons.net.Identifier; import edu.asu.commons.net.event.ConnectionEvent; +import edu.asu.commons.net.event.DisconnectionEvent; import edu.asu.commons.net.event.DisconnectionRequest; import edu.asu.commons.util.Duration; @@ -152,32 +153,32 @@ private void initializeClientHandlers() { // client handlers addEventProcessor(new EventTypeProcessor<ConnectionEvent>(ConnectionEvent.class) { + @Override public void handle(ConnectionEvent event) { // handle incoming connections Identifier identifier = event.getId(); ClientData clientData = new ClientData(identifier); synchronized (clients) { clients.put(identifier, clientData); + serverDataModel.addClient(clientData); } - serverDataModel.addClient(clientData); + transmit(new RegistrationEvent(clientData.getId(), getRoundConfiguration(), clientData)); } }); addEventProcessor(new EventTypeProcessor<DisconnectionRequest>(DisconnectionRequest.class) { - public void handle(DisconnectionRequest event) { + @Override + public void handleInExperimentThread(DisconnectionRequest request) { + getLogger().warning("disconnecting: " + request); + Identifier disconnectedClientId = request.getId(); synchronized (clients) { - // FIXME: thread-safe? - //removing the entire group from the client list, when one of the members get disconnected - GroupDataModel groupDataModel =clients.get(event.getId()).getGroupDataModel(); - for(ClientData clientData : groupDataModel.getClientDataMap().values()){ - System.out.println("Removing the client id :"+clientData.getId()); - clients.remove(clientData.getId()); - } - //clients.remove(event.getId()); + clients.remove(request.getId()); + serverDataModel.removeClient(request.getId()); } } }); addEventProcessor(new EventTypeProcessor<ChatRequest>(ChatRequest.class) { + @Override public void handle(ChatRequest request) { Identifier source = request.getSource(); Identifier target = request.getTarget(); @@ -282,7 +283,6 @@ * @param group */ private void process(GroupDataModel group) { - // reset group's available bandwidth and re-allocate client delivery bandwidths. group.resetCurrentlyAvailableFlowCapacity(); long time = currentRoundDuration.getTimeLeft() / 1000; @@ -299,10 +299,10 @@ //System.out.println("Downloading file"+clientData.getFileNumber()+"Current time"+System.currentTimeMillis()/1000); group.allocateFlowCapacity(clientData); } - else if (clientData.isGateClosed()) { clientData.init(group.getCurrentlyAvailableFlowCapacity()); } + // right now the clients cannot be paused. else if (clientData.isPaused()) { } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: Kalin J. <kj...@as...> - 2009-10-09 21:47:53
|
I check out at 14:45pm (1.5hr) Seema has instructed me to install several different browsers and test the game by creating three students and running it, to see if that would help. Will work on this tomorrow or my next time i work. On 10/9/09, Kalin Jonas <kj...@as...> wrote: > > I'm checking in today at 13:15pm > > On Thu, Oct 8, 2009 at 6:06 PM, Kalin Jonas <kj...@as...> wrote: > >> I'm heading out now at 18:00pm. (2hr) >> I can't tell how the program could be ending up in the empty game state, >> unless perhaps Seema's code is sending me an empty block at some point on >> accident, or if my code is broken in a similar way. >> >> >> On Thu, Oct 8, 2009 at 4:17 PM, Kalin Jonas <kj...@as...> wrote: >> >>> I came in to work today at 16:00pm, and am reading over the code to try >>> and see if the problem with blocks is client side or not. >>> >> >> > |