1use anyhow::Result;
21use arc_swap::ArcSwap;
22use crossterm::event::{
23 self, Event, KeyCode as CtKeyCode, KeyEventKind, KeyModifiers, MouseButton as CtMouseButton,
24 MouseEvent as CtMouseEvent, MouseEventKind,
25};
26use rand::RngExt;
27use ratatui::{Terminal, prelude::*};
28use std::sync::{
29 Arc,
30 atomic::{AtomicBool, Ordering},
31 mpsc,
32};
33use std::thread;
34use std::time::{Duration, Instant};
35
36use crate::game::achievement::ACHIEVEMENTS;
37use crate::game::fingerer;
38use crate::game::fingerer::FINGERERS;
39use crate::game::golden::{self, GoldenVariant};
40use crate::game::state::{GameState, TICK_HZ};
41use crate::game::upgrade::UPGRADES;
42use crate::input::{
43 self, InputContext, InputEvent, KeyCode as InKeyCode, Modifiers, MouseButton as InMouseButton,
44 UiState, WheelDelta,
45};
46use crate::platform::Persistence;
47use crate::sim::{self, Action, SimGeometry};
48use crate::ui::{self, Mode};
49
50const SAVE_INTERVAL_TICKS: u64 = TICK_HZ as u64 * 10;
51const DEMO_GOLDEN_COOLDOWN: u32 = 40;
54const INPUT_POLL_MS: u64 = 16;
58const MAX_TICK_CATCHUP: u32 = 20;
62
63enum SimMsg {
67 DemoSetMode(Mode),
68 DemoQuit,
69}
70
71pub struct App {
72 state: GameState,
73 debug: bool,
74 demo_seconds: Option<u32>,
75 persistence: Persistence,
76}
77
78impl App {
79 pub fn new(
80 state: GameState,
81 debug: bool,
82 demo_seconds: Option<u32>,
83 persistence: Persistence,
84 ) -> Self {
85 Self {
86 state,
87 debug,
88 demo_seconds,
89 persistence,
90 }
91 }
92
93 pub fn run<B: Backend>(self, terminal: &mut Terminal<B>) -> Result<()>
94 where
95 B::Error: Send + Sync + 'static,
96 {
97 let App {
98 state,
99 debug,
100 demo_seconds,
101 persistence,
102 } = self;
103
104 let snapshot = Arc::new(ArcSwap::from_pointee(state.clone()));
105 let shutdown = Arc::new(AtomicBool::new(false));
106 let (action_tx, action_rx) = mpsc::channel::<Action>();
107 let (sim_msg_tx, sim_msg_rx) = mpsc::channel::<SimMsg>();
108
109 let sim_handle = {
110 let snapshot = snapshot.clone();
111 let shutdown = shutdown.clone();
112 thread::Builder::new()
113 .name("cuque-sim".into())
114 .spawn(move || {
115 sim_loop(
116 state,
117 snapshot,
118 action_rx,
119 sim_msg_tx,
120 shutdown,
121 demo_seconds,
122 persistence,
123 );
124 })
125 .expect("spawn sim thread")
126 };
127
128 let mut ui = UiState::new();
129 let mut layout: ui::DrawOutput = Default::default();
134 let mut actions: Vec<Action> = Vec::with_capacity(4);
137
138 while ui.running && !shutdown.load(Ordering::Relaxed) {
139 for msg in sim_msg_rx.try_iter() {
142 match msg {
143 SimMsg::DemoSetMode(m) => ui.mode = m,
144 SimMsg::DemoQuit => ui.running = false,
145 }
146 }
147
148 let current = snapshot.load_full();
149 terminal.draw(|f| {
150 layout = ui::draw(f, ¤t, ui.mode, ui.zoom_idx, debug, ui.last_mouse_pos);
151 })?;
152
153 let _ = action_tx.send(Action::UpdateGeometry {
156 biscuit: layout.biscuit_rect,
157 });
158
159 if event::poll(Duration::from_millis(INPUT_POLL_MS))? {
160 let ctx = InputContext::from_layout(&layout, ¤t, debug);
161 loop {
162 let ev = event::read()?;
163 if let Some(input_ev) = translate_crossterm(ev) {
164 actions.clear();
165 input::process_input_event(input_ev, &mut ui, &ctx, &mut actions);
166 for a in actions.drain(..) {
167 let _ = action_tx.send(a);
168 }
169 }
170 if !event::poll(Duration::ZERO)? {
171 break;
172 }
173 }
174 }
175 }
176
177 shutdown.store(true, Ordering::Relaxed);
179 drop(action_tx);
180 sim_handle.join().expect("sim thread panicked");
181 Ok(())
182 }
183}
184
185fn sim_loop(
188 mut state: GameState,
189 snapshot: Arc<ArcSwap<GameState>>,
190 actions: mpsc::Receiver<Action>,
191 sim_msg_tx: mpsc::Sender<SimMsg>,
192 shutdown: Arc<AtomicBool>,
193 demo_seconds: Option<u32>,
194 persistence: Persistence,
195) {
196 let tick_dt = Duration::from_micros(1_000_000 / TICK_HZ as u64);
197 let mut next_tick = Instant::now() + tick_dt;
198 let mut ticks_since_save: u64 = 0;
199 let mut demo_ticks: u64 = 0;
200 let mut demo_golden_spawns: u32 = 0;
201 let mut geom = SimGeometry::default();
202
203 loop {
204 if shutdown.load(Ordering::Relaxed) {
205 break;
206 }
207
208 let timeout = next_tick.saturating_duration_since(Instant::now());
211 match actions.recv_timeout(timeout) {
212 Ok(action) => sim::apply_action(&mut state, action, &mut geom),
213 Err(mpsc::RecvTimeoutError::Timeout) => {}
214 Err(mpsc::RecvTimeoutError::Disconnected) => break,
215 }
216
217 let mut catchup = 0u32;
221 while Instant::now() >= next_tick {
222 sim::sim_tick(&mut state, &geom);
223 if demo_seconds.is_some() {
227 demo_driver_tick(
228 &mut state,
229 &geom,
230 demo_seconds,
231 &mut demo_ticks,
232 &mut demo_golden_spawns,
233 &sim_msg_tx,
234 );
235 } else {
236 ticks_since_save += 1;
237 if ticks_since_save >= SAVE_INTERVAL_TICKS {
238 ticks_since_save = 0;
239 let _ = persistence.save(&state);
240 }
241 }
242 next_tick += tick_dt;
243 catchup += 1;
244 if catchup >= MAX_TICK_CATCHUP && Instant::now() > next_tick {
245 next_tick = Instant::now() + tick_dt;
246 break;
247 }
248 }
249
250 snapshot.store(Arc::new(state.clone()));
253 }
254
255 if demo_seconds.is_none() {
258 state.tick_achievements();
259 let _ = persistence.save(&state);
260 }
261}
262
263fn demo_driver_tick(
267 state: &mut GameState,
268 geom: &SimGeometry,
269 demo_seconds: Option<u32>,
270 demo_ticks: &mut u64,
271 demo_golden_spawns: &mut u32,
272 sim_msg_tx: &mpsc::Sender<SimMsg>,
273) {
274 *demo_ticks += 1;
275 let t = *demo_ticks;
276 let mut rng = rand::rng();
277
278 if t.is_multiple_of(13) {
280 let r = geom.biscuit;
281 if r.width > 0 && r.height > 0 {
282 state.click((r.x + r.width / 2, r.y + r.height / 2), r);
283 }
284 }
285
286 if state.golden.is_none() && state.golden_cooldown == 0 {
288 state.golden_cooldown = DEMO_GOLDEN_COOLDOWN;
289 }
290
291 if let Some(g) = &mut state.golden
295 && g.life_ticks == golden::GOLDEN_LIFE_TICKS
296 {
297 g.variant = match *demo_golden_spawns % 3 {
298 0 => GoldenVariant::Buff,
299 1 => GoldenVariant::Frenzy,
300 _ => GoldenVariant::Lucky,
301 };
302 *demo_golden_spawns += 1;
303 }
304
305 if let Some(g) = &state.golden
308 && g.life_ticks + 20 < golden::GOLDEN_LIFE_TICKS
309 {
310 state.catch_golden();
311 }
312
313 if t.is_multiple_of(80) {
315 let candidates: Vec<usize> = (0..fingerer::count())
316 .filter(|&i| state.can_buy(i))
317 .collect();
318 if !candidates.is_empty() {
319 let idx = candidates[rng.random_range(0..candidates.len())];
320 state.buy_n(idx, rng.random_range(1..=2));
321 }
322 }
323
324 if t.is_multiple_of(160) {
326 let available = crate::game::upgrade::available_ids(state);
327 if let Some(&u_idx) = available
328 .iter()
329 .min_by(|&&a, &&b| UPGRADES[a].cost.partial_cmp(&UPGRADES[b].cost).unwrap())
330 {
331 state.buy_upgrade(u_idx);
332 }
333 }
334
335 let phase = t % 300;
337 let panel_swap = if phase == 100 {
338 Some(Mode::Stats)
339 } else if phase == 140 {
340 Some(Mode::Achievements)
341 } else if phase == 180 {
342 Some(Mode::Upgrades)
343 } else if phase == 220 {
344 Some(Mode::Game)
345 } else {
346 None
347 };
348 if let Some(m) = panel_swap {
349 let _ = sim_msg_tx.send(SimMsg::DemoSetMode(m));
350 }
351
352 if let Some(secs) = demo_seconds
355 && t >= (secs as u64) * (TICK_HZ as u64)
356 {
357 let _ = sim_msg_tx.send(SimMsg::DemoQuit);
358 }
359}
360
361fn translate_crossterm(ev: Event) -> Option<InputEvent> {
367 match ev {
368 Event::Key(k) if k.kind == KeyEventKind::Press => {
369 let code = translate_key_code(k.code)?;
370 Some(InputEvent::KeyPress {
371 code,
372 mods: translate_mods(k.modifiers),
373 })
374 }
375 Event::Mouse(m) => translate_mouse(m),
376 _ => None,
377 }
378}
379
380fn translate_key_code(code: CtKeyCode) -> Option<InKeyCode> {
381 match code {
382 CtKeyCode::Char(c) => Some(InKeyCode::Char(c)),
383 CtKeyCode::Esc => Some(InKeyCode::Esc),
384 CtKeyCode::F(n) => Some(InKeyCode::F(n)),
385 _ => None,
386 }
387}
388
389fn translate_mods(mods: KeyModifiers) -> Modifiers {
390 Modifiers {
391 shift: mods.contains(KeyModifiers::SHIFT),
392 alt: mods.contains(KeyModifiers::ALT),
393 ctrl: mods.contains(KeyModifiers::CONTROL),
394 }
395}
396
397fn translate_mouse_button(button: CtMouseButton) -> Option<InMouseButton> {
402 match button {
403 CtMouseButton::Left => Some(InMouseButton::Left),
404 CtMouseButton::Right => Some(InMouseButton::Right),
405 CtMouseButton::Middle => None,
406 }
407}
408
409fn translate_mouse(m: CtMouseEvent) -> Option<InputEvent> {
410 let mods = translate_mods(m.modifiers);
411 match m.kind {
412 MouseEventKind::Down(button) => Some(InputEvent::MouseDown {
413 col: m.column,
414 row: m.row,
415 button: translate_mouse_button(button)?,
416 mods,
417 }),
418 MouseEventKind::ScrollUp => Some(InputEvent::Wheel {
419 col: m.column,
420 row: m.row,
421 delta: WheelDelta::Up,
422 }),
423 MouseEventKind::ScrollDown => Some(InputEvent::Wheel {
424 col: m.column,
425 row: m.row,
426 delta: WheelDelta::Down,
427 }),
428 MouseEventKind::Moved | MouseEventKind::Drag(CtMouseButton::Left) => {
433 Some(InputEvent::MouseMoved {
434 col: m.column,
435 row: m.row,
436 })
437 }
438 _ => None,
439 }
440}
441
442pub fn build_demo_state() -> GameState {
451 let mut s = GameState {
452 cuques: 500_000.0,
455 lifetime_cuques: 500_000_000.0, total_clicks: 500,
457 total_play_ticks: 3600 * TICK_HZ as u64, prestige: 3,
459 golden_caught: 7,
460 golden_cooldown: 0,
464 best_fps: 50_000.0,
465 ..GameState::default()
466 };
467 const DEMO_FINGERER_COUNTS: &[u32] = &[40, 40, 35, 30, 25, 20, 15, 10];
475 for (idx, &count) in DEMO_FINGERER_COUNTS.iter().enumerate() {
476 if let Some(f) = FINGERERS.get(idx)
477 && count > 0
478 {
479 s.fingerers_state.entry(f.id.to_string()).or_default().count = count;
480 }
481 }
482 for u in UPGRADES.iter().take(10) {
486 s.upgrades_earned.insert(u.id.to_string());
487 }
488 for a in ACHIEVEMENTS.iter().take(6) {
490 s.achievements_earned.insert(a.id.to_string());
491 }
492 s
493}