Day 12
[advent-of-code-2020.git] / day12 / ship-2.py
1 #!/usr/bin/python3
2
3 import sys
4
5 waypoint_horz=10
6 waypoint_vert=1
7 directions=["E", "S", "W", "N"]
8 ship_x=0
9 ship_y=0
10
11 def do_waypoint_move(direction, amount):
12     global waypoint_horz
13     global waypoint_vert
14     if direction in ["E", "W"]:
15         if direction == "W":
16             amount=amount*-1
17         waypoint_horz+=amount
18     elif direction in ["N", "S"]:
19         if direction == "S":
20             amount=amount*-1
21         waypoint_vert+=amount
22
23 def turn(amount,multiplier):
24     global waypoint_horz,waypoint_vert
25     steps=int(amount / 90)
26     steps=steps * multiplier
27
28     print("Started at: {},{} rotating {}".format(waypoint_horz,waypoint_vert,amount*multiplier))
29     print("Steps: {}".format(steps))
30     # translate left in to moves right
31     if (steps < 0):
32         steps=4+steps
33
34     if steps == 4 or steps == 0:
35         return
36
37     print("Steps: {}".format(steps))
38
39     # and now we just step round that many steps to the right
40     # now 1,2 will go round to 2,-1, i.e. x,y -> y,-x
41     for step in range(steps):
42         temp=waypoint_vert
43         waypoint_vert=(waypoint_horz*-1)
44         waypoint_horz=temp
45
46     print("Ended at: {},{}".format(waypoint_horz,waypoint_vert))
47
48 def do_ship_move(amount):
49     global waypoint_horz,waypoint_vert,ship_x,ship_y
50     print("Waypoint {},{}, Ship {},{}, Amount {}".format(waypoint_horz, waypoint_vert, ship_x, ship_y, amount))
51     ship_x+=(amount*waypoint_horz)
52     ship_y+=(amount*waypoint_vert)
53     print("Ship {},{}".format(ship_x, ship_y))
54
55 def turn_right(amount):
56     turn(amount, 1)
57
58 def turn_left(amount):
59     turn(amount, -1)
60
61 filename="input.txt"
62
63 if len(sys.argv) > 1:
64     filename=sys.argv[1]
65
66 for line in open(filename, "r"):
67     line=line.rstrip()
68     command=line[0]
69     amount=int(line[1:])
70
71     if command in [ "N", "S", "E", "W" ]:
72         do_waypoint_move(command, amount)
73     elif command == "R":
74         turn_right(amount)
75     elif command == "L":
76         turn_left(amount)
77     elif command == "F":
78         do_ship_move(amount)
79
80 print("Moved to {}, {} - MD: {}".format(ship_x,ship_y,(abs(ship_x)+abs(ship_y))))