plt.imshow(grid) def triples(it): for i in it: yield (i, it.next(), it.next()) def move(ball, paddle): if ball > paddle: return 1 if ball < paddle: return -1 return 0 # Answer part 1 print sum(tile == 2 for (x, y, tile) in triples(IntCode.fromfile('input.txt'))) # Answer part 2 # Setup game inp = [] code = IntCode.fromfile('input.txt', iter(inp)) code.mem[0] = 2 # We're actually not interested in blocks or walls, only in score and # ball/paddle positions, so we filter those out. it = ifilter(lambda t: (t[0] == -1) or (t[2] in [3, 4]), triples(code)) # Read initial ball and paddle position for i in range(2): (x, y, tile) = it.next() if tile == 4: ball = x
return self.panels.get((self.y, self.x), 0) def set_color(self, c): self.panels[(self.y, self.x)] = c def run(self): for (c, t) in pairs(self.code): self.set_color(c) self.turn(t) self.move() self.inp.append(self.get_color()) # Answer part 1 inp = [0] robot = Robot(IntCode.fromfile('input.txt', iter(inp)), inp) robot.run() print len(robot.panels) # Answer part 2 inp = [1] robot = Robot(IntCode.fromfile('input.txt', iter(inp)), inp, {(0, 0): 1}) robot.run() xmin = min(x for (y, x) in robot.panels.keys()) xmax = max(x for (y, x) in robot.panels.keys()) ymin = min(y for (y, x) in robot.panels.keys()) ymax = max(y for (y, x) in robot.panels.keys()) image = np.zeros(((ymax - ymin + 1), (xmax - xmin + 1)), dtype=int) for ((y, x), c) in robot.panels.iteritems(): image[y, x] = c
def printmap(knownmap, pos): xmin = min(x for (x, y) in knownmap.keys()) xmax = max(x for (x, y) in knownmap.keys()) ymin = min(y for (x, y) in knownmap.keys()) ymax = max(y for (x, y) in knownmap.keys()) lines = [list(' ' * (xmax - xmin + 1)) for y in range(ymin, ymax + 1)] for ((x, y), t) in knownmap.iteritems(): lines[y - ymin][x - xmin] = t lines[-ymin][-xmin] = 'o' lines[pos[1] - ymin][pos[0] - xmin] = 'X' print '\n'.join(map(''.join, lines)) inp = [] code = IntCode.fromfile('input.txt', iter(inp)) knownmap = {(0, 0): '.'} toexplore = dirs.values() pos = (0, 0) while toexplore: newpos = toexplore.pop(0) route = findroute(knownmap, newpos, pos) inp.extend(route) for (r, s) in zip(route[0:-1], code): if s == 0: print 'Unexpected wall!' (dx, dy) = dirs[r] pos = (pos[0] + dx, pos[1] + dy) status = code.next() if status == 0: knownmap[newpos] = '#'