diff options
| author | Mica White <botahamec@outlook.com> | 2026-10-31 12:38:00 -0400 |
|---|---|---|
| committer | Mica White <botahamec@outlook.com> | 2026-10-31 12:38:00 -0400 |
| commit | 3b39c7561ec71dadb0cb03a153550e9a6e2cddff (patch) | |
| tree | c4d5dd4b4314371a818053c4c6741209967089b3 /src | |
| parent | 2987e310e8e6eaeaa60546bb92a61d9c3713263a (diff) | |
Diffstat (limited to 'src')
| -rw-r--r-- | src/detect_controller.rs | 13 | ||||
| -rw-r--r-- | src/exit_on_escape.rs | 4 | ||||
| -rw-r--r-- | src/main.rs | 43 | ||||
| -rw-r--r-- | src/move_snake.rs | 30 | ||||
| -rw-r--r-- | src/render.rs | 259 | ||||
| -rw-r--r-- | src/render_frametime.rs | 37 | ||||
| -rw-r--r-- | src/snake_controller.rs | 90 | ||||
| -rw-r--r-- | src/update_high_score.rs | 14 |
8 files changed, 390 insertions, 100 deletions
diff --git a/src/detect_controller.rs b/src/detect_controller.rs new file mode 100644 index 0000000..2890826 --- /dev/null +++ b/src/detect_controller.rs @@ -0,0 +1,13 @@ +use tortuise_script::TortuiseScript; + +use crate::CONNECTED_GAMEPAD_QUEUE; + +pub const DETECT_CONTROLLER: TortuiseScript = TortuiseScript { + update: |context| { + let mut connected_gamepads = CONNECTED_GAMEPAD_QUEUE.get_mut(&context); + if let Some(gamepad) = context.is_gamepad_connected_this_frame() { + connected_gamepads.push(gamepad); + } + }, + ..TortuiseScript::empty() +}; diff --git a/src/exit_on_escape.rs b/src/exit_on_escape.rs index a7885ca..8748244 100644 --- a/src/exit_on_escape.rs +++ b/src/exit_on_escape.rs @@ -2,7 +2,9 @@ use tortuise_script::{input::KeyCode, ScriptContext, TortuiseScript}; pub const EXIT_ON_ESCAPE: TortuiseScript = TortuiseScript { update: |mut context: ScriptContext| { - if context.is_key_pressed_this_frame(KeyCode::Esc) { + if context.is_key_pressed_this_frame(KeyCode::Esc) + || context.is_key_pressed_this_frame(KeyCode::Char('q')) + { context.exit(); } }, diff --git a/src/main.rs b/src/main.rs index 3b6605a..bf6eae4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,16 +1,25 @@ -#![cfg_attr(target_arch = "wasm32", no_std)] +#![no_std] #![cfg_attr(target_arch = "wasm32", no_main)] extern crate alloc; +mod detect_controller; mod exit_on_escape; mod move_snake; mod render; +mod render_frametime; mod snake_controller; +mod update_high_score; use alloc::vec::Vec; use core::time::Duration; -use tortuise_script::{entity::Entity, time::Instant, TortuiseScene}; +use tortuise_script::{ + entity::Entity, + input::Gamepad, + storage::{Config, Storage}, + time::Instant, + TortuiseScene, +}; use serde::{Deserialize, Serialize}; @@ -20,8 +29,25 @@ struct Position { pub y: i16, } +#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +struct SaveData { + high_score: usize, +} + +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +struct ConfigOptions { + #[serde(default)] + framerate_limit: Option<u32>, +} + const GRID_SIZE: u16 = 16; +static SAVE_DATA: Storage<SaveData> = Storage::new(SaveData::default); +static CONFIG: Config<ConfigOptions> = Config::new(ConfigOptions::default); + +static CONNECTED_GAMEPAD_QUEUE: Entity<Vec<Gamepad>> = + Entity::new("connected_gamepad_queue", |_| Vec::new()); +static IS_PAUSED: Entity<bool> = Entity::new("is_paused", |_| false); static APPLE_LOCATION: Entity<Position> = Entity::new("apple_location", |_| Position { x: 2, y: 2 }); static SNAKE_CELLS: Entity<Vec<Position>> = Entity::new("snake_cells", |_| { @@ -39,10 +65,21 @@ tortuise_script::game! { first_scene: "main", scenes: { "main" => TortuiseScene { - scripts: &["snake_controller", "exit_on_escape", "move_snake", "render"], + scripts: &[ + "frametime", + "detect_controller", + "update_high_score", + "snake_controller", + "exit_on_escape", + "move_snake", + "render" + ], } }, scripts: { + "frametime" => render_frametime::RENDER_FRAMETIME, + "detect_controller" => detect_controller::DETECT_CONTROLLER, + "update_high_score" => update_high_score::UPDATE_HIGH_SCORE, "snake_controller" => snake_controller::SNAKE_CONTROLLER, "exit_on_escape" => exit_on_escape::EXIT_ON_ESCAPE, "move_snake" => move_snake::MOVE_SNAKE, diff --git a/src/move_snake.rs b/src/move_snake.rs index 453e795..4439be5 100644 --- a/src/move_snake.rs +++ b/src/move_snake.rs @@ -1,10 +1,11 @@ use core::time::Duration; -use alloc::vec::Vec; use rand::RngExt; use tortuise_script::{random::TortuiseRng, time::Instant, ScriptContext, TortuiseScript}; -use crate::{Position, APPLE_LOCATION, DIRECTION, GRID_SIZE, NEXT_MOVE_TIME, SNAKE_CELLS}; +use crate::{ + Position, APPLE_LOCATION, DIRECTION, GRID_SIZE, IS_PAUSED, NEXT_MOVE_TIME, SNAKE_CELLS, +}; pub const MOVE_SNAKE: TortuiseScript = TortuiseScript { update: |context: ScriptContext| { @@ -12,26 +13,16 @@ pub const MOVE_SNAKE: TortuiseScript = TortuiseScript { let mut snake_cells = SNAKE_CELLS.get_mut(&context); let mut next_move = NEXT_MOVE_TIME.get_mut(&context); let direction = DIRECTION.get(&context); - - let mut available_squares = - Vec::with_capacity((GRID_SIZE * GRID_SIZE) as usize - snake_cells.len()); - for i in 0..GRID_SIZE { - for j in 0..GRID_SIZE { - let position = Position { - x: i as i16, - y: j as i16, - }; - if !snake_cells.contains(&position) { - available_squares.push(position); - } - } - } + let is_paused = IS_PAUSED.get(&context); let mut rng = TortuiseRng::new(); let time = Instant::now(&context); - if time > *next_move { + if time > *next_move && !*is_paused { if snake_cells[0] == *apple_location { - *apple_location = available_squares[rng.random_range(0..available_squares.len())]; + *apple_location = Position { + x: rng.random_range(0..GRID_SIZE as i16), + y: rng.random_range(0..GRID_SIZE as i16), + }; let new_head = Position { x: snake_cells[0].x + direction.x, y: snake_cells[0].y + direction.y, @@ -45,6 +36,9 @@ pub const MOVE_SNAKE: TortuiseScript = TortuiseScript { snake_cells[0].x += direction.x; snake_cells[0].y += direction.y; } + if time > *next_move { + *next_move += Duration::from_millis(200); + } }, ..TortuiseScript::empty() }; diff --git a/src/render.rs b/src/render.rs index 80b06f7..77075f7 100644 --- a/src/render.rs +++ b/src/render.rs @@ -1,39 +1,82 @@ -use alloc::string::ToString; +use alloc::format; +use hashbrown::HashSet; +use serde::{Deserialize, Serialize}; use tortuise_script::{ - buffer::{Cell, Color}, + buffer::{Cell, Color, WindowSize}, + state::ScriptState, ScriptContext, TortuiseScript, }; -use crate::{APPLE_LOCATION, GRID_SIZE, SNAKE_CELLS}; +use crate::{Position, APPLE_LOCATION, GRID_SIZE, IS_PAUSED, SAVE_DATA, SNAKE_CELLS}; + +#[derive(Serialize, Deserialize)] +struct OldState { + old_snake_cells: HashSet<Position>, + old_score: usize, + old_high_score: usize, + old_window_size: WindowSize, +} + +static OLD_STATE: ScriptState<OldState> = ScriptState::new(|_| OldState { + old_snake_cells: HashSet::new(), + old_score: usize::MAX, + old_high_score: usize::MAX, + old_window_size: WindowSize { + rows: 0, + columns: 0, + }, +}); + +fn draw_text(cx: &mut ScriptContext, text: &str, x: u16, y: u16) { + for (x, character) in (x..).zip(text.chars()) { + cx.add_eternal_cell(Cell { + character, + x, + y, + ..Cell::default() + }); + } +} + +fn remove_text(cx: &mut ScriptContext, text: &str, x: u16, y: u16) { + for (x, character) in (x..).zip(text.chars()) { + cx.remove_eternal_cell(Cell { + character, + x, + y, + ..Cell::default() + }); + } +} fn draw_box(cx: &mut ScriptContext, char: char, x: u16, y: u16) { for i in 1..5 { - cx.add_cell(Cell { + cx.add_eternal_cell(Cell { character: '-', x: x + i, y, ..Default::default() }); - cx.add_cell(Cell { + cx.add_eternal_cell(Cell { character: '-', x: x + i, y: y + 2, ..Default::default() }); } - cx.add_cell(Cell { + cx.add_eternal_cell(Cell { character: '|', x, y: y + 1, ..Default::default() }); - cx.add_cell(Cell { + cx.add_eternal_cell(Cell { character: '|', x: x + 5, y: y + 1, ..Default::default() }); - cx.add_cell(Cell { + cx.add_eternal_cell(Cell { character: char, x: x + 3, y: y + 1, @@ -41,71 +84,144 @@ fn draw_box(cx: &mut ScriptContext, char: char, x: u16, y: u16) { }); } +fn draw_grid(context: &mut ScriptContext<'_>, offset_x: u16, offset_y: u16) { + for i in 0..GRID_SIZE { + context.add_eternal_cell(Cell { + character: '|', + x: offset_x.saturating_sub(1), + y: offset_y + i, + z: 0, + ..Default::default() + }); + context.add_eternal_cell(Cell { + character: '|', + x: offset_x + GRID_SIZE, + y: offset_y + i, + z: 0, + ..Default::default() + }); + context.add_eternal_cell(Cell { + character: '-', + x: offset_x + i, + y: offset_y.saturating_sub(1), + z: 0, + ..Default::default() + }); + context.add_eternal_cell(Cell { + character: '-', + x: offset_x + i, + y: offset_y + GRID_SIZE, + z: 0, + ..Default::default() + }); + } +} + +fn delete_grid(context: &mut ScriptContext<'_>, offset_x: u16, offset_y: u16) { + for i in 0..GRID_SIZE { + context.remove_eternal_cell(Cell { + character: '|', + x: offset_x.saturating_sub(1), + y: offset_y + i, + z: 0, + ..Default::default() + }); + context.remove_eternal_cell(Cell { + character: '|', + x: offset_x + GRID_SIZE, + y: offset_y + i, + z: 0, + ..Default::default() + }); + context.remove_eternal_cell(Cell { + character: '-', + x: offset_x + i, + y: offset_y.saturating_sub(1), + z: 0, + ..Default::default() + }); + context.remove_eternal_cell(Cell { + character: '-', + x: offset_x + i, + y: offset_y + GRID_SIZE, + z: 0, + ..Default::default() + }); + } +} + pub const RENDER: TortuiseScript = TortuiseScript { + start: |mut context| { + draw_box(&mut context, '<', 4, 4); + draw_box(&mut context, '>', 16, 4); + draw_box(&mut context, '^', 10, 1); + draw_box(&mut context, 'v', 10, 7); + }, update: |mut context: ScriptContext| { + let mut old_state = OLD_STATE.get_mut(&context); let apple_location = APPLE_LOCATION.get(&context); let snake_cells = SNAKE_CELLS.get(&context); + let is_paused = IS_PAUSED.get(&context); + let high_score = SAVE_DATA.load(&context).high_score; + + let old_window_size = old_state.old_window_size; + let old_offset_x = (old_window_size.columns.saturating_sub(GRID_SIZE) / 2).max(24); + let old_offset_y = old_window_size.rows.saturating_sub(GRID_SIZE) / 2; let window_size = context.window_size(); - let offset_x = window_size.columns.saturating_sub(GRID_SIZE) / 2; + let offset_x = (window_size.columns.saturating_sub(GRID_SIZE) / 2).max(24); let offset_y = window_size.rows.saturating_sub(GRID_SIZE) / 2; - - for i in 0..GRID_SIZE { - context.add_cell(Cell { - character: '|', - x: offset_x.saturating_sub(1), - y: offset_y + i, - z: 0, - ..Default::default() - }); - context.add_cell(Cell { - character: '|', - x: offset_x + GRID_SIZE, - y: offset_y + i, - z: 0, - ..Default::default() - }); - context.add_cell(Cell { - character: '-', - x: offset_x + i, - y: offset_y.saturating_sub(1), - z: 0, - ..Default::default() - }); - context.add_cell(Cell { - character: '-', - x: offset_x + i, - y: offset_y + GRID_SIZE, - z: 0, - ..Default::default() - }); + if window_size != old_window_size { + old_state.old_window_size = window_size; + delete_grid(&mut context, old_offset_x, old_offset_y); + draw_grid(&mut context, offset_x, offset_y); } - for (i, char) in "Score:".chars().enumerate() { - context.add_cell(Cell { - character: char, - x: offset_x + GRID_SIZE - 10 + i as u16, - y: offset_y.saturating_sub(2), - ..Default::default() - }); + let old_score = old_state.old_score; + let score = snake_cells.len() - 2; + if score != old_score || window_size != old_window_size { + old_state.old_score = score; + let score_counter = format!("Score: {score:>3}"); + let old_score_counter = format!("Score: {old_score:>3}"); + remove_text( + &mut context, + &old_score_counter, + offset_x + GRID_SIZE - 10, + offset_y.saturating_sub(2), + ); + draw_text( + &mut context, + &score_counter, + offset_x + GRID_SIZE - 10, + offset_y.saturating_sub(2), + ); } - draw_box(&mut context, '<', 4, 4); - draw_box(&mut context, '>', 16, 4); - draw_box(&mut context, '^', 10, 1); - draw_box(&mut context, 'v', 10, 7); + let old_high_score = old_state.old_high_score; + if high_score != old_high_score || window_size != old_window_size { + old_state.old_high_score = high_score; + let score_counter = format!("High Score: {high_score:>3}"); + let old_score_counter = format!("High Score: {old_high_score:>3}"); + remove_text( + &mut context, + &old_score_counter, + offset_x + GRID_SIZE - 15, + offset_y.saturating_sub(3), + ); + draw_text( + &mut context, + &score_counter, + offset_x + GRID_SIZE - 15, + offset_y.saturating_sub(3), + ); + } - for (i, char) in (snake_cells.len() - 2) - .to_string() - .chars() - .rev() - .enumerate() - { - context.add_cell(Cell { - character: char, - x: offset_x + GRID_SIZE - i as u16, - y: offset_y.saturating_sub(2), - ..Default::default() - }); + if *is_paused { + draw_text( + &mut context, + "-- Paused --", + offset_x + 2, + offset_y + GRID_SIZE + 1, + ); } context.add_cell(Cell { @@ -116,8 +232,22 @@ pub const RENDER: TortuiseScript = TortuiseScript { z: 0, ..Default::default() }); - for cell in &*snake_cells { - context.add_cell(Cell { + + let snake_cells = HashSet::from_iter(snake_cells.iter().cloned()); + let old_snake_cells = old_state.old_snake_cells.difference(&snake_cells); + let new_snake_cells = snake_cells.difference(&old_state.old_snake_cells); + for cell in old_snake_cells { + context.remove_eternal_cell(Cell { + character: '█', + foreground_color: Color::Green, + x: cell.x.unsigned_abs() + offset_x, + y: cell.y.unsigned_abs() + offset_y, + z: 1, + ..Default::default() + }); + } + for cell in new_snake_cells { + context.add_eternal_cell(Cell { character: '█', foreground_color: Color::Green, x: cell.x.unsigned_abs() + offset_x, @@ -126,6 +256,7 @@ pub const RENDER: TortuiseScript = TortuiseScript { ..Default::default() }); } + old_state.old_snake_cells = snake_cells; }, ..TortuiseScript::empty() }; diff --git a/src/render_frametime.rs b/src/render_frametime.rs new file mode 100644 index 0000000..6756fa7 --- /dev/null +++ b/src/render_frametime.rs @@ -0,0 +1,37 @@ +use alloc::format; +use tortuise_script::{buffer::Cell, TortuiseScript}; + +use crate::CONFIG; + +pub const RENDER_FRAMETIME: TortuiseScript = TortuiseScript { + start: |mut cx| { + let config = CONFIG.load_mut(&mut cx); + let fps_limit = config.framerate_limit; + drop(config); + cx.set_framerate_limit(fps_limit); + }, + update: |mut cx| { + let frametime = cx.delta_time().as_micros(); + let fps = 1_000_000u128.checked_div(frametime).unwrap_or(u128::MAX); + let frametime = format!("{frametime:05} us"); + let counter = format!("{fps} FPS"); + + for (x, character) in (9..).zip(frametime.chars()) { + cx.add_cell(Cell { + character, + y: 14, + x, + ..Cell::default() + }); + } + for (x, character) in (9..).zip(counter.chars()) { + cx.add_cell(Cell { + character, + y: 15, + x, + ..Cell::default() + }); + } + }, + ..TortuiseScript::empty() +}; diff --git a/src/snake_controller.rs b/src/snake_controller.rs index 0c48175..15dfcea 100644 --- a/src/snake_controller.rs +++ b/src/snake_controller.rs @@ -1,9 +1,9 @@ use tortuise_script::{ - input::{KeyCode, Position as MousePosition}, + input::{Button, Direction, Gamepad, KeyCode, Position as MousePosition}, ScriptContext, TortuiseScript, }; -use crate::{Position, DIRECTION}; +use crate::{Position, CONNECTED_GAMEPAD_QUEUE, DIRECTION, IS_PAUSED}; fn is_inside_box(mouse: Option<MousePosition>, button: MousePosition, size: u16) -> bool { mouse.is_some_and(|mouse| { @@ -12,25 +12,87 @@ fn is_inside_box(mouse: Option<MousePosition>, button: MousePosition, size: u16) }) } +fn did_move_left( + context: &ScriptContext, + mouse_location: Option<MousePosition>, + scroll_direction: Option<Direction>, + gamepad: Option<Gamepad>, +) -> bool { + is_inside_box(mouse_location, MousePosition { x: 4, y: 4 }, 3) + || scroll_direction == Some(Direction::Right) + || gamepad.is_some_and(|gamepad| gamepad.is_button_down(context, Button::DPadLeft)) + || context.is_key_pressed_this_frame(KeyCode::Left) + || context.is_key_pressed_this_frame(KeyCode::Char('h')) + || context.is_key_pressed_this_frame(KeyCode::Char('a')) +} + +fn did_move_right( + context: &ScriptContext, + mouse_location: Option<MousePosition>, + scroll_direction: Option<Direction>, + gamepad: Option<Gamepad>, +) -> bool { + is_inside_box(mouse_location, MousePosition { x: 16, y: 4 }, 3) + || scroll_direction == Some(Direction::Left) + || gamepad.is_some_and(|gamepad| gamepad.is_button_down(context, Button::DPadRight)) + || context.is_key_pressed_this_frame(KeyCode::Right) + || context.is_key_pressed_this_frame(KeyCode::Char('d')) + || context.is_key_pressed_this_frame(KeyCode::Char('l')) +} + +fn did_move_up( + context: &ScriptContext, + mouse_location: Option<MousePosition>, + scroll_direction: Option<Direction>, + gamepad: Option<Gamepad>, +) -> bool { + is_inside_box(mouse_location, MousePosition { x: 10, y: 1 }, 3) + || scroll_direction == Some(Direction::Down) + || gamepad.is_some_and(|gamepad| gamepad.is_button_down(context, Button::DPadUp)) + || context.is_key_pressed_this_frame(KeyCode::Up) + || context.is_key_pressed_this_frame(KeyCode::Char('w')) + || context.is_key_pressed_this_frame(KeyCode::Char('k')) +} + +fn did_move_down( + context: &ScriptContext, + mouse_location: Option<MousePosition>, + scroll_direction: Option<Direction>, + gamepad: Option<Gamepad>, +) -> bool { + is_inside_box(mouse_location, MousePosition { x: 10, y: 7 }, 3) + || scroll_direction == Some(Direction::Up) + || gamepad.is_some_and(|gamepad| gamepad.is_button_down(context, Button::DPadDown)) + || context.is_key_pressed_this_frame(KeyCode::Down) + || context.is_key_pressed_this_frame(KeyCode::Char('s')) + || context.is_key_pressed_this_frame(KeyCode::Char('j')) +} + pub const SNAKE_CONTROLLER: TortuiseScript = TortuiseScript { update: |context: ScriptContext| { let mut direction = DIRECTION.get_mut(&context); + let mut is_paused = IS_PAUSED.get_mut(&context); + let gamepad = CONNECTED_GAMEPAD_QUEUE.get(&context).first().copied(); + + if context.was_unfocused_this_frame() { + *is_paused = true; + } + if context.is_key_pressed_this_frame(KeyCode::Char('p')) { + *is_paused = !*is_paused; + } + if *is_paused { + return; + } + let mouse_location = context.mouse_location(); - if is_inside_box(mouse_location, MousePosition { x: 4, y: 4 }, 3) { + let scroll_direction = context.scroll_direction_this_frame(); + if did_move_left(&context, mouse_location, scroll_direction, gamepad) { *direction = Position { x: -1, y: 0 }; - } else if is_inside_box(mouse_location, MousePosition { x: 16, y: 4 }, 3) { + } else if did_move_right(&context, mouse_location, scroll_direction, gamepad) { *direction = Position { x: 1, y: 0 }; - } else if is_inside_box(mouse_location, MousePosition { x: 10, y: 1 }, 3) { + } else if did_move_up(&context, mouse_location, scroll_direction, gamepad) { *direction = Position { x: 0, y: -1 }; - } else if is_inside_box(mouse_location, MousePosition { x: 10, y: 7 }, 3) { - *direction = Position { x: 0, y: 1 }; - } else if context.is_key_pressed_this_frame(KeyCode::Up) { - *direction = Position { x: 0, y: -1 }; - } else if context.is_key_pressed_this_frame(KeyCode::Right) { - *direction = Position { x: 1, y: 0 }; - } else if context.is_key_pressed_this_frame(KeyCode::Left) { - *direction = Position { x: -1, y: 0 }; - } else if context.is_key_pressed_this_frame(KeyCode::Down) { + } else if did_move_down(&context, mouse_location, scroll_direction, gamepad) { *direction = Position { x: 0, y: 1 }; } }, diff --git a/src/update_high_score.rs b/src/update_high_score.rs new file mode 100644 index 0000000..b38b08a --- /dev/null +++ b/src/update_high_score.rs @@ -0,0 +1,14 @@ +use tortuise_script::TortuiseScript; + +use crate::{SAVE_DATA, SNAKE_CELLS}; + +pub const UPDATE_HIGH_SCORE: TortuiseScript = TortuiseScript { + update: |mut context| { + let score = SNAKE_CELLS.get(&context).len() - 2; + let mut save = SAVE_DATA.load_mut(&mut context); + if save.high_score < score { + save.high_score = score; + } + }, + ..TortuiseScript::empty() +}; |
