-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
439 lines (381 loc) · 15.6 KB
/
Copy pathMain.java
File metadata and controls
439 lines (381 loc) · 15.6 KB
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
/* CRITTERS Main.java
* EE422C Project 5 submission by
* Anthony Bauer
* amb6869
* 16480
* Grant Uy
* gau84
* 16480
* Slip days used: <0>
* Fall 2016
*/
package assignment5; // cannot be in default package
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.scene.text.*;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/*
* Usage: java <pkgname>.Main <input file> test
* input file is optional. If input file is specified, the word 'test' is optional.
* May not use 'test' argument without specifying input file.
*/
public class Main extends Application {
private static Timeline timeline;
private static int animationSpeed = 1;
private static boolean animating = false;
static Scanner kb; // scanner connected to keyboard input, or input file
private static String inputFile; // input file, used instead of keyboard input if specified
static ByteArrayOutputStream testOutputString; // if test specified, holds all console output
private static String myPackage; // package of Critter file. Critter cannot be in default pkg.
private static boolean DEBUG = false; // Use it or not, as you wish!
static PrintStream old = System.out; // if you want to restore output to console
public static double BOXSIZE = 7.5;
static ArrayList<StatsWindow> statsWindows;
static HashMap<Integer,StackPane> gridPanes;
// Gets the package name. The usage assumes that Critter and its subclasses are all in the same package.
static {
myPackage = Critter.class.getPackage().toString().split(" ")[1];
}
/**
* Main method.
* @param args args can be empty. If not empty, provide two parameters -- the first is a file name,
* and the second is test (for test output, where all output to be directed to a String), or nothing.
*/
public static void main(String[] args) {
launch(Main.class, args);
}
@Override
/**
* start method to launch javafx.
* @param stage the first stage window
*/
public void start(Stage stage) {
BorderPane border = new BorderPane();
statsWindows = new ArrayList<>();
//File[] pkgFiles = new File("./src/assignment5").listFiles();
File[] pkgFiles = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"/assignment5").listFiles();
if (pkgFiles == null) {
System.err.println("Something's wrong with the package structure...");
System.exit(1);
}
List<String> critClasses = Stream.of(pkgFiles)
.map(File::getName) // convert to names
//.filter(s -> s.endsWith(".java")) // get class files
//.map(s -> s.substring(0, s.length() - 5)) // strip extension
.filter(s -> s.endsWith(".class")) // get class files
.filter(s -> !s.contains("$")) // get class files
.map(s -> s.substring(0, s.length() - 6)) // strip extension
.filter(s -> { // save only subclasses of critter
try {
return !s.equals("Critter") && Critter.class.isAssignableFrom(Class.forName(myPackage+"."+s));
} catch (Exception e) {
return false;
}
})
.collect(Collectors.toList());
ObservableList<String> ol = FXCollections.observableArrayList(critClasses);
border.setLeft(addVBox(ol));
border.setCenter(createGrid());
Scene scene = new Scene(border);
stage.setScene(scene);
stage.setTitle("Critter World");
stage.show();
stage.setOnCloseRequest(event -> Platform.exit());
border.layoutBoundsProperty().addListener((observable, oldValue, newValue) -> {
double hsize = newValue.getHeight()/Params.world_height;
double wsize = (newValue.getWidth()-324)/Params.world_width;
BOXSIZE = hsize<wsize ? hsize-2 : wsize-2;
border.setCenter(createGrid());
Critter.displayWorld();
});
}
/**
* updates every instance of a Critter's runStats
*/
public static void updateRunStats() {
statsWindows.stream().forEach(StatsWindow::updateStats);
}
/**
* Creates a grid for the center region to display the world
*/
private static GridPane createGrid() {
GridPane grid = new GridPane();
gridPanes = new HashMap<>();
grid.setHgap(0);
grid.setVgap(0);
grid.setPadding(new Insets(10));
for (int i = 0; i < Params.world_width; i++) {
for (int j = 0; j < Params.world_height; j++) {
StackPane sp = new StackPane();
Shape s = new Rectangle(BOXSIZE,BOXSIZE); s.setFill(Color.WHITE); s.setStroke(Color.GRAY);
sp.getChildren().addAll(s);
gridPanes.put(hashCoords(i,j),sp);
grid.add(sp, i, j);
}
}
grid.setAlignment(Pos.CENTER);
return grid;
}
/**
* the hash method for accessing the stackpanes in the grid, see Critter.hashCorods
* @param x
* @param y
* @return an integer hash based off of the max width, max height, given x, and given y
*/
private static int hashCoords(int x, int y) {
int w = Params.world_width;
int h = Params.world_height;
return (w>h) ? x+y*w : y+x*h;
}
/**
* Creates a VBox with all the buttons, fields, and labels for the View and Controller
*/
private Node addVBox(ObservableList<String> crits) {
BorderPane border = new BorderPane();
GridPane grid = new GridPane();
grid.setVgap(10);
grid.setHgap(5);
border.setCenter(grid);
grid.setPadding(new Insets(10)); // Set all sides to 10
Text seedLabel = new Text("Select a Seed:");
seedLabel.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
grid.add(seedLabel,0,0);
TextField seedField = new NumberField(""+Critter.getRandomInt(Integer.MAX_VALUE));
Critter.setSeed(Integer.valueOf(seedField.getText()));
seedField.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
grid.add(seedField,1,0);
Button setSeed = new Button("Set Seed");
setSeed.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
setSeed.setOnAction(event -> {
if (!animating) {
Critter.setSeed(Integer.valueOf(seedField.getText()));
}
});
grid.add(setSeed,1,1);
GridPane.setHalignment(setSeed,HPos.RIGHT);
Text addCritter = new Text("Add Critter of Type:");
addCritter.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
grid.add(addCritter,0,4);
ComboBox<String> critterDropdown = new ComboBox(crits);
critterDropdown.setValue(crits.get(0));
grid.add(critterDropdown,1,4);
Text amtLabel = new Text("Amount:");
amtLabel.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
grid.add(amtLabel,0,5);
TextField addField = new NumberField("1");
addField.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
grid.add(addField,1,5);
Button addButton = new Button("Add Critters");
addButton.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
addButton.setOnAction(event -> {
if (!animating) {
String critterType = critterDropdown.getValue();
int num = (addField.getText().length() > 0) ? Integer.parseInt(addField.getText()) : 1;
if (critterType != null)
makeCritters(critterType, num);
}
});
grid.add(addButton,1,6);
GridPane.setHalignment(addButton, HPos.RIGHT);
Text stepText = new Text("Step World:");
stepText.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
grid.add(stepText,0,9);
TextField stepField = new NumberField("1");
stepField.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
grid.add(stepField,1,9);
Button stepButton = new Button("Step");
stepButton.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
stepButton.setOnAction(event -> {
if (!animating) {
int num = (stepField.getText().length() > 0) ? Integer.parseInt(stepField.getText()) : 1;
runSteps(num);
}
});
grid.add(stepButton,1,10);
GridPane.setHalignment(stepButton, HPos.RIGHT);
Text animateLabel = new Text("Animate World:");
animateLabel.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
grid.add(animateLabel,0,13);
Slider animSlider = new Slider(0,100,1);
Text animSpeedLabel = new Text();
BorderPane animBorderPane = new BorderPane();
Button animButton = new Button("Start");
animSlider.setShowTickLabels(true);
animSlider.setShowTickMarks(true);
animSlider.setSnapToTicks(false);
animSlider.setMajorTickUnit(25);
animSlider.setMinorTickCount(5);
animSlider.setOnMouseReleased(event -> {
animSlider.setValue(Math.round(animSlider.getValue()));
animButton.setDisable(animSlider.getValue() == 0);
animationSpeed = (int)Math.round(animSlider.getValue());
animSpeedLabel.setText("Speed: "+animationSpeed+" ");
});
grid.add(animSlider,0,14,2,1);
animButton.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
timeline = new Timeline(new KeyFrame(Duration.millis(500), event -> runSteps(animationSpeed)));
timeline.setCycleCount(Timeline.INDEFINITE);
animButton.setOnAction(event -> {
if (!animating && animationSpeed > 0) {
animButton.setText("Stop");
animating = true;
addButton.setDisable(true);
stepButton.setDisable(true);
setSeed.setDisable(true);
timeline.play();
} else {
animButton.setText("Start");
animating = false;
addButton.setDisable(false);
stepButton.setDisable(false);
setSeed.setDisable(false);
timeline.stop();
}
});
animBorderPane.setRight(animButton);
animSpeedLabel.setText("Speed: "+(int)animSlider.getValue()+" ");
animBorderPane.setCenter(animSpeedLabel);
grid.add(animBorderPane,1,13);
GridPane.setHalignment(animBorderPane,HPos.RIGHT);
Text runStatsLabel = new Text("Run Stats for Type:");
runStatsLabel.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
grid.add(runStatsLabel,0,16);
ComboBox<String> runStatsDropdown = new ComboBox(crits);
runStatsDropdown.setValue(crits.get(0));
grid.add(runStatsDropdown,1,16);
Button seeStats = new Button("See Stats");
seeStats.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
seeStats.setOnAction(event -> statsWindows.add(new StatsWindow(runStatsDropdown.getValue()).updateStats()));
grid.add(seeStats,1,17);
GridPane.setHalignment(seeStats, HPos.RIGHT);
BorderPane quitBorderPane = new BorderPane();
HBox quitHbox = new HBox();
Button quitButton = new Button("QUIT");
quitButton.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
quitButton.setTextFill(Color.FIREBRICK);
quitButton.setOnAction(event -> Platform.exit());
quitButton.setAlignment(Pos.CENTER);
quitButton.setPadding(new Insets(10));
Button clearWorldButton = new Button("Clear World");
clearWorldButton.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
clearWorldButton.setOnAction(event -> {Critter.clearWorld(); Critter.displayWorld();});
clearWorldButton.setAlignment(Pos.CENTER);
clearWorldButton.setPadding(new Insets(10));
quitHbox.getChildren().addAll(quitButton,clearWorldButton);
quitHbox.setSpacing(10);
quitHbox.setAlignment(Pos.CENTER);
quitBorderPane.setCenter(quitHbox);
quitBorderPane.setPadding(new Insets(10));
border.setBottom(quitBorderPane);
return border;
}
/**
* runs the worldTimestep and updates the display
* @param steps number of steps to simulate
*/
private static void runSteps(int steps) {
for (int i = 0; i < steps; i++)
Critter.worldTimeStep();
Critter.displayWorld();
}
/**
* makes a new critter
* @param type String representation of the Critter to make
* @param num number of new Critters
*/
private static void makeCritters(String type, int num) {
try {
for (int i = 0; i < num; i++)
Critter.makeCritter(type);
} catch (Exception e) {
System.err.println("Invalid critter!");
}
Critter.displayWorld();
}
}
class StatsWindow{
private String crit;
private ByteArrayOutputStream baos;
private Text stats;
/**
* Window to display a Critter's runStats
* @param critter the type of Critter to show stats for
*/
public StatsWindow(String critter){
crit = critter;
baos = new ByteArrayOutputStream();
BorderPane bp = new BorderPane();
Text critterName = new Text("Viewing stats for "+critter);
critterName.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
bp.setTop(critterName);
bp.setPadding(new Insets(10));
stats = new Text("test");
stats.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
bp.setBottom(stats);
Stage stage = new Stage();
stage.setOnCloseRequest(event -> Main.statsWindows.remove(this));
Scene scene = new Scene(bp,470,80);
stage.setScene(scene);
stage.setTitle(critter+" Stats");
stage.show();
}
/**
* Update this window and the stats for this Critter
* @return this StatsWindow object for simplicity
*/
public StatsWindow updateStats(){
System.setOut(new PrintStream(baos));
try {
String critterPackage = Critter.class.getPackage().toString().split(" ")[1];
Class.forName(critterPackage + "." + crit)
.getMethod("runStats", List.class)
.invoke(null, Critter.getInstances(crit));
} catch (Exception e) {
}
String result = baos.toString();
if(result.length()>73){
result = result.substring(0,67) + "...";
}
stats.setText(result);
baos.reset();
return this;
}
}
class NumberField extends TextField {
/**
* a type of TextField that restricts input to numbers only
* @param s starting number to display in the TextField
*/
public NumberField(String s){super(s);}
@Override public void replaceText(int start, int end, String text) {
if (text.matches("\\d*")) {
super.replaceText(start, end, text);
}
}
@Override public void replaceSelection(String text) {
if (text.matches("\\d*")) {
super.replaceSelection(text);
}
}
}