-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patha2_solution.py
1725 lines (1376 loc) · 57.1 KB
/
a2_solution.py
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
"""
A model of a zombie survival game wherein the player has to reach
the hospital whilst evading zombies.
"""
from typing import Tuple, Optional, Dict, List
import random
from constants import *
import math
## Support code
def random_directions() -> List[Tuple[int, int]]:
"""
Return a randomly sorted list of directions.
The list will always contain (0, 1), (0, -1), (1, 0), (-1, 0)
but the order will be random.
Each direction is represented by an offset that is the change
in (x, y) coordinates that results from moving in the direction.
"""
return random.sample(OFFSETS, k=4)
def first_in_direction(
grid: 'Grid', start: 'Position', offset: 'Position'
) -> Optional[Tuple['Position', 'Entity']]:
"""
Get the first entity in in the direction of a position
Parameters:
grid: Grid of the current game
start: Point of reference
offset: Position offset representing a direction to look at
Returns: A tuple of a position and the first entity found in the
given direction, None if no entity found
"""
position = start.add(offset)
while grid.in_bounds(position):
entity = grid.get_entity(position)
if entity is not None:
return position, entity
position = position.add(offset)
return None
class Position:
"""
The position class represents a location in a 2D grid.
A position is made up of an x coordinate and a y coordinate.
The x and y coordinates are assumed to be non-negative whole numbers which
represent a square in a 2D grid.
Examples:
>>> position = Position(2, 4)
>>> position
Position(2, 4)
>>> position.get_x()
2
>>> position.get_y()
4
"""
def __init__(self, x: int, y: int):
"""
The position class is constructed from the x and y coordinate which the
position represents.
Parameters:
x: The x coordinate of the position
y: The y coordinate of the position
"""
self._x = x
self._y = y
def get_x(self) -> int:
"""Returns the x coordinate of the position."""
return self._x
def get_y(self) -> int:
"""Returns the y coordinate of the position."""
return self._y
def distance(self, position: "Position") -> int:
"""
Returns the manhattan distance between this point and another point.
The manhattan distance for two points (x_1, y_1) and (x_2, y_2)
is calculated with the formula
|x_1 - x_2| + |y_1 - y_2|
where |x| is the absolute value of x.
Parameters:
position: Another position to calculate the distance from
the current position.
"""
dx = abs(self.get_x() - position.get_x())
dy = abs(self.get_y() - position.get_y())
return dx + dy
def in_range(self, position: "Position", range: int) -> bool:
"""
Returns true if the given position is in range of the current position.
The distance between the two positions are calculated by the manhattan
distance. See the Position.distance method for details.
Parameters:
position: Another position to check if it is within range
of this current position.
range: The maximum distance for another position to be considered
within range of this position.
Precondition:
range >= 0
"""
distance = self.distance(position)
return distance < range
def add(self, position: "Position") -> "Position":
"""
Add a given position to this position and return a new instance of
Position that represents the cumulative location.
This method shouldn't modify the current position.
Examples:
>>> start = Position(1, 2)
>>> offset = Position(2, 1)
>>> end = start.add(offset)
>>> end
Position(3, 3)
Parameters:
position: Another position to add with this position.
Returns:
A new position representing the current position plus
the given position.
"""
return Position(self._x + position.get_x(), self._y + position.get_y())
def __eq__(self, other: object) -> bool:
"""
Return whether the given other object is equal to this position.
If the other object is not a Position instance, returns False.
If the other object is a Position instance and the
x and y coordinates are equal, return True.
Parameters:
other: Another instance to compare with this position.
"""
# an __eq__ method needs to support any object for example
# so it can handle `Position(1, 2) == 2`
# https://www.pythontutorial.net/python-oop/python-__eq__/
if not isinstance(other, Position):
return False
return self.get_x() == other.get_x() and self.get_y() == other.get_y()
def __hash__(self) -> int:
"""
Calculate and return a hash code value for this position instance.
This allows Position instances to be used as keys in dictionaries.
A hash should be based on the unique data of a class, in the case
of the position class, the unique data is the x and y values.
Therefore, we can calculate an appropriate hash by hashing a tuple of
the x and y values.
Reference: https://stackoverflow.com/questions/17585730/what-does-hash-do-in-python
"""
return hash((self.get_x(), self.get_y()))
def __repr__(self) -> str:
"""
Return the representation of a position instance.
The format should be 'Position({x}, {y})' where {x} and {y} are replaced
with the x and y value for the position.
Examples:
>>> repr(Position(12, 21))
'Position(12, 21)'
>>> Position(12, 21).__repr__()
'Position(12, 21)'
"""
return f"Position({self.get_x()}, {self.get_y()})"
def __str__(self) -> str:
"""
Return a string of this position instance.
The format should be 'Position({x}, {y})' where {x} and {y} are replaced
with the x and y value for the position.
"""
return self.__repr__()
class GameInterface:
"""
The GameInterface class is an abstract class that handles the communication
between the interface used to play the game and the game itself.
For this assignment, we will only have one interface to play the game,
the text interface.
"""
def draw(self, game) -> None:
"""
Draw the state of a game to the respective interface.
The abstract GameInterface class should raise a NotImplementedError for
this method.
Parameters:
map (Game): An instance of the game class that is to be displayed
to the user by printing the grid.
"""
raise NotImplementedError
def play(self, game) -> None:
"""
The play method takes a game instance and orchestrates the running of
the game, including the interaction between the player and the game.
The abstract GameInterface class should raise a NotImplementedError for
this method.
Parameters:
game (Game): An instance of the Game class to play.
"""
raise NotImplementedError
EntityLocations = Dict[Tuple[int, int], str]
"""
EntityLocations stores locations of entities in the game map.
The key is a tuple, as (x, y) coordinates,
which represents the location of the entity.
The value is a string representing the entity.
"""
def load_map(filename: str) -> Tuple[EntityLocations, int]:
"""
Open and read a map file, converting it into a tuple.
The first element of the returned tuple contains a dictionary which maps
(x, y) coordinates to a string representing an entity in the map.
The second element of the returned tuple is the size of the map.
Parameters:
filename: Path where the map file should be found.
Returns:
A tuple containing the serialized map and the size of the map.
"""
with open(filename) as map_file:
contents = map_file.readlines()
result = {}
for y, line in enumerate(contents):
for x, char in enumerate(line.strip("\n")):
if char != " ":
result[(x, y)] = char
return result, len(contents)
## Task 1
class Entity:
"""
Entity is an abstract class that is used to represent anything that can
appear on the game's grid.
For example, the game grid will always have a player, so a player is
considered a type of entity. A game grid may also have a zombie, so a
zombie is considered a type of entity.
"""
def step(self, position: Position, game: "Game") -> None:
"""
The `step` method is called on every entity in the game grid after each
move made by the player, it controls what actions an entity will perform
during the _step_ event.
The abstract Entity class will not perform any action during the
_step_ event. Therefore, this method should do nothing.
Parameters:
position: The position of this entity when the _step_ event
is triggered.
game: The current game being played.
"""
pass
def display(self) -> str:
"""
Return the character used to represent this entity in a text-based grid.
An instance of the abstract Entity class should never be placed in the
grid, so this method should only be implemented by subclasses of Entity.
To indicate that this method needs to be implemented by subclasses,
this method should raise a NotImplementedError.
Raises:
NotImplementedError: Whenever this method is called.
"""
raise NotImplementedError()
def __repr__(self) -> str:
"""
Return a representation of this entity.
By convention, the repr string of a class should look as close as
possible to how the class is constructed. Since entities do not take
constructor parameters, the repr string will be the class name followed
by parentheses, ().
For example, the representation of the Entity class will be Entity().
Examples:
>>> repr(Entity())
'Entity()'
>>> Entity().__repr__()
'Entity()'
>>> entity = Entity()
>>> repr(entity)
'Entity()'
"""
return f"{self.__class__.__name__}()"
class Player(Entity):
"""
A player is a subclass of the entity class that represents the player
that the user controls on the game grid.
Examples:
>>> player = Player()
>>> repr(player)
'Player()'
>>> player.display()
'P'
"""
def display(self) -> str:
"""
Return the character used to represent the player entity in a
text-based grid.
A player should be represented by the 'P' character.
"""
return PLAYER
class Hospital(Entity):
"""
A hospital is a subclass of the entity class that represents the hospital
in the grid.
The hospital is the entity that the player has to reach in order to win
the game.
Examples:
>>> hospital = Hospital()
>>> repr(hospital)
'Hospital()'
>>> hospital.display()
'H'
"""
def display(self) -> str:
"""
Return the character used to represent the hospital entity in a
text-based grid.
A hospital should be represented by the 'H' character.
"""
return HOSPITAL
class Grid:
"""
The Grid class is used to represent the 2D grid of entities.
The grid can vary in size but it is always a square.
Each (x, y) position in the grid can only contain one entity at a time.
Examples:
>>> grid = Grid(5)
>>> grid.get_size()
5
>>> grid.in_bounds(Position(2, 2))
True
>>> grid.in_bounds(Position(0, 6))
False
>>> grid.get_entities()
[]
>>> grid.add_entity(Position(2, 2), Hospital())
>>> grid.get_entity(Position(2, 2))
Hospital()
>>> grid.get_entities()
[Hospital()]
>>> grid.serialize()
{(2, 2): 'H'}
"""
def __init__(self, size: int):
"""
A grid is constructed with a size that dictates the length and width
of the grid.
Initially a grid does not contain any entities.
Parameters:
size: The length and width of the grid.
"""
self._size = size
self._tiles: Dict[Position, Entity] = {}
def get_size(self) -> int:
"""Returns the size of the grid."""
return self._size
def in_bounds(self, position: Position) -> bool:
"""
Return True if the given position is within the bounds of the grid.
For a position to be within the bounds of the grid, both the x and y
coordinates have to be greater than or equal to zero but less than
the size of the grid.
Parameters:
position: An (x, y) position that we want to check is
within the bounds of the grid.
Examples:
>>> grid5 = Grid(5)
>>> grid5.in_bounds(Position(0, 10))
False
>>> grid5.in_bounds(Position(0, 5))
False
>>> grid5.in_bounds(Position(0, 4))
True
>>> grid5.in_bounds(Position(-1, 4))
False
>>> grid10 = Grid(10)
>>> grid10.in_bounds(Position(9, 8))
True
>>> grid10.in_bounds(Position(9, 10))
False
"""
return (0 <= position.get_x() < self._size
and 0 <= position.get_y() < self._size)
def add_entity(self, position: Position, entity: Entity) -> None:
"""
Place a given entity at a given position of the grid.
If there is already an entity at the given position, the given
entity will replace the existing entity.
If the given position is outside the bounds of the grid, the entity
should not be added.
\\textbf{Hint:} You may find it helpful to implement `get_entity` below
at the same time as this method.
Parameters:
position: An (x, y) position in the grid to place the entity.
entity: The entity to place on the grid.
Examples:
>>> grid = Grid(4)
>>> grid.add_entity(Position(0, 0), Player())
>>> grid.get_entity(Position(0, 0))
Player()
>>> grid.add_entity(Position(0, 0), Hospital())
>>> grid.get_entity(Position(0, 0))
Hospital()
>>> grid.add_entity(Position(-1, 0), Player())
>>> grid.get_entity(Position(-1, 0))
"""
if self.in_bounds(position):
self._tiles[position] = entity
def remove_entity(self, position: Position) -> None:
"""
Remove the entity, if any, at the given position.
Parameters:
position: An (x, y) position in the grid from which the entity
is removed.
Examples:
>>> grid = Grid(4)
>>> grid.add_entity(Position(0, 0), Player())
>>> grid.get_entity(Position(0, 0))
Player()
>>> grid.remove_entity(Position(0, 0))
>>> grid.get_entity(Position(0, 0))
"""
self._tiles.pop(position, None)
def get_entity(self, position: Position) -> Optional[Entity]:
"""
Return the entity that is at the given position in the grid.
If there is no entity at the given position, returns None.
If the given position is out of bounds, returns None.
See the above `add_entity` method for examples.
Parameters:
position: The (x, y) position in the grid to check for an entity.
"""
return self._tiles.get(position)
def get_mapping(self) -> Dict[Position, Entity]:
"""
Return a dictionary with position instances as the keys and entity
instances as the values.
For every position in the grid that has an entity, the returned
dictionary should contain an entry with the position instance
mapped to the entity instance.
Updating the returned dictionary should have no side-effects.
It would not modify the grid.
Examples:
>>> grid = Grid(4)
>>> grid.add_entity(Position(0, 0), Player())
>>> grid.add_entity(Position(3, 3), Hospital())
>>> grid.get_mapping()
{Position(0, 0): Player(), Position(3, 3): Hospital()}
"""
return self._tiles.copy()
def get_entities(self) -> List[Entity]:
"""
Return a list of all the entities in the grid.
Updating the returned list should have no side-effects.
It would not modify the grid.
Examples:
# The example below shows a grid with multiple hospitals this should
# never occur in practice but isn't prohibited
>>> grid = Grid(5)
>>> grid.add_entity(Position(0, 0), Hospital())
>>> grid.add_entity(Position(0, 1), Player())
>>> grid.add_entity(Position(2, 2), Hospital())
>>> grid.add_entity(Position(4, 4), Hospital())
>>> grid.get_entities()
[Hospital(), Player(), Hospital(), Hospital()]
"""
return list(self._tiles.values())
def move_entity(self, start: Position, end: Position) -> None:
"""
Move an entity from the given start position to the given end position.
* If the end position or start position is out of the grid bounds,
do not attempt to move.
* If there is no entity at the given start position,
do not attempt to move.
* If there is an entity at the given end position, replace that entity
with the entity from the start position.
The start position should not have an entity after moving.
Parameters:
start: The position the entity is in initially.
end: The position to which the entity will be moved.
Examples:
>>> grid = Grid(10)
>>> grid.add_entity(Position(1, 2), Player())
>>> grid.move_entity(Position(1, 2), Position(3, 5))
>>> grid.get_entity(Position(1, 2))
>>> grid.get_entity(Position(3, 5))
Player()
"""
if start == end:
return
if self.in_bounds(start) and self.in_bounds(end):
entity = self.get_entity(start)
if entity is not None:
self._tiles[end] = entity
del self._tiles[start]
def find_player(self) -> Optional[Position]:
"""
Return the position of the player within the grid.
Return None if there is no player in the grid.
If the grid has multiple players (which it should not),
returning any of the player positions is sufficient.
Examples:
>>> grid = Grid(10)
>>> grid.add_entity(Position(4, 6), Player())
>>> grid.find_player()
Position(4, 6)
"""
for position, entity in self._tiles.items():
if entity.display() == PLAYER:
return position
return None
def serialize(self) -> Dict[Tuple[int, int], str]:
"""
Serialize the grid into a dictionary that maps tuples to characters.
The tuples should have two values, the x and y coordinate representing
a postion.
The characters are the display representation of the entity at that
position. i.e. 'P' for player, `H' for hospital.
Only positions that have an entity should exist in the dictionary.
Examples:
>>> grid = Grid(50)
>>> grid.add_entity(Position(3, 8), Player())
>>> grid.add_entity(Position(3, 20), Hospital())
>>> grid.serialize()
{(3, 8): 'P', (3, 20): 'H'}
"""
serialized = {}
for position, entity in self._tiles.items():
pair = (position.get_x(), position.get_y())
serialized[pair] = entity.display()
return serialized
class MapLoader:
"""
The MapLoader class is used to read a map file and create an appropriate
Grid instance which stores all the map file entities.
The MapLoader class is an abstract class to allow for extensible map
definitions. The BasicMapLoader class described below is a very simple
implementation of the MapLoader which only handles the player and hospital
entities.
"""
def load(self, filename: str) -> Grid:
"""
Load a new Grid instance from a map file.
Load will open the map file and read each line to find all the entities
in the grid and add them to the new Grid instance.
The `create_entity` method below is used to turn a character
in the map file into an Entity instance.
\\textbf{Hint:} The `load_map` function in the support code may be helpful.
Parameters:
filename: Path where the map file should be found.
"""
mapping, size = load_map(filename)
grid = Grid(size)
for position, entity in mapping.items():
grid.add_entity(Position(*position), self.create_entity(entity))
return grid
def create_entity(self, token: str) -> Entity:
"""
Create and return a new instance of the Entity class based on the
provided token.
For example, if the given token is 'P' a Player instance will be
returned.
The abstract MapLoader class does not support any entities, when this
method is called, it should raise a NotImplementedError.
Parameters:
token: Character representing the Entity subtype.
"""
raise NotImplementedError(token)
class BasicMapLoader(MapLoader):
"""
BasicMapLoader is a subclass of MapLoader which can handle loading map
files which include the following entities:
* Player
* Hospital
"""
def create_entity(self, token: str) -> Entity:
"""
Create and return a new instance of the Entity class based on the
provided token.
For example, if the given token is 'P' a Player instance will be
returned.
The BasicMapLoader class only supports the Player and Hospital entities.
When a token is provided that does not represent the Player or Hospital,
this method should raise a ValueError.
Parameters:
token: Character representing the Entity subtype.
"""
if token == PLAYER:
return Player()
elif token == HOSPITAL:
return Hospital()
raise ValueError(f"Unrecognised entity '{token}' in map file.")
class Game:
"""
The Game handles some of the logic for controlling the actions of the player
within the grid.
The Game class stores an instance of the Grid and keeps track of the player
within the grid so that the player can be controlled.
"""
def __init__(self, grid: Grid):
"""
The construction of a Game instance takes the grid upon which the game
is being played.
Preconditions:
The grid has a player, i.e. `grid.find_player()` is not None.
Parameters:
grid (Grid): The game's grid.
"""
self._grid = grid
self._player_position = grid.find_player()
self._steps = 0
def get_grid(self) -> Grid:
"""Return the grid on which this game is being played."""
return self._grid
def get_player(self) -> Optional[Player]:
"""
Return the instance of the Player class in the grid.
If there is no player in the grid, return None.
If there are multiple players in the grid, returning any player is
sufficient.
"""
if self._player_position is None:
return None
player = self.get_grid().get_entity(self._player_position)
return player # type: ignore
def step(self) -> None:
"""
The _step_ method of the game will be called after every action
performed by the player.
This method triggers the _step_ event by calling the step method
of every entity in the grid. When the entity's step method is called,
it should pass the entity's current position and this game as parameters.
Note: Do not call this method in the `move_player` method.
"""
for position, entity in self._grid.get_mapping().items():
entity.step(position, self)
self._steps += 1
def get_steps(self) -> int:
"""
Return the amount of steps made in the game,
i.e. how many times the `step` method has been called.
"""
return self._steps
def move_player(self, offset: Position) -> None:
"""
Move the player entity in the grid by a given offset.
Add the offset to the current position of the player, move the player
entity within the grid to the new position.
If the new position is outside the bounds of the grid, or there is no
player in the grid, this method should not move the player.
Parameters:
offset: A position to add to the player's current position
to produce the player's new desired position.
"""
if self._player_position is not None:
destination = self._player_position.add(offset)
if self._grid.in_bounds(destination):
self._grid.move_entity(self._player_position, destination)
self._player_position = destination
def direction_to_offset(self, direction: str) -> Optional[Position]:
"""
Convert a direction, as a string, to a offset position.
The offset position can be added to a position to move in the
given direction.
If the given direction is not valid, this method should return None.
Parameters:
direction: Character representing the direction in which the
player should be moved.
Examples:
>>> game = Game(Grid(5))
>>> game.direction_to_offset("W")
Position(0, -1)
>>> game.direction_to_offset("S")
Position(0, 1)
>>> game.direction_to_offset("A")
Position(-1, 0)
>>> game.direction_to_offset("D")
Position(1, 0)
>>> game.direction_to_offset("N")
>>> game.direction_to_offset("that way!")
"""
if direction == UP:
return Position(0, -1)
elif direction == DOWN:
return Position(0, 1)
elif direction == LEFT:
return Position(-1, 0)
elif direction == RIGHT:
return Position(1, 0)
else:
return None
def has_won(self) -> bool:
"""
Return true if the player has won the game.
The player wins the game by stepping onto the hospital. When the player
steps on the hospital, there will be no hospital entity in the grid.
"""
return HOSPITAL not in self._grid.serialize().values()
def has_lost(self) -> bool:
"""
Return true if the player has lost the game.
Currently there is no way for the player to lose the game so this
method should always return false.
"""
return False
class TextInterface(GameInterface):
"""
A text-based interface between the user and the game instance.
This class handles all input collection from the user and printing to the
console.
"""
def __init__(self, size: int):
"""
The text-interface is constructed knowing the size of the game to be
played, this allows the draw method to correctly print the right
sized grid.
Parameters:
size (int): The size of the game to be displayed and played.
"""
self._size = size
def draw(self, game: Game) -> None:
"""
The draw method should print out the given game surrounded
by '#' characters representing the border of the game.
Parameters:
game: An instance of the game class that is to be displayed
to the user by printing the grid.
Examples:
>>> grid = Grid(4)
>>> grid.add_entity(Position(2, 2), Player())
>>> game = Game(grid)
>>> interface = TextInterface(4)
>>> interface.draw(game)
######
# #
# #
# P #
# #
######
"""
mapping = game.get_grid().serialize()
size = self._size
print(BORDER * (size + 2))
for y in range(size):
print(BORDER, end="")
for x in range(size):
tile = mapping.get((x, y), " ") or " "
print(tile, end="")
print(BORDER)
print(BORDER * (size + 2))
def play(self, game: Game) -> None:
"""
The play method implements the game loop, constantly prompting the user
for their action, performing the action and printing the game until the
game is over.
\\textbf{Hint:} Refer to the Gameplay section for a detailed
explanation of the game loop.
Parameters:
game: The game to start playing.
"""
won_game = False
lost_game = False
while not won_game and not lost_game:
self.draw(game)
action = input(ACTION_PROMPT)
self.handle_action(game, action)
if game.has_won():
print(WIN_MESSAGE)
won_game = True
if not won_game and game.has_lost():
print(LOSE_MESSAGE)
lost_game = True
def handle_action(self, game: Game, action: str) -> None:
"""
The handle_action method is used to process the actions entered
by the user during the game loop in the play method.
The handle_action method should be able to handle all movement
actions, i.e. 'W', 'A', 'S', 'D'.
If the given action is not a direction, this method should
only trigger the step event and do nothing else.
\\textbf{Hint:} Refer to the Gameplay section for a detailed
explanation of the game loop.
Parameters:
game: The game that is currently being played.
action: An action entered by the player during the game loop.
"""
if action in DIRECTIONS:
offset = game.direction_to_offset(action)
if offset is not None:
game.move_player(offset)
game.step()
## Task 2
class VulnerablePlayer(Player):
"""
The VulnerablePlayer class is a subclass of the Player, this class extends
the player by allowing them to become infected.
Examples:
>>> player = VulnerablePlayer()
>>> player.is_infected()
False
>>> player.infect()
>>> player.is_infected()
True
>>> player.infect()
>>> player.is_infected()
True
"""