Trait dunge::Update

source ·
pub trait Update: Draw {
    type Flow: Flow;
    type Event: 'static;

    // Required method
    fn update(&mut self, ctrl: &Control) -> Self::Flow;

    // Provided method
    fn event(&mut self, _: Self::Event) { ... }
}
Expand description

The update stage.

This trait handles the application’s state updation by taking a control object and returns a variant of the execution control flow. It also allows you to handle arbitrary custom events.

§Example

use dunge::{Draw, Control, Frame, KeyCode, Then, Update};

struct App {/***/}

impl Draw for App {
    fn draw(&self, mut frame: Frame) {/***/}
}

impl Update for App {
    type Flow = Then;
    type Event = ();

    fn update(&mut self, ctrl: &Control) -> Then {
        for key in ctrl.pressed_keys() {
            // Exit by pressing escape key
            if key.code == KeyCode::Escape {
                return Then::Close;
            }
        }

        // Otherwise continue running
        Then::Run
    }
}

Instead of manually implementing the trait, you can use an helper function that will make an implementation from a closure:

use dunge::{Control, Frame, KeyCode, Then, Update};

fn make_update() -> impl Update {
    let draw = |frame: Frame| {/***/};
    let upd = |ctrl: &Control| -> Then {
        for key in ctrl.pressed_keys() {
            if key.code == KeyCode::Escape {
                return Then::Close;
            }
        }

        Then::Run
    };

    dunge::update(upd, draw)
}

§Shared state

Draw and update stages may share some state. This is not a problem to implement traits manually for some type. However, to be able to use helpers, dunge has the update_with_state function.

use dunge::{Control, Frame, Update};

struct State { counter: usize }

fn make_update() -> impl Update {
    let draw = |state: &State, frame: Frame| {
        dbg!(state.counter);
    };

    let upd = |state: &mut State, ctrl: &Control| {
        state.counter += 1;
    };

    let state = State { counter: 0 };
    dunge::update_with_state(state, upd, draw)
}

Also see the update_with_event function to set a custom event handler.

Required Associated Types§

source

type Flow: Flow

source

type Event: 'static

Required Methods§

source

fn update(&mut self, ctrl: &Control) -> Self::Flow

Provided Methods§

source

fn event(&mut self, _: Self::Event)

Implementors§