1
2
3
4
5
6
7
8
9
10
11
12
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
use crate::game::state::{AppState, AppScreen};
use crate::game::terminal::{TerminalController, CommandResult};
use crate::ui::{title::GlitchyTitle, menu::{MainMenu, MenuAction}};
use crate::ui::markdown::MarkdownRenderer;
use std::time::{Duration, Instant};
use std::path::PathBuf;
use anyhow::{Result, Context};
use crossterm::event::{self, Event, KeyCode, KeyModifiers};
use ratatui::backend::Backend;
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};
use ratatui::Frame;
use rand::Rng;
const TICK_RATE: Duration = Duration::from_millis(50);
/// The main application that handles the game logic and UI
pub struct App {
pub state: AppState,
pub title: GlitchyTitle,
pub main_menu: MainMenu,
pub rules_content: MarkdownRenderer,
pub about_content: MarkdownRenderer,
pub last_tick: Instant,
pub content_scroll: usize,
pub terminal_controller: TerminalController,
}
impl App {
/// Create a new app instance
pub fn new() -> Result<Self> {
let title = GlitchyTitle::new("TERRR");
let main_menu = MainMenu::new();
// Load content from markdown files
let content_dir = PathBuf::from("src/content");
let rules_path = content_dir.join("RULES.md");
let about_path = content_dir.join("about.md");
let rules_content = MarkdownRenderer::from_file(&rules_path)
.context("Failed to load rules content")?;
let about_content = MarkdownRenderer::from_file(&about_path)
.context("Failed to load about content")?;
// Create a new app state
let state = AppState::default();
// Create terminal controller and copy the win conditions to AppState to avoid unsafe access
let mut terminal_controller = TerminalController::new();
Ok(Self {
state,
title,
main_menu,
rules_content,
about_content,
last_tick: Instant::now(),
content_scroll: 0,
terminal_controller,
})
}
/// Run the main application loop
pub fn run<B: Backend>(&mut self, terminal: &mut ratatui::Terminal<B>) -> Result<()> {
while !self.state.quit {
// Update timing
let timeout = self.update_timing();
// Render UI
terminal.draw(|f| self.render(f))?;
// Handle input
if event::poll(timeout)? {
self.handle_events()?;
}
}
Ok(())
}
/// Update all timing-related components
fn update_timing(&mut self) -> Duration {
let now = Instant::now();
let elapsed = now.duration_since(self.last_tick);
if elapsed >= TICK_RATE {
// Update title animation
self.title.update();
// Update menu items
self.main_menu.update();
// Update game time
self.state.game_time.update();
// Midnight/3 AM affects corruption level more
let corruption_chance = if self.state.game_time.is_midnight() || self.state.game_time.is_three_am() {
15 // Higher chance at special times
} else if self.state.game_time.is_after_midnight() {
8 // Moderate chance after midnight
} else {
3 // Lower chance during regular hours
};
// Gradually increase corruption/glitchiness
if self.state.corruption_level < 255 {
let mut rng = rand::thread_rng();
if rng.gen_range(0..100) < corruption_chance {
self.state.corruption_level += 1;
self.title.increase_intensity(0.001);
}
}
self.last_tick = now;
Duration::from_millis(0)
} else {
TICK_RATE - elapsed
}
}
/// Handle keyboard and other events
fn handle_events(&mut self) -> Result<()> {
if let Event::Key(key) = event::read()? {
match self.state.screen {
AppScreen::MainMenu => {
if let Some(action) = self.main_menu.handle_input(Event::Key(key)) {
self.handle_menu_action(action);
}
},
AppScreen::Rules | AppScreen::About => {
// Back to main menu on ESC
if key.code == KeyCode::Esc {
self.state.screen = AppScreen::MainMenu;
self.content_scroll = 0; // Reset scroll position when leaving content view
} else if key.code == KeyCode::Up && self.content_scroll > 0 {
// Scroll up
self.content_scroll -= 1;
} else if key.code == KeyCode::Down {
// Scroll down (limits handled in the render function)
self.content_scroll += 1;
} else if key.code == KeyCode::PageUp && self.content_scroll > 0 {
// Page up
self.content_scroll = self.content_scroll.saturating_sub(10);
} else if key.code == KeyCode::PageDown {
// Page down
self.content_scroll += 10;
}
},
AppScreen::Game => {
self.handle_game_input(key);
},
}
// Global quit shortcut
if key.code == KeyCode::Char('q') && key.modifiers == event::KeyModifiers::CONTROL {
self.state.quit = true;
}
}
Ok(())
}
/// Handle game terminal input
fn handle_game_input(&mut self, key: event::KeyEvent) {
match key.code {
// Back to main menu on ESC
KeyCode::Esc => {
self.state.screen = AppScreen::MainMenu;
},
// Process enter key to execute commands
KeyCode::Enter => {
let command = std::mem::take(&mut self.state.terminal.current_command);
if !command.is_empty() {
// Process the command
let result = self.terminal_controller.process_command(
&mut self.state.terminal,
&self.state.game_time,
&command,
&mut self.state.win_conditions
);
// Add command with prompt to output history
let prompt = format!("{}@{} {}$ {}",
self.state.terminal.username,
self.state.terminal.system_name,
self.state.terminal.current_dir,
command
);
self.state.terminal.command_output.push(prompt);
// Check if it's an event and handle corruption level increase first
let is_event = matches!(result, CommandResult::Event(_));
// Check if this is the system break command (game win)
let is_game_win = command == "systerrr-destroy-drnovakisdead-shouldhavelistened-systemisalive";
// Add result to output history if not empty
match result {
CommandResult::Success(msg) | CommandResult::Error(msg) | CommandResult::Event(msg) => {
if !msg.is_empty() {
self.state.terminal.command_output.push(msg);
}
},
CommandResult::Empty => {},
}
// Handle winning condition
if is_game_win {
// Return to main menu after showing win message
self.state.screen = AppScreen::MainMenu;
return;
}
// Watcher attack at 100% awareness returns to main menu
if self.state.win_conditions.watcher_awareness >= 100 &&
(self.state.game_time.is_midnight() ||
self.state.game_time.is_three_am() ||
self.state.game_time.is_after_midnight()) {
self.state.screen = AppScreen::MainMenu;
return;
}
// Corrupted event should increase corruption level
if is_event {
// Special events increase corruption faster
self.state.corruption_level = std::cmp::min(255, self.state.corruption_level + 5);
self.title.increase_intensity(0.01);
}
}
},
// Handle backspace for command editing
KeyCode::Backspace => {
if !self.state.terminal.current_command.is_empty() {
self.state.terminal.current_command.pop();
}
},
// Handle character input
KeyCode::Char(c) => {
// Ignore control key combinations except ctrl+c (which clears input)
if key.modifiers == KeyModifiers::CONTROL {
if c == 'c' {
self.state.terminal.current_command.clear();
}
return;
}
// Add character to current command
self.state.terminal.current_command.push(c);
},
// Other keys ignored
_ => {},
}
}
/// Handle menu actions
fn handle_menu_action(&mut self, action: MenuAction) {
// Reset scroll position when changing screens
self.content_scroll = 0;
match action {
MenuAction::StartGame => {
self.state.screen = AppScreen::Game;
},
MenuAction::ShowRules => {
self.state.screen = AppScreen::Rules;
},
MenuAction::ShowAbout => {
self.state.screen = AppScreen::About;
},
MenuAction::Quit => {
self.state.quit = true;
},
}
}
/// Render the UI based on current application state
fn render(&self, f: &mut Frame) {
match self.state.screen {
AppScreen::MainMenu => self.render_main_menu(f),
AppScreen::Rules => self.render_rules(f),
AppScreen::About => self.render_about(f),
AppScreen::Game => self.render_game(f),
}
}
/// Render the main menu screen
fn render_main_menu(&self, f: &mut Frame) {
let size = f.size();
// Create vertical layout for title and menu
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), // Title
Constraint::Length(2), // Spacer
Constraint::Length(10), // Menu
Constraint::Min(0), // Remaining space
])
.split(size);
// Render title with glitch effect
self.render_title(f, chunks[0]);
// Render menu items
let menu_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(vec![Constraint::Length(1); self.main_menu.items.len()])
.split(chunks[2]);
for (i, item) in self.main_menu.items.iter().enumerate() {
let text = vec![Line::from(vec![
Span::styled(&item.label, item.get_style())
])];
let paragraph = Paragraph::new(text)
.alignment(Alignment::Center);
f.render_widget(paragraph, menu_chunks[i]);
}
// Render a creepy message at the bottom
let footer_text = if self.state.corruption_level > 50 {
"D̸̦̠͋Ơ̴̫͒ ̶̨̦̇N̸̠̲̈́̔O̵̧͓̅T̷̬̭͋ ̴͍͇̕T̶̡̠̔̈́R̶̖̖͐U̵̞̽̊S̵̹͠T̸̜͠ ̴̛̲͖̌T̶̬͍̏Ḥ̴͝E̶̱̐ ̴̙͗Ṯ̶͒E̶͚̅̀R̴̛̗̋M̵̢̞̿I̶̺͑Ņ̴̛̱̈́A̴̡̖̚L̴̻̎̚"
} else {
"Press ESC to exit. Arrow keys to navigate."
};
let footer = Paragraph::new(footer_text)
.style(Style::default().fg(Color::Gray))
.alignment(Alignment::Center);
f.render_widget(footer, chunks[3]);
}
/// Render the animated title
fn render_title(&self, f: &mut Frame, area: Rect) {
let display_text = self.title.get_display_text();
let title_spans: Vec<Span> = display_text
.iter()
.map(|(text, color)| {
if let Some(c) = color {
Span::styled(text, Style::default().fg(*c))
} else {
Span::styled(text, Style::default().fg(Color::White))
}
})
.collect();
let title = Paragraph::new(Line::from(title_spans))
.alignment(Alignment::Center)
.block(Block::default());
f.render_widget(title, area);
}
/// Render the rules screen
fn render_rules(&self, f: &mut Frame) {
let size = f.size();
// Create a layout for the title and content
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), // Title
Constraint::Min(0), // Content
Constraint::Length(2), // Footer with scrollbar
])
.split(size);
// Render title
let title = Paragraph::new("RULES")
.style(Style::default().fg(Color::Red))
.alignment(Alignment::Center)
.block(Block::default().borders(Borders::BOTTOM));
f.render_widget(title, chunks[0]);
// Render markdown content
self.render_markdown(f, chunks[1], &self.rules_content);
// Create a footer with scroll indicators
let scroll_text = format!("Press ESC to return to menu | ↑↓ to scroll {}/{}",
self.content_scroll,
self.rules_content.styled_lines.len().saturating_sub(chunks[1].height as usize));
let footer = Paragraph::new(scroll_text)
.style(Style::default().fg(Color::Gray))
.alignment(Alignment::Center);
f.render_widget(footer, chunks[2]);
}
/// Render the about screen
fn render_about(&self, f: &mut Frame) {
let size = f.size();
// Create a layout for the title and content
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), // Title
Constraint::Min(0), // Content
Constraint::Length(2), // Footer with scrollbar
])
.split(size);
// Render title
let title = Paragraph::new("ABOUT")
.style(Style::default().fg(Color::Red))
.alignment(Alignment::Center)
.block(Block::default().borders(Borders::BOTTOM));
f.render_widget(title, chunks[0]);
// Render markdown content
self.render_markdown(f, chunks[1], &self.about_content);
// Create a footer with scroll indicators
let scroll_text = format!("Press ESC to return to menu | ↑↓ to scroll {}/{}",
self.content_scroll,
self.about_content.styled_lines.len().saturating_sub(chunks[1].height as usize));
let footer = Paragraph::new(scroll_text)
.style(Style::default().fg(Color::Gray))
.alignment(Alignment::Center);
f.render_widget(footer, chunks[2]);
}
/// Render markdown content
fn render_markdown(&self, f: &mut Frame, area: Rect, content: &MarkdownRenderer) {
let block = Block::default()
.borders(Borders::NONE)
.style(Style::default());
let inner_area = block.inner(area);
f.render_widget(block, area);
// Convert styled lines to text for rendering
let lines: Vec<Line> = content.styled_lines.iter()
.map(|styled_line| {
let spans: Vec<Span> = styled_line.iter()
.map(|styled_text| Span::styled(&styled_text.text, styled_text.style))
.collect();
Line::from(spans)
})
.collect();
// Apply scrolling
// Calculate maximum scroll position
let max_scroll = lines.len().saturating_sub(inner_area.height as usize);
let effective_scroll = if self.content_scroll > max_scroll {
max_scroll
} else {
self.content_scroll
};
let paragraph = Paragraph::new(lines)
.wrap(Wrap { trim: true })
.scroll((0, effective_scroll as u16));
f.render_widget(paragraph, inner_area);
}
/// Render the game screen (placeholder)
fn render_game(&self, f: &mut Frame) {
let size = f.size();
// Create layout for header, terminal area, and input
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(1), // Header with time
Constraint::Min(5), // Terminal output area
Constraint::Length(1), // Input prompt
])
.split(size);
// Render time in the header (top-right)
let time_str = self.state.game_time.formatted();
let time_style = if self.state.game_time.is_three_am() {
Style::default().fg(Color::Red).add_modifier(Modifier::BOLD | Modifier::SLOW_BLINK)
} else if self.state.game_time.is_midnight() {
Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
} else if self.state.game_time.is_after_midnight() {
Style::default().fg(Color::Red)
} else {
Style::default().fg(Color::White)
};
let header_text = format!("Time: {}", time_str);
let header = Paragraph::new(header_text)
.style(time_style)
.alignment(Alignment::Right);
f.render_widget(header, chunks[0]);
// Render terminal output area
let terminal_area = Block::default()
.borders(Borders::ALL)
.title("TERRR Terminal")
.border_style(Style::default().fg(Color::White));
let inner_terminal_area = terminal_area.inner(chunks[1]);
f.render_widget(terminal_area, chunks[1]);
// Render command output
let mut output_text: Vec<Line> = Vec::new();
// Process each line in command output, splitting on newlines
for line in &self.state.terminal.command_output {
// Split the line by newline characters and add each part as its own Line
for part in line.split('\n') {
output_text.push(Line::from(part.to_string()));
}
}
let output = Paragraph::new(output_text)
.style(Style::default().fg(Color::White))
.wrap(Wrap { trim: false });
f.render_widget(output, inner_terminal_area);
// Render command prompt
let prompt = format!("{}@{} {}$ {}",
self.state.terminal.username,
self.state.terminal.system_name,
self.state.terminal.current_dir,
self.state.terminal.current_command
);
// Calculate cursor position before moving prompt
let cursor_x = prompt.len() as u16;
let input = Paragraph::new(prompt)
.style(Style::default().fg(Color::Green));
f.render_widget(input, chunks[2]);
f.set_cursor(cursor_x, chunks[2].y);
}
}