#!/usr/bin/python3 # # # What direction the mouse is facing NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 # N:-1 E:0 S:+1 W:0 FORWARD_ROW = (-1, 0, +1, 0) # N:0 E:1 S:0 W:-1 FORWARD_COL = (0, +1, 0, -1) class Mouse(object): def __init__(self): # We always start at (15, 0) self.r = 15 self.c = 0 # Starting direction is always north self.d = NORTH # How many total moves? self.moves = 0 def reset(self): ### unclear whether we want to keep this, when considering ### the idea of "navigate back to start" self.r = 15 self.c = 0 self.d = NORTH self.moves = 0 def turn_right(self): self.d = (self.d + 1) & 3 def turn_around(self): self.d = (self.d + 2) & 3 # or ^= 2 def turn_left(self): self.d = (self.d + 3) & 3 def turn_towards(self, r, c): ### robot instructions should be inserted here. Just set our ### direction immediately. if r < self.r: self.d = NORTH elif c > self.c: self.d = EAST elif r > self.r: self.d = SOUTH else: assert c < self.c self.d = WEST def forward(self): # Caller should not have moved self forward, to an impossible # location. Double-check. assert ( (self.d == NORTH and self.r > 0) or (self.d == EAST and self.c < 15) or (self.d == SOUTH and self.r < 15) or (self.d == WEST and self.c > 0) ) self.r += FORWARD_ROW[self.d] self.c += FORWARD_COL[self.d] self.moves += 1 class Path(object): def __init__(self): self.crumbs = [ ] def moved_to(self, r, c): # If we have returned to a prior location on our path, then # cut out all the wandering. try: ### something is broken. hold on this. raise ValueError i = self.crumbs.index((r, c)) print('IDX:', i) print('OLD:', self.crumbs) # Delete the found location (about to be added), and all # locations after that. Thus, our crumbs have no loops. del self.crumbs[i:] print('NEW:', self.crumbs) except ValueError: pass self.crumbs.append((r, c)) def retreat(self): # Yield all locations, starting at the end of the path. for _ in range(len(self.crumbs)): yield self.crumbs.pop()