summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: b06e30c448a7141c5eb846ec174d1eae7ac137cb (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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
use bevy::math::Vec3;
use bevy::prelude::*;
use bevy::window::{PrimaryWindow, WindowResolution};
use gems::cell::{self, AnimationTimer, Cell, Occupant};
use gems::constants;
use rand::{thread_rng, Rng};
use std::time::Duration;

fn star_spawning(
    mut commands: Commands,
    time: Res<Time>,
    mut query: Query<(&mut AnimationTimer, &Handle<TextureAtlas>)>,
) {
    for (mut timer, texture_atlas_handle) in &mut query {
        if !timer.repeating() {
            timer.tick(time.delta());
            if timer.just_finished() {
                timer.set_duration(Duration::new(thread_rng().gen_range(2..5), 0));
                timer.reset();
                commands
                    .spawn(SpriteSheetBundle {
                        sprite: TextureAtlasSprite::new(constants::TILESHEET_STAR1),
                        texture_atlas: texture_atlas_handle.clone(),
                        transform: Transform {
                            translation: Vec3::new(
                                thread_rng().gen_range(-300.0..300.0),
                                thread_rng().gen_range(-200.0..300.0),
                                0.1,
                            ),
                            scale: Vec3::splat(thread_rng().gen_range(1.0..3.0)),
                            ..Default::default()
                        },
                        ..Default::default()
                    })
                    .insert(AnimationTimer::from_seconds(0.15, TimerMode::Once));
            }
        }
    }
}

pub fn setup(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    mut texture_atlases: ResMut<Assets<TextureAtlas>>,
) {
    let background = asset_server.load("background.png");
    let tileset = asset_server.load("tileset.png");
    let title = asset_server.load("title.png");

    let atlas = TextureAtlas::from_grid(
        tileset,
        Vec2::new(constants::TILE_SIZE, constants::TILE_SIZE),
        5,
        5,
        None,
        None,
    );
    let atlas_handle = texture_atlases.add(atlas);

    commands.spawn(Camera2dBundle::default());
    commands.spawn(SpriteBundle {
        texture: background,
        transform: Transform {
            translation: Vec3::new(50.0, 0.0, 0.0),
            scale: Vec3::splat(constants::TILE_SCALE),
            ..Default::default()
        },
        ..Default::default()
    });
    commands.spawn(SpriteBundle {
        texture: title,
        transform: Transform {
            translation: Vec3::new(240.0, 200.0, 0.2),
            scale: Vec3::splat(2.0),
            ..Default::default()
        },
        ..Default::default()
    });
    commands.spawn(SpriteSheetBundle {
        sprite: TextureAtlasSprite::new(constants::TILESHEET_COSMONAUT1),
        texture_atlas: atlas_handle.clone(),
        transform: Transform {
            translation: Vec3::new(225.0, -200.0, 0.2),
            scale: Vec3::splat(constants::TILE_SCALE),
            ..Default::default()
        },
        ..Default::default()
    });
    commands.spawn((
        AnimationTimer::from_seconds(1.0, TimerMode::Once),
        atlas_handle.clone(),
    ));
    commands.spawn(SpriteSheetBundle {
        sprite: TextureAtlasSprite::new(constants::TILESHEET_COSMONAUT2),
        texture_atlas: atlas_handle.clone(),
        transform: Transform {
            translation: Vec3::new(
                225.0,
                -200.0 + (-constants::TILE_SIZE) * constants::TILE_SCALE,
                0.2,
            ),
            scale: Vec3::splat(constants::TILE_SCALE),
            ..Default::default()
        },
        ..Default::default()
    });

    for i in 0..constants::GRID_SIZE {
        for j in 0..constants::GRID_SIZE {
            commands
                .spawn(SpriteSheetBundle {
                    texture_atlas: atlas_handle.clone(),
                    transform: Transform {
                        translation: Vec3::new(
                            ((i as f32) * constants::TILE_SIZE * constants::TILE_SCALE) - 330.0,
                            ((j as f32) * constants::TILE_SIZE * constants::TILE_SCALE) - 160.0,
                            0.2,
                        ),
                        scale: Vec3::splat(constants::TILE_SCALE),
                        ..Default::default()
                    },
                    ..Default::default()
                })
                .insert(Cell::new(i, j));
        }
    }
}

fn animation(
    mut commands: Commands,
    time: Res<Time>,
    mut q: Query<(
        Entity,
        Option<&mut Cell>,
        &mut AnimationTimer,
        &mut TextureAtlasSprite,
    )>,
) {
    for (entity, cell, mut timer, mut sprite) in q.iter_mut() {
        timer.tick(time.delta());
        if timer.finished() {
            let index = match sprite.index {
                constants::TILESHEET_EXPLOSION1 => Some(constants::TILESHEET_EXPLOSION2),
                constants::TILESHEET_EXPLOSION2 => Some(constants::TILESHEET_EXPLOSION3),
                constants::TILESHEET_EXPLOSION3 => Some(constants::TILESHEET_EXPLOSION4),
                constants::TILESHEET_EXPLOSION4 => Some(constants::TILESHEET_EXPLOSION5),

                constants::TILESHEET_VISOR1 => Some(constants::TILESHEET_VISOR2),
                constants::TILESHEET_VISOR2 => Some(constants::TILESHEET_VISOR3),
                constants::TILESHEET_VISOR3 => Some(constants::TILESHEET_VISOR4),

                constants::TILESHEET_STAR1 => Some(constants::TILESHEET_STAR2),
                constants::TILESHEET_STAR2 => Some(constants::TILESHEET_STAR3),

                _ => None,
            };

            if let Some(index) = index {
                sprite.index = index;
            } else if let Some(mut cell) = cell {
                cell.set_occupant(Occupant::None, &mut sprite);
                commands.entity(entity).remove::<AnimationTimer>();
            } else {
                commands.entity(entity).despawn();
            }
        }
    }
}

fn cosmonaut_detect(
    mut commands: Commands,
    mut q: Query<(&Transform, &TextureAtlasSprite, &Handle<TextureAtlas>)>,
    mut windows: Query<&Window, With<PrimaryWindow>>,
) {
    let window = windows.single_mut();
    if let Some(mut cursor_position) = window.cursor_position() {
        cursor_position.x -=
            (constants::WINDOW_WIDTH / 2.0) - constants::TILE_SIZE * constants::TILE_SCALE * 0.5;
        cursor_position.y -=
            (constants::WINDOW_HEIGHT / 2.0) - constants::TILE_SIZE * constants::TILE_SCALE * 0.5;
        for (transform, sprite, texture_atlas_handle) in q.iter_mut() {
            if transform.translation.x < cursor_position.x
                && transform.translation.x + constants::TILE_SIZE * constants::TILE_SCALE
                    > cursor_position.x
                && transform.translation.y < cursor_position.y
                && transform.translation.y + constants::TILE_SIZE * constants::TILE_SCALE
                    > cursor_position.y
                && sprite.index == constants::TILESHEET_COSMONAUT1
            {
                commands
                    .spawn(SpriteSheetBundle {
                        sprite: TextureAtlasSprite::new(constants::TILESHEET_VISOR1),
                        texture_atlas: texture_atlas_handle.clone(),
                        transform: *transform,
                        ..Default::default()
                    })
                    .insert(AnimationTimer::from_seconds(0.1, TimerMode::Repeating));
            }
        }
    }
}

fn mouse(
    mut q: Query<(&mut Cell, &mut Transform, &mut TextureAtlasSprite)>,
    mut windows: Query<&Window, With<PrimaryWindow>>,
    mouse_button_input: Res<Input<MouseButton>>,
) {
    let window = windows.single_mut();
    if let Some(mut cursor_position) = window.cursor_position() {
        cursor_position.x -=
            (constants::WINDOW_WIDTH / 2.0) - constants::TILE_SIZE * constants::TILE_SCALE * 0.5;
        cursor_position.y -=
            (constants::WINDOW_HEIGHT / 2.0) - constants::TILE_SIZE * constants::TILE_SCALE * 0.5;

        for (cell, _, mut sprite) in q.iter_mut() {
            if cell.selected {
                sprite.color.set_a(0.2);
            } else if cell.hovered {
                sprite.color.set_a(0.5);
            } else {
                sprite.color.set_a(1.0);
            }
        }

        for (mut cell, transform, _) in q.iter_mut() {
            if transform.translation.x < cursor_position.x
                && transform.translation.x + constants::TILE_SIZE * constants::TILE_SCALE
                    > cursor_position.x
                && transform.translation.y < cursor_position.y
                && transform.translation.y + constants::TILE_SIZE * constants::TILE_SCALE
                    > cursor_position.y
            {
                cell.hovered = true;
                if mouse_button_input.just_pressed(MouseButton::Left) {
                    cell.selected = true;
                }
            } else {
                cell.hovered = false;
            }
        }
    }

    if mouse_button_input.just_released(MouseButton::Left) {
        let mut cells: Vec<Cell> = Vec::new();
        for (cell, _, _) in q.iter_mut() {
            cells.push(*cell);
        }
        if let Some(selected) = cells.clone().iter_mut().find(|c| c.selected) {
            if let Some(hovered) = cells.iter_mut().find(|c| c.hovered) {
                if ((selected.x == hovered.x + 1 || selected.x == hovered.x.overflowing_sub(1).0)
                    && selected.y == hovered.y)
                    || ((selected.y == hovered.y + 1
                        || selected.y == hovered.y.overflowing_sub(1).0)
                        && selected.x == hovered.x)
                {
                    std::mem::swap(&mut selected.occupant, &mut hovered.occupant);
                    for (mut cell, _, mut sprite) in q.iter_mut() {
                        if cell.x == selected.x && cell.y == selected.y {
                            cell.occupant = selected.occupant;
                            sprite.index = cell.occupant.to_index();
                        } else if cell.x == hovered.x && cell.y == hovered.y {
                            cell.occupant = hovered.occupant;
                            sprite.index = cell.occupant.to_index();
                        }
                    }
                }
            }
        }
        for (mut cell, _, _) in q.iter_mut() {
            cell.selected = false;
        }
    }
}

pub fn main() {
    App::new()
        .add_plugins(
            DefaultPlugins
                .set(ImagePlugin::default_nearest())
                .set(WindowPlugin {
                    primary_window: Some(Window {
                        title: "gems".to_string(),
                        resolution: WindowResolution::new(
                            constants::WINDOW_WIDTH,
                            constants::WINDOW_HEIGHT,
                        ),
                        resizable: false,
                        ..default()
                    }),
                    ..default()
                }),
        )
        .add_startup_system(setup)
        .add_systems((
            cell::insert,
            cell::falling,
            cell::check,
            cell::start_explosion,
            mouse,
            cosmonaut_detect,
            animation,
            star_spawning,
        ))
        .run();
}