Add tick thread and Skirmish state update #1

Merged
GarandPLG merged 2 commits from todo_gameplayloop into main 2026-05-03 22:28:33 +02:00
10 changed files with 148 additions and 79 deletions
+24 -21
View File
@@ -1,17 +1,13 @@
use crate::{
app::{
GameStates, handle_keybindings,
threads::{AppEvent, AudioCmd},
threads::{AppChannels, AudioCmd},
view::View,
},
cli::Cli,
};
use ratatui::{DefaultTerminal, Frame, crossterm::event::KeyEvent, layout::Rect};
use std::{
io::Result,
sync::mpsc::{Receiver, RecvTimeoutError, Sender},
time::Duration,
};
use std::{io::Result, sync::mpsc::Sender, thread::sleep, time::Duration};
pub struct App {
pub exit: bool,
@@ -42,30 +38,29 @@ impl App {
self.states.as_mut()
}
pub fn run(&mut self, terminal: &mut DefaultTerminal, rx: Receiver<AppEvent>) -> Result<()> {
pub fn run(&mut self, terminal: &mut DefaultTerminal, channels: AppChannels) -> Result<()> {
while !self.exit {
terminal.draw(|frame: &mut Frame<'_>| self.draw(frame))?;
let event = match rx.recv_timeout(Duration::from_millis(100)) {
Ok(ev) => ev,
Err(RecvTimeoutError::Timeout) => {
continue;
}
Err(_) => break,
};
match event {
AppEvent::Input(key_event) => self.handle_key_event(key_event)?,
AppEvent::Resize(_, _) => {
let window_area: Rect = self.window_area;
let Some(state) = self.states_mut() else {
panic!("State issue")
};
if let Ok(key) = channels.input_rx.try_recv() {
self.handle_key_event(key)?;
}
if let Ok((_, _)) = channels.resize_rx.try_recv() {
let window_area: Rect = self.window_area;
if let Some(state) = self.states_mut() {
state
.skirmish
.board
.change_resize(&window_area, state.skirmish.side_panel);
}
}
if let Ok(()) = channels.tick_rx.try_recv() {
self.update()?;
}
sleep(Duration::from_millis(10));
}
Ok(())
@@ -90,4 +85,12 @@ impl App {
handle_keybindings(self, key_event);
Ok(())
}
fn update(&mut self) -> Result<()> {
if let Some(state) = self.states_mut() {
state.skirmish.tick_update();
}
Ok(())
}
}
+1
View File
@@ -35,6 +35,7 @@ impl GameStates {
false,
),
side_panel: false,
turn_counter: 0,
},
perk_decks: PerkDecksState {
id: 2,
+11
View File
@@ -6,4 +6,15 @@ pub struct SkirmishState {
pub name: &'static str,
pub board: BoardState,
pub side_panel: bool,
pub turn_counter: u64,
}
impl SkirmishState {
pub fn tick_update(&mut self) {
// self.board.advance_turn();
// if self.board.is_victory() {}
self.turn_counter += 1;
}
}
+37
View File
@@ -0,0 +1,37 @@
use crate::app::threads::AudioCmd;
use ratatui::crossterm::event::KeyEvent;
use std::sync::mpsc::{Receiver, Sender, channel};
pub struct AppChannels {
pub input_tx: Sender<KeyEvent>,
pub input_rx: Receiver<KeyEvent>,
pub resize_tx: Sender<(u16, u16)>,
pub resize_rx: Receiver<(u16, u16)>,
pub tick_tx: Sender<()>,
pub tick_rx: Receiver<()>,
pub audio_tx: Sender<AudioCmd>,
pub audio_rx: Receiver<AudioCmd>,
}
impl AppChannels {
pub fn new() -> Self {
let (input_tx, input_rx) = channel::<KeyEvent>();
let (resize_tx, resize_rx) = channel::<(u16, u16)>();
let (tick_tx, tick_rx) = channel::<()>();
let (audio_tx, audio_rx) = channel::<AudioCmd>();
Self {
input_tx,
input_rx,
resize_tx,
resize_rx,
tick_tx,
tick_rx,
audio_tx,
audio_rx,
}
}
}
+11 -20
View File
@@ -1,29 +1,20 @@
use ratatui::crossterm::event::KeyEvent;
use ratatui::crossterm::event::{Event, read};
use ratatui::crossterm::event::{Event, KeyEvent, read};
use std::sync::mpsc::Sender;
pub enum AppEvent {
Input(KeyEvent),
Resize(u16, u16),
}
/// Reads *all* crossterm events and forwards the ones we care about.
pub fn handle_events(tx: Sender<AppEvent>) {
pub fn handle_ct_events(input_tx: Sender<KeyEvent>, resize_tx: Sender<(u16, u16)>) {
loop {
match read() {
Ok(ev) => match ev {
Event::Key(key) => {
if tx.send(AppEvent::Input(key)).is_err() {
break;
}
Ok(Event::Key(k)) => {
if input_tx.send(k).is_err() {
break;
}
Event::Resize(cols, rows) => {
if tx.send(AppEvent::Resize(cols, rows)).is_err() {
break;
}
}
Ok(Event::Resize(cols, rows)) => {
if resize_tx.send((cols, rows)).is_err() {
break;
}
_ => {}
},
}
Ok(_) => {}
Err(_) => continue,
}
}
+5 -1
View File
@@ -1,5 +1,9 @@
mod app_channels;
mod audio;
mod events;
mod tick;
pub use app_channels::AppChannels;
pub use audio::{AudioCmd, SoundrackParts, Soundtrack, handle_audio};
pub use events::{AppEvent, handle_events};
pub use events::handle_ct_events;
pub use tick::handle_tick_event;
+19
View File
@@ -0,0 +1,19 @@
use std::{
sync::mpsc::Sender,
thread,
time::{Duration, Instant},
};
pub fn handle_tick_event(tx: Sender<()>, interval_ms: u8) {
let interval: Duration = Duration::from_millis(interval_ms as u64);
loop {
if tx.send(()).is_err() {
break;
}
let elapsed: Duration = Instant::now().elapsed();
if interval > elapsed {
thread::sleep(interval - elapsed);
}
}
}
+2 -1
View File
@@ -72,7 +72,8 @@ pub fn skirmish_view(app: &App, area: Rect, buf: &mut Buffer) {
"Skills points: {} ({}/{}) | ",
1, 20, states.settings.skill_points_limit
),
format!("Perk Deck: {}/9", 5),
format!("Perk Deck: {}/9 | ", 5),
format!("Tick: {}", states.skirmish.turn_counter),
]),
]);
+17 -8
View File
@@ -1,10 +1,13 @@
use crate::app::{
states::{
PerkDecks,
skirmish_states::{GameMode, ZoomLevel},
use crate::{
app::{
states::{
PerkDecks,
skirmish_states::{GameMode, ZoomLevel},
},
threads::Soundtrack,
view::View,
},
threads::Soundtrack,
view::View,
logs::init_logger,
};
use clap::{Error, Parser, error::ErrorKind, value_parser};
use std::num::ParseFloatError;
@@ -15,7 +18,7 @@ use std::num::ParseFloatError;
/// The `clap` attributes describe the flag name, help text, default value,
/// and any validation constraints. The struct derives `Parser` so that
/// `Cli::parse()` can be called directly to obtain a populated instance.
#[derive(Parser, Debug)]
#[derive(Parser, Debug, Clone)]
#[command(version, about = "War in Tunnels", long_about = "War in Tunnels")]
pub struct Cli {
/// The initial view/window to display.
@@ -169,7 +172,13 @@ pub struct Cli {
/// handles argument validation and displays helpful error messages if
/// the user supplies invalid input.
pub fn get_args() -> Cli {
Cli::parse()
let args: Cli = Cli::parse();
if args.log {
init_logger();
}
args
}
/// Parses a string into a floatingpoint XP modifier and validates that it
+21 -28
View File
@@ -1,21 +1,20 @@
use ratatui::{Terminal, prelude::CrosstermBackend};
use ratatui::{Terminal, crossterm::event::KeyEvent, prelude::CrosstermBackend};
use std::{
io::{Result, Stdout},
sync::mpsc::channel,
thread::{
self,
// JoinHandle
},
mem::replace,
sync::mpsc::{Receiver, Sender, channel},
thread::{self, JoinHandle},
};
use war_in_tunnels::{
app::{
App,
threads::{AppEvent, AudioCmd, handle_audio, handle_events},
threads::{AppChannels, AudioCmd, handle_audio, handle_ct_events, handle_tick_event},
},
cli::{Cli, get_args},
logs::init_logger,
};
const TICK_MS: u8 = 33;
/// Starts the terminal UI application.
///
/// The function follows the steps outlined in the modulelevel documentation.
@@ -23,39 +22,33 @@ use war_in_tunnels::{
/// terminal, or while running the `App`.
fn main() -> Result<()> {
let args: Cli = get_args();
if args.log {
init_logger();
}
let (app_event_tx, app_event_rx) = channel::<AppEvent>();
let mut channels: AppChannels = AppChannels::new();
// let app_event_thread: JoinHandle<()> = thread::spawn(move || {
// handle_events(app_event_tx);
// });
let input_tx: Sender<KeyEvent> = channels.input_tx.clone();
let resize_tx: Sender<(u16, u16)> = channels.resize_tx.clone();
let events_thread: JoinHandle<()> =
thread::spawn(move || handle_ct_events(input_tx, resize_tx));
thread::spawn(move || {
handle_events(app_event_tx);
});
let (audio_tx, audio_rx) = channel::<AudioCmd>();
// let audio_event_thread: JoinHandle<()> = thread::spawn(move || {
// handle_audio(audio_rx);
// });
let tick_tx: Sender<()> = channels.tick_tx.clone();
let tick_thread: JoinHandle<()> = thread::spawn(move || handle_tick_event(tick_tx, TICK_MS));
let audio_rx: Receiver<AudioCmd> = replace(&mut channels.audio_rx, channel().1);
// let audio_thread: JoinHandle<()> =
thread::spawn(move || {
handle_audio(audio_rx, args.mute, args.sound_track);
});
let mut terminal: Terminal<CrosstermBackend<Stdout>> = ratatui::init();
let mut app: App = App::new(args, audio_tx);
let mut app: App = App::new(args, channels.audio_tx.clone());
let app_result: Result<()> = app.run(&mut terminal, app_event_rx);
let app_result: Result<()> = app.run(&mut terminal, channels);
ratatui::restore();
// let _ = app_event_thread.;
// let _ = audio_event_thread.join();
let _ = events_thread.join();
let _ = tick_thread.join();
// let _ = audio_thread.join(); // TODO: kill playing music
app_result
}