Skip to content

Commit

Permalink
Continue game working;
Browse files Browse the repository at this point in the history
Fix VarState::snapshot not accounting for birth ts;
Team reordering reducer;
Battle working;
Battle result panel showing stats;
Shop info window;
UnitCard statuses fix;
  • Loading branch information
makscee committed Jan 18, 2024
1 parent f370176 commit 0fba14b
Show file tree
Hide file tree
Showing 12 changed files with 227 additions and 153 deletions.
13 changes: 13 additions & 0 deletions server/src/arena_run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,9 @@ fn run_submit_result(ctx: ReducerContext, win: bool) -> Result<(), String> {
run.enemies.push(enemy.id);
}
}
run.change_g(G_PER_ROUND);
run.state.case.clear();
run.fill_case();
run.update();
Ok(())
}
Expand Down Expand Up @@ -173,6 +176,16 @@ fn run_stack(ctx: ReducerContext, target: u64, dragged: u64) -> Result<(), Strin
Ok(())
}

#[spacetimedb(reducer)]
fn run_team_reorder(ctx: ReducerContext, order: Vec<u64>) -> Result<(), String> {
let (_, mut run) = ArenaRun::get_by_identity(&ctx.sender)?;
run.state
.team
.sort_by_key(|u| order.iter().position(|o| u.id.eq(o)));
run.update();
Ok(())
}

#[spacetimedb(reducer)]
fn run_change_g(ctx: ReducerContext, delta: i64) -> Result<(), String> {
UserRight::UnitSync.check(&ctx.sender)?;
Expand Down
10 changes: 6 additions & 4 deletions src/components/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,12 @@ impl Status {
if s.name.eq(status) {
let mut state =
VarState::try_get_mut(entity, world).context("Failed to get state")?;
let visible = state.get_int(VarName::Charges)? > 0;
state
.push_back(VarName::Visible, VarChange::new(VarValue::Bool(visible)))
.change_int(VarName::Charges, delta);

let visible = state.get_bool(VarName::Visible).unwrap_or(true);
state.change_int(VarName::Charges, delta);
if visible != (state.get_int(VarName::Charges)? > 0) {
state.push_back(VarName::Visible, VarChange::new(VarValue::Bool(!visible)));
}

return Ok(entity);
}
Expand Down
4 changes: 3 additions & 1 deletion src/components/var_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,10 @@ impl VarState {
.with_context(|| format!("VarState not found for {entity:?}"))
}
pub fn snapshot(entity: Entity, world: &World, t: f32) -> Self {
let source = Self::get(entity, world);
let t = t - source.birth;
let mut state = VarState::default();
for (key, history) in Self::get(entity, world).history.iter() {
for (key, history) in source.history.iter() {
if let Ok(value) = history.find_value(t) {
state.init(*key, value);
}
Expand Down
4 changes: 4 additions & 0 deletions src/module_bindings/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub mod run_sell_reducer;
pub mod run_stack_reducer;
pub mod run_start_reducer;
pub mod run_submit_result_reducer;
pub mod run_team_reorder_reducer;
pub mod set_name_reducer;
pub mod set_password_reducer;
pub mod shop_offer;
Expand Down Expand Up @@ -75,6 +76,7 @@ pub use run_sell_reducer::*;
pub use run_stack_reducer::*;
pub use run_start_reducer::*;
pub use run_submit_result_reducer::*;
pub use run_team_reorder_reducer::*;
pub use set_name_reducer::*;
pub use set_password_reducer::*;
pub use shop_offer::*;
Expand Down Expand Up @@ -108,6 +110,7 @@ pub enum ReducerEvent {
RunStack(run_stack_reducer::RunStackArgs),
RunStart(run_start_reducer::RunStartArgs),
RunSubmitResult(run_submit_result_reducer::RunSubmitResultArgs),
RunTeamReorder(run_team_reorder_reducer::RunTeamReorderArgs),
SetName(set_name_reducer::SetNameArgs),
SetPassword(set_password_reducer::SetPasswordArgs),
SyncAbilities(sync_abilities_reducer::SyncAbilitiesArgs),
Expand Down Expand Up @@ -212,6 +215,7 @@ match &function_call.reducer[..] {
"run_stack" => _reducer_callbacks.handle_event_of_type::<run_stack_reducer::RunStackArgs, ReducerEvent>(event, _state, ReducerEvent::RunStack),
"run_start" => _reducer_callbacks.handle_event_of_type::<run_start_reducer::RunStartArgs, ReducerEvent>(event, _state, ReducerEvent::RunStart),
"run_submit_result" => _reducer_callbacks.handle_event_of_type::<run_submit_result_reducer::RunSubmitResultArgs, ReducerEvent>(event, _state, ReducerEvent::RunSubmitResult),
"run_team_reorder" => _reducer_callbacks.handle_event_of_type::<run_team_reorder_reducer::RunTeamReorderArgs, ReducerEvent>(event, _state, ReducerEvent::RunTeamReorder),
"set_name" => _reducer_callbacks.handle_event_of_type::<set_name_reducer::SetNameArgs, ReducerEvent>(event, _state, ReducerEvent::SetName),
"set_password" => _reducer_callbacks.handle_event_of_type::<set_password_reducer::SetPasswordArgs, ReducerEvent>(event, _state, ReducerEvent::SetPassword),
"sync_abilities" => _reducer_callbacks.handle_event_of_type::<sync_abilities_reducer::SyncAbilitiesArgs, ReducerEvent>(event, _state, ReducerEvent::SyncAbilities),
Expand Down
52 changes: 52 additions & 0 deletions src/module_bindings/run_team_reorder_reducer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN RUST INSTEAD.

#[allow(unused)]
use spacetimedb_sdk::{
anyhow::{anyhow, Result},
identity::Identity,
reducer::{Reducer, ReducerCallbackId, Status},
sats::{de::Deserialize, ser::Serialize},
spacetimedb_lib,
table::{TableIter, TableType, TableWithPrimaryKey},
Address,
};

#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct RunTeamReorderArgs {
pub order: Vec<u64>,
}

impl Reducer for RunTeamReorderArgs {
const REDUCER_NAME: &'static str = "run_team_reorder";
}

#[allow(unused)]
pub fn run_team_reorder(order: Vec<u64>) {
RunTeamReorderArgs { order }.invoke();
}

#[allow(unused)]
pub fn on_run_team_reorder(
mut __callback: impl FnMut(&Identity, Option<Address>, &Status, &Vec<u64>) + Send + 'static,
) -> ReducerCallbackId<RunTeamReorderArgs> {
RunTeamReorderArgs::on_reducer(move |__identity, __addr, __status, __args| {
let RunTeamReorderArgs { order } = __args;
__callback(__identity, __addr, __status, order);
})
}

#[allow(unused)]
pub fn once_on_run_team_reorder(
__callback: impl FnOnce(&Identity, Option<Address>, &Status, &Vec<u64>) + Send + 'static,
) -> ReducerCallbackId<RunTeamReorderArgs> {
RunTeamReorderArgs::once_on_reducer(move |__identity, __addr, __status, __args| {
let RunTeamReorderArgs { order } = __args;
__callback(__identity, __addr, __status, order);
})
}

#[allow(unused)]
pub fn remove_on_run_team_reorder(id: ReducerCallbackId<RunTeamReorderArgs>) {
RunTeamReorderArgs::remove_on_reducer(id);
}
132 changes: 62 additions & 70 deletions src/plugins/battle.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use bevy_egui::egui::Align2;

use crate::module_bindings::{run_submit_result, ArenaRun};

use super::*;

pub struct BattlePlugin;
Expand All @@ -17,47 +19,26 @@ pub struct BattleData {
pub left: Option<PackedTeam>,
pub right: Option<PackedTeam>,
pub result: BattleResult,
pub end: BattleEnd,
}

#[derive(Clone, Copy)]
pub enum BattleEnd {
Defeat,
Victory,
}

impl BattlePlugin {
pub fn on_enter(world: &mut World) {
GameTimer::get().reset();
let result = Self::run_battle(world).unwrap();
if matches!(Self::process_battle_result(result, world), Err(..)) {
let mut bd = world.resource_mut::<BattleData>();
bd.end = match result {
BattleResult::Left(_) | BattleResult::Even => BattleEnd::Victory,
BattleResult::Right(_) => BattleEnd::Defeat,
BattleResult::Tbd => panic!("Failed to get BattleResult"),
};
bd.result = result;
if let Some(win) = result.is_win() {
run_submit_result(win);
} else {
error!("Failed to get battle result");
}
}

fn process_battle_result(result: BattleResult, world: &mut World) -> Result<()> {
let mut bd = world.resource_mut::<BattleData>();
bd.end = match result {
BattleResult::Tbd => panic!("Failed to get BattleResult"),
BattleResult::Left(_) | BattleResult::Even => BattleEnd::Victory,
BattleResult::Right(_) => BattleEnd::Defeat,
};
bd.result = result;
Ok(())
}

pub fn load_teams(left: PackedTeam, right: PackedTeam, world: &mut World) {
world.insert_resource(BattleData {
left: Some(left),
right: Some(right),
result: default(),
end: BattleEnd::Defeat,
});
}

Expand Down Expand Up @@ -192,55 +173,56 @@ impl BattlePlugin {
if !GameTimer::get().ended() {
return;
}
let end = world.resource::<BattleData>().end;
let text = match end {
BattleEnd::Defeat => "Defeat".to_owned(),
BattleEnd::Victory => "Victory".to_owned(),
};
let subtext = match end {
BattleEnd::Defeat => {
format!(":(")
}
if let Some(win) = world.resource::<BattleData>().result.is_win() {
let run = ArenaRun::current();
let text = match win {
true => "Victory".to_owned(),
false => "Defeat".to_owned(),
};
let subtext = "Wins: "
.to_colored()
.push(format!("{}/10", run.state.wins), white())
.push("\nLoses: ".to_owned(), light_gray())
.push(format!("{}/3", run.state.loses), white())
.take();
let color = match win {
true => {
hex_color!("#80D8FF")
}
false => hex_color!("#FF1744"),
};

BattleEnd::Victory => format!(":)"),
};
let color = match end {
BattleEnd::Defeat => hex_color!("#FF1744"),
BattleEnd::Victory => {
hex_color!("#80D8FF")
}
};

window("BATTLE END")
.set_width(400.0)
.set_color(color)
.anchor(Align2::CENTER_CENTER, [0.0, -200.0])
.show(ctx, |ui| {
frame(ui, |ui| {
ui.heading(text.add_color(color).rich_text());
ui.label(subtext.add_color(white()).rich_text());
ui.columns(2, |ui| {
ui[0].vertical_centered_justified(|ui| {
if ui.button("REPLAY").clicked() {
let t = -AudioPlugin::to_next_beat(world);
GameTimer::get().play_head_to(t);
}
});
ui[1].vertical_centered_justified(|ui| {
if ui.button_primary("OK").clicked() {
match end {
BattleEnd::Defeat => {
GameState::MainMenu.change(world);
}
BattleEnd::Victory => {
GameState::Shop.change(world);
window("BATTLE END")
.set_width(400.0)
.set_color(color)
.anchor(Align2::CENTER_CENTER, [0.0, -200.0])
.show(ctx, |ui| {
frame(ui, |ui| {
ui.heading(text.add_color(color).rich_text());
ui.label(subtext.widget());
ui.columns(2, |ui| {
ui[0].vertical_centered_justified(|ui| {
if ui.button("REPLAY").clicked() {
let t = -AudioPlugin::to_next_beat(world);
GameTimer::get().play_head_to(t);
}
});
ui[1].vertical_centered_justified(|ui| {
if ui.button_primary("OK").clicked() {
match win {
true => {
GameState::Shop.change(world);
}
false => {
GameState::MainMenu.change(world);
}
}
}
}
});
})
});
})
});
});
});
}
}
}

Expand All @@ -252,3 +234,13 @@ pub enum BattleResult {
Right(usize),
Even,
}

impl BattleResult {
pub fn is_win(&self) -> Option<bool> {
match self {
BattleResult::Tbd => None,
BattleResult::Left(..) | BattleResult::Even => Some(true),
BattleResult::Right(..) => Some(false),
}
}
}
10 changes: 4 additions & 6 deletions src/plugins/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,11 @@ pub struct RegisterData {
pub pass_repeat: String,
}

#[derive(BevyEvent)]
pub struct LoginEvent;

impl Plugin for LoginPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, Self::setup)
app.add_systems(OnExit(GameState::Loading), Self::setup)
.init_resource::<LoginData>()
.init_resource::<RegisterData>()
.add_event::<LoginEvent>();
.init_resource::<RegisterData>();
}
}

Expand Down Expand Up @@ -153,6 +149,7 @@ impl LoginPlugin {
Status::Committed => {
let user = User::find(|u| u.identities.contains(identity)).unwrap();
Self::save_current_user(user.name, user.id, identity.clone());
OperationsPlugin::add(|w| PoolsPlugin::cache_server_pools(w));
}
Status::Failed(e) => {
AlertPlugin::add_error(
Expand Down Expand Up @@ -275,6 +272,7 @@ fn subscribe_to_tables(user_id: u64) {
"select * from Ability",
"select * from Vfx",
&format!("select * from ArenaRun where user_id = {user_id}"),
"select * from ArenaPool",
]) {
Ok(_) => debug!("Subscribe successful"),
Err(e) => error!("Subscription error: {e}"),
Expand Down
4 changes: 2 additions & 2 deletions src/plugins/main_menu.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::module_bindings::{once_on_run_start, run_start};
use crate::module_bindings::{once_on_run_start, run_start, ArenaRun};

use super::*;
pub struct MainMenuPlugin;
Expand Down Expand Up @@ -34,7 +34,7 @@ impl MainMenuPlugin {
ui.label(format!("Welcome {name}!"));
});
frame(ui, |ui| {
let enabled = false;
let enabled = ArenaRun::filter_by_active(true).next().is_some();
ui.set_enabled(enabled);
let btn = if enabled {
ui.button_primary("CONTINUE")
Expand Down
Loading

0 comments on commit 0fba14b

Please sign in to comment.