You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
3.0 KiB

use rand::prelude::*;
use redis::Commands as RedisCommands;
use valence::prelude::*;
use crate::{db::Connection, player::Alive, GameState, CONFIG};
pub fn start_game(
mut clients: Query<(&mut Client, &mut Position, &mut GameMode, &mut Alive)>,
mut instances: Query<&mut Instance>,
) {
tracing::debug!("Starting game!");
let mut instance = instances.single_mut();
for (mut client, mut pos, mut gamemode, mut alive) in &mut clients {
*gamemode = GameMode::Survival;
let mut rng = rand::thread_rng();
let x = rng.gen_range(0..=CONFIG.platform_size);
let z = rng.gen_range(0..=CONFIG.platform_size);
pos.set([x.into(), CONFIG.spawn_y as f64 + 1.0, z.into()]);
alive.0 = true;
// TODO: add colors
client.set_title("Game started!", "Have fun!", None);
}
for platform in -CONFIG.platforms..CONFIG.platforms * CONFIG.platform_gap {
if platform % CONFIG.platform_gap == 0 {
for z in -CONFIG.platform_size..CONFIG.platform_size {
for x in -CONFIG.platform_size..CONFIG.platform_size {
instance.set_block([x, CONFIG.spawn_y - platform, z], BlockState::SNOW_BLOCK);
}
}
}
}
}
pub fn stop_game(
mut clients: Query<(
&mut Client,
&mut Position,
&mut GameMode,
&mut Alive,
&Username,
&UniqueId,
)>,
mut connection: ResMut<Connection>,
) {
tracing::debug!("Stopping game!");
let mut alive_players = vec![];
for (mut client, mut pos, mut gamemode, mut alive, username, uuid) in &mut clients {
if alive.0 {
alive_players.push((username, uuid));
}
*gamemode = GameMode::Spectator;
pos.set([0.0, CONFIG.spawn_y as f64 + 10.0, 0.0]);
alive.0 = false;
// TODO: add colors
client.set_title(
"Game has ended!",
format!(
"{} wins!",
// if statement to not panic if somehow no one was alive when the game ended
if alive_players.len() >= 1 {
// let's assume there's only one alive player
alive_players[0].0 .0.clone()
} else {
"Somehow, no one".to_string()
}
),
None,
);
if alive_players.len() == 1 {
let _: i32 = connection
.0
.hincr("wins".to_string(), alive_players[0].1 .0.to_string(), 1)
.unwrap();
}
}
}
pub fn auto_stop(
clients: Query<&Alive, With<Client>>,
mut next_state: ResMut<NextState<GameState>>,
state: Res<State<GameState>>,
) {
if state.0 == GameState::Started {
let alive_clients = clients
.iter()
.filter(|alive| alive.0)
.collect::<Vec<&Alive>>();
if alive_clients.len() <= 1 {
next_state.set(GameState::Stopped);
}
}
}