-
Notifications
You must be signed in to change notification settings - Fork 1
/
MazeImpl.java
928 lines (827 loc) · 36.8 KB
/
MazeImpl.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
/*
Copyright (C) 2004 Geoffrey Alan Washburn
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
USA.
*/
import java.lang.Thread;
import java.lang.Runnable;
import java.io.Serializable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Random;
import java.util.Vector;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Collection;
import java.util.LinkedList;
import java.util.HashMap;
/**
* A concrete implementation of a {@link Maze}.
* @author Geoffrey Washburn <<a href="mailto:geoffw@cis.upenn.edu">geoffw@cis.upenn.edu</a>>
* @version $Id: MazeImpl.java 371 2004-02-10 21:55:32Z geoffw $
*/
public class MazeImpl extends Maze implements Serializable, ClientListener, Runnable {
/**
* Create a {@link Maze}.
* @param point Treat the {@link Point} as a magintude specifying the
* size of the maze.
* @param seed Initial seed for the random number generator.
*/
public MazeImpl(Point point, long seed) {
maxX = point.getX();
assert(maxX > 0);
maxY = point.getY();
assert(maxY > 0);
// Initialize the maze matrix of cells
mazeVector = new Vector(maxX);
for(int i = 0; i < maxX; i++) {
Vector colVector = new Vector(maxY);
for(int j = 0; j < maxY; j++) {
colVector.insertElementAt(new CellImpl(), j);
}
mazeVector.insertElementAt(colVector, i);
}
thread = new Thread(this);
// Initialized the random number generator
randomGen = new Random(seed);
// Build the maze starting at the corner
buildMaze(new Point(0,0));
thread.start();
}
/**
* Create a maze from a serialized {@link MazeImpl} object written to a file.
* @param mazefile The filename to load the serialized object from.
* @return A reconstituted {@link MazeImpl}.
*/
public static Maze readMazeFile(String mazefile)
throws IOException, ClassNotFoundException {
assert(mazefile != null);
FileInputStream in = new FileInputStream(mazefile);
ObjectInputStream s = new ObjectInputStream(in);
Maze maze = (Maze) s.readObject();
return maze;
}
/**
* Serialize this {@link MazeImpl} to a file.
* @param mazefile The filename to write the serialized object to.
* */
public void save(String mazefile)
throws IOException {
assert(mazefile != null);
FileOutputStream out = new FileOutputStream(mazefile);
ObjectOutputStream s = new ObjectOutputStream(out);
s.writeObject(this);
s.flush();
}
/**
* Display an ASCII version of the maze to stdout for debugging purposes.
*/
public void print() {
for(int i = 0; i < maxY; i++) {
for(int j = 0; j < maxX; j++) {
CellImpl cell = getCellImpl(new Point(j,i));
if(j == maxY - 1) {
if(cell.isWall(Direction.South)) {
System.out.print("+-+");
} else {
System.out.print("+ +");
}
} else {
if(cell.isWall(Direction.South)) {
System.out.print("+-");
} else {
System.out.print("+ ");
}
}
}
System.out.print("\n");
for(int j = 0; j < maxX; j++) {
CellImpl cell = getCellImpl(new Point(j,i));
if(cell.getContents() != null) {
if(cell.isWall(Direction.West)) {
System.out.print("|*");
} else {
System.out.print(" *");
}
} else {
if(cell.isWall(Direction.West)) {
System.out.print("| ");
} else {
System.out.print(" ");
}
}
if(j == maxY - 1) {
if(cell.isWall(Direction.East)) {
System.out.print("|");
} else {
System.out.print(" ");
}
}
}
System.out.print("\n");
if(i == maxX - 1) {
for(int j = 0; j < maxX; j++) {
CellImpl cell = getCellImpl(new Point(j,i));
if(j == maxY - 1) {
if(cell.isWall(Direction.North)) {
System.out.print("+-+");
} else {
System.out.print("+ +");
}
} else {
if(cell.isWall(Direction.North)) {
System.out.print("+-");
} else {
System.out.print("+ ");
}
}
}
System.out.print("\n");
}
}
}
public boolean checkBounds(Point point) {
assert(point != null);
return (point.getX() >= 0) && (point.getY() >= 0) &&
(point.getX() < maxX) && (point.getY() < maxY);
}
public Point getSize() {
return new Point(maxX, maxY);
}
public synchronized Cell getCell(Point point) {
assert(point != null);
return getCellImpl(point);
}
public synchronized void addClient(Client client) {
assert(client != null);
// Pick a random starting point, and check to see if it is already occupied
Point point = new Point(randomGen.nextInt(maxX),randomGen.nextInt(maxY));
CellImpl cell = getCellImpl(point);
// Repeat until we find an empty cell
while(cell.getContents() != null) {
point = new Point(randomGen.nextInt(maxX),randomGen.nextInt(maxY));
cell = getCellImpl(point);
}
addClient(client, point);
}
public synchronized void addClient(Client client, DirectedPoint dp) {
assert(client != null);
assert(checkBounds(dp));
Direction d = dp.getDirection();
CellImpl cell = getCellImpl(dp);
cell.setContents(client);
clientMap.put(client, new DirectedPoint(dp));
client.registerMaze(this);
client.addClientListener(this);
update();
notifyClientAdd(client);
}
public synchronized Point getClientPoint(Client client) {
assert(client != null);
Object o = clientMap.get(client);
assert(o instanceof Point);
return (Point)o;
}
public synchronized Direction getClientOrientation(Client client) {
assert(client != null);
Object o = clientMap.get(client);
assert(o instanceof DirectedPoint);
DirectedPoint dp = (DirectedPoint)o;
return dp.getDirection();
}
public synchronized void removeClient(Client client) {
assert(client != null);
Object o = clientMap.remove(client);
assert(o instanceof Point);
Point point = (Point)o;
CellImpl cell = getCellImpl(point);
cell.setContents(null);
clientMap.remove(client);
client.unregisterMaze();
client.removeClientListener(this);
update();
notifyClientRemove(client);
}
public synchronized boolean clientFire(Client client) {
assert(client != null);
// If the client already has a projectile in play
if(clientFired.contains(client)) {
// Since it came from the server, it reaches here cause client is lagging
// Update score anyways to be consistent.
notifyClientFired(client);
return false;
}
Point point = getClientPoint(client);
Direction d = getClientOrientation(client);
CellImpl cell = getCellImpl(point);
/* Check that you can fire in that direction */
if(cell.isWall(d)) {
return false;
}
DirectedPoint newPoint = new DirectedPoint(point.move(d), d);
/* Is the point withint the bounds of maze? */
assert(checkBounds(newPoint));
CellImpl newCell = getCellImpl(newPoint);
Object contents = newCell.getContents();
if(contents != null) {
notifyClientFired(client);
// If it is a Client, update scores and wait for server reply for next step
if (contents instanceof Client) {
// If it is a GUIClient (myself), alert the server
if (contents instanceof GUIClient) {
GUIClient c = (GUIClient) contents;
c.reportDeath(client.getName());
// If it's robot, check if myself and alert server
} else if (contents instanceof RobotClient) {
RobotClient r = (RobotClient) contents;
r.reportDeath(r.getName(), client.getName());
}
return true;
} else {
// Otherwise fail (bullets will destroy each other)
return false;
}
}
clientFired.add(client);
Projectile prj = new Projectile(client);
/* Write the new cell */
projectileMap.put(prj, newPoint);
newCell.setContents(prj);
notifyClientFired(client);
update();
return true;
}
public synchronized boolean getClientFired (Client client) {
if (clientFired.contains(client)) {
return true;
}
return false;
}
public synchronized boolean moveClientForward(Client client) {
assert(client != null);
Object o = clientMap.get(client);
assert(o instanceof DirectedPoint);
DirectedPoint dp = (DirectedPoint)o;
return moveClient(client, dp.getDirection());
}
public synchronized boolean moveClientBackward(Client client) {
assert(client != null);
Object o = clientMap.get(client);
assert(o instanceof DirectedPoint);
DirectedPoint dp = (DirectedPoint)o;
return moveClient(client, dp.getDirection().invert());
}
public synchronized Iterator getClients() {
return clientMap.keySet().iterator();
}
public void addMazeListener(MazeListener ml) {
listenerSet.add(ml);
}
public void removeMazeListener(MazeListener ml) {
listenerSet.remove(ml);
}
/**
* Listen for notifications about action performed by
* {@link Client}s in the maze.
* @param c The {@link Client} that acted.
* @param ce The action the {@link Client} performed.
*/
public void clientUpdate(Client c, ClientEvent ce) {
// When a client turns, update our state.
if(ce == ClientEvent.turnLeft) {
rotateClientLeft(c);
} else if(ce == ClientEvent.turnRight) {
rotateClientRight(c);
}
}
/**
* Server handler for the death of a {@link Client}.
* @param source The {@link Client} that fired the projectile.
* @param target The {@link Client} that was killed.
*/
public synchronized DirectedPoint killClient(Client source, Client target) {
assert(source != null);
assert(target != null);
Mazewar.consolePrintLn(source.getName() + " just vaporized " + target.getName());
Object o = clientMap.remove(target);
assert(o instanceof Point);
Point point = (Point)o;
CellImpl cell = getCellImpl(point);
cell.setContents(null);
// Pick a random starting point, and check to see if it is already occupied
point = new Point(randomGen.nextInt(maxX),randomGen.nextInt(maxY));
cell = getCellImpl(point);
// Repeat until we find an empty cell
while(cell.getContents() != null) {
point = new Point(randomGen.nextInt(maxX),randomGen.nextInt(maxY));
cell = getCellImpl(point);
}
Direction d = Direction.random();
while(cell.isWall(d)) {
d = Direction.random();
}
cell.setContents(target);
DirectedPoint dp = new DirectedPoint(point, d);
clientMap.put(target, dp);
update();
notifyClientKilled(source, target);
return dp;
}
/**
* Client handler for the death of a {@link Client} with respawn point dp.
* @param source The {@link Client} that fired the projectile.
* @param target The {@link Client} that was killed.
* @param dp The {@link DirectedPoint} that marks the respawn position.
*/
public synchronized void killClient(Client source, Client target, DirectedPoint dp) {
assert(source != null);
assert(target != null);
Mazewar.consolePrintLn(source.getName() + " just vaporized " + target.getName());
Object o = clientMap.remove(target);
assert(o instanceof Point);
Point point = (Point)o;
CellImpl cell = getCellImpl(point);
cell.setContents(null);
cell = getCellImpl(dp);
cell.setContents(target);
clientMap.put(target, dp);
update();
notifyClientKilled(source, target);
}
/**
* Control loop for {@link Projectile}s.
*/
public void run() {
Collection deadPrj = new HashSet();
while(true) {
if(!projectileMap.isEmpty()) {
Iterator it = projectileMap.keySet().iterator();
synchronized(projectileMap) {
while(it.hasNext()) {
Object o = it.next();
assert(o instanceof Projectile);
if (!deadPrj.contains((Projectile)o)) {
deadPrj.addAll(moveProjectile((Projectile)o));
}
}
it = deadPrj.iterator();
while(it.hasNext()) {
Object o = it.next();
assert(o instanceof Projectile);
Projectile prj = (Projectile)o;
projectileMap.remove(prj);
clientFired.remove(prj.getOwner());
}
deadPrj.clear();
}
}
try {
thread.sleep(200);
} catch(Exception e) {
// shouldn't happen
}
}
}
/* Internals */
private synchronized Collection moveProjectile(Projectile prj) {
Collection deadPrj = new LinkedList();
assert(prj != null);
Object o = projectileMap.get(prj);
assert(o instanceof DirectedPoint);
DirectedPoint dp = (DirectedPoint)o;
Direction d = dp.getDirection();
CellImpl cell = getCellImpl(dp);
/* Check for a wall */
if(cell.isWall(d)) {
// If there is a wall, the projectile goes away.
cell.setContents(null);
deadPrj.add(prj);
update();
return deadPrj;
}
DirectedPoint newPoint = new DirectedPoint(dp.move(d), d);
/* Is the point within the bounds of maze? */
assert(checkBounds(newPoint));
CellImpl newCell = getCellImpl(newPoint);
Object contents = newCell.getContents();
if(contents != null) {
// Clear projectile and wait for server reply for next step
if (contents instanceof Client) {
// If it is a GUIClient (myself), alert the server
if (contents instanceof GUIClient) {
GUIClient c = (GUIClient) contents;
c.reportDeath(prj.getOwner().getName());
// If it's robot, check if myself and alert server
} else if (contents instanceof RobotClient) {
RobotClient r = (RobotClient) contents;
r.reportDeath(r.getName(), prj.getOwner().getName());
}
cell.setContents(null);
deadPrj.add(prj);
update();
return deadPrj;
} else {
// Bullets destroy each other
assert(contents instanceof Projectile);
newCell.setContents(null);
cell.setContents(null);
deadPrj.add(prj);
deadPrj.add(contents);
update();
return deadPrj;
}
}
/* Clear the old cell */
cell.setContents(null);
/* Write the new cell */
projectileMap.put(prj, newPoint);
newCell.setContents(prj);
update();
return deadPrj;
}
/**
* Internal helper for adding a {@link Client} to the {@link Maze}.
* @param client The {@link Client} to be added.
* @param point The location the {@link Client} should be added.
*/
private synchronized void addClient(Client client, Point point) {
assert(client != null);
assert(checkBounds(point));
CellImpl cell = getCellImpl(point);
Direction d = Direction.random();
while(cell.isWall(d)) {
d = Direction.random();
}
cell.setContents(client);
clientMap.put(client, new DirectedPoint(point, d));
client.registerMaze(this);
client.addClientListener(this);
update();
notifyClientAdd(client);
}
/**
* Internal helper called when a {@link Client} emits a turnLeft action.
* @param client The {@link Client} to rotate.
*/
private synchronized void rotateClientLeft(Client client) {
assert(client != null);
Object o = clientMap.get(client);
assert(o instanceof DirectedPoint);
DirectedPoint dp = (DirectedPoint)o;
clientMap.put(client, new DirectedPoint(dp, dp.getDirection().turnLeft()));
update();
}
/**
* Internal helper called when a {@link Client} emits a turnRight action.
* @param client The {@link Client} to rotate.
*/
private synchronized void rotateClientRight(Client client) {
assert(client != null);
Object o = clientMap.get(client);
assert(o instanceof DirectedPoint);
DirectedPoint dp = (DirectedPoint)o;
clientMap.put(client, new DirectedPoint(dp, dp.getDirection().turnRight()));
update();
}
/**
* Internal helper called to move a {@link Client} in the specified
* {@link Direction}.
* @param client The {@link Client} to be move.
* @param d The {@link Direction} to move.
* @return If the {@link Client} cannot move in that {@link Direction}
* for some reason, return <code>false</code>, otherwise return
* <code>true</code> indicating success.
*/
private synchronized boolean moveClient(Client client, Direction d) {
assert(client != null);
assert(d != null);
Point oldPoint = getClientPoint(client);
CellImpl oldCell = getCellImpl(oldPoint);
/* Check that you can move in the given direction */
if(oldCell.isWall(d)) {
/* Move failed */
clientMap.put(client, oldPoint);
return false;
}
DirectedPoint newPoint = new DirectedPoint(oldPoint.move(d), getClientOrientation(client));
/* Is the point withint the bounds of maze? */
assert(checkBounds(newPoint));
CellImpl newCell = getCellImpl(newPoint);
if(newCell.getContents() != null) {
/* Move failed */
clientMap.put(client, oldPoint);
return false;
}
/* Write the new cell */
clientMap.put(client, newPoint);
newCell.setContents(client);
/* Clear the old cell */
oldCell.setContents(null);
update();
return true;
}
/**
* The random number generator used by the {@link Maze}.
*/
private final Random randomGen;
/**
* The maximum X coordinate of the {@link Maze}.
*/
private final int maxX;
/**
* The maximum Y coordinate of the {@link Maze}.
*/
private final int maxY;
/**
* The {@link Vector} of {@link Vector}s holding the
* {@link Cell}s of the {@link Maze}.
*/
private final Vector mazeVector;
/**
* A map between {@link Client}s and {@link DirectedPoint}s
* locating them in the {@link Maze}.
*/
private final Map clientMap = new HashMap();
/**
* The set of {@link MazeListener}s that are presently
* in the notification queue.
*/
private final Set listenerSet = new HashSet();
/**
* Mapping from {@link Projectile}s to {@link DirectedPoint}s.
*/
private final Map projectileMap = new HashMap();
/**
* The set of {@link Client}s that have {@link Projectile}s in
* play.
*/
private final Set clientFired = new HashSet();
/**
* The thread used to manage {@link Projectile}s.
*/
private final Thread thread;
/**
* Generate a notification to listeners that a
* {@link Client} has been added.
* @param c The {@link Client} that was added.
*/
private void notifyClientAdd(Client c) {
assert(c != null);
Iterator i = listenerSet.iterator();
while (i.hasNext()) {
Object o = i.next();
assert(o instanceof MazeListener);
MazeListener ml = (MazeListener)o;
ml.clientAdded(c);
}
}
/**
* Generate a notification to listeners that a
* {@link Client} has been removed.
* @param c The {@link Client} that was removed.
*/
private void notifyClientRemove(Client c) {
assert(c != null);
Iterator i = listenerSet.iterator();
while (i.hasNext()) {
Object o = i.next();
assert(o instanceof MazeListener);
MazeListener ml = (MazeListener)o;
ml.clientRemoved(c);
}
}
/**
* Generate a notification to listeners that a
* {@link Client} has fired.
* @param c The {@link Client} that fired.
*/
private void notifyClientFired(Client c) {
assert(c != null);
Iterator i = listenerSet.iterator();
while (i.hasNext()) {
Object o = i.next();
assert(o instanceof MazeListener);
MazeListener ml = (MazeListener)o;
ml.clientFired(c);
}
}
/**
* Generate a notification to listeners that a
* {@link Client} has been killed.
* @param source The {@link Client} that fired the projectile.
* @param target The {@link Client} that was killed.
*/
private void notifyClientKilled(Client source, Client target) {
assert(source != null);
assert(target != null);
Iterator i = listenerSet.iterator();
while (i.hasNext()) {
Object o = i.next();
assert(o instanceof MazeListener);
MazeListener ml = (MazeListener)o;
ml.clientKilled(source, target);
}
}
/**
* Generate a notification that the {@link Maze} has
* changed in some fashion.
*/
private void update() {
Iterator i = listenerSet.iterator();
while (i.hasNext()) {
Object o = i.next();
assert(o instanceof MazeListener);
MazeListener ml = (MazeListener)o;
ml.mazeUpdate();
}
}
/**
* A concrete implementation of the {@link Cell} class that
* special to this implementation of {@link Maze}s.
*/
private class CellImpl extends Cell implements Serializable {
/**
* Has this {@link CellImpl} been visited while
* constructing the {@link Maze}.
*/
private boolean visited = false;
/**
* The walls of this {@link Cell}.
*/
private boolean walls[] = {true, true, true, true};
/**
* The contents of the {@link Cell}.
* <code>null</code> indicates that it is empty.
*/
private Object contents = null;
/**
* Helper function to convert a {@link Direction} into
* an array index for easier access.
* @param d The {@link Direction} to convert.
* @return An integer index into <code>walls</code>.
*/
private int directionToArrayIndex(Direction d) {
assert(d != null);
if(d.equals(Direction.North)) {
return 0;
} else if(d.equals(Direction.East)) {
return 1;
} else if(d.equals(Direction.South)) {
return 2;
} else if(d.equals(Direction.West)) {
return 3;
}
/* Impossible */
return -1;
}
/* Required for the abstract implementation */
public boolean isWall(Direction d) {
assert(d != null);
return this.walls[directionToArrayIndex(d)];
}
public synchronized Object getContents() {
return this.contents;
}
/* Internals used by MazeImpl */
/**
* Indicate that this {@link Cell} has been
* visited while building the {@link MazeImpl}.
*/
public void setVisited() {
visited = true;
}
/**
* Has this {@link Cell} been visited in the process
* of recursviely building the {@link Maze}?
* @return <code>true</code> if visited, <code>false</code>
* otherwise.
*/
public boolean visited() {
return visited;
}
/**
* Add a wall to this {@link Cell} in the specified
* Cardinal {@link Direction}.
* @param d Which wall to add.
*/
public void setWall(Direction d) {
assert(d != null);
this.walls[directionToArrayIndex(d)] = true;
}
/**
* Remove the wall from this {@link Cell} in the specified
* Cardinal {@link Direction}.
* @param d Which wall to remove.
*/
public void removeWall(Direction d) {
assert(d != null);
this.walls[directionToArrayIndex(d)] = false;
}
/**
* Set the contents of this {@link Cell}.
* @param contents Object to place in the {@link Cell}.
* Use <code>null</code> if you want to empty it.
*/
public synchronized void setContents(Object contents) {
this.contents = contents;
}
}
/**
* Removes the wall in the {@link Cell} at the specified {@link Point} and
* {@link Direction}, and the opposite wall in the adjacent {@link Cell}.
* @param point Location to remove the wall.
* @param d Cardinal {@link Direction} specifying the wall to be removed.
*/
private void removeWall(Point point, Direction d) {
assert(point != null);
assert(d != null);
CellImpl cell = getCellImpl(point);
cell.removeWall(d);
Point adjacentPoint = point.move(d);
CellImpl adjacentCell = getCellImpl(adjacentPoint);
adjacentCell.removeWall(d.invert());
}
/**
* Pick randomly pick an unvisited neighboring {@link CellImpl},
* if none return <code>null</code>.
* @param point The location to pick a neighboring {@link CellImpl} from.
* @return The Cardinal {@link Direction} of a {@link CellImpl} that hasn't
* yet been visited.
*/
private Direction pickNeighbor(Point point) {
assert(point != null);
Direction directions[] = {
Direction.North,
Direction.East,
Direction.West,
Direction.South };
// Create a vector of the possible choices
Vector options = new Vector();
// Iterate through the directions and see which
// Cells have been visited, adding those that haven't
for(int i = 0; i < 4; i++) {
Point newPoint = point.move(directions[i]);
if(checkBounds(newPoint)) {
CellImpl cell = getCellImpl(newPoint);
if(!cell.visited()) {
options.add(directions[i]);
}
}
}
// If there are no choices just return null
if(options.size() == 0) {
return null;
}
// If there is at least one option, randomly choose one.
int n = randomGen.nextInt(options.size());
Object o = options.get(n);
assert(o instanceof Direction);
return (Direction)o;
}
/**
* Recursively carve out a {@link Maze}
* @param point The location in the {@link Maze} to start carving.
*/
private void buildMaze(Point point) {
assert(point != null);
CellImpl cell = getCellImpl(point);
cell.setVisited();
Direction d = pickNeighbor(point);
while(d != null) {
removeWall(point, d);
Point newPoint = point.move(d);
buildMaze(newPoint);
d = pickNeighbor(point);
}
}
/**
* Obtain the {@link CellImpl} at the specified point.
* @param point Location in the {@link Maze}.
* @return The {@link CellImpl} representing that location.
*/
private CellImpl getCellImpl(Point point) {
assert(point != null);
Object o1 = mazeVector.get(point.getX());
assert(o1 instanceof Vector);
Vector v1 = (Vector)o1;
Object o2 = v1.get(point.getY());
assert(o2 instanceof CellImpl);
return (CellImpl)o2;
}
}