def process(self): posX = self.in_wire.get() posY = self.in_wire.get() third = self.in_wire.get() pos = Coord(posX, posY) if pos == Coord(-1, 0): # third is "score" if self.debug: print('{self}: SCORE: {tid}'.format(self=self, pos=pos, tid=third)) self.score = third else: # third is "tile id" # if self.debug: # print('{self}: Update Tile: Pos: {pos}, Type: {tid}'.format(self=self, pos=pos, tid=third)) self.grid[pos] = third update_joystick = False if third == PADDLE: self.paddle_pos = pos update_joystick = True if self.debug: print('{self}: PADDLE: moved to: {pos}'.format(self=self, pos=pos)) elif third == BALL: self.ball_pos = pos update_joystick = True if self.debug: print('{self}: BALL: moved to: {pos}'.format(self=self, pos=pos)) if update_joystick and \ self.joystick is not None and \ self.paddle_pos and self.ball_pos: blocks = self.grid.numBlocks() if blocks == 0: self.joystick.set( JOYSTICK_NEUTRAL ) print('*********************************') print('*********** BLOCKS: 0 ***********') print('*********************************') else: if self.paddle_pos.x > self.ball_pos.x: self.joystick.set( JOYSTICK_TILT_LEFT ) if self.debug: print('{self}: Joystick: TILT LEFT (PADDLE: {paddle}, BALL: {ball}, BLOCKS: {blocks})'.format( self=self, paddle=self.paddle_pos, ball=self.ball_pos, blocks=blocks) ) elif self.paddle_pos.x < self.ball_pos.x: self.joystick.set( JOYSTICK_TILT_RIGHT ) if self.debug: print('{self}: Joystick: TILT RIGHT (PADDLE: {paddle}, BALL: {ball}, BLOCKS: {blocks})'.format( self=self, paddle=self.paddle_pos, ball=self.ball_pos, blocks=blocks) ) else: self.joystick.set( JOYSTICK_NEUTRAL ) if self.debug: print('{self}: Joystick: NEUTRAL (PADDLE: {paddle}, BALL: {ball}, BLOCKS: {blocks})'.format( self=self, paddle=self.paddle_pos, ball=self.ball_pos, blocks=blocks) )
def print_grid(grid, droid_pos): os.system('clear') xMin, xMax = None, None yMin, yMax = None, None for coord, _ in grid.items(): x, y = coord.x, coord.y if xMin is None or xMin > x: xMin = x if xMax is None or xMax < x: xMax = x if yMin is None or yMin > y: yMin = y if yMax is None or yMax < y: yMax = y marks = [] for y in range(yMin, yMax + 1): row__ = "" for x in range(xMin, xMax + 1): pos = Coord(x, y) status = MazeGrid.UNKNOWN if pos in grid: status = grid[pos] if pos == Coord(0, 0): status = MazeGrid.START if pos == droid_pos: status = MazeGrid.DROID row__ += MazeGrid.render(status) marks.append(row__) print('\n'.join(marks))
class Directions(object): NORTH = Direction('NORTH', Coord(0, -1)) WEST = Direction('WEST', Coord(-1, 0)) SOUTH = Direction('SOUTH', Coord(0, 1)) EAST = Direction('EAST', Coord(1, 0)) @staticmethod def left(dir): if dir == Directions.NORTH: return Directions.WEST elif dir == Directions.WEST: return Directions.SOUTH elif dir == Directions.SOUTH: return Directions.EAST elif dir == Directions.EAST: return Directions.NORTH else: raise Exception("Unsupported direction: {}".format(dir)) @staticmethod def right(dir): if dir == Directions.NORTH: return Directions.EAST elif dir == Directions.EAST: return Directions.SOUTH elif dir == Directions.SOUTH: return Directions.WEST elif dir == Directions.WEST: return Directions.NORTH else: raise Exception("Unsupported direction: {}".format(dir))
def print_grid(grid, droid_pos): # os.system('clear') xMin, xMax = None, None yMin, yMax = None, None for coord, _ in grid.items(): x, y = coord.x, coord.y if xMin is None or xMin > x: xMin = x if xMax is None or xMax < x: xMax = x if yMin is None or yMin > y: yMin = y if yMax is None or yMax < y: yMax = y marks = [] for y in range(yMin, yMax + 1): row__ = "" for x in range(xMin, xMax + 1): pos = Coord(x, y) ch = grid[pos] row__ += ch marks.append(row__) print('\n'.join(marks))
def debug_map(rows, cols, asteroids, hits, station): marks = [] for y in range(rows): row__ = "" for x in range(cols): pos = Coord(x, y) if pos in asteroids: if pos in hits: try: # access as a dict row__ += str(hits[pos])[-1] except: # access as list row__ += "o" elif pos == station: row__ += "@" else: # erm .. row__ += "#" else: row__ += '.' marks.append(row__) print('\n'.join(marks))
def print_grid(grid): xMin, xMax = None, None yMin, yMax = None, None for coord, _ in grid.items(): x, y = coord.x, coord.y if xMin is None or xMin > x: xMin = x if xMax is None or xMax < x: xMax = x if yMin is None or yMin > y: yMin = y if yMax is None or yMax < y: yMax = y marks = [] for y in range(yMin, yMax+1): row__ = "" for x in range(xMin, xMax+1): pos = Coord(x, y) color = PaintGrid.BLACK if pos in grid: color = grid[pos] row__ += PaintGrid.render_color( color ) marks.append(row__) print('\n'.join(marks))
def __init__(self, id, pos=Coord(0,0), dir=Directions.NORTH, grid=None, in_wire=None, out_wire=None, debug=False): super(RobotMover, self).__init__(id, in_wire=in_wire, out_wire=out_wire, debug=debug) self.grid = grid self.pos = pos self.dir = dir
def get_asteroids(map_data): rows = len(map_data) cols = len(map_data[0]) asteroids = set() for y in range(rows): for x in range(cols): if map_data[y][x] == '#': asteroids.add(Coord(x, y)) # X,Y -> X is dist from left return asteroids, rows, cols
def __init__(self, id, pos=Coord(0, 0), grid=None, droid=None, in_wire=None, out_wire=None, debug=False): super(DroidController, self).__init__(id, in_wire=in_wire, out_wire=out_wire, debug=debug) self.grid = grid self.pos = pos
ord('>'): '>', ord('X'): 'X', } class Direction(object): def __init__(self, id, step): self.id = id self.step = step def __repr__(self): return self.id DIRS = [ Direction('^', Coord(0, -1)), Direction('>', Coord(1, 0)), Direction('v', Coord(0, 1)), Direction('<', Coord(-1, 0)), ] def getTurns(facingDir): fdi = DIRS.index(facingDir) return { "R": DIRS[(fdi + 1) % len(DIRS)], "L": DIRS[(fdi - 1 + len(DIRS)) % len(DIRS)], } def isBot(ch):
def run_tests(): maps = [(""" .#..# ..... ##### ....# ...## """, Coord(3, 4), 8), (""" ......#.#. #..#.#.... ..#######. .#.#.###.. .#..#..... ..#....#.# #..#....#. .##.#..### ##...#..#. .#....#### """, Coord(5, 8), 33), (""" #.#...#.#. .###....#. .#....#... ##.#.#.#.# ....#.#.#. .##..###.# ..#...##.. ..##....## ......#... .####.###. """, Coord(1, 2), 35), (""" .#..#..### ####.###.# ....###.#. ..###.##.# ##.##.#.#. ....###..# ..#.#..#.# #..#.#.### .##...##.# .....#.#.. """, Coord(6, 3), 41), (""" .#..##.###...####### ##.############..##. .#.######.########.# .###.#######.####.#. #####.##.#.##.###.## ..#####..#.######### #################### #.####....###.#.#.## ##.################# #####.##.###..####.. ..######..##.####### ####.##.####...##..# .#####..#.######.### ##...#.##########... #.##########.####### .####.#.###.###.#.## ....##.##.###..##### .#.#.###########.### #.#.#.#####.####.### ###.##.####.##.#..## """, Coord(11, 13), 210)] # part 1 for m, c, s in maps: c_, s_ = process_map(m) if c_ != c and s_ != s: print("TEST ERROR: Expected @{c} ({s}); Got: @{c_} ({s_})".format( **locals())) sys.exit(1) # part 2 print("\nTest Pattern #1") test_map = """ ............... ...#...#...#... ............... ...#...#...#... ............... ...#...#...#... ............... """ rotary_laser_hits(test_map, Coord(7, 3), debug=False) # sys.exit(1) test_map = """ ............... ...#########... ...#.......#... ...#...#...#... ...#.......#... ...#########... ............... """ rotary_laser_hits(test_map, Coord(7, 3), debug=False) test_map = """ ############### #..#########..# #..#.......#..# #..#...#...#..# #..#.......#..# #..#########..# ############### """ rotary_laser_hits(test_map, Coord(7, 3), debug=False) # sys.exit(1) print("\nTest Pattern #2") test_map = """ .#....#####...#.. ##...##.#####..## ##...#...#.#####. ..#.....#...###.. ..#.#.....#....## """ rotary_laser_hits(test_map, Coord(8, 3), debug=False) print("\nTest Pattern #3") test_map = maps[4] test_hits = { 1: Coord(11, 12), 2: Coord(12, 1), 3: Coord(12, 2), 10: Coord(12, 8), 20: Coord(16, 0), 50: Coord(16, 9), 100: Coord(10, 16), 199: Coord(9, 6), 200: Coord(8, 2), 201: Coord(10, 9), 299: Coord(11, 1) } hits = rotary_laser_hits(test_map[0], test_map[1], debug=False) for index, test_hit in test_hits.items(): if hits[index - 1] != test_hit: print("TEST ERROR: Expected Hit #{} is {}, found: {}".format( index, test_hit, hits[index])) sys.exit(1)
class Directions(object): NORTH = Direction('NORTH', 1, Coord(0, -1)) SOUTH = Direction('SOUTH', 2, Coord(0, 1)) WEST = Direction('WEST', 3, Coord(-1, 0)) EAST = Direction('EAST', 4, Coord(1, 0)) STOP = 'STOP'
print('\n'.join(marks)) def run_tests(): pass if __name__ == '__main__': print("Reading input..") with open('./day15/input') as input: initMemory = [int(x) for x in input.readline().split(',')] grid = MazeGrid() start = Coord(0, 0) grid[start] = MazeGrid.OPEN grid.track(start) robot = create_droid_with_controller(initMemory, grid, debug=False) run_robot(robot, debug=False) print('MazeGrid Size: {}'.format(len(grid))) print_grid(grid, start) goal = [k for k, v in grid.items() if v == MazeGrid.GOAL][0] print('Goal: {goal}'.format(**locals())) gradient = grid.gradient_descent(goal) print(f'Cost @ {start} = {gradient[start]}') print(f'Max Cost = {max(gradient.values())}')
for x in range(xMin, xMax+1): pos = Coord(x, y) color = PaintGrid.BLACK if pos in grid: color = grid[pos] row__ += PaintGrid.render_color( color ) marks.append(row__) print('\n'.join(marks)) def run_tests(): pass if __name__ == '__main__': print("Reading input..") with open('./day11/input') as input: initMemory = [int(x) for x in input.readline().split(',')] grid = PaintGrid() grid[Coord(0,0)] = PaintGrid.WHITE robot = create_robot(initMemory, grid, debug=False) run_robot(robot, debug=False) # print('PaintGrid End State: {}'.format(grid)) print('PaintGrid Size: {}'.format(len(grid))) print_grid(grid)