1
- import sys
1
+ import sys , time
2
2
3
3
sys .path .append ('../common' )
4
4
import intcode
5
5
6
+ # Delay time in ms.
7
+ ANIMATION_SPEED = 1
8
+
6
9
TILE_EMPTY = 0
7
10
TILE_WALL = 1
8
11
TILE_BLOCK = 2
9
12
TILE_PADDLE = 3
10
13
TILE_BALL = 4
11
14
15
+ W = 40
16
+ H = 20
17
+
18
+ ball = 0
19
+ paddle = 0
20
+
21
+ def save_tile (x ,y ,tile ):
22
+ screen [(x ,y )] = tile
23
+
24
+ def print_tile (x ,y ):
25
+ global screen , ball , paddle
26
+ if (x ,y )== (- 1 ,0 ):
27
+ score = screen [(- 1 , 0 )] if (- 1 ,0 ) in screen else 0
28
+ c = f'Score: { score :05} Blocks left: { count_blocks ():03} '
29
+ elif screen [(x ,y )] == TILE_EMPTY :
30
+ c = ' '
31
+ elif screen [(x ,y )] == TILE_WALL :
32
+ c = '⬛️'
33
+ elif screen [(x ,y )] == TILE_BLOCK :
34
+ c = '⬜️'
35
+ elif screen [(x ,y )] == TILE_PADDLE :
36
+ c = '=='
37
+ paddle = x
38
+ elif screen [(x ,y )] == TILE_BALL :
39
+ c = '⚫'
40
+ ball = x
41
+ if x == - 1 :
42
+ pos = '\33 [25;0H'
43
+ else :
44
+ pos = '\33 [' + str (y + 4 ) + ';' + str (x * 2 + 1 ) + 'H'
45
+ sys .stdout .write (pos + c + '\33 [25;0H' )
46
+ sys .stdout .flush ()
47
+
48
+ def print_screen ():
49
+ print_tile (- 1 ,0 )
50
+ for y in range (H ):
51
+ for x in range (W ):
52
+ print_tile (x ,y )
53
+
54
+ def print_more (input ):
55
+ output = intcode .runIntCode (input )
56
+ for i in range (len (output )// 3 ):
57
+ save_tile (* output [i * 3 :i * 3 + 3 ])
58
+ print_tile (* output [i * 3 :i * 3 + 2 ])
59
+ if output [i * 3 + 2 ]:
60
+ # No sleep if it is an erase instruction
61
+ time .sleep (ANIMATION_SPEED / 1000 )
62
+
63
+ def count_blocks ():
64
+ return sum ([tile == TILE_BLOCK for tile in screen .values ()])
65
+
12
66
values = list (map (int , open ('d13.in' ).read ().strip ().split (',' )))
13
67
intcode .init (values )
14
68
output = intcode .runIntCode ([])
15
69
screen = {}
16
70
for i in range (len (output )// 3 ):
17
- x ,y , tile = output [i * 3 :i * 3 + 3 ]
18
- screen [(x ,y )] = tile
19
-
20
- def print_screen ():
21
- for y in range (20 ):
22
- for x in range (40 ):
23
- if screen [(x ,y )] == TILE_EMPTY :
24
- c = ' '
25
- elif screen [(x ,y )] == TILE_WALL :
26
- c = '⬛️'
27
- elif screen [(x ,y )] == TILE_BLOCK :
28
- c = '⬜️'
29
- elif screen [(x ,y )] == TILE_PADDLE :
30
- c = '=='
31
- elif screen [(x ,y )] == TILE_BALL :
32
- c = '⚫'
33
- print (c , end = '' )
34
- print ()
71
+ save_tile (* output [i * 3 :i * 3 + 3 ])
35
72
73
+ sys .stdout .write ('\33 [2J' )
74
+ print ('\33 [0;0HPart 1:' , count_blocks ())
36
75
print_screen ()
37
- print ('Part 1:' , sum ([tile == TILE_BLOCK for tile in screen .values ()]))
76
+
77
+
78
+ values [0 ] = 2
79
+ intcode .init (values )
80
+ intcode .runIntCode ([])
81
+ while True :
82
+ input = 1 if ball > paddle else - 1 if ball < paddle else 0
83
+ print_more ([input ])
84
+ if count_blocks ()== 0 :
85
+ break
86
+
87
+ print ('\33 [26;0HPart 2:' , screen [(- 1 , 0 )])
0 commit comments