-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCritter.java
More file actions
549 lines (503 loc) · 16.9 KB
/
Copy pathCritter.java
File metadata and controls
549 lines (503 loc) · 16.9 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
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
/* CRITTERS Main.java
* EE422C Project 5 submission by
* Anthony Bauer
* amb6869
* 16480
* Grant Uy
* gau84
* 16480
* Slip days used: <0>
* Fall 2016
*/
package assignment5;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import java.util.*;
import java.util.stream.Collectors;
public abstract class Critter {
private static String myPackage;
private static List<Critter> population = new ArrayList<>();
private static List<Critter> babies = new ArrayList<>();
public enum CritterShape {
CIRCLE,
SQUARE,
TRIANGLE,
DIAMOND,
STAR
}
/* the default color is white, which I hope makes critters invisible by default
* If you change the background color of your View component, then update the default
* color to be the same as you background
*
* critters must override at least one of the following three methods, it is not
* proper for critters to remain invisible in the view
*
* If a critter only overrides the outline color, then it will look like a non-filled
* shape, at least, that's the intent. You can edit these default methods however you
* need to, but please preserve that intent as you implement them.
*/
public javafx.scene.paint.Color viewColor() {
return javafx.scene.paint.Color.WHITE;
}
public javafx.scene.paint.Color viewOutlineColor() { return viewColor(); }
public javafx.scene.paint.Color viewFillColor() { return viewColor(); }
public abstract CritterShape viewShape();
// Gets the package name. This assumes that Critter and its subclasses are all in the same package.
static {
myPackage = Critter.class.getPackage().toString().split(" ")[1];
}
private static java.util.Random rand = new java.util.Random();
/**
* Gets a random number from a (possibly) seeded generator.
* @param max the exclusive upper bound
* @return a random number in the range [0,max)
*/
public static int getRandomInt(int max) {
return rand.nextInt(max);
}
/**
* Resets the random number generator, seeding it with a given value.
* @param new_seed the new seed value
*/
public static void setSeed(long new_seed) {
rand = new java.util.Random(new_seed);
}
/**
* Gets the string representation of a Critter.
* @return a one-character long string that visually depicts your critter in the ASCII interface
*/
public String toString() { return ""; }
private int energy = 0;
protected int getEnergy() { return energy; }
private int x_coord;
private int y_coord;
private boolean hasMoved = false;
/**
* Internal method for moving a Critter a given number of tiles in a given direction
* Only allows one movement per time step
* @param direction integer in range [0,7] corresponding to a direction
* @param distance number of squares to travel
*/
private void moveInDirection(int direction, int distance) {
if (hasMoved) return;
hasMoved = true;
x_coord = updateX(x_coord, direction, distance);
y_coord = updateY(y_coord, direction, distance);
}
/**
* Moves a Critter one tile in a given direction (at an energy cost)
* @param direction integer in range [0,7] corresponding to a direction
*/
protected final void walk(int direction) {
energy -= Params.walk_energy_cost;
moveInDirection(direction, 1);
}
/**
* Moves a Critter two tiles in a given direction (at an energy cost)
* @param direction integer in range [0,7] corresponding to a direction
*/
protected final void run(int direction) {
energy -= Params.run_energy_cost;
moveInDirection(direction, 2);
}
/**
* Initializes a new Critter one tile away from this Critter in a given direction
* @param offspring newly-created Critter to initialize
* @param direction integer in range [0,7] corresponding to a direction
*/
protected final void reproduce(Critter offspring, int direction) {
if (energy < Params.min_reproduce_energy) return;
offspring.energy = energy/2; // round down
energy -= energy/2; // round up
// spawn offspring adjacent to parent
offspring.x_coord = x_coord;
offspring.y_coord = y_coord;
offspring.moveInDirection(direction, 1);
babies.add(offspring);
}
/**
* Abstract method for Critters' custom behavior during each world time step
*/
public abstract void doTimeStep();
/**
* Checks whether a Critter wants to fight, giving it an opportunity to flee
* @param opponent string representation of the opposing Critter
* @return whether or not the Critter wants to fight
*/
public abstract boolean fight(String opponent);
protected String look(int direction, boolean steps) {
energy -= Params.look_energy_cost;
int distance = steps ? 2 : 1;
int x = updateX(x_coord, direction, distance);
int y = updateY(y_coord, direction, distance);
// return
LinkedList<Critter> critList = cacheMap.get(hashCoords(x,y));
return (critList != null) ? critList.get(0).toString() : null;
}
private int updateX(int x, int direction, int distance) {
if (direction == 7 || direction == 0 || direction == 1)
return (x+distance+Params.world_width)%Params.world_width;
else if (direction == 3 || direction == 4 || direction == 5)
return (x-distance+Params.world_width)%Params.world_width;
else
return x;
}
private int updateY(int y, int direction, int distance) {
if (direction == 1 || direction == 2 || direction == 3)
return (y-distance+Params.world_height)%Params.world_height;
else if (direction == 5 || direction == 6 || direction == 7)
return (y+distance+Params.world_height)%Params.world_height;
else
return y;
}
/**
* create and initialize a Critter subclass.
* critter_class_name must be the unqualified name of a concrete subclass of Critter, if not,
* an InvalidCritterException must be thrown.
* (Java weirdness: Exception throwing does not work properly if the parameter has lower-case instead of
* upper. For example, if craig is supplied instead of Craig, an error is thrown instead of
* an Exception.)
* @param critter_class_name
* @throws InvalidCritterException
*/
public static void makeCritter(String critter_class_name) throws InvalidCritterException {
try {
Critter c = (Critter)Class.forName(myPackage+"."+critter_class_name).newInstance();
c.energy = Params.start_energy;
c.x_coord = getRandomInt(Params.world_width);
c.y_coord = getRandomInt(Params.world_height);
population.add(c);
} catch(Exception e) {
throw new InvalidCritterException("Could not find Critter of type "+critter_class_name);
}
}
/**
* Gets a list of critters of a specific type.
* @param critter_class_name What kind of Critter is to be listed. Unqualified class name.
* @return List of Critters.
* @throws InvalidCritterException
*/
public static List<Critter> getInstances(String critter_class_name) throws InvalidCritterException {
try {
Class c = Class.forName(myPackage+"."+critter_class_name);
return population.stream().filter(c::isInstance).collect(Collectors.toList());
} catch(Exception e) {
throw new InvalidCritterException("Could not find Critter of type "+critter_class_name);
}
}
/**
* Prints out how many Critters of each type there are on the board.
* @param critters List of Critters.
*/
public static void runStats(List<Critter> critters) {
System.out.print("" + critters.size() + " critters as follows -- ");
java.util.Map<String, Integer> critter_count = new java.util.HashMap<String, Integer>();
for (Critter crit : critters) {
String crit_string = crit.toString();
Integer old_count = critter_count.get(crit_string);
if (old_count == null) {
critter_count.put(crit_string, 1);
} else {
critter_count.put(crit_string, old_count + 1);
}
}
String prefix = "";
for (String s : critter_count.keySet()) {
System.out.print(prefix + s + ":" + critter_count.get(s));
prefix = ", ";
}
System.out.println();
}
/** the TestCritter class allows some critters to "cheat". If you want to
* create tests of your Critter model, you can create subclasses of this class
* and then use the setter functions contained here.
*
*/
static abstract class TestCritter extends Critter {
/**
* This method sets the energy of the Critter
* @param new_energy_value new energy value
*/
protected void setEnergy(int new_energy_value) {
super.energy = new_energy_value;
}
/**
* This method sets the X coordinate of the Critter
* @param new_x_coord new x coordinate
*/
protected void setX_coord(int new_x_coord) {
super.x_coord = new_x_coord;
}
/**
* Sets the Y coordinate of the Critter
* @param new_y_coord new y coordinate
*/
protected void setY_coord(int new_y_coord) {
super.y_coord = new_y_coord;
}
/**
* Returns the X coordinate
* @return current x value of Critter
*/
protected int getX_coord() {
return super.x_coord;
}
/**
* Returns the Y coordinate
* @return current y value of Critter
*/
protected int getY_coord() {
return super.y_coord;
}
/**
* Returns the list of existing Critters
* @return the Critters alive at the start of this world time step
*/
protected static List<Critter> getPopulation() {
return population;
}
/**
* Returns the newly created Critters
* @return the offspring created during this world time step
*/
protected static List<Critter> getBabies() {
return babies;
}
}
/**
* Clear the world of all critters, dead and alive
*/
public static void clearWorld() {
population = new ArrayList<>();
babies = new ArrayList<>();
}
/**
* Create a one to one hash given the X and Y coordinates
* @param x the x coordinate to hash
* @param y the y coordinate to hash
* @return the hashcode generated from x and 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;
}
/**
* Get the X value from the hashcode
* @param hash the hashcode containing the X value
* @return the X value hashed in the hashcode
*/
private static int unhashX(int hash) {
int w = Params.world_width;
int h = Params.world_height;
return (w>h) ? hash%w : hash/h;
}
/**
* Get the Y value from the hashcode
* @param hash the hashcode containing the Y value
* @return the Y value hashed in the hashcode
*/
private static int unhashY(int hash) {
int w = Params.world_width;
int h = Params.world_height;
return (w>h) ? hash/w : hash%h;
}
/**
* This method calculates the hash for Critter c and adds it to the ArrayList in the HashMap hash
* If no ArrayList exists at the hash a new one will be created
* @param c the Critter to add to the HashMap
* @param hash the HashMap the Critter should be added to
*/
private static void updateHash(Critter c, HashMap<Integer,LinkedList<Critter>> hash){
int aHash = hashCoords(c.x_coord, c.y_coord);
if (!hash.containsKey(aHash))
hash.put(aHash,new LinkedList<>());
hash.get(aHash).add(c);
}
private static HashMap<Integer,LinkedList<Critter>> cacheMap;
/**
* This method performs the timestep for each Critter as follows
* Allow each Critter to perform individual timestep
* Determine locations of multiple Critters (where conflicts happen)
* Resolve conflicts such that each Critter can run before the fight, removing the loser
* Remove all Critters that are dead from world
* Add new Algae and babies to world
*/
public static void worldTimeStep() {
cacheMap = new HashMap<>();
population.forEach(c ->
cacheMap.put(hashCoords(c.x_coord, c.y_coord), new LinkedList<>(Collections.singletonList(c)))
);
// do time step
population.forEach(c -> {
c.hasMoved = false;
c.doTimeStep();
});
// pre-process locations
Set<Integer> locations = new HashSet<>();
cacheMap = new HashMap<>();
Set<Integer> collisions = new HashSet<>();
for(Critter c : population) { //identify collisions
if(c.energy<=0) //Critter is dead, ignore it
continue;
int hash = hashCoords(c.x_coord, c.y_coord);
// create list if necessary, then add critter
if (!cacheMap.containsKey(hash))
cacheMap.put(hash,new LinkedList<>());
cacheMap.get(hash).add(c);
// check if seen, adding to collisions if necessary
if (!locations.contains(hash))
locations.add(hash);
else
collisions.add(hash);
}
// handle collisions
for (Integer hash : collisions){
LinkedList<Critter> result = cacheMap.get(hash);
int origx = unhashX(hash);
int origy = unhashY(hash);
while (result.size() > 1) {
Critter A = result.poll();
Critter B = result.poll();
boolean aFlag = A.fight(B.toString()); //give critter option to move
boolean bFlag = B.fight(A.toString());
// check if either critter moved or died
boolean aMoved = A.x_coord!=origx || A.y_coord!=origy;
boolean aDied = A.energy <= 0;
boolean bMoved = B.x_coord!=origx || B.y_coord!=origy;
boolean bDied = B.energy <= 0;
//determine if move was valid
if (aMoved && cacheMap.containsKey(hashCoords(A.x_coord,A.y_coord))){ //if space is already occupied, move back to conflict space
A.x_coord = origx;
A.y_coord = origy;
aMoved = false;
}
if (bMoved && cacheMap.containsKey(hashCoords(B.x_coord,B.y_coord))){ //if space is already occupied, move back to conflict space
B.x_coord = origx;
B.y_coord = origy;
bMoved = false;
}
if(!(aMoved||aDied||bMoved||bDied)) {
int aRoll = aFlag ? getRandomInt(A.getEnergy()+1) : 0; //if we are still fighting, roll
int bRoll = bFlag ? getRandomInt(B.getEnergy()+1) : 0;
if (aRoll >= bRoll) { //A wins tiebreaker
A.energy += B.energy / 2;
B.energy = 0;
bDied = true;
} else {
B.energy += A.energy / 2;
A.energy = 0;
aDied = true;
}
}
if(!aDied)
updateHash(A,cacheMap);
if(!bDied)
updateHash(B,cacheMap);
}
}
// remove dead stuff
Iterator<Critter> it = population.iterator();
while (it.hasNext()) {
Critter c = it.next();
c.energy-=Params.rest_energy_cost;
if (c.energy <= 0)
it.remove();
}
// add new Algae
for(int i = 0; i<Params.refresh_algae_count; i++) {
try{
makeCritter("Algae");
} catch (Exception e){
e.printStackTrace();
}
}
// handle reproduce
population.addAll(babies);
babies.clear();
}
/*
* Returns a square or a circle, according to shapeIndex
*/
private static Shape getIcon(Critter.CritterShape shapeIndex) {
double size = Main.BOXSIZE; //change the double arrays below if you change this
if (shapeIndex == null)
return new Polygon();
switch(shapeIndex) {
case SQUARE: return new Rectangle(size, size);
case CIRCLE: return new Circle(size/2);
case DIAMOND: return new Diamond(size,size);
case STAR: return new Star(size,size);
case TRIANGLE: return new Triangle(size,size);
default: return new Polygon();
}
}
/**
* This method prints the world borders and Critters in the world to the screen
* Typical use case is to be called from show command.
*/
public static void displayWorld() {
Main.gridPanes.values().forEach(sp -> {
if (sp.getChildren().size() > 1) {
List<Node> list = sp.getChildrenUnmodifiable();
sp.getChildren().removeAll(list.subList(1,list.size()));
}
});
for(Critter c : population){
Shape s = getIcon(c.viewShape());
s.setFill(c.viewFillColor());
s.setStroke(c.viewOutlineColor());
StackPane sp = Main.gridPanes.get(hashCoords(c.x_coord,c.y_coord));
sp.getChildren().add(s); //add new children
}
Main.updateRunStats();
}
}
class Diamond extends Polygon {
public Diamond(double width, double height){
width-=2;
height-=2;
getPoints().addAll(
width/2.0, 0.0,
width, height/2.0,
width/2.0, height,
0.0, height/2.0
);
}
}
class Triangle extends Polygon {
public Triangle(double width, double height) {
width-=2;
height-=2;
getPoints().addAll(
0.0, height,
width/2, 0.0,
width, height
);
}
}
class Star extends Polygon {
public Star(double width, double height) {
width-=2;
height-=2;
getPoints().addAll(
0.0, height/4,
width/4, height/4,
width/2, 0.0,
3*width/4, height/4,
width, height/4,
3*width/4, 2*height/3,
7*width/8, height,
width/2, 3*height/4,
width/8, height,
width/4, 2*height/3
);
}
}