summaryrefslogtreecommitdiff
path: root/src/bin/day_3.rs
blob: 5e6f0bdecd49cd02b700e87b497c117cd3696b38 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use bevy::app::AppExit;
use bevy::prelude::*;
use bevy::render::camera::Camera;
use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
    App::build()
        .add_resource(WindowDescriptor {
            title: "Advent of Code".to_string(),
            width: 1920,
            height: 1080,
            ..Default::default()
        })
        .add_resource(ClearColor(Color::rgb(0., 0., 0.)))
        .add_startup_system(setup_camera.system())
        .add_startup_stage("game_entities")
        .add_startup_system_to_stage("game_entities", read_input_file.system())
        .add_system(move_tobogganist.system())
        .add_system(collide_with_trees.system())
        .add_system(clear_finished_tobogganists.system())
        .add_system(end_of_slope.system())
        .add_system(translate_positions.system())
        .add_system(tobogganist_cam.system())
        .add_plugins(DefaultPlugins)
        .run();
}

fn setup_camera(mut commands: Commands, mut materials: ResMut<Assets<ColorMaterial>>) {
    commands.spawn(Camera2dComponents::default());

    commands.insert_resource(Materials {
        tobogganist_material: materials.add(Color::rgb(0., 0., 255.).into()),
        tree_material: materials.add(Color::rgb(0., 255., 0.).into()),
    });
}

struct Materials {
    tobogganist_material: Handle<ColorMaterial>,
    tree_material: Handle<ColorMaterial>,
}

struct Tobogganist;

struct Tree;
#[derive(PartialEq, Eq)]
struct Position {
    x: usize,
    y: usize,
}
struct Velocity {
    x: usize,
    y: usize,
}
struct MapSize {
    width: usize,
    height: usize,
}
struct TreeHitCount(usize);
struct Score(usize);

fn read_input_file(mut commands: Commands, materials: Res<Materials>) {
    commands
        .spawn(SpriteComponents {
            sprite: Sprite::new(Vec2::new(10., 10.)),
            material: materials.tobogganist_material.clone(),
            ..Default::default()
        })
        .with(Tobogganist)
        .with(Position { x: 0, y: 0 })
        .with(Velocity { x: 1, y: 1 })
        .with(TreeHitCount(0));

    commands
        .spawn(SpriteComponents {
            sprite: Sprite::new(Vec2::new(10., 10.)),
            material: materials.tobogganist_material.clone(),
            ..Default::default()
        })
        .with(Tobogganist)
        .with(Position { x: 0, y: 0 })
        .with(Velocity { x: 3, y: 1 })
        .with(TreeHitCount(0));

    commands
        .spawn(SpriteComponents {
            sprite: Sprite::new(Vec2::new(10., 10.)),
            material: materials.tobogganist_material.clone(),
            ..Default::default()
        })
        .with(Tobogganist)
        .with(Position { x: 0, y: 0 })
        .with(Velocity { x: 5, y: 1 })
        .with(TreeHitCount(0));

    commands
        .spawn(SpriteComponents {
            sprite: Sprite::new(Vec2::new(10., 10.)),
            material: materials.tobogganist_material.clone(),
            ..Default::default()
        })
        .with(Tobogganist)
        .with(Position { x: 0, y: 0 })
        .with(Velocity { x: 7, y: 1 })
        .with(TreeHitCount(0));

    commands
        .spawn(SpriteComponents {
            sprite: Sprite::new(Vec2::new(10., 10.)),
            material: materials.tobogganist_material.clone(),
            ..Default::default()
        })
        .with(Tobogganist)
        .with(Position { x: 0, y: 0 })
        .with(Velocity { x: 1, y: 2 })
        .with(TreeHitCount(0));

    let f = File::open("./inputs/day_3.txt").expect("Failed to read file"); // TODO: Use the asset loading system to load this rather?
    let mut width = 0;
    let mut height = 0;
    for (y, line) in BufReader::new(f).lines().enumerate() {
        let line = line.expect("Error reading file");
        let line = line.trim();
        width = width.max(line.len());
        for (x, c) in line.chars().enumerate() {
            if c == '#' {
                commands
                    .spawn(SpriteComponents {
                        sprite: Sprite::new(Vec2::new(10., 10.)),
                        material: materials.tree_material.clone(),
                        ..Default::default()
                    })
                    .with(Tree)
                    .with(Position { x, y })
                    .with(TreeHitCount(0));
            }
        }
        height = y + 1;
    }
    commands.insert_resource(MapSize { width, height });
    commands.insert_resource(Score(1));
}

fn translate_positions(mut transform: Mut<Transform>, position: &Position) {
    transform.translation = Vec3::new(position.x as f32 * 10., position.y as f32 * -10., 0.);
}

fn tobogganist_cam(
    tobogganist: Query<With<Tobogganist, &Transform>>,
    mut camera: Query<With<Camera, &mut Transform>>,
) {
    for mut camera_transform in camera.iter_mut() {
        if let Some(tobogganist_transform) = tobogganist.iter().next() {
            camera_transform.translation = Vec3::new(0., tobogganist_transform.translation.y(), 0.);
        }
    }
}

fn move_tobogganist(map_size: Res<MapSize>, mut position: Mut<Position>, velocity: &Velocity) {
    position.x += velocity.x;
    position.x %= map_size.width;
    position.y += velocity.y;
}

fn collide_with_trees(
    mut tobogganists: Query<With<Tobogganist, (&Position, &mut TreeHitCount)>>,
    trees: Query<With<Tree, &Position>>,
) {
    for (tobogganist_position, mut tree_hit_count) in tobogganists.iter_mut() {
        for tree_position in trees.iter() {
            if *tree_position == *tobogganist_position {
                tree_hit_count.0 += 1;
            }
        }
    }
}

fn clear_finished_tobogganists(
    mut commands: Commands,
    map_size: Res<MapSize>,
    mut score: ResMut<Score>,
    tobogganists: Query<With<Tobogganist, (Entity, &Position, &Velocity, &TreeHitCount)>>,
) {
    for (entity, position, velocity, tree_hit_count) in tobogganists.iter() {
        if position.y >= map_size.height {
            println!(
                "A tobogganist finished heading at incline {} x {}, after hitting {} trees",
                velocity.x, velocity.y, tree_hit_count.0
            );
            score.0 *= tree_hit_count.0;
            commands.despawn(entity);
        }
    }
}

fn end_of_slope(
    score: Res<Score>,
    mut exit_events: ResMut<Events<AppExit>>,
    tobogganists: Query<&Tobogganist>,
) {
    if tobogganists.iter().count() == 0 {
        println!("All tobogganists finished. Total score: {}", score.0);
        exit_events.send(AppExit);
    }
}