-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimulatorView.java
executable file
·1542 lines (1310 loc) · 63.2 KB
/
SimulatorView.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import java.awt.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.event.*;
import java.util.*;
import java.awt.Dimension;
import java.util.function.*;
/**
* A graphical view of all the gui. This includes the tabs, the main grid,
* the number of animals present, the clock, the weather, etc...
* The view displays a colored rectangle for each location
* representing its contents. It uses a default background color.
* Colors for each type of species can be defined and changed during the simulation
*
* @author Syraj Alkhalil and Cosmo Colman
* @version 2022.02.27 (2)
*/
public class SimulatorView extends JFrame {
private static final Color EMPTY_COLOR = Color.white; // Colors used for empty locations.
private final Color SUCCESS_COLOR = new Color(27, 157, 21);
private final Color FAIL_COLOR = new Color(207, 39, 39);
// Constants or MAIN -> NORTH Simulation Stats Panel (sim stats)
private final String SIMSTATS_STEP_PREFIX = "Step: ";
private final String SIMSTATS_TIME_PREFIX = "Time: ";
private final String SIMSTATS_DAYTIME_PREFIX = "Daytime: ";
private final String SIMSTATS_DAYCOUNT_PREFIX = "Number of days: ";
// The spacing for the JLabel for North and South of mainPanel
private final int LABEL_SPACING_HGAP = 20;
private final int LABEL_SPACING_VGAP = 5;
private final Dimension PLAYPAUSE_BUTTON_SIZE = new Dimension(40, 40);
private final Dimension SMALL_BUTTON_SIZE = new Dimension(23, 23);
private final Dimension TEXTFIELD_SIZE = new Dimension(100, 25);
// TAB 1 SPAWN RATE
private final Insets SPAWNRATE_INSETS = new Insets(1 ,1 ,1 ,5);
// The Main Panel of the whole Window
Container mainPanel;
private JLabel simStats_StepLabel, simStats_TimeLabel, simStats_DaytimeLabel, simStats_DayCountLabel;
// Components for MAIN -> SOUTH Population Stats Panel (pop stats)
private JLabel popStats_TotalLabel, popStats_TypeLabel;
private ArrayList<Integer> popStats_EntityCount;
private ArrayList<JLabel> popStats_EntityLabels;
// Components for MAIN -> EAST -> NORTH Control Buttons (play pause)
private JPanel playPause_Panel;
private JButton playPause_playPauseButton, playPause_speedButton, playPause_stepButton, playPause_resetButton;
// Components for MAIN -> EAST -> CENTRE Tab Many components (tab menu)
private JTabbedPane tabMenu_TabbedPane;
// Components for MAIN -> EAST -> CENTRE -> TAB1 Spawn rate Panel (spawn rate)
private JPanel spawnRate_Panel;
private JTextField spawnRate_seedTextField;
private JButton spawnRate_seedResetButton;
// Components for MAIN -> EAST -> CENTRE -> TAB2 Value Editor Panel (valEdit)
private JPanel valEdit_Panel;
private JPanel valEdit_Container;
private ArrayList<JPanel> valEdit_TypeContainerPanels;
// Components for MAIN -> EAST -> CENTRE -> TAB3 Add Entity Panel (addend)
private JPanel addend_Panel;
private JPanel addend_Container;
private HashMap<Enum<EntityStats.EntityType>, JPanel> typePanel;
private EntityStats newEntity;
// Components for MAIN -> EAST -> CENTRE -> TAB4 Draw Entity Panel (drawer)
private JPanel drawer_Panel;
private JButton drawer_EnableButton;
private boolean drawModeEnabled = false;
// Components for MAIN -> EAST -> SOUTH -> NORTH details Label
private JLabel detailsLabel; // For telling the user important details
private JLabel weather;
private ArrayList<ImageIcon> enview_clockFaces;
private JLabel enview_clock;
// A list of all the icons/images + the full reset button
private JButton fullResetButton;
private final ImageIcon playIcon, pauseIcon, stepIcon, resetIcon, restoreIcon, deleteIcon;
private final static ArrayList<Color> COLORS = new ArrayList<>(Arrays.asList(Color.RED,Color.BLUE,Color.MAGENTA,Color.ORANGE,Color.GREEN, Color.CYAN, Color.BLACK, Color.DARK_GRAY, Color.LIGHT_GRAY, Color.PINK));
private HashMap<Color, EntityStats> entityColor;
private final int MAX_ENTITIES = COLORS.size();
// A statistics object computing and storing simulation information
private final FieldView fieldView;
private final FieldStats stats;
private final Simulator simulator;
private final Field field;
private final int height, width;
/**
* Create a view of the given width and height.
*
* @param height The simulation's height.
* @param width The simulation's width.
* @param simulator The current simulation
* @param field The field on which the simulation is taking place // maybe remove so that the access is better
*/
public SimulatorView(int height, int width, Simulator simulator, Field field) {
this.height = height;
this.width = width;
this.simulator = simulator;
this.field = field;
stats = new FieldStats();
fieldView = new FieldView(height, width);
mainPanel = getContentPane();
setupInspector();
// getting the icons had to be done this way so that icons work in .jar files.
playIcon = new ImageIcon(this.getClass().getClassLoader().getResource("resources/play.png"));
pauseIcon = new ImageIcon(this.getClass().getClassLoader().getResource("resources/pause.png"));
stepIcon = new ImageIcon(this.getClass().getClassLoader().getResource("resources/step.png"));
resetIcon = new ImageIcon(this.getClass().getClassLoader().getResource("resources/reset.png"));
restoreIcon = new ImageIcon(this.getClass().getClassLoader().getResource("resources/restore.png"));
deleteIcon = new ImageIcon(this.getClass().getClassLoader().getResource("resources/delete.png"));
setupTab1();
mainPanel.add(fieldView, BorderLayout.CENTER); // CENTRE Simulation Panel
initialiseSimStatsPanel(mainPanel, BorderLayout.NORTH); // NORTH Simulation Stats Panel
initialisePopStatsPanel(mainPanel, BorderLayout.SOUTH); // SOUTH Population Stats Panel
initialiseOptionsPanel(mainPanel, BorderLayout.EAST); // EAST Options Stats Panel
// setting the title, packing and showing the simulation
setTitle("Predator vs Prey (and some plants) Simulation");
pack();
setSize(new Dimension(1681,948));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
/**
* This method will help in setting up tab1 so that not everything is
* initialised everytime the tab is being drawn
*/
private void setupTab1() {
spawnRate_seedTextField = new JTextField(Randomizer.getSeed() + "");
spawnRate_seedResetButton = new JButton(restoreIcon);
spawnRate_seedResetButton.setPreferredSize(SMALL_BUTTON_SIZE);
}
/**
* Sets up the hover inspector frame when you hold your mouse over an entity pixel.
*/
private void setupInspector(){
JFrame inspectFrame = new JFrame();
Container inspectContainer = inspectFrame.getContentPane();
JPanel inspectPanel = new JPanel(new BorderLayout());
inspectContainer.add(inspectPanel, BorderLayout.CENTER);
inspectFrame.setUndecorated(true);
inspectFrame.setPreferredSize(new Dimension(150,110));
inspectFrame.pack();
fieldView.addMouseMotionListener(new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
inspectPanel.removeAll();
inspectFrame.setLocation(e.getXOnScreen() + 20, e.getYOnScreen() + 20);
int fieldX = e.getX()/(fieldView.getWidth()/width);
int fieldY = e.getY()/(fieldView.getHeight()/height);
Entity entity = (Entity)field.getObjectAt(fieldY, fieldX);
if (entity == null){
inspectFrame.setVisible(false);
}
else {
inspectFrame.setVisible(true);
if (entity instanceof Animal){
inspectPanel.add(((Animal) entity).getInspectPanel(), BorderLayout.CENTER);
}
else if(entity instanceof Plant){
inspectPanel.add(((Plant) entity).getInspectPanel(), BorderLayout.CENTER);
}
}
inspectPanel.updateUI();
}
});
fieldView.addMouseListener(new MouseAdapter() {
public void mouseExited(MouseEvent evt) {
inspectFrame.setVisible(false);
}
});
}
/**
* Initialises the Simulator Statistic panel located at the North of the main frame.
*
* @param container The container you want to initialise components to.
* @param layout The position to assign the components.
*/
private void initialiseSimStatsPanel(Container container, String layout){
// Components for MAIN -> NORTH Simulation Stats Panel (sim stats)
JPanel simStats_Panel = new JPanel(new FlowLayout(FlowLayout.CENTER, LABEL_SPACING_HGAP, LABEL_SPACING_VGAP));
// The anchor for the JLabel for North and South of mainPanel
int SIMSTATS_LABEL_LAYOUT = JLabel.CENTER;
simStats_StepLabel = new JLabel(SIMSTATS_STEP_PREFIX, SIMSTATS_LABEL_LAYOUT);
simStats_TimeLabel = new JLabel(SIMSTATS_TIME_PREFIX, SIMSTATS_LABEL_LAYOUT);
simStats_DaytimeLabel = new JLabel(SIMSTATS_DAYTIME_PREFIX, SIMSTATS_LABEL_LAYOUT);
simStats_DayCountLabel = new JLabel(SIMSTATS_DAYCOUNT_PREFIX, SIMSTATS_LABEL_LAYOUT);
addAll(simStats_Panel, simStats_StepLabel, simStats_TimeLabel, simStats_DaytimeLabel, simStats_DayCountLabel);
container.add(simStats_Panel, layout);
}
/**
* Initialises the Population Statistic panel located at the South of the main frame.
*
* @param container The container you want to initialise components to.
* @param layout The position to assign the components.
*/
private void initialisePopStatsPanel(Container container, String layout){
JPanel popStats_Panel = new JPanel(new FlowLayout(FlowLayout.CENTER, LABEL_SPACING_HGAP, LABEL_SPACING_VGAP));
popStats_TotalLabel = new JLabel();
popStats_TypeLabel = new JLabel();
addAll(popStats_Panel, popStats_TotalLabel, new JLabel(" ", JLabel.CENTER), popStats_TypeLabel, new JLabel(" ", JLabel.CENTER));
popStats_EntityCount = new ArrayList<>();
popStats_EntityLabels = new ArrayList<>();
for (EntityStats entity : simulator.getPossibleEntities()){
popStats_EntityCount.add(0);
JLabel currentEntity = new JLabel();
popStats_EntityLabels.add(currentEntity);
popStats_Panel.add(currentEntity); // IF THIS BREAKS THEN USE INDEX OF
}
container.add(popStats_Panel, layout);
popStats_Panel.updateUI();
}
/**
* Initialises the Options panel located at the East of the main frame.
* @param container The container you want to initialise components to.
* @param layout The position to assign the components.
*/
private void initialiseOptionsPanel(Container container, String layout){
// Components for MAIN -> EAST Options Panel (options)
JPanel options_Panel = new JPanel(new BorderLayout());
container.add(options_Panel, layout);
initialisePlayPauseButtons(options_Panel, BorderLayout.NORTH);
initialiseTabbedMenu(options_Panel, BorderLayout.CENTER);
initialiseExtrasPanel(options_Panel, BorderLayout.SOUTH);
}
/**
* Initialise the extra panels located South of tabs
* @param panel The panel you want to initialise components to.
* @param layout The position to assign the components.
*/
private void initialiseExtrasPanel(JPanel panel, String layout){
// Components for MAIN -> EAST -> SOUTH Extras panel (extras)
JPanel extras_Panel = new JPanel(new BorderLayout());
panel.add(extras_Panel, layout);
//North
detailsLabel = new JLabel("", JLabel.CENTER);
detailsLabel.setHorizontalAlignment(JLabel.CENTER);
detailsLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1, true));
extras_Panel.add(detailsLabel, BorderLayout.NORTH);
// Centre
initialiseEnvViewPanel(extras_Panel, BorderLayout.CENTER);
// South
String FULL_RESET = "Full Reset";
fullResetButton = new JButton(FULL_RESET);
fullResetButton.setEnabled(simulator.isRunning());
extras_Panel.add(fullResetButton, BorderLayout.SOUTH);
fullResetButton.addActionListener(e -> {
simulator.resetEntities();
Randomizer.restoreDefaultSeed();
refreshPanels();
playPause_resetButton.doClick();
});
}
/**
* Initialises the environment views located centre of extras panel.
* @param panel The panel you want to initialise components to.
* @param layout The position to assign the components.
*/
private void initialiseEnvViewPanel(JPanel panel, String layout){
// Components for MAIN -> EAST -> SOUTH -> CENTRE Environment View (enview)
// For telling the user important details
JPanel enview_Panel = new JPanel(new BorderLayout());
panel.add(enview_Panel, layout);
// Weather text
weather = new JLabel("", JLabel.CENTER);
enview_Panel.add(weather, BorderLayout.CENTER);
enview_Panel.setPreferredSize(new Dimension(200,200));
// Time Clock
JPanel clockPanel = new JPanel(new BorderLayout());
enview_Panel.add(clockPanel, BorderLayout.SOUTH);
enview_clockFaces = new ArrayList<>();
for (int index = 0; index < 24; index++){
String stage;
if (index < 10)
stage = "0" + index;
else
stage = index + "";
ImageIcon clockIcon = new ImageIcon(this.getClass().getClassLoader().getResource(String.format("resources/clock/clock_%s.png", stage)));
clockIcon = new ImageIcon(clockIcon.getImage().getScaledInstance(120,120, Image.SCALE_FAST));
enview_clockFaces.add(clockIcon);
}
enview_clock = new JLabel(enview_clockFaces.get(0));
clockPanel.add(enview_clock,BorderLayout.CENTER);
}
/**
* This method is responsible for setting and displaying the text in
* a particular colour
*
* @param text The string of text being edited
* @param color the colour we wish to display the text in
*/
private void setDetailText(String text, Color color){
detailsLabel.setForeground(color);
detailsLabel.setText("<html><p style=\"width:" + 160 + "px\">"+text+"</p></html>");
detailsLabel.updateUI();
}
/**
* Refreshes the content of all tabs.
*/
private void refreshPanels(){
initialisePopStatsPanel(mainPanel, BorderLayout.SOUTH);
drawTab1SpawnRate(spawnRate_Panel, BorderLayout.CENTER);
drawTab2Validate(valEdit_Panel, BorderLayout.CENTER);
drawTab3Addend(addend_Panel, BorderLayout.CENTER);
drawTab4Drawer(drawer_Panel, BorderLayout. CENTER);
simulator.showStatus();
}
/**
* Initialises the Control Buttons located North of the Options frame.
*
* @param panel The panel you want to initialise components to.
* @param layout The position to assign the components.
*/
private void initialisePlayPauseButtons(JPanel panel, String layout){
// The spacing for the PlayPause Buttons
int PLAYPAUSE_BUTTON_SPACING_HGAP = 5;
int PLAYPAUSE_BUTTON_SPACING_VGAP = 5;
playPause_Panel = new JPanel(new FlowLayout(FlowLayout.CENTER, PLAYPAUSE_BUTTON_SPACING_HGAP, PLAYPAUSE_BUTTON_SPACING_VGAP));
playPause_playPauseButton = new JButton(pauseIcon);
String PLAYPAUSE_TOOLTIP = "Play or pause the simulation";
playPause_playPauseButton.setToolTipText(PLAYPAUSE_TOOLTIP);
playPause_speedButton = new JButton(simulator.getSpeedSymbol());
String SPEED_TOOLTIP = "Toggle simulator speeds";
playPause_speedButton.setToolTipText(SPEED_TOOLTIP);
playPause_stepButton = new JButton(stepIcon);
String STEP_TOOLTIP = "Step the simulation once";
playPause_stepButton.setToolTipText(STEP_TOOLTIP);
playPause_resetButton = new JButton(resetIcon);
String RESET_TOOLTIP = "Reset the simulation";
playPause_resetButton.setToolTipText(RESET_TOOLTIP);
setSizeForAll(PLAYPAUSE_BUTTON_SIZE, playPause_playPauseButton, playPause_speedButton, playPause_stepButton, playPause_resetButton);
addAll(playPause_Panel, playPause_playPauseButton, playPause_speedButton, playPause_stepButton, playPause_resetButton);
panel.add(playPause_Panel, layout);
playPause_speedButton.setEnabled(simulator.isRunning());
playPause_stepButton.setEnabled(simulator.isRunning());
playPause_resetButton.setEnabled(simulator.isRunning());
// Button Events
// Stops and Starts the simulation
playPause_playPauseButton.addActionListener(e -> {
simulator.toggleRunning();
if(!simulator.isRunning()){
playPause_playPauseButton.setIcon(playIcon);
playPause_speedButton.setEnabled(true);
playPause_stepButton.setEnabled(true);
playPause_resetButton.setEnabled(true);
fullResetButton.setEnabled(true);
setTabsEnabled(true);
}
else{
playPause_playPauseButton.setIcon(pauseIcon);
playPause_speedButton.setEnabled(false);
playPause_stepButton.setEnabled(false);
playPause_resetButton.setEnabled(false);
fullResetButton.setEnabled(false);
setTabsEnabled(false);
}
});
// Toggles the speed at which the simulator runs
playPause_speedButton.addActionListener(e -> {
simulator.incSpeed();
playPause_speedButton.setText(simulator.getSpeedSymbol());
});
// Steps the simulation forward by one
playPause_stepButton.addActionListener(e -> simulator.simulateOneStep());
// Resets the simulation to default
playPause_resetButton.addActionListener(e -> simulator.reset());
}
/**
* Disables the interaction of tabs 2, 3 and 4.
* @param isEnabled The state you want to set the tabs
*/
void setTabsEnabled(boolean isEnabled){
tabMenu_TabbedPane.setEnabledAt(1, isEnabled);
setPanelEnabled((JPanel) tabMenu_TabbedPane.getComponentAt(1), isEnabled);
tabMenu_TabbedPane.setEnabledAt(2, isEnabled);
setPanelEnabled((JPanel) tabMenu_TabbedPane.getComponentAt(2), isEnabled);
tabMenu_TabbedPane.setEnabledAt(3, isEnabled);
drawer_EnableButton.setEnabled(isEnabled);
}
/**
* Sets the state of all components within a panel, as well as all the components within all the panels within the panel.
* @author Creit to https://stackoverflow.com/a/32481577/11245518
* @param panel The panel you wish to set the state of.
* @param isEnabled The state you wish to set the panel's components.
*/
void setPanelEnabled(JPanel panel, Boolean isEnabled) {
panel.setEnabled(isEnabled);
Component[] components = panel.getComponents();
for (Component component : components) {
if (component instanceof JPanel) {
setPanelEnabled((JPanel) component, isEnabled);
}
component.setEnabled(isEnabled);
}
}
/**
* Initialises the TabPane located Centre of the Options frame.
*
* @param panel The panel you want to initialise components to.
* @param layout The position to assign the components.
*/
private void initialiseTabbedMenu(JPanel panel, String layout){
tabMenu_TabbedPane = new JTabbedPane();
// Tab 1
spawnRate_Panel = new JPanel(new BorderLayout());
drawTab1SpawnRate(spawnRate_Panel, BorderLayout.CENTER);
// Constants for MAIN -> EAST -> CENTRE TabbedPane (tab menu)
String TAB1_NAME = "SpawnRate";
tabMenu_TabbedPane.addTab(TAB1_NAME, spawnRate_Panel);
String TAB1_TOOLTIP = "Control the spawn rate of an entity on simulation restart";
tabMenu_TabbedPane.setToolTipTextAt(0, TAB1_TOOLTIP);
// Tab 2
valEdit_Panel = new JPanel(new BorderLayout());
drawTab2Validate(valEdit_Panel, BorderLayout.CENTER);
String TAB2_NAME = "Values";
tabMenu_TabbedPane.addTab(TAB2_NAME, valEdit_Panel);
String TAB2_TOOLTIP = "Change the constants that define an entity";
tabMenu_TabbedPane.setToolTipTextAt(1, TAB2_TOOLTIP);
// Tab 3
addend_Panel = new JPanel(new BorderLayout());
drawTab3Addend(addend_Panel, BorderLayout.CENTER);
String TAB3_NAME = "Add";
tabMenu_TabbedPane.addTab(TAB3_NAME, addend_Panel);
String TAB3_TOOLTIP = "Add your own custom entities";
tabMenu_TabbedPane.setToolTipTextAt(2, TAB3_TOOLTIP);
// Tab 4
drawer_Panel = new JPanel(new BorderLayout());
drawTab4Drawer(drawer_Panel, BorderLayout.CENTER);
String TAB4_NAME = "Draw";
tabMenu_TabbedPane.addTab(TAB4_NAME, drawer_Panel);
String TAB4_TOOLTIP = "Draw entities on the simulation";
tabMenu_TabbedPane.setToolTipTextAt(3, TAB4_TOOLTIP);
setTabsEnabled(simulator.isRunning());
panel.add(tabMenu_TabbedPane, layout);
}
/**
* Initialises the first tab of the TabbedPane, the Spawn rate tab.
* This tab lets you change the spawn rate, remove, or disable an entity on reset.
*
* @param panel The panel you want to initialise components to.
* @param layout The position to assign the components.
*/
private void drawTab1SpawnRate(JPanel panel, String layout){
panel.removeAll();
ArrayList<JSlider> spawnRate_Slider = new ArrayList<>();
ArrayList<JCheckBox> spawnRate_CheckBox = new ArrayList<>();
ArrayList<JButton> spawnRate_DeleteButton = new ArrayList<>();
ArrayList<JButton> spawnRate_RestoreDefaultButton = new ArrayList<>();
JPanel holder = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = SPAWNRATE_INSETS;
gbc.gridy = 0;
for (EntityStats stat : simulator.getPossibleEntities()) {
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = 0;
gbc.gridy++;
JCheckBox checkBox = new JCheckBox(stat.getName() + ": " + stat.getCreationProbability() + "%", true);
spawnRate_CheckBox.add(checkBox);
holder.add(checkBox, gbc);
gbc.anchor = GridBagConstraints.SOUTH;
gbc.gridx = -1;
JButton deleteButton = new JButton(deleteIcon);
deleteButton.setPreferredSize(SMALL_BUTTON_SIZE);
spawnRate_DeleteButton.add(deleteButton);
holder.add(deleteButton, gbc);
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx = 0;
gbc.gridy++;
JSlider slider = new JSlider(0, 200, (int) (stat.getCreationProbability() * 10));
slider.setPaintTicks(true);
slider.setMinorTickSpacing(10);
slider.setMajorTickSpacing(50);
spawnRate_Slider.add(slider);
holder.add(slider, gbc);
gbc.anchor = GridBagConstraints.NORTH;
gbc.gridx = -1;
JButton defaultsButton = new JButton(restoreIcon);
defaultsButton.setPreferredSize(SMALL_BUTTON_SIZE);
spawnRate_RestoreDefaultButton.add(defaultsButton);
holder.add(defaultsButton, gbc);
}
// Makes it so the tab is anchored to the top of the tab
gbc.gridy++;
gbc.weightx = 0;
gbc.weighty = 1;
holder.add(new JLabel(""),gbc);
JScrollPane scrollPanel = new JScrollPane(holder);
// HOPEFULLY FIX LATER BECAUSE I DON'T WANT THE SCROLLBAR ALWAYS THERE, BUT WITHOUT THIS THE BAR OVERLAPS
scrollPanel.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPanel.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
spawnRate_seedTextField.setPreferredSize(TEXTFIELD_SIZE);
JPanel seedPanel = new JPanel(new FlowLayout());
seedPanel.add(new JLabel("Seed: "));
seedPanel.add(spawnRate_seedTextField);
seedPanel.add(spawnRate_seedResetButton);
scrollPanel.setColumnHeaderView(seedPanel);
panel.add(scrollPanel, layout);
// Event Listeners
// Accepts input for Seed Box. Changes the seed of the Randomizer
spawnRate_seedTextField.addKeyListener(new KeyAdapter() {
// BETTER WAYS TO DO THIS BUT A BIT COMPLICATED (KeyListener bad)
// ALSO WEIRD PROBLEM WITH STRING INPUT, LIKE INITIALLY 1111 AND 11111 ARE THE SAME
public void keyTyped(KeyEvent e) {
char character = e.getKeyChar();
if ((((character < '0') || (character > '9')) && (character != KeyEvent.VK_BACK_SPACE)) || (spawnRate_seedTextField.getText().length() > 8)) {
e.consume();
}
Randomizer.setSeed(Integer.parseInt(spawnRate_seedTextField.getText()));
}
});
// Resets the field
spawnRate_seedResetButton.addActionListener(e -> {
Randomizer.restoreDefaultSeed();
spawnRate_seedTextField.setText(Randomizer.getSeed() + "");
});
//Creates listener for each existing entity in the simulation
for (EntityStats entity : simulator.getPossibleEntities()){
int index = simulator.getPossibleEntities().indexOf(entity);
JSlider currentSlider = spawnRate_Slider.get(index);
JCheckBox currentCheckBox = spawnRate_CheckBox.get(index);
JButton currentDeleteButton = spawnRate_DeleteButton.get(index);
JButton currentDefaultsButton = spawnRate_RestoreDefaultButton.get(index);
currentSlider.addChangeListener(e -> {
double currentSpawnProb = (double) currentSlider.getValue() / 10;
currentCheckBox.setText(entity.getName() + ": " + currentSpawnProb + "%");
entity.setCreationProbability(currentSpawnProb);
});
currentCheckBox.addItemListener(e -> {
currentSlider.setEnabled(currentCheckBox.isSelected());
entity.toggleEnabled();
});
currentDeleteButton.addActionListener(e -> {
if (!(simulator.getPossibleEntities().size() > 1)) {
setDetailText("Removal Failed. There needs to be at least one entity!", FAIL_COLOR);
}
else if (simulator.isRunning()){
setDetailText("Please don't remove while simulator is running", FAIL_COLOR);
}
else {
setDetailText("Successfully removed the " + entity.getName() + " entity!", SUCCESS_COLOR);
simulator.removeFromOrganisms(entity);
field.removeAllObjectsOf(entity);
simulator.removeEntity(entity);
initialisePopStatsPanel(mainPanel, BorderLayout.SOUTH);
simulator.showStatus();
refreshPanels();
}
});
currentDefaultsButton.addActionListener(e -> {
double defaultSpawnProb = entity.getDefaults().getCreationProbability();
currentSlider.setValue((int)(defaultSpawnProb * 10));
currentCheckBox.setText(entity.getName() + ": " + defaultSpawnProb + "%");
entity.setCreationProbability(defaultSpawnProb);
});
}
panel.updateUI();
}
/**
* Initialises the second tab of the TabbedPane, the Value Editor tab.
* This tab lets you live edit an entities properties in the simulation.
*
* @param panel The panel you want to initialise components to.
* @param layout The position to assign the components.
*/
private void drawTab2Validate(JPanel panel, String layout){
panel.removeAll();
JComboBox<EntityStats> valuesComboBox = new JComboBox<>(simulator.getPossibleEntities().toArray(new EntityStats[0]));
panel.add(valuesComboBox, BorderLayout.NORTH);
valEdit_Container = new JPanel(new BorderLayout()); // THIS METHOD ISN'T GREAT BUT ROLL WITH IT
panel.add(valEdit_Container, BorderLayout.CENTER);
entityColor = new HashMap<>();
for (Color color : COLORS){
entityColor.put(color, null);
}
valEdit_TypeContainerPanels = new ArrayList<>();
for (EntityStats stat : simulator.getPossibleEntities()){
JPanel currentStatSliderContainer = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
createSlider(currentStatSliderContainer, 1, "Breeding Prob", EntityStats.BREEDINGPROBABILITY_MAX, 0.01, stat::getBreedingProbability, stat::setBreedingProbability, stat.getDefaults()::getBreedingProbability);
// IF ANIMAL
if (!stat.getEntityType().equals(EntityStats.EntityType.PLANT)){
AnimalStats animalStat = (AnimalStats)stat;
// isNocturnal
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 3;
gbc.insets = new Insets(3,0,3,0);
JCheckBox nocturnalBox = new JCheckBox("Nocturnal", animalStat.isNocturnal());
currentStatSliderContainer.add(nocturnalBox, gbc);
// DEFAULT BUTTON
gbc.gridx = 2;
JButton defaultButton = new JButton(restoreIcon);
defaultButton.setPreferredSize(new Dimension(23, 23));
currentStatSliderContainer.add(defaultButton, gbc);
nocturnalBox.addItemListener(e -> animalStat.setNocturnal(nocturnalBox.isSelected()));
defaultButton.addActionListener(e -> {
boolean defaultValue = animalStat.getDefaults().isNocturnal();
nocturnalBox.setSelected(defaultValue);
animalStat.setNocturnal(defaultValue);
});
createSlider(currentStatSliderContainer, 4, "Breeding Age",AnimalStats.BREEDINGAGE_MAX, animalStat::getBreedingAge, animalStat::setBreedingAge, animalStat.getDefaults()::getBreedingAge);
createSlider(currentStatSliderContainer, 6, "Max Age", AnimalStats.MAXAGE_MAX, animalStat::getMaxAge, animalStat::setMaxAge, animalStat.getDefaults()::getMaxAge);
createSlider(currentStatSliderContainer, 8, "Max Litter Size", AnimalStats.MAXLITTERSIZE_MAX, animalStat::getMaxLitterSize, animalStat::setMaxLitterSize, animalStat.getDefaults()::getMaxLitterSize);
createSlider(currentStatSliderContainer, 10, "Hunger Value", AnimalStats.HUNGERVALUE_MAX, animalStat::getHungerValue, animalStat::setHungerValue, animalStat.getDefaults()::getHungerValue);
gbc.gridy = 11;
}
else{ // IF PLANT
PlantStats plantStat = (PlantStats)stat;
createSlider(currentStatSliderContainer, 3, "Food Value", PlantStats.FOODVALUE_MAX, plantStat::getFoodValue, plantStat::setFoodValue, plantStat.getDefaults()::getFoodValue);
createSlider(currentStatSliderContainer, 5, "Max Level", PlantStats.MAXLEVEL_MAX, plantStat::getMaxLevel, plantStat::setMaxLevel, plantStat.getDefaults()::getMaxLevel);
gbc.gridy = 6;
}
gbc.gridx = 0;
gbc.gridwidth = 2;
gbc.gridy ++;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
JComboBox<Color> colorComboBox = new JComboBox<>(COLORS.toArray(new Color[0]));
colorComboBox.setSelectedIndex(simulator.getPossibleEntities().indexOf(stat));
colorComboBox.setBackground(stat.getColor());
entityColor.replace(stat.getColor(), stat);
ComboBoxRenderer renderer = new ComboBoxRenderer(colorComboBox, entityColor);
colorComboBox.setRenderer(renderer);
currentStatSliderContainer.add(colorComboBox, gbc);
colorComboBox.addActionListener(e -> {
Color selectedColor = (Color) colorComboBox.getSelectedItem();
if (entityColor.get(selectedColor) == null){
entityColor.replace(stat.getColor(), null);
entityColor.replace(selectedColor, stat);
stat.setColor(selectedColor);
colorComboBox.setBackground(selectedColor);
setDetailText("Changed colour of " + stat.getName() + "." , SUCCESS_COLOR);
}
else{
setDetailText("Colour already taken by " + entityColor.get(selectedColor).getName() + "!", FAIL_COLOR);
}
});
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 3;
currentStatSliderContainer.add(new Label(stat.getEntityType().toString()), gbc);
// Adds Panel to ArrayList
valEdit_TypeContainerPanels.add(currentStatSliderContainer);
}
valEdit_Container.add(valEdit_TypeContainerPanels.get(0), BorderLayout.CENTER);
valuesComboBox.addActionListener(e -> {
int index = valuesComboBox.getSelectedIndex();
valEdit_Container.removeAll();
valEdit_Container.add(valEdit_TypeContainerPanels.get(index), BorderLayout.CENTER);
valEdit_Container.updateUI();
});
panel.add(valEdit_Container, BorderLayout.CENTER);
panel.updateUI();
}
/**
* Initialises the third tab of the TabbedPane, the Add Entity tab.
* This tab lets you add a custom entity to the simulation.
*
* @param panel The panel you want to initialise components to.
* @param layout The position to assign the components.
*/
private void drawTab3Addend(JPanel panel, String layout){
panel.removeAll();
JPanel nameAndTypesPanel = new JPanel(new GridBagLayout());
addend_Container = new JPanel(new BorderLayout());
newEntity = new EntityStats();
AnimalStats newAnimal = new AnimalStats();
PlantStats newPlant = new PlantStats();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
JComboBox<EntityStats.EntityType> typeComboBox = new JComboBox(EntityStats.EntityType.values());
nameAndTypesPanel.add(typeComboBox, gbc);
typeComboBox.addItemListener(e -> {
EntityStats.EntityType type = (EntityStats.EntityType) typeComboBox.getSelectedItem();
if (type.equals(EntityStats.EntityType.PLANT)){
newEntity = newPlant;
}
else {
newEntity = newAnimal;
}
newEntity.setEntityType(type);
addend_Container.removeAll();
addend_Container.add(typePanel.get(type),BorderLayout.CENTER);
addend_Container.updateUI();
});
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
JComboBox<Color> colorComboBox = new JComboBox<>(COLORS.toArray(new Color[0]));
ComboBoxRenderer renderer = new ComboBoxRenderer(colorComboBox, entityColor);
colorComboBox.setRenderer(renderer);
nameAndTypesPanel.add(colorComboBox, gbc);
colorComboBox.addActionListener(e -> {
Color selectedColor = (Color) colorComboBox.getSelectedItem();
if (entityColor.get(selectedColor) == null){
newEntity.setColor(selectedColor);
colorComboBox.setBackground(selectedColor);
}
});
tabMenu_TabbedPane.addChangeListener(e -> {
if (tabMenu_TabbedPane.getSelectedIndex() != 2){
newEntity.setColor(null);
colorComboBox.setBackground(null);
}
});
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.VERTICAL;
JTextField nameTextField = new JTextField();
nameTextField.setText("SampleName");
nameTextField.setPreferredSize(TEXTFIELD_SIZE);
nameAndTypesPanel.add(nameTextField, gbc);
nameTextField.getDocument().addDocumentListener(new DocumentListener() {
final Runnable setNameAction = () -> {newEntity.setName(nameTextField.getText());};
@Override
public void changedUpdate(DocumentEvent e) {
setNameAction.run();
}
@Override
public void insertUpdate(DocumentEvent e) {
setNameAction.run();
}
@Override
public void removeUpdate(DocumentEvent e) {
setNameAction.run();
}
});
panel.add(nameAndTypesPanel, BorderLayout.NORTH);
// Panel with input boxes
JPanel inputBoxesPanel = new JPanel(new GridBagLayout());
newEntity = newAnimal;
createSlider(inputBoxesPanel, 0, "Creation Prob", EntityStats.CREATIONPROBABILITY_MAX, 0.1, newAnimal::getCreationProbability, newAnimal::setCreationProbability);
createSlider(inputBoxesPanel, 2, "Breeding Prob", EntityStats.BREEDINGPROBABILITY_MAX, 0.01, newAnimal::getBreedingProbability, newAnimal::setBreedingProbability);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 4;
gbc.gridwidth = 2;
gbc.anchor = GridBagConstraints.WEST;
JCheckBox nocturnalBox = new JCheckBox("Nocturnal", false);
inputBoxesPanel.add(nocturnalBox, gbc);
nocturnalBox.addItemListener(e -> newAnimal.setNocturnal(nocturnalBox.isSelected()));
createSlider(inputBoxesPanel, 5, "Breeding Age", AnimalStats.BREEDINGAGE_MAX, newAnimal::getBreedingAge, newAnimal::setBreedingAge);
createSlider(inputBoxesPanel, 7, "Max Age", AnimalStats.MAXAGE_MAX, newAnimal::getMaxAge, newAnimal::setMaxAge);
createSlider(inputBoxesPanel, 9, "Max Litter Size", AnimalStats.MAXLITTERSIZE_MAX, newAnimal::getMaxLitterSize, newAnimal::setMaxLitterSize);
createSlider(inputBoxesPanel, 11, "Hunger Value", AnimalStats.HUNGERVALUE_MAX, newAnimal::getHungerValue, newAnimal::setHungerValue);
typePanel = new HashMap<>();
typePanel.put(EntityStats.EntityType.PREY, inputBoxesPanel);
typePanel.put(EntityStats.EntityType.PREDATOR, inputBoxesPanel);
inputBoxesPanel = new JPanel(new GridBagLayout());
createSlider(inputBoxesPanel, 0, "Creation Prob", EntityStats.CREATIONPROBABILITY_MAX,0.1, newPlant::getCreationProbability, newPlant::setCreationProbability);
createSlider(inputBoxesPanel, 2, "Breeding Prob", EntityStats.BREEDINGPROBABILITY_MAX,0.01, newPlant::getBreedingProbability, newPlant::setBreedingProbability);
createSlider(inputBoxesPanel, 4, "Food Value", PlantStats.FOODVALUE_MAX, newPlant::getFoodValue, newPlant::setFoodValue);
createSlider(inputBoxesPanel, 6, "Max Level", PlantStats.MAXLEVEL_MAX, newPlant::getMaxLevel, newPlant::setMaxLevel);
typePanel.put(EntityStats.EntityType.PLANT, inputBoxesPanel);
addend_Container.add(typePanel.get(EntityStats.EntityType.PREY), BorderLayout.CENTER);
panel.add(addend_Container, layout);
// Buttons
JPanel addAndClearButtonsPanel = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.HORIZONTAL;
JButton addButton = new JButton("Add");
addAndClearButtonsPanel.add(addButton, gbc);
addButton.addActionListener(e -> {
boolean nameTaken = false;
for (EntityStats entity : simulator.getPossibleEntities()){
if (entity.getName().equals(newEntity.getName())){
nameTaken = true;
}
}
if (!(simulator.getPossibleEntities().size() < MAX_ENTITIES)){
setDetailText("Too many entities! Max of " + MAX_ENTITIES + ".", FAIL_COLOR);
}
else if (nameTaken) {
setDetailText("Entity with that name already exists!", FAIL_COLOR);
}
else if (newEntity.getColor() == null){
setDetailText("Please choose a colour!", FAIL_COLOR);
}
else {
try {
simulator.addEntityToPossibilities(newEntity.clone());
} catch (CloneNotSupportedException ex) {
ex.printStackTrace();
}
initialisePopStatsPanel(mainPanel, BorderLayout.SOUTH);
setDetailText("Successfully added new " + newEntity.getName() + " " + newEntity.getEntityType().toString().toLowerCase() + "!", SUCCESS_COLOR);
newEntity.resetToDefault();
refreshPanels();
}
});
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.HORIZONTAL;
JButton clearButton = new JButton("Clear");
addAndClearButtonsPanel.add(clearButton, gbc);
clearButton.addActionListener(e -> {
newEntity = new EntityStats();
newEntity.resetToDefault();
panel.removeAll();
drawTab3Addend(panel, layout);
panel.updateUI();
});
panel.add(addAndClearButtonsPanel, BorderLayout.SOUTH);
panel.updateUI();
}
/**
* Initialises the fourth tab of the TabbedPane, the Draw Entity tab.
* This tab lets you draw entities wherever you want on the field.
*
* @param panel The panel you want to initialise components to.
* @param layout The position to assign the components.
*/
private void drawTab4Drawer(JPanel panel, String layout){
panel.removeAll();
drawer_EnableButton = new JButton();
panel.add(drawer_EnableButton, BorderLayout.NORTH);
JPanel drawer_OptionsPanel = new JPanel(new GridBagLayout());
panel.add(drawer_OptionsPanel, layout);
ButtonGroup buttonGroup = new ButtonGroup();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
JComboBox<EntityStats> entityComboBox = new JComboBox<>(simulator.getPossibleEntities().toArray(new EntityStats[0]));
drawer_OptionsPanel.add(entityComboBox, gbc);
gbc.gridwidth = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.NONE;
drawer_OptionsPanel.add(new JLabel("Brush Size: "), gbc);
gbc.gridx = 1;