b.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import os, argparse
  2. def solve_task(lines):
  3. c = CRT()
  4. signal_strengths = []
  5. print(c)
  6. for line in lines:
  7. signal_strengths.extend(c.parse_instruction(line))
  8. total = sum(signal_strengths)
  9. print(signal_strengths)
  10. print(f"Total signal strength: {total}")
  11. print(c)
  12. class CRT:
  13. def __init__(self):
  14. self.x = 1
  15. self.cycle = 0
  16. self.screen = [['.' for x in range(40)] for y in range(6)]
  17. def parse_instruction(self, instruction):
  18. states_to_return = []
  19. tokens = instruction.split()
  20. if tokens[0] == "noop":
  21. states_to_return.extend(self.tick())
  22. else:
  23. xdiff = int(tokens[1])
  24. states_to_return.extend(self.tick())
  25. states_to_return.extend(self.tick())
  26. self.x += xdiff
  27. return states_to_return
  28. def tick(self):
  29. to_return = []
  30. self.update_screen()
  31. self.cycle += 1
  32. if (self.cycle+20) % 40 == 0:
  33. to_return = [self.cycle*self.x]
  34. return to_return
  35. def update_screen(self):
  36. y = self.cycle // 40
  37. x = self.cycle % 40
  38. hit = abs(x-self.x) <= 1
  39. self.screen[y][x] = '#' if hit else '.'
  40. def __str__(self):
  41. to_return = str()
  42. for line in self.screen:
  43. to_return += ''.join(line) + "\n"
  44. return to_return
  45. def read_lines(filename):
  46. lines = []
  47. with open(filename) as infile:
  48. for raw_line in infile:
  49. line = raw_line.rstrip()
  50. lines.append(line)
  51. return lines
  52. def parse_arguments():
  53. parser = argparse.ArgumentParser(description="Script that solves the case",epilog="Have a nice day!")
  54. parser.add_argument('filename', nargs='?', default="example.txt", help='Input file')
  55. args = parser.parse_args()
  56. return args
  57. def main():
  58. args = parse_arguments()
  59. lines = read_lines(args.filename)
  60. solve_task(lines)
  61. if __name__ == "__main__":
  62. main()