-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
agents4e.py
1089 lines (875 loc) · 36.1 KB
/
agents4e.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
"""
Implement Agents and Environments. (Chapters 1-2)
The class hierarchies are as follows:
Thing ## A physical object that can exist in an environment
Agent
Wumpus
Dirt
Wall
...
Environment ## An environment holds objects, runs simulations
XYEnvironment
VacuumEnvironment
WumpusEnvironment
An agent program is a callable instance, taking percepts and choosing actions
SimpleReflexAgentProgram
...
EnvGUI ## A window with a graphical representation of the Environment
EnvToolbar ## contains buttons for controlling EnvGUI
EnvCanvas ## Canvas to display the environment of an EnvGUI
"""
# TODO
# Implement grabbing correctly.
# When an object is grabbed, does it still have a location?
# What if it is released?
# What if the grabbed or the grabber is deleted?
# What if the grabber moves?
# Speed control in GUI does not have any effect -- fix it.
from utils4e import distance_squared, turn_heading
from statistics import mean
from ipythonblocks import BlockGrid
from IPython.display import HTML, display, clear_output
from time import sleep
import random
import copy
import collections
import numbers
# ______________________________________________________________________________
class Thing:
"""This represents any physical object that can appear in an Environment.
You subclass Thing to get the things you want. Each thing can have a
.__name__ slot (used for output only)."""
def __repr__(self):
return '<{}>'.format(getattr(self, '__name__', self.__class__.__name__))
def is_alive(self):
"""Things that are 'alive' should return true."""
return hasattr(self, 'alive') and self.alive
def show_state(self):
"""Display the agent's internal state. Subclasses should override."""
print("I don't know how to show_state.")
def display(self, canvas, x, y, width, height):
"""Display an image of this Thing on the canvas."""
# Do we need this?
pass
class Agent(Thing):
"""An Agent is a subclass of Thing with one required slot,
.program, which should hold a function that takes one argument, the
percept, and returns an action. (What counts as a percept or action
will depend on the specific environment in which the agent exists.)
Note that 'program' is a slot, not a method. If it were a method,
then the program could 'cheat' and look at aspects of the agent.
It's not supposed to do that: the program can only look at the
percepts. An agent program that needs a model of the world (and of
the agent itself) will have to build and maintain its own model.
There is an optional slot, .performance, which is a number giving
the performance measure of the agent in its environment."""
def __init__(self, program=None):
self.alive = True
self.bump = False
self.holding = []
self.performance = 0
if program is None or not isinstance(program, collections.abc.Callable):
print("Can't find a valid program for {}, falling back to default.".format(self.__class__.__name__))
def program(percept):
return eval(input('Percept={}; action? '.format(percept)))
self.program = program
def can_grab(self, thing):
"""Return True if this agent can grab this thing.
Override for appropriate subclasses of Agent and Thing."""
return False
def TraceAgent(agent):
"""Wrap the agent's program to print its input and output. This will let
you see what the agent is doing in the environment."""
old_program = agent.program
def new_program(percept):
action = old_program(percept)
print('{} perceives {} and does {}'.format(agent, percept, action))
return action
agent.program = new_program
return agent
# ______________________________________________________________________________
def TableDrivenAgentProgram(table):
"""
[Figure 2.7]
This agent selects an action based on the percept sequence.
It is practical only for tiny domains.
To customize it, provide as table a dictionary of all
{percept_sequence:action} pairs.
"""
percepts = []
def program(percept):
percepts.append(percept)
action = table.get(tuple(percepts))
return action
return program
def RandomAgentProgram(actions):
"""An agent that chooses an action at random, ignoring all percepts.
>>> list = ['Right', 'Left', 'Suck', 'NoOp']
>>> program = RandomAgentProgram(list)
>>> agent = Agent(program)
>>> environment = TrivialVacuumEnvironment()
>>> environment.add_thing(agent)
>>> environment.run()
>>> environment.status == {(1, 0): 'Clean' , (0, 0): 'Clean'}
True
"""
return lambda percept: random.choice(actions)
# ______________________________________________________________________________
def SimpleReflexAgentProgram(rules, interpret_input):
"""
[Figure 2.10]
This agent takes action based solely on the percept.
"""
def program(percept):
state = interpret_input(percept)
rule = rule_match(state, rules)
action = rule.action
return action
return program
def ModelBasedReflexAgentProgram(rules, update_state, transition_model, sensor_model):
"""
[Figure 2.12]
This agent takes action based on the percept and state.
"""
def program(percept):
program.state = update_state(program.state, program.action, percept, transition_model, sensor_model)
rule = rule_match(program.state, rules)
action = rule.action
return action
program.state = program.action = None
return program
def rule_match(state, rules):
"""Find the first rule that matches state."""
for rule in rules:
if rule.matches(state):
return rule
# ______________________________________________________________________________
loc_A, loc_B = (0, 0), (1, 0) # The two locations for the Vacuum world
def RandomVacuumAgent():
"""Randomly choose one of the actions from the vacuum environment.
>>> agent = RandomVacuumAgent()
>>> environment = TrivialVacuumEnvironment()
>>> environment.add_thing(agent)
>>> environment.run()
>>> environment.status == {(1,0):'Clean' , (0,0) : 'Clean'}
True
"""
return Agent(RandomAgentProgram(['Right', 'Left', 'Suck', 'NoOp']))
def TableDrivenVacuumAgent():
"""Tabular approach towards vacuum world as mentioned in [Figure 2.3]
>>> agent = TableDrivenVacuumAgent()
>>> environment = TrivialVacuumEnvironment()
>>> environment.add_thing(agent)
>>> environment.run()
>>> environment.status == {(1,0):'Clean' , (0,0) : 'Clean'}
True
"""
table = {((loc_A, 'Clean'),): 'Right',
((loc_A, 'Dirty'),): 'Suck',
((loc_B, 'Clean'),): 'Left',
((loc_B, 'Dirty'),): 'Suck',
((loc_A, 'Dirty'), (loc_A, 'Clean')): 'Right',
((loc_A, 'Clean'), (loc_B, 'Dirty')): 'Suck',
((loc_B, 'Clean'), (loc_A, 'Dirty')): 'Suck',
((loc_B, 'Dirty'), (loc_B, 'Clean')): 'Left',
((loc_A, 'Dirty'), (loc_A, 'Clean'), (loc_B, 'Dirty')): 'Suck',
((loc_B, 'Dirty'), (loc_B, 'Clean'), (loc_A, 'Dirty')): 'Suck'}
return Agent(TableDrivenAgentProgram(table))
def ReflexVacuumAgent():
"""
[Figure 2.8]
A reflex agent for the two-state vacuum environment.
>>> agent = ReflexVacuumAgent()
>>> environment = TrivialVacuumEnvironment()
>>> environment.add_thing(agent)
>>> environment.run()
>>> environment.status == {(1,0):'Clean' , (0,0) : 'Clean'}
True
"""
def program(percept):
location, status = percept
if status == 'Dirty':
return 'Suck'
elif location == loc_A:
return 'Right'
elif location == loc_B:
return 'Left'
return Agent(program)
def ModelBasedVacuumAgent():
"""An agent that keeps track of what locations are clean or dirty.
>>> agent = ModelBasedVacuumAgent()
>>> environment = TrivialVacuumEnvironment()
>>> environment.add_thing(agent)
>>> environment.run()
>>> environment.status == {(1,0):'Clean' , (0,0) : 'Clean'}
True
"""
model = {loc_A: None, loc_B: None}
def program(percept):
"""Same as ReflexVacuumAgent, except if everything is clean, do NoOp."""
location, status = percept
model[location] = status # Update the model here
if model[loc_A] == model[loc_B] == 'Clean':
return 'NoOp'
elif status == 'Dirty':
return 'Suck'
elif location == loc_A:
return 'Right'
elif location == loc_B:
return 'Left'
return Agent(program)
# ______________________________________________________________________________
class Environment:
"""Abstract class representing an Environment. 'Real' Environment classes
inherit from this. Your Environment will typically need to implement:
percept: Define the percept that an agent sees.
execute_action: Define the effects of executing an action.
Also update the agent.performance slot.
The environment keeps a list of .things and .agents (which is a subset
of .things). Each agent has a .performance slot, initialized to 0.
Each thing has a .location slot, even though some environments may not
need this."""
def __init__(self):
self.things = []
self.agents = []
def thing_classes(self):
return [] # List of classes that can go into environment
def percept(self, agent):
"""Return the percept that the agent sees at this point. (Implement this.)"""
raise NotImplementedError
def execute_action(self, agent, action):
"""Change the world to reflect this action. (Implement this.)"""
raise NotImplementedError
def default_location(self, thing):
"""Default location to place a new thing with unspecified location."""
return None
def exogenous_change(self):
"""If there is spontaneous change in the world, override this."""
pass
def is_done(self):
"""By default, we're done when we can't find a live agent."""
return not any(agent.is_alive() for agent in self.agents)
def step(self):
"""Run the environment for one time step. If the
actions and exogenous changes are independent, this method will
do. If there are interactions between them, you'll need to
override this method."""
if not self.is_done():
actions = []
for agent in self.agents:
if agent.alive:
actions.append(agent.program(self.percept(agent)))
else:
actions.append("")
for (agent, action) in zip(self.agents, actions):
self.execute_action(agent, action)
self.exogenous_change()
def run(self, steps=1000):
"""Run the Environment for given number of time steps."""
for step in range(steps):
if self.is_done():
return
self.step()
def list_things_at(self, location, tclass=Thing):
"""Return all things exactly at a given location."""
if isinstance(location, numbers.Number):
return [thing for thing in self.things
if thing.location == location and isinstance(thing, tclass)]
return [thing for thing in self.things
if all(x == y for x, y in zip(thing.location, location)) and isinstance(thing, tclass)]
def some_things_at(self, location, tclass=Thing):
"""Return true if at least one of the things at location
is an instance of class tclass (or a subclass)."""
return self.list_things_at(location, tclass) != []
def add_thing(self, thing, location=None):
"""Add a thing to the environment, setting its location. For
convenience, if thing is an agent program we make a new agent
for it. (Shouldn't need to override this.)"""
if not isinstance(thing, Thing):
thing = Agent(thing)
if thing in self.things:
print("Can't add the same thing twice")
else:
thing.location = location if location is not None else self.default_location(thing)
self.things.append(thing)
if isinstance(thing, Agent):
thing.performance = 0
self.agents.append(thing)
def delete_thing(self, thing):
"""Remove a thing from the environment."""
try:
self.things.remove(thing)
except ValueError as e:
print(e)
print(" in Environment delete_thing")
print(" Thing to be removed: {} at {}".format(thing, thing.location))
print(" from list: {}".format([(thing, thing.location) for thing in self.things]))
if thing in self.agents:
self.agents.remove(thing)
class Direction:
"""A direction class for agents that want to move in a 2D plane
Usage:
d = Direction("down")
To change directions:
d = d + "right" or d = d + Direction.R #Both do the same thing
Note that the argument to __add__ must be a string and not a Direction object.
Also, it (the argument) can only be right or left."""
R = "right"
L = "left"
U = "up"
D = "down"
def __init__(self, direction):
self.direction = direction
def __add__(self, heading):
"""
>>> d = Direction('right')
>>> l1 = d.__add__(Direction.L)
>>> l2 = d.__add__(Direction.R)
>>> l1.direction
'up'
>>> l2.direction
'down'
>>> d = Direction('down')
>>> l1 = d.__add__('right')
>>> l2 = d.__add__('left')
>>> l1.direction == Direction.L
True
>>> l2.direction == Direction.R
True
"""
if self.direction == self.R:
return {
self.R: Direction(self.D),
self.L: Direction(self.U),
}.get(heading, None)
elif self.direction == self.L:
return {
self.R: Direction(self.U),
self.L: Direction(self.D),
}.get(heading, None)
elif self.direction == self.U:
return {
self.R: Direction(self.R),
self.L: Direction(self.L),
}.get(heading, None)
elif self.direction == self.D:
return {
self.R: Direction(self.L),
self.L: Direction(self.R),
}.get(heading, None)
def move_forward(self, from_location):
"""
>>> d = Direction('up')
>>> l1 = d.move_forward((0, 0))
>>> l1
(0, -1)
>>> d = Direction(Direction.R)
>>> l1 = d.move_forward((0, 0))
>>> l1
(1, 0)
"""
# get the iterable class to return
iclass = from_location.__class__
x, y = from_location
if self.direction == self.R:
return iclass((x + 1, y))
elif self.direction == self.L:
return iclass((x - 1, y))
elif self.direction == self.U:
return iclass((x, y - 1))
elif self.direction == self.D:
return iclass((x, y + 1))
class XYEnvironment(Environment):
"""This class is for environments on a 2D plane, with locations
labelled by (x, y) points, either discrete or continuous.
Agents perceive things within a radius. Each agent in the
environment has a .location slot which should be a location such
as (0, 1), and a .holding slot, which should be a list of things
that are held."""
def __init__(self, width=10, height=10):
super().__init__()
self.width = width
self.height = height
self.observers = []
# Sets iteration start and end (no walls).
self.x_start, self.y_start = (0, 0)
self.x_end, self.y_end = (self.width, self.height)
perceptible_distance = 1
def things_near(self, location, radius=None):
"""Return all things within radius of location."""
if radius is None:
radius = self.perceptible_distance
radius2 = radius * radius
return [(thing, radius2 - distance_squared(location, thing.location))
for thing in self.things if distance_squared(
location, thing.location) <= radius2]
def percept(self, agent):
"""By default, agent perceives things within a default radius."""
return self.things_near(agent.location)
def execute_action(self, agent, action):
agent.bump = False
if action == 'TurnRight':
agent.direction += Direction.R
elif action == 'TurnLeft':
agent.direction += Direction.L
elif action == 'Forward':
agent.bump = self.move_to(agent, agent.direction.move_forward(agent.location))
# elif action == 'Grab':
# things = [thing for thing in self.list_things_at(agent.location)
# if agent.can_grab(thing)]
# if things:
# agent.holding.append(things[0])
elif action == 'Release':
if agent.holding:
agent.holding.pop()
def default_location(self, thing):
location = self.random_location_inbounds()
while self.some_things_at(location, Obstacle):
# we will find a random location with no obstacles
location = self.random_location_inbounds()
return location
def move_to(self, thing, destination):
"""Move a thing to a new location. Returns True on success or False if there is an Obstacle.
If thing is holding anything, they move with him."""
thing.bump = self.some_things_at(destination, Obstacle)
if not thing.bump:
thing.location = destination
for o in self.observers:
o.thing_moved(thing)
for t in thing.holding:
self.delete_thing(t)
self.add_thing(t, destination)
t.location = destination
return thing.bump
def add_thing(self, thing, location=None, exclude_duplicate_class_items=False):
"""Add things to the world. If (exclude_duplicate_class_items) then the item won't be
added if the location has at least one item of the same class."""
if location is None:
super().add_thing(thing)
elif self.is_inbounds(location):
if (exclude_duplicate_class_items and
any(isinstance(t, thing.__class__) for t in self.list_things_at(location))):
return
super().add_thing(thing, location)
def is_inbounds(self, location):
"""Checks to make sure that the location is inbounds (within walls if we have walls)"""
x, y = location
return not (x < self.x_start or x > self.x_end or y < self.y_start or y > self.y_end)
def random_location_inbounds(self, exclude=None):
"""Returns a random location that is inbounds (within walls if we have walls)"""
location = (random.randint(self.x_start, self.x_end),
random.randint(self.y_start, self.y_end))
if exclude is not None:
while location == exclude:
location = (random.randint(self.x_start, self.x_end),
random.randint(self.y_start, self.y_end))
return location
def delete_thing(self, thing):
"""Deletes thing, and everything it is holding (if thing is an agent)"""
if isinstance(thing, Agent):
for obj in thing.holding:
super().delete_thing(obj)
for obs in self.observers:
obs.thing_deleted(obj)
super().delete_thing(thing)
for obs in self.observers:
obs.thing_deleted(thing)
def add_walls(self):
"""Put walls around the entire perimeter of the grid."""
for x in range(self.width):
self.add_thing(Wall(), (x, 0))
self.add_thing(Wall(), (x, self.height - 1))
for y in range(1, self.height - 1):
self.add_thing(Wall(), (0, y))
self.add_thing(Wall(), (self.width - 1, y))
# Updates iteration start and end (with walls).
self.x_start, self.y_start = (1, 1)
self.x_end, self.y_end = (self.width - 1, self.height - 1)
def add_observer(self, observer):
"""Adds an observer to the list of observers.
An observer is typically an EnvGUI.
Each observer is notified of changes in move_to and add_thing,
by calling the observer's methods thing_moved(thing)
and thing_added(thing, loc)."""
self.observers.append(observer)
def turn_heading(self, heading, inc):
"""Return the heading to the left (inc=+1) or right (inc=-1) of heading."""
return turn_heading(heading, inc)
class Obstacle(Thing):
"""Something that can cause a bump, preventing an agent from
moving into the same square it's in."""
pass
class Wall(Obstacle):
pass
# ______________________________________________________________________________
class GraphicEnvironment(XYEnvironment):
def __init__(self, width=10, height=10, boundary=True, color={}, display=False):
"""Define all the usual XYEnvironment characteristics,
but initialise a BlockGrid for GUI too."""
super().__init__(width, height)
self.grid = BlockGrid(width, height, fill=(200, 200, 200))
if display:
self.grid.show()
self.visible = True
else:
self.visible = False
self.bounded = boundary
self.colors = color
def get_world(self):
"""Returns all the items in the world in a format
understandable by the ipythonblocks BlockGrid."""
result = []
x_start, y_start = (0, 0)
x_end, y_end = self.width, self.height
for x in range(x_start, x_end):
row = []
for y in range(y_start, y_end):
row.append(self.list_things_at((x, y)))
result.append(row)
return result
"""
def run(self, steps=1000, delay=1):
"" "Run the Environment for given number of time steps,
but update the GUI too." ""
for step in range(steps):
sleep(delay)
if self.visible:
self.reveal()
if self.is_done():
if self.visible:
self.reveal()
return
self.step()
if self.visible:
self.reveal()
"""
def run(self, steps=1000, delay=1):
"""Run the Environment for given number of time steps,
but update the GUI too."""
for step in range(steps):
self.update(delay)
if self.is_done():
break
self.step()
self.update(delay)
def update(self, delay=1):
sleep(delay)
self.reveal()
def reveal(self):
"""Display the BlockGrid for this world - the last thing to be added
at a location defines the location color."""
self.draw_world()
# wait for the world to update and
# apply changes to the same grid instead
# of making a new one.
clear_output(1)
self.grid.show()
self.visible = True
def draw_world(self):
self.grid[:] = (200, 200, 200)
world = self.get_world()
for x in range(0, len(world)):
for y in range(0, len(world[x])):
if len(world[x][y]):
self.grid[y, x] = self.colors[world[x][y][-1].__class__.__name__]
def conceal(self):
"""Hide the BlockGrid for this world"""
self.visible = False
display(HTML(''))
# ______________________________________________________________________________
# Continuous environment
class ContinuousWorld(Environment):
"""Model for Continuous World"""
def __init__(self, width=10, height=10):
super().__init__()
self.width = width
self.height = height
def add_obstacle(self, coordinates):
self.things.append(PolygonObstacle(coordinates))
class PolygonObstacle(Obstacle):
def __init__(self, coordinates):
"""Coordinates is a list of tuples."""
super().__init__()
self.coordinates = coordinates
# ______________________________________________________________________________
# Vacuum environment
class Dirt(Thing):
pass
class VacuumEnvironment(XYEnvironment):
"""The environment of [Ex. 2.12]. Agent perceives dirty or clean,
and bump (into obstacle) or not; 2D discrete world of unknown size;
performance measure is 100 for each dirt cleaned, and -1 for
each turn taken."""
def __init__(self, width=10, height=10):
super().__init__(width, height)
self.add_walls()
def thing_classes(self):
return [Wall, Dirt, ReflexVacuumAgent, RandomVacuumAgent,
TableDrivenVacuumAgent, ModelBasedVacuumAgent]
def percept(self, agent):
"""The percept is a tuple of ('Dirty' or 'Clean', 'Bump' or 'None').
Unlike the TrivialVacuumEnvironment, location is NOT perceived."""
status = ('Dirty' if self.some_things_at(
agent.location, Dirt) else 'Clean')
bump = ('Bump' if agent.bump else 'None')
return status, bump
def execute_action(self, agent, action):
agent.bump = False
if action == 'Suck':
dirt_list = self.list_things_at(agent.location, Dirt)
if dirt_list != []:
dirt = dirt_list[0]
agent.performance += 100
self.delete_thing(dirt)
else:
super().execute_action(agent, action)
if action != 'NoOp':
agent.performance -= 1
class TrivialVacuumEnvironment(Environment):
"""This environment has two locations, A and B. Each can be Dirty
or Clean. The agent perceives its location and the location's
status. This serves as an example of how to implement a simple
Environment."""
def __init__(self):
super().__init__()
self.status = {loc_A: random.choice(['Clean', 'Dirty']),
loc_B: random.choice(['Clean', 'Dirty'])}
def thing_classes(self):
return [Wall, Dirt, ReflexVacuumAgent, RandomVacuumAgent, TableDrivenVacuumAgent, ModelBasedVacuumAgent]
def percept(self, agent):
"""Returns the agent's location, and the location status (Dirty/Clean)."""
return agent.location, self.status[agent.location]
def execute_action(self, agent, action):
"""Change agent's location and/or location's status; track performance.
Score 10 for each dirt cleaned; -1 for each move."""
if action == 'Right':
agent.location = loc_B
agent.performance -= 1
elif action == 'Left':
agent.location = loc_A
agent.performance -= 1
elif action == 'Suck':
if self.status[agent.location] == 'Dirty':
agent.performance += 10
self.status[agent.location] = 'Clean'
def default_location(self, thing):
"""Agents start in either location at random."""
return random.choice([loc_A, loc_B])
# ______________________________________________________________________________
# The Wumpus World
class Gold(Thing):
def __eq__(self, rhs):
"""All Gold are equal"""
return rhs.__class__ == Gold
pass
class Bump(Thing):
pass
class Glitter(Thing):
pass
class Pit(Thing):
pass
class Breeze(Thing):
pass
class Arrow(Thing):
pass
class Scream(Thing):
pass
class Wumpus(Agent):
screamed = False
pass
class Stench(Thing):
pass
class Explorer(Agent):
holding = []
has_arrow = True
killed_by = ""
direction = Direction("right")
def can_grab(self, thing):
"""Explorer can only grab gold"""
return thing.__class__ == Gold
class WumpusEnvironment(XYEnvironment):
pit_probability = 0.2 # Probability to spawn a pit in a location. (From Chapter 7.2)
# Room should be 4x4 grid of rooms. The extra 2 for walls
def __init__(self, agent_program, width=6, height=6):
super().__init__(width, height)
self.init_world(agent_program)
def init_world(self, program):
"""Spawn items in the world based on probabilities from the book"""
"WALLS"
self.add_walls()
"PITS"
for x in range(self.x_start, self.x_end):
for y in range(self.y_start, self.y_end):
if random.random() < self.pit_probability:
self.add_thing(Pit(), (x, y), True)
self.add_thing(Breeze(), (x - 1, y), True)
self.add_thing(Breeze(), (x, y - 1), True)
self.add_thing(Breeze(), (x + 1, y), True)
self.add_thing(Breeze(), (x, y + 1), True)
"WUMPUS"
w_x, w_y = self.random_location_inbounds(exclude=(1, 1))
self.add_thing(Wumpus(lambda x: ""), (w_x, w_y), True)
self.add_thing(Stench(), (w_x - 1, w_y), True)
self.add_thing(Stench(), (w_x + 1, w_y), True)
self.add_thing(Stench(), (w_x, w_y - 1), True)
self.add_thing(Stench(), (w_x, w_y + 1), True)
"GOLD"
self.add_thing(Gold(), self.random_location_inbounds(exclude=(1, 1)), True)
"AGENT"
self.add_thing(Explorer(program), (1, 1), True)
def get_world(self, show_walls=True):
"""Return the items in the world"""
result = []
x_start, y_start = (0, 0) if show_walls else (1, 1)
if show_walls:
x_end, y_end = self.width, self.height
else:
x_end, y_end = self.width - 1, self.height - 1
for x in range(x_start, x_end):
row = []
for y in range(y_start, y_end):
row.append(self.list_things_at((x, y)))
result.append(row)
return result
def percepts_from(self, agent, location, tclass=Thing):
"""Return percepts from a given location,
and replaces some items with percepts from chapter 7."""
thing_percepts = {
Gold: Glitter(),
Wall: Bump(),
Wumpus: Stench(),
Pit: Breeze()}
"""Agents don't need to get their percepts"""
thing_percepts[agent.__class__] = None
"""Gold only glitters in its cell"""
if location != agent.location:
thing_percepts[Gold] = None
result = [thing_percepts.get(thing.__class__, thing) for thing in self.things
if thing.location == location and isinstance(thing, tclass)]
return result if len(result) else [None]
def percept(self, agent):
"""Return things in adjacent (not diagonal) cells of the agent.
Result format: [Left, Right, Up, Down, Center / Current location]"""
x, y = agent.location
result = []
result.append(self.percepts_from(agent, (x - 1, y)))
result.append(self.percepts_from(agent, (x + 1, y)))
result.append(self.percepts_from(agent, (x, y - 1)))
result.append(self.percepts_from(agent, (x, y + 1)))
result.append(self.percepts_from(agent, (x, y)))
"""The wumpus gives out a loud scream once it's killed."""
wumpus = [thing for thing in self.things if isinstance(thing, Wumpus)]
if len(wumpus) and not wumpus[0].alive and not wumpus[0].screamed:
result[-1].append(Scream())
wumpus[0].screamed = True
return result
def execute_action(self, agent, action):
"""Modify the state of the environment based on the agent's actions.
Performance score taken directly out of the book."""
if isinstance(agent, Explorer) and self.in_danger(agent):
return
agent.bump = False
if action == 'TurnRight':
agent.direction += Direction.R
agent.performance -= 1
elif action == 'TurnLeft':
agent.direction += Direction.L
agent.performance -= 1
elif action == 'Forward':
agent.bump = self.move_to(agent, agent.direction.move_forward(agent.location))
agent.performance -= 1
elif action == 'Grab':
things = [thing for thing in self.list_things_at(agent.location)
if agent.can_grab(thing)]
if len(things):
print("Grabbing", things[0].__class__.__name__)
if len(things):
agent.holding.append(things[0])
agent.performance -= 1
elif action == 'Climb':
if agent.location == (1, 1): # Agent can only climb out of (1,1)
agent.performance += 1000 if Gold() in agent.holding else 0
self.delete_thing(agent)
elif action == 'Shoot':
"""The arrow travels straight down the path the agent is facing"""
if agent.has_arrow:
arrow_travel = agent.direction.move_forward(agent.location)
while self.is_inbounds(arrow_travel):
wumpus = [thing for thing in self.list_things_at(arrow_travel)
if isinstance(thing, Wumpus)]
if len(wumpus):
wumpus[0].alive = False
break
arrow_travel = agent.direction.move_forward(agent.location)