Function pixel_game_lib::window

source ·
pub fn window<G, U, R>(
    game_state: G,
    window_config: WindowConfig,
    update: U,
    render: R
) -> Result<()>
where G: 'static, U: FnMut(&mut G, &WinitInputHelper, Option<Vec2<usize>>, f32) -> bool + 'static, R: FnMut(&mut G, &mut [u32], f32) + 'static,
Expand description

Create a new window with an event loop and run the game.

Arguments

  • game_state - Global state passed around in the render and update functions.
  • window_config - Configuration options for the window.
  • update - Function called every update tick, arguments are the state, window input event that can be used to handle input events, mouse position in pixels and the time between this and the previous tick. When true is returned the window will be closed.
  • render - Function called every render tick, arguments are the state and the time between this and the previous tick.
Examples found in repository?
examples/window.rs (lines 25-47)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
fn main() {
    // Active modifiable state
    let state = GameState { pixels_to_draw: 0 };

    // Window configuration with huge pixels
    let window_config = WindowConfig {
        buffer_size: Extent2::new(64, 64),
        scaling: 8,
        ..Default::default()
    };

    // Open the window and start the game-loop
    pixel_game_lib::window(
        state,
        window_config.clone(),
        // Update loop exposing input events we can handle, this is where you would handle the game logic
        |state, input, _mouse, _dt| {
            // Increment when mouse is clicked
            if input.mouse_held(0) {
                state.pixels_to_draw += 1;
            }

            // Exit when escape is pressed
            input.key_pressed(Key::Escape)
        },
        // Render loop exposing the pixel buffer we can mutate
        move |state, canvas, _dt| {
            // Ensure that we don't draw pixels outside of the canvas
            let max_pixels_to_draw = window_config.buffer_size.product();
            let pixels_to_draw = state.pixels_to_draw.min(max_pixels_to_draw);

            // Draw a red color for each pixel
            canvas[0..pixels_to_draw].fill(0xFFFF0000);
        },
    )
    .expect("Error opening window");
}