Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Fix flake8 for main files #399

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 25, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
[flake8]
max-line-length = 100
ignore = E121,E123,E126,E221,E222,E225,E226,E242,E701,E702,E704,E731,W503,F405
exclude = tests
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ install:
script:
- py.test
- python -m doctest -v *.py
- flake8 .

after_success:
- flake8 --max-line-length 100 --ignore=E121,E123,E126,E221,E222,E225,E226,E242,E701,E702,E704,E731,W503 .
Expand Down
74 changes: 35 additions & 39 deletions agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ def rule_match(state, rules):

# ______________________________________________________________________________


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


Expand Down Expand Up @@ -394,8 +395,9 @@ def things_near(self, location, radius=None):
if radius is None:
radius = self.perceptible_distance
radius2 = radius * radius
return [(thing, radius2 - distance_squared(location, thing.location)) for thing in self.things
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I actually like this indentation better than the correction

if distance_squared(location, thing.location) <= radius2]
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."""
Expand Down Expand Up @@ -435,33 +437,28 @@ def move_to(self, thing, destination):
t.location = destination
return thing.bump

# def add_thing(self, thing, location=(1, 1)):
# super(XYEnvironment, self).add_thing(thing, location)
# thing.holding = []
# thing.held = None
# for obs in self.observers:
# obs.thing_added(thing)

def add_thing(self, thing, location=(1, 1), exclude_duplicate_class_items=False):
"""Adds 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 (self.is_inbounds(location)):
if (exclude_duplicate_class_items and
any(isinstance(t, thing.__class__) for t in self.list_things_at(location))):
return
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
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))
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))
location = (random.randint(self.x_start, self.x_end),
random.randint(self.y_start, self.y_end))
return location

def delete_thing(self, thing):
Expand Down Expand Up @@ -514,19 +511,21 @@ class Wall(Obstacle):

# ______________________________________________________________________________


try:
from ipythonblocks import BlockGrid
from IPython.display import HTML, display
from time import sleep
except:
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))
self.grid = BlockGrid(width, height, fill=(200, 200, 200))
if display:
self.grid.show()
self.visible = True
Expand All @@ -535,11 +534,6 @@ def __init__(self, width=10, height=10, boundary=True, color={}, display=False):
self.bounded = boundary
self.colors = color

#def list_things_at(self, location, tclass=Thing): # need to override because locations
# """Return all things exactly at a given location."""
# return [thing for thing in self.things
# if thing.location == location and isinstance(thing, tclass)]

def get_world(self):
"""Returns all the items in the world in a format
understandable by the ipythonblocks BlockGrid"""
Expand Down Expand Up @@ -589,34 +583,24 @@ def update(self, delay=1):
def reveal(self):
"""display the BlockGrid for this world - the last thing to be added
at a location defines the location color"""
#print("Grid={}".format(self.grid))
self.draw_world()
#if not self.visible == True:
# self.grid.show()
self.grid.show()
self.visible == True
self.visible = True

def draw_world(self):
self.grid[:] = (200, 200, 200)
world = self.get_world()
#print("world {}".format(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__]
#print('location: ({}, {}) got color: {}'
#.format(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

Expand Down Expand Up @@ -733,21 +717,27 @@ def __eq__(self, rhs):
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

Expand All @@ -756,6 +746,7 @@ class Wumpus(Agent):
screamed = False
pass


class Stench(Thing):
pass

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


class WumpusEnvironment(XYEnvironment):
pit_probability = 0.2 # Probability to spawn a pit in a location. (From Chapter 7.2)
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):
Expand Down Expand Up @@ -805,7 +796,6 @@ def init_world(self, program):

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

"AGENT"
self.add_thing(Explorer(program), (1, 1), True)
Expand All @@ -814,7 +804,12 @@ def get_world(self, show_walls=True):
"""Returns the items in the world"""
result = []
x_start, y_start = (0, 0) if show_walls else (1, 1)
x_end, y_end = (self.width, self.height) if show_walls else (self.width - 1, self.height - 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):
Expand All @@ -837,7 +832,6 @@ def percepts_from(self, agent, location, tclass=Thing):
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]
Expand Down Expand Up @@ -916,18 +910,19 @@ def in_danger(self, agent):
def is_done(self):
"""The game is over when the Explorer is killed
or if he climbs out of the cave only at (1,1)."""
explorer = [agent for agent in self.agents if isinstance(agent, Explorer) ]
explorer = [agent for agent in self.agents if isinstance(agent, Explorer)]
if len(explorer):
if explorer[0].alive:
return False
return False
else:
print("Death by {} [-1000].".format(explorer[0].killed_by))
else:
print("Explorer climbed out {}."
.format("with Gold [+1000]!" if Gold() not in self.things else "without Gold [+0]"))
.format(
"with Gold [+1000]!" if Gold() not in self.things else "without Gold [+0]"))
return True

#Almost done. Arrow needs to be implemented
# Almost done. Arrow needs to be implemented
# ______________________________________________________________________________


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

# _________________________________________________________________________


__doc__ += """
>>> a = ReflexVacuumAgent()
>>> a.program((loc_A, 'Clean'))
Expand Down
10 changes: 6 additions & 4 deletions canvas.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from IPython.display import HTML, display, clear_output
from IPython.display import HTML, display

_canvas = """
<script type="text/javascript" src="./js/canvas.js"></script>
Expand All @@ -7,7 +7,8 @@
</div>

<script> var {0}_canvas_object = new Canvas("{0}");</script>
"""
""" # noqa


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

def arc_n(self, xn ,yn, rn, start, stop):
def arc_n(self, xn, yn, rn, start, stop):
"""Similar to arc(), but the dimensions are normalized to fall between 0 and 1
The normalizing factor for radius is selected between width and height by seeing which is smaller
The normalizing factor for radius is selected between width and height by
seeing which is smaller
"""
x = round(xn * self.width)
y = round(yn * self.height)
Expand Down
4 changes: 3 additions & 1 deletion csp.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,7 @@ def parse_neighbors(neighbors, variables=[]):
dic[B].append(A)
return dic


australia = MapColoringCSP(list('RGB'),
'SA: WA NT Q NSW V; NT: WA Q; NSW: Q V; T: ')

Expand Down Expand Up @@ -584,7 +585,8 @@ class Sudoku(CSP):
>>> h = Sudoku(harder1)
>>> backtracking_search(h, select_unassigned_variable=mrv, inference=forward_checking) is not None
True
"""
""" # noqa

R3 = _R3
Cell = _CELL
bgrid = _BGRID
Expand Down
12 changes: 7 additions & 5 deletions games.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ def display(self, state):

def __repr__(self):
return '<{}>'.format(self.__class__.__name__)

def play_game(self, *players):
"""Play an n-person, move-alternating game."""
state = self.initial
Expand Down Expand Up @@ -259,8 +259,8 @@ def actions(self, state):
def result(self, state, move):
if move not in state.moves:
return GameState(to_move=('O' if state.to_move == 'X' else 'X'),
utility=self.compute_utility(state.board, move, state.to_move),
board=state.board, moves=state.moves) # Illegal move has no effect
utility=self.compute_utility(state.board, move, state.to_move),
board=state.board, moves=state.moves) # Illegal move has no effect
board = state.board.copy()
board[move] = state.to_move
moves = list(state.moves)
Expand Down Expand Up @@ -327,7 +327,8 @@ class Canvas_TicTacToe(Canvas):
"""Play a 3x3 TicTacToe game on HTML canvas
TODO: Add restart button
"""
def __init__(self, varname, player_1='human', player_2='random', id=None, width=300, height=300):
def __init__(self, varname, player_1='human', player_2='random', id=None,
width=300, height=300):
valid_players = ('human', 'random', 'alphabeta')
if player_1 not in valid_players or player_2 not in valid_players:
raise TypeError("Players must be one of {}".format(valid_players))
Expand Down Expand Up @@ -381,7 +382,8 @@ def draw_board(self):
else:
self.text_n('Player {} wins!'.format(1 if utility > 0 else 2), 0.1, 0.1)
else: # Print which player's turn it is
self.text_n("Player {}'s move({})".format(self.turn+1, self.players[self.turn]), 0.1, 0.1)
self.text_n("Player {}'s move({})".format(self.turn+1, self.players[self.turn]),
0.1, 0.1)

self.update()

Expand Down
6 changes: 4 additions & 2 deletions ipyviews.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
var all_polygons = {3};
{4}
</script>
'''
''' # noqa

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

def show(self):
clear_output()
total_html = _CONTINUOUS_WORLD_HTML.format(self.width, self.height, self.object_name(), str(self.get_polygon_obstacles_coordinates()), _JS_CONTINUOUS_WORLD)
total_html = _CONTINUOUS_WORLD_HTML.format(self.width, self.height, self.object_name(),
str(self.get_polygon_obstacles_coordinates()),
_JS_CONTINUOUS_WORLD)
display(HTML(total_html))


Expand Down
Loading