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 let any_golden = state.goldens.iter().any(|g| g.is_some());
290 if !any_golden {
291 for cd in state.golden_cooldowns.iter_mut() {
292 if *cd == 0 {
293 *cd = DEMO_GOLDEN_COOLDOWN;
294 }
295 }
296 }
297
298 for slot_idx in 0..state.goldens.len() {
304 if let Some(g) = state.goldens[slot_idx].as_ref()
305 && g.life_ticks == golden::GOLDEN_LIFE_TICKS
306 {
307 let target = match *demo_golden_spawns % 3 {
308 0 => GoldenVariant::Buff,
309 1 => GoldenVariant::Frenzy,
310 _ => GoldenVariant::Lucky,
311 };
312 *demo_golden_spawns += 1;
313 if slot_idx != target as usize {
314 let mut g = state.goldens[slot_idx].take().unwrap();
315 g.variant = target;
316 state.goldens[target as usize] = Some(g);
317 } else if let Some(g) = state.goldens[slot_idx].as_mut() {
318 g.variant = target;
319 }
320 break;
321 }
322 }
323
324 for variant in GoldenVariant::ALL {
328 let alive = state.goldens[variant as usize]
329 .as_ref()
330 .map(|g| g.life_ticks + 20 < golden::GOLDEN_LIFE_TICKS)
331 .unwrap_or(false);
332 if alive {
333 state.catch_golden(variant);
334 }
335 }
336
337 if t.is_multiple_of(80) {
339 let candidates: Vec<usize> = (0..fingerer::count())
340 .filter(|&i| state.can_buy(i))
341 .collect();
342 if !candidates.is_empty() {
343 let idx = candidates[rng.random_range(0..candidates.len())];
344 state.buy_n(idx, rng.random_range(1..=2));
345 }
346 }
347
348 if t.is_multiple_of(160) {
350 let available = crate::game::upgrade::available_ids(state);
351 if let Some(&u_idx) = available
352 .iter()
353 .min_by(|&&a, &&b| UPGRADES[a].cost.partial_cmp(&UPGRADES[b].cost).unwrap())
354 {
355 state.buy_upgrade(u_idx);
356 }
357 }
358
359 let phase = t % 300;
361 let panel_swap = if phase == 100 {
362 Some(Mode::Stats)
363 } else if phase == 140 {
364 Some(Mode::Achievements)
365 } else if phase == 180 {
366 Some(Mode::Upgrades)
367 } else if phase == 220 {
368 Some(Mode::Game)
369 } else {
370 None
371 };
372 if let Some(m) = panel_swap {
373 let _ = sim_msg_tx.send(SimMsg::DemoSetMode(m));
374 }
375
376 if let Some(secs) = demo_seconds
379 && t >= (secs as u64) * (TICK_HZ as u64)
380 {
381 let _ = sim_msg_tx.send(SimMsg::DemoQuit);
382 }
383}
384
385fn translate_crossterm(ev: Event) -> Option<InputEvent> {
391 match ev {
392 Event::Key(k) if k.kind == KeyEventKind::Press => {
393 let code = translate_key_code(k.code)?;
394 Some(InputEvent::KeyPress {
395 code,
396 mods: translate_mods(k.modifiers),
397 })
398 }
399 Event::Mouse(m) => translate_mouse(m),
400 _ => None,
401 }
402}
403
404fn translate_key_code(code: CtKeyCode) -> Option<InKeyCode> {
405 match code {
406 CtKeyCode::Char(c) => Some(InKeyCode::Char(c)),
407 CtKeyCode::Esc => Some(InKeyCode::Esc),
408 CtKeyCode::F(n) => Some(InKeyCode::F(n)),
409 _ => None,
410 }
411}
412
413fn translate_mods(mods: KeyModifiers) -> Modifiers {
414 Modifiers {
415 shift: mods.contains(KeyModifiers::SHIFT),
416 alt: mods.contains(KeyModifiers::ALT),
417 ctrl: mods.contains(KeyModifiers::CONTROL),
418 }
419}
420
421fn translate_mouse_button(button: CtMouseButton) -> Option<InMouseButton> {
426 match button {
427 CtMouseButton::Left => Some(InMouseButton::Left),
428 CtMouseButton::Right => Some(InMouseButton::Right),
429 CtMouseButton::Middle => None,
430 }
431}
432
433fn translate_mouse(m: CtMouseEvent) -> Option<InputEvent> {
434 let mods = translate_mods(m.modifiers);
435 match m.kind {
436 MouseEventKind::Down(button) => Some(InputEvent::MouseDown {
437 col: m.column,
438 row: m.row,
439 button: translate_mouse_button(button)?,
440 mods,
441 }),
442 MouseEventKind::ScrollUp => Some(InputEvent::Wheel {
443 col: m.column,
444 row: m.row,
445 delta: WheelDelta::Up,
446 }),
447 MouseEventKind::ScrollDown => Some(InputEvent::Wheel {
448 col: m.column,
449 row: m.row,
450 delta: WheelDelta::Down,
451 }),
452 MouseEventKind::Moved | MouseEventKind::Drag(CtMouseButton::Left) => {
457 Some(InputEvent::MouseMoved {
458 col: m.column,
459 row: m.row,
460 })
461 }
462 _ => None,
463 }
464}
465
466pub fn build_demo_state() -> GameState {
475 let mut s = GameState {
476 cuques: 500_000.0,
479 lifetime_cuques: 500_000_000.0, total_clicks: 500,
481 total_play_ticks: 3600 * TICK_HZ as u64, prestige: 3,
483 golden_caught: 7,
484 golden_cooldowns: [0; 3],
489 best_fps: 50_000.0,
490 ..GameState::default()
491 };
492 const DEMO_FINGERER_COUNTS: &[u32] = &[40, 40, 35, 30, 25, 20, 15, 10];
500 for (idx, &count) in DEMO_FINGERER_COUNTS.iter().enumerate() {
501 if let Some(f) = FINGERERS.get(idx)
502 && count > 0
503 {
504 s.fingerers_state.entry(f.id.to_string()).or_default().count = count;
505 }
506 }
507 for u in UPGRADES.iter().take(10) {
511 s.upgrades_earned.insert(u.id.to_string());
512 }
513 for a in ACHIEVEMENTS.iter().take(6) {
515 s.achievements_earned.insert(a.id.to_string());
516 }
517 s
518}