Skip to content

Commit cdd6823

Browse files
lucasmouranorvig
authored andcommitted
Fix flake8 for main files (aimacode#399)
* Exclude test files from flake8 check * Fix flake8 for main files * Add flake8 check to build
1 parent 9f147f7 commit cdd6823

File tree

16 files changed

+331
-214
lines changed

16 files changed

+331
-214
lines changed

.flake8

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
[flake8]
22
max-line-length = 100
33
ignore = E121,E123,E126,E221,E222,E225,E226,E242,E701,E702,E704,E731,W503,F405
4+
exclude = tests

.travis.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ install:
1616
script:
1717
- py.test
1818
- python -m doctest -v *.py
19+
- flake8 .
1920

2021
after_success:
2122
- flake8 --max-line-length 100 --ignore=E121,E123,E126,E221,E222,E225,E226,E242,E701,E702,E704,E731,W503 .

agents.py

Lines changed: 35 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,7 @@ def rule_match(state, rules):
162162

163163
# ______________________________________________________________________________
164164

165+
165166
loc_A, loc_B = (0, 0), (1, 0) # The two locations for the Vacuum world
166167

167168

@@ -394,8 +395,9 @@ def things_near(self, location, radius=None):
394395
if radius is None:
395396
radius = self.perceptible_distance
396397
radius2 = radius * radius
397-
return [(thing, radius2 - distance_squared(location, thing.location)) for thing in self.things
398-
if distance_squared(location, thing.location) <= radius2]
398+
return [(thing, radius2 - distance_squared(location, thing.location))
399+
for thing in self.things if distance_squared(
400+
location, thing.location) <= radius2]
399401

400402
def percept(self, agent):
401403
"""By default, agent perceives things within a default radius."""
@@ -435,33 +437,28 @@ def move_to(self, thing, destination):
435437
t.location = destination
436438
return thing.bump
437439

438-
# def add_thing(self, thing, location=(1, 1)):
439-
# super(XYEnvironment, self).add_thing(thing, location)
440-
# thing.holding = []
441-
# thing.held = None
442-
# for obs in self.observers:
443-
# obs.thing_added(thing)
444-
445440
def add_thing(self, thing, location=(1, 1), exclude_duplicate_class_items=False):
446441
"""Adds things to the world. If (exclude_duplicate_class_items) then the item won't be
447442
added if the location has at least one item of the same class."""
448443
if (self.is_inbounds(location)):
449444
if (exclude_duplicate_class_items and
450-
any(isinstance(t, thing.__class__) for t in self.list_things_at(location))):
451-
return
445+
any(isinstance(t, thing.__class__) for t in self.list_things_at(location))):
446+
return
452447
super().add_thing(thing, location)
453448

454449
def is_inbounds(self, location):
455450
"""Checks to make sure that the location is inbounds (within walls if we have walls)"""
456-
x,y = location
451+
x, y = location
457452
return not (x < self.x_start or x >= self.x_end or y < self.y_start or y >= self.y_end)
458453

459454
def random_location_inbounds(self, exclude=None):
460455
"""Returns a random location that is inbounds (within walls if we have walls)"""
461-
location = (random.randint(self.x_start, self.x_end), random.randint(self.y_start, self.y_end))
456+
location = (random.randint(self.x_start, self.x_end),
457+
random.randint(self.y_start, self.y_end))
462458
if exclude is not None:
463459
while(location == exclude):
464-
location = (random.randint(self.x_start, self.x_end), random.randint(self.y_start, self.y_end))
460+
location = (random.randint(self.x_start, self.x_end),
461+
random.randint(self.y_start, self.y_end))
465462
return location
466463

467464
def delete_thing(self, thing):
@@ -514,19 +511,21 @@ class Wall(Obstacle):
514511

515512
# ______________________________________________________________________________
516513

514+
517515
try:
518516
from ipythonblocks import BlockGrid
519517
from IPython.display import HTML, display
520518
from time import sleep
521519
except:
522520
pass
523521

522+
524523
class GraphicEnvironment(XYEnvironment):
525524
def __init__(self, width=10, height=10, boundary=True, color={}, display=False):
526525
"""define all the usual XYEnvironment characteristics,
527526
but initialise a BlockGrid for GUI too"""
528527
super().__init__(width, height)
529-
self.grid = BlockGrid(width, height, fill=(200,200,200))
528+
self.grid = BlockGrid(width, height, fill=(200, 200, 200))
530529
if display:
531530
self.grid.show()
532531
self.visible = True
@@ -535,11 +534,6 @@ def __init__(self, width=10, height=10, boundary=True, color={}, display=False):
535534
self.bounded = boundary
536535
self.colors = color
537536

538-
#def list_things_at(self, location, tclass=Thing): # need to override because locations
539-
# """Return all things exactly at a given location."""
540-
# return [thing for thing in self.things
541-
# if thing.location == location and isinstance(thing, tclass)]
542-
543537
def get_world(self):
544538
"""Returns all the items in the world in a format
545539
understandable by the ipythonblocks BlockGrid"""
@@ -589,34 +583,24 @@ def update(self, delay=1):
589583
def reveal(self):
590584
"""display the BlockGrid for this world - the last thing to be added
591585
at a location defines the location color"""
592-
#print("Grid={}".format(self.grid))
593586
self.draw_world()
594-
#if not self.visible == True:
595-
# self.grid.show()
596587
self.grid.show()
597-
self.visible == True
588+
self.visible = True
598589

599590
def draw_world(self):
600591
self.grid[:] = (200, 200, 200)
601592
world = self.get_world()
602-
#print("world {}".format(world))
603593
for x in range(0, len(world)):
604594
for y in range(0, len(world[x])):
605595
if len(world[x][y]):
606596
self.grid[y, x] = self.colors[world[x][y][-1].__class__.__name__]
607-
#print('location: ({}, {}) got color: {}'
608-
#.format(y, x, self.colors[world[x][y][-1].__class__.__name__]))
609597

610598
def conceal(self):
611599
"""hide the BlockGrid for this world"""
612600
self.visible = False
613601
display(HTML(''))
614602

615603

616-
617-
618-
619-
620604
# ______________________________________________________________________________
621605
# Continuous environment
622606

@@ -733,21 +717,27 @@ def __eq__(self, rhs):
733717
return rhs.__class__ == Gold
734718
pass
735719

720+
736721
class Bump(Thing):
737722
pass
738723

724+
739725
class Glitter(Thing):
740726
pass
741727

728+
742729
class Pit(Thing):
743730
pass
744731

732+
745733
class Breeze(Thing):
746734
pass
747735

736+
748737
class Arrow(Thing):
749738
pass
750739

740+
751741
class Scream(Thing):
752742
pass
753743

@@ -756,6 +746,7 @@ class Wumpus(Agent):
756746
screamed = False
757747
pass
758748

749+
759750
class Stench(Thing):
760751
pass
761752

@@ -772,7 +763,7 @@ def can_grab(self, thing):
772763

773764

774765
class WumpusEnvironment(XYEnvironment):
775-
pit_probability = 0.2 # Probability to spawn a pit in a location. (From Chapter 7.2)
766+
pit_probability = 0.2 # Probability to spawn a pit in a location. (From Chapter 7.2)
776767
# Room should be 4x4 grid of rooms. The extra 2 for walls
777768

778769
def __init__(self, agent_program, width=6, height=6):
@@ -805,7 +796,6 @@ def init_world(self, program):
805796

806797
"GOLD"
807798
self.add_thing(Gold(), self.random_location_inbounds(exclude=(1, 1)), True)
808-
#self.add_thing(Gold(), (2,1), True) Making debugging a whole lot easier
809799

810800
"AGENT"
811801
self.add_thing(Explorer(program), (1, 1), True)
@@ -814,7 +804,12 @@ def get_world(self, show_walls=True):
814804
"""Returns the items in the world"""
815805
result = []
816806
x_start, y_start = (0, 0) if show_walls else (1, 1)
817-
x_end, y_end = (self.width, self.height) if show_walls else (self.width - 1, self.height - 1)
807+
808+
if show_walls:
809+
x_end, y_end = self.width, self.height
810+
else:
811+
x_end, y_end = self.width - 1, self.height - 1
812+
818813
for x in range(x_start, x_end):
819814
row = []
820815
for y in range(y_start, y_end):
@@ -837,7 +832,6 @@ def percepts_from(self, agent, location, tclass=Thing):
837832
if location != agent.location:
838833
thing_percepts[Gold] = None
839834

840-
841835
result = [thing_percepts.get(thing.__class__, thing) for thing in self.things
842836
if thing.location == location and isinstance(thing, tclass)]
843837
return result if len(result) else [None]
@@ -916,18 +910,19 @@ def in_danger(self, agent):
916910
def is_done(self):
917911
"""The game is over when the Explorer is killed
918912
or if he climbs out of the cave only at (1,1)."""
919-
explorer = [agent for agent in self.agents if isinstance(agent, Explorer) ]
913+
explorer = [agent for agent in self.agents if isinstance(agent, Explorer)]
920914
if len(explorer):
921915
if explorer[0].alive:
922-
return False
916+
return False
923917
else:
924918
print("Death by {} [-1000].".format(explorer[0].killed_by))
925919
else:
926920
print("Explorer climbed out {}."
927-
.format("with Gold [+1000]!" if Gold() not in self.things else "without Gold [+0]"))
921+
.format(
922+
"with Gold [+1000]!" if Gold() not in self.things else "without Gold [+0]"))
928923
return True
929924

930-
#Almost done. Arrow needs to be implemented
925+
# Almost done. Arrow needs to be implemented
931926
# ______________________________________________________________________________
932927

933928

@@ -952,6 +947,7 @@ def score(env):
952947

953948
# _________________________________________________________________________
954949

950+
955951
__doc__ += """
956952
>>> a = ReflexVacuumAgent()
957953
>>> a.program((loc_A, 'Clean'))

canvas.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from IPython.display import HTML, display, clear_output
1+
from IPython.display import HTML, display
22

33
_canvas = """
44
<script type="text/javascript" src="./js/canvas.js"></script>
@@ -7,7 +7,8 @@
77
</div>
88
99
<script> var {0}_canvas_object = new Canvas("{0}");</script>
10-
"""
10+
""" # noqa
11+
1112

1213
class Canvas:
1314
"""Inherit from this class to manage the HTML canvas element in jupyter notebooks.
@@ -81,9 +82,10 @@ def arc(self, x, y, r, start, stop):
8182
"Draw an arc with (x, y) as centre, 'r' as radius from angles 'start' to 'stop'"
8283
self.execute("arc({0}, {1}, {2}, {3}, {4})".format(x, y, r, start, stop))
8384

84-
def arc_n(self, xn ,yn, rn, start, stop):
85+
def arc_n(self, xn, yn, rn, start, stop):
8586
"""Similar to arc(), but the dimensions are normalized to fall between 0 and 1
86-
The normalizing factor for radius is selected between width and height by seeing which is smaller
87+
The normalizing factor for radius is selected between width and height by
88+
seeing which is smaller
8789
"""
8890
x = round(xn * self.width)
8991
y = round(yn * self.height)

csp.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,7 @@ def parse_neighbors(neighbors, variables=[]):
414414
dic[B].append(A)
415415
return dic
416416

417+
417418
australia = MapColoringCSP(list('RGB'),
418419
'SA: WA NT Q NSW V; NT: WA Q; NSW: Q V; T: ')
419420

@@ -584,7 +585,8 @@ class Sudoku(CSP):
584585
>>> h = Sudoku(harder1)
585586
>>> backtracking_search(h, select_unassigned_variable=mrv, inference=forward_checking) is not None
586587
True
587-
"""
588+
""" # noqa
589+
588590
R3 = _R3
589591
Cell = _CELL
590592
bgrid = _BGRID

games.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ def display(self, state):
196196

197197
def __repr__(self):
198198
return '<{}>'.format(self.__class__.__name__)
199-
199+
200200
def play_game(self, *players):
201201
"""Play an n-person, move-alternating game."""
202202
state = self.initial
@@ -259,8 +259,8 @@ def actions(self, state):
259259
def result(self, state, move):
260260
if move not in state.moves:
261261
return GameState(to_move=('O' if state.to_move == 'X' else 'X'),
262-
utility=self.compute_utility(state.board, move, state.to_move),
263-
board=state.board, moves=state.moves) # Illegal move has no effect
262+
utility=self.compute_utility(state.board, move, state.to_move),
263+
board=state.board, moves=state.moves) # Illegal move has no effect
264264
board = state.board.copy()
265265
board[move] = state.to_move
266266
moves = list(state.moves)
@@ -327,7 +327,8 @@ class Canvas_TicTacToe(Canvas):
327327
"""Play a 3x3 TicTacToe game on HTML canvas
328328
TODO: Add restart button
329329
"""
330-
def __init__(self, varname, player_1='human', player_2='random', id=None, width=300, height=300):
330+
def __init__(self, varname, player_1='human', player_2='random', id=None,
331+
width=300, height=300):
331332
valid_players = ('human', 'random', 'alphabeta')
332333
if player_1 not in valid_players or player_2 not in valid_players:
333334
raise TypeError("Players must be one of {}".format(valid_players))
@@ -381,7 +382,8 @@ def draw_board(self):
381382
else:
382383
self.text_n('Player {} wins!'.format(1 if utility > 0 else 2), 0.1, 0.1)
383384
else: # Print which player's turn it is
384-
self.text_n("Player {}'s move({})".format(self.turn+1, self.players[self.turn]), 0.1, 0.1)
385+
self.text_n("Player {}'s move({})".format(self.turn+1, self.players[self.turn]),
386+
0.1, 0.1)
385387

386388
self.update()
387389

ipyviews.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
var all_polygons = {3};
2121
{4}
2222
</script>
23-
'''
23+
''' # noqa
2424

2525
with open('js/continuousworld.js', 'r') as js_file:
2626
_JS_CONTINUOUS_WORLD = js_file.read()
@@ -61,7 +61,9 @@ def get_polygon_obstacles_coordinates(self):
6161

6262
def show(self):
6363
clear_output()
64-
total_html = _CONTINUOUS_WORLD_HTML.format(self.width, self.height, self.object_name(), str(self.get_polygon_obstacles_coordinates()), _JS_CONTINUOUS_WORLD)
64+
total_html = _CONTINUOUS_WORLD_HTML.format(self.width, self.height, self.object_name(),
65+
str(self.get_polygon_obstacles_coordinates()),
66+
_JS_CONTINUOUS_WORLD)
6567
display(HTML(total_html))
6668

6769

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy