1
- use std:: fs;
1
+ use screen:: Screen ;
2
+ use std:: { env, fs} ;
3
+
4
+ mod screen;
2
5
3
6
fn is_movable_vertical ( grid : & [ u8 ] , w : usize , b : ( usize , usize ) , y : usize , dy : isize ) -> bool {
4
7
let ny = y. checked_add_signed ( dy) . unwrap ( ) ;
@@ -92,6 +95,7 @@ fn run_instructions(
92
95
mut grid : Vec < u8 > ,
93
96
w : usize ,
94
97
h : usize ,
98
+ screen : & mut Option < Screen > ,
95
99
) -> usize {
96
100
for instr in instructions {
97
101
match instr {
@@ -136,6 +140,12 @@ fn run_instructions(
136
140
137
141
_ => panic ! ( "Unknown instruction: {}" , instr) ,
138
142
}
143
+
144
+ if let Some ( ref mut screen) = screen {
145
+ grid[ pos. 1 * w + pos. 0 ] = b'@' ;
146
+ screen. update ( & grid) ;
147
+ grid[ pos. 1 * w + pos. 0 ] = b'.' ;
148
+ }
139
149
}
140
150
141
151
let mut total = 0 ;
@@ -152,6 +162,9 @@ fn run_instructions(
152
162
}
153
163
154
164
fn main ( ) {
165
+ // should the grid be visualized on the terminal?
166
+ let visualize = env:: var ( "AOC_DAY15_VISUALIZE" ) . is_ok ( ) ;
167
+
155
168
for part1 in [ true , false ] {
156
169
let input = fs:: read_to_string ( "input.txt" ) . expect ( "Could not read file" ) ;
157
170
let ( grid, instructions) = input. split_once ( "\n \n " ) . unwrap ( ) ;
@@ -197,6 +210,12 @@ fn main() {
197
210
grid = wider_grid;
198
211
}
199
212
213
+ let mut screen = if visualize {
214
+ Some ( Screen :: new ( width, height) )
215
+ } else {
216
+ None
217
+ } ;
218
+
200
219
// find robot
201
220
let mut pos = ( 0 , 0 ) ;
202
221
' outer: for y in 0 ..height {
@@ -209,7 +228,12 @@ fn main() {
209
228
}
210
229
grid[ pos. 1 * width + pos. 0 ] = b'.' ;
211
230
212
- let total = run_instructions ( pos, instructions, grid, width, height) ;
231
+ let total = run_instructions ( pos, instructions, grid, width, height, & mut screen) ;
232
+
233
+ if let Some ( mut screen) = screen {
234
+ screen. finish ( ) ;
235
+ }
236
+
213
237
println ! ( "{}" , total) ;
214
238
}
215
239
}
0 commit comments