extern crate ggez;
extern crate statez;
use ggez::{conf, event, graphics, Context, GameResult};
use statez::{State, StateManager, StateTransition};
#[derive(Default)]
struct SharedData;
#[derive(Default)]
struct StateOne {
go_to_next_state: bool,
}
#[derive(Default)]
struct StateTwo {
go_to_next_state: bool,
}
impl State<SharedData> for StateOne {
fn update(
&mut self,
_shared_data: &mut SharedData,
_ctx: &mut Context,
) -> GameResult<StateTransition<SharedData>> {
if self.go_to_next_state {
Ok(StateTransition::Replace(Box::new(StateTwo::default())))
} else {
Ok(StateTransition::None)
}
}
fn draw(&mut self, _shared_data: &mut SharedData, ctx: &mut Context) -> GameResult<()> {
graphics::set_background_color(ctx, graphics::WHITE);
graphics::clear(ctx);
graphics::present(ctx);
Ok(())
}
fn key_up_event(
&mut self,
_shared_data: &mut SharedData,
_ctx: &mut Context,
keycode: event::Keycode,
_keymod: event::Mod,
_repeat: bool,
) {
if keycode == event::Keycode::Space {
self.go_to_next_state = true;
}
}
}
impl State<SharedData> for StateTwo {
fn update(
&mut self,
_shared_data: &mut SharedData,
_ctx: &mut Context,
) -> GameResult<StateTransition<SharedData>> {
if self.go_to_next_state {
Ok(StateTransition::Replace(Box::new(StateOne::default())))
} else {
Ok(StateTransition::None)
}
}
fn draw(&mut self, _shared_data: &mut SharedData, ctx: &mut Context) -> GameResult<()> {
graphics::set_background_color(ctx, graphics::BLACK);
graphics::clear(ctx);
graphics::present(ctx);
Ok(())
}
fn key_up_event(
&mut self,
_shared_data: &mut SharedData,
_ctx: &mut Context,
keycode: event::Keycode,
_keymod: event::Mod,
_repeat: bool,
) {
if keycode == event::Keycode::Space {
self.go_to_next_state = true;
}
}
}
fn main() {
let mut conf = conf::Conf::new();
conf.window_setup =
conf::WindowSetup::default().title("statez - hello_world - press space to swap state");
let ctx = &mut Context::load_from_conf("hello_world", "statez", conf)
.expect("Unable to create context");
let shared_data = SharedData::default();
let state_manager = &mut StateManager::new(shared_data, Box::new(StateOne::default()));
event::run(ctx, state_manager).expect("Fatal error");
println!("Terminated successfully.");
}