Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make alien_cake_addict deterministic with a seeded random #12515

Merged
merged 2 commits into from Mar 17, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 12 additions & 4 deletions examples/games/alien_cake_addict.rs
Expand Up @@ -3,7 +3,7 @@
use std::f32::consts::PI;

use bevy::prelude::*;
use rand::Rng;
use rand::{rngs::StdRng, Rng, SeedableRng};

#[derive(Clone, Eq, PartialEq, Debug, Hash, Default, States)]
enum GameState {
Expand Down Expand Up @@ -81,6 +81,9 @@ struct Game {
camera_is_focus: Vec3,
}

#[derive(Resource, Deref, DerefMut)]
struct SeededRng(StdRng);

const BOARD_SIZE_I: usize = 14;
const BOARD_SIZE_J: usize = 21;

Expand All @@ -105,6 +108,8 @@ fn setup_cameras(mut commands: Commands, mut game: ResMut<Game>) {
}

fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut game: ResMut<Game>) {
let mut seeded_rng = StdRng::seed_from_u64(19878367467713);
mockersf marked this conversation as resolved.
Show resolved Hide resolved

// reset the game state
game.cake_eaten = 0;
game.score = 0;
Expand All @@ -129,7 +134,7 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut game: ResMu
.map(|j| {
(0..BOARD_SIZE_I)
.map(|i| {
let height = rand::thread_rng().gen_range(-0.1..0.1);
let height = seeded_rng.gen_range(-0.1..0.1);
commands.spawn(SceneBundle {
transform: Transform::from_xyz(i as f32, height - 0.2, j as f32),
scene: cell_scene.clone(),
Expand Down Expand Up @@ -180,6 +185,8 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut game: ResMu
..default()
}),
);

commands.insert_resource(SeededRng(seeded_rng));
}

// remove all entities that are not a camera or window
Expand Down Expand Up @@ -305,6 +312,7 @@ fn spawn_bonus(
mut next_state: ResMut<NextState<GameState>>,
mut commands: Commands,
mut game: ResMut<Game>,
mut rng: ResMut<SeededRng>,
) {
// make sure we wait enough time before spawning the next cake
if !timer.0.tick(time.delta()).finished() {
Expand All @@ -323,8 +331,8 @@ fn spawn_bonus(

// ensure bonus doesn't spawn on the player
loop {
game.bonus.i = rand::thread_rng().gen_range(0..BOARD_SIZE_I);
game.bonus.j = rand::thread_rng().gen_range(0..BOARD_SIZE_J);
game.bonus.i = rng.gen_range(0..BOARD_SIZE_I);
game.bonus.j = rng.gen_range(0..BOARD_SIZE_J);
if game.bonus.i != game.player.i || game.bonus.j != game.player.j {
break;
}
Expand Down