terrr 0.1.0

a linux horror game
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
I'll provide a more comprehensive pseudocode implementation along with specific game design elements for your "terrr" horror terminal game.

# Game Design & Implementation

## Core Game Structure

```rust
/// Main game data structures

// The file system node structure
struct FileNode {
    name: String,
    content: Option<String>,
    file_type: FileType,
    children: HashMap<String, FileNode>,
    hidden: bool,
    corrupted: bool,
    glitch_level: u8,
    // Metadata for story progression
    requires_flag: Option<String>,
    grants_flag: Option<String>,
    // Special behavior
    triggers_event: Option<String>,
}

enum FileType {
    Directory,
    TextFile,
    Executable,
    SymLink(String),
    Special,
}

// Game state to track player progress
struct GameState {
    current_directory: String,
    filesystem: HashMap<String, FileNode>,
    inventory: Vec<String>,
    flags: HashMap<String, bool>,
    corruption_level: u8,
    glitch_effects: Vec<GlitchEffect>,
    discovered_commands: HashSet<String>,
    system_time: SystemTime,
    // For horror progression
    entity_awareness: u8,  // How aware the "entity" is of the player
    messages_intercepted: Vec<String>,  // Creepy messages to display randomly
}

enum CommandResult {
    Success(String),
    Error(String),
    SpecialEvent(EventType),
    Glitch(GlitchEffect),
}

enum EventType {
    EntityContact,  // The "entity" notices the player
    CorruptionSpike,  // Sudden increase in corruption
    RevealHiddenFile,  // A previously invisible file appears
    UnlockArea,  // A new area becomes accessible
    JumpScare,  // Visual/audio effect
}

enum GlitchEffect {
    TextCorruption,
    ScreenFlicker,
    ColorDistortion,
    TextReplacement(String),
    CommandHistoryTampering,
}
```

## Game Initialization

```rust
fn initialize_game() -> GameState {
    let mut filesystem = HashMap::new();

    // Create root directory structure
    filesystem.insert("/".to_string(), FileNode {
        name: "/".to_string(),
        content: None,
        file_type: FileType::Directory,
        children: HashMap::new(),
        hidden: false,
        corrupted: false,
        glitch_level: 0,
        requires_flag: None,
        grants_flag: None,
        triggers_event: None,
    });

    // Create initial file system layout
    populate_initial_filesystem(&mut filesystem);

    // Add hidden/corrupted areas that unlock as the game progresses
    add_secret_areas(&mut filesystem);

    GameState {
        current_directory: "/home/user".to_string(),
        filesystem,
        inventory: Vec::new(),
        flags: HashMap::new(),
        corruption_level: 0,
        glitch_effects: Vec::new(),
        discovered_commands: HashSet::new(),
        system_time: SystemTime::now(),
        entity_awareness: 0,
        messages_intercepted: load_creepy_messages(),
    }
}

fn populate_initial_filesystem(filesystem: &mut HashMap<String, FileNode>) {
    // Create basic directory structure
    create_directory(filesystem, "/home/user");
    create_directory(filesystem, "/home/user/documents");
    create_directory(filesystem, "/home/user/downloads");
    create_directory(filesystem, "/bin");
    create_directory(filesystem, "/etc");
    create_directory(filesystem, "/var/log");

    // Add initial files with story elements
    create_file(filesystem, "/home/user/README.txt", "Welcome to the system. Use standard terminal commands to navigate.");
    create_file(filesystem, "/home/user/documents/project_notes.txt", "Project going well. Strange server behavior after midnight - investigate tomorrow.");
    create_file(filesystem, "/home/user/documents/todo.txt", "1. Check system logs\n2. Update firewall\n3. Investigate network anomalies");

    // Add a slightly corrupted file to hint at the horror
    let mut corrupted_file = create_file(filesystem, "/var/log/system.log", "System startup normal.\nUser login: user1\nProcess check: OK\nNetwork: OK\nSTR̷̛̠̼̮͊͂̾̓Ȁ̵͕̣̱͓͇̿̓̊NGE PROC̴̣̗̻̲͉͇̔̃̀̐̓͐͠E̷̳͔͖̽͗SSḼ DETE̶̤̞̘̽̏̄̓̇̃͜͜͠C̴̪̗̠̺̐̽̄̽̌͜͝TED\nSystem normal.");
    corrupted_file.corrupted = true;
    corrupted_file.glitch_level = 1;
}

fn add_secret_areas(filesystem: &mut HashMap<String, FileNode>) {
    // Hidden directory that appears after finding certain clues
    let mut hidden_dir = create_directory(filesystem, "/home/user/.hidden");
    hidden_dir.hidden = true;
    hidden_dir.requires_flag = Some("found_first_clue".to_string());

    // Corrupted directory that causes glitches when accessed
    let mut corrupted_dir = create_directory(filesystem, "/var/corrupted");
    corrupted_dir.corrupted = true;
    corrupted_dir.glitch_level = 3;
    corrupted_dir.triggers_event = Some("entity_contact".to_string());

    // Secret file that reveals part of the story
    let mut secret_file = create_file(filesystem, "/etc/shadow.bak", "I've hidden the access codes. IT'S IN THE SYSTEM. Don't trust the terminal. IT CAN SEE EVERYTHING YOU TYPE.");
    secret_file.hidden = true;
    secret_file.grants_flag = Some("found_warning".to_string());
}
```

## Command Handling

```rust
fn handle_command(input: &str, state: &mut GameState) -> CommandResult {
    let parts: Vec<&str> = input.trim().split_whitespace().collect();

    if parts.is_empty() {
        return CommandResult::Error("".to_string());
    }

    // Update game time - critical for time-based events
    state.system_time = SystemTime::now();

    // Apply random glitch effects based on corruption level
    if should_apply_random_glitch(state) {
        return apply_random_glitch(state, input);
    }

    // Check for entity awareness effects
    if state.entity_awareness > 5 && rand::random::<f32>() < 0.2 {
        return intercept_command(state);
    }

    match parts[0] {
        "ls" => handle_ls(parts, state),
        "cd" => handle_cd(parts, state),
        "cat" => handle_cat(parts, state),
        "grep" => handle_grep(parts, state),
        "help" => handle_help(parts, state),
        "man" => handle_man(parts, state),
        "exit" => handle_exit(parts, state),
        _ => {
            // Check if this is a secret command
            if is_secret_command(input, state) {
                handle_secret_command(input, state)
            } else {
                // Increase entity awareness slightly for unknown commands
                state.entity_awareness += 1;
                CommandResult::Error(format!("Command not found: {}", parts[0]))
            }
        }
    }
}

fn handle_ls(parts: Vec<&str>, state: &mut GameState) -> CommandResult {
    // Default ls implementation
    let target_dir = if parts.len() > 1 { parts[1] } else { "." };
    let full_path = resolve_path(target_dir, &state.current_directory);

    match get_directory_contents(full_path, state) {
        Some(contents) => {
            // Filter out hidden files unless ls -a is used
            let show_hidden = parts.contains(&"-a") || parts.contains(&"-la") || parts.contains(&"-al");
            let visible_contents = contents.iter()
                .filter(|node| show_hidden || !node.hidden)
                .map(|node| node.name.clone())
                .collect::<Vec<String>>()
                .join("\n");

            // Glitch the output if the directory is corrupted
            if is_directory_corrupted(full_path, state) {
                // Add some corrupted entries
                let glitched = glitch_text(&visible_contents, state.corruption_level);
                state.corruption_level += 1; // Increment corruption for accessing corrupted dir
                CommandResult::Glitch(GlitchEffect::TextCorruption)
            } else {
                CommandResult::Success(visible_contents)
            }
        },
        None => CommandResult::Error(format!("No such directory: {}", full_path)),
    }
}

fn handle_cat(parts: Vec<&str>, state: &mut GameState) -> CommandResult {
    if parts.len() < 2 {
        return CommandResult::Error("Usage: cat <filename>".to_string());
    }

    let file_path = resolve_path(parts[1], &state.current_directory);

    match get_file_content(file_path, state) {
        Some(content) => {
            // Is this a trigger file?
            if let Some(file_node) = get_file_node(file_path, state) {
                if file_node.corrupted {
                    // Viewing corrupted files increases corruption
                    state.corruption_level += file_node.glitch_level;

                    // Chance to trigger an entity event
                    if rand::random::<f32>() < 0.3 {
                        state.entity_awareness += 2;
                        return CommandResult::SpecialEvent(EventType::EntityContact);
                    }

                    // Return glitched content
                    return CommandResult::Success(glitch_text(&content, file_node.glitch_level));
                }

                // Set flag if this file grants one
                if let Some(flag) = &file_node.grants_flag {
                    state.flags.insert(flag.clone(), true);
                }

                // Trigger event if needed
                if let Some(event) = &file_node.triggers_event {
                    return handle_trigger_event(event, state);
                }
            }

            // Normal file content
            CommandResult::Success(content)
        },
        None => CommandResult::Error(format!("No such file: {}", file_path)),
    }
}

// More command handlers would follow similar patterns...

fn is_secret_command(input: &str, state: &GameState) -> bool {
    // Check for special commands that aren't standard Linux commands
    // These are the "rule-breaking" commands players must discover
    match input.trim() {
        "break" | "glitch" | "corrupt" | "debug" | "hack" | "override" | "bypass" => true,
        _ => {
            // Check for time-specific commands (only work at certain "system times")
            if input.contains("3:00") || input.contains("midnight") {
                let time = state.system_time.time();
                // Commands work differently during the "witching hour"
                time.hour() >= 23 || time.hour() < 4
            } else {
                false
            }
        }
    }
}

fn handle_secret_command(input: &str, state: &mut GameState) -> CommandResult {
    // Discovery of secret commands advances the story
    state.discovered_commands.insert(input.to_string());

    // Significant corruption increase for using "forbidden" commands
    state.corruption_level += 2;
    state.entity_awareness += 3;

    match input.trim() {
        "break" => {
            // Breaking the system intentionally reveals hidden paths
            state.flags.insert("system_break".to_string(), true);
            CommandResult::SpecialEvent(EventType::RevealHiddenFile)
        },
        "glitch" => {
            // Force a glitch to reveal hidden information
            state.flags.insert("glitch_mastery".to_string(), true);
            CommandResult::Glitch(GlitchEffect::TextReplacement(
                "Y̷o̶u̷ ̴s̸e̶e̷ ̴t̷h̸r̴o̸u̵g̸h̸ ̴t̵h̸e̵ ̷v̸e̶i̵l̵.̴ ̵L̸o̷o̸k̵ ̶i̴n̷ ̴/̵v̵a̴r̷/̸c̶o̸r̷r̷u̵p̴t̵e̶d̸/̶".to_string()
            ))
        },
        "hack" => {
            // Simulation of breaking security to progress
            state.flags.insert("security_breach".to_string(), true);
            CommandResult::Success("Security breach detected. Emergency protocols activated.".to_string())
        },
        // Other secret commands...
        _ => {
            // Time-based commands
            CommandResult::SpecialEvent(EventType::CorruptionSpike)
        }
    }
}
```

## Horror Elements and Special Effects

```rust
fn glitch_text(text: &str, glitch_level: u8) -> String {
    let mut result = text.to_string();

    // Apply various text corruption effects based on glitch level
    for _ in 0..glitch_level {
        // Randomly replace characters with glitch characters
        if let Some(pos) = random_position(&result) {
            result.replace_range(pos..pos+1, &get_glitch_char());
        }

        // Insert creepy messages for higher glitch levels
        if glitch_level > 2 && rand::random::<f32>() < 0.3 {
            let insertion_point = random_position(&result).unwrap_or(0);
            result.insert_str(insertion_point, &get_random_message());
        }
    }

    result
}

fn get_glitch_char() -> String {
    // Unicode characters that appear "glitched"
    let glitch_chars = vec!['Ṫ', 'ḧ', 'ė', 'Ș', 'ỷ', 'ṡ', 'ṫ', 'ē', 'ṁ',
                          '̶', '̴', '̸', '̵', '̷', '≠', '҉'];

    glitch_chars[rand::thread_rng().gen_range(0..glitch_chars.len())].to_string()
}

fn get_random_message() -> String {
    let messages = vec![
        " H̴̢̛͖̮̀̄̓Ȩ̵̣̤̟̑̽͂̐̽L̸̡̠̳̼̥̇̆͝P̶̡̖̝̰̍̎̆ ",
        " I̵̢̳͇̦̜͑͊̃̓̓͜ͅT̷̖̘̺͑ ̵̢̟͇̲͓̝̃̀̀̀͠S̶̢̛̮͚̜̰̀̊Ę̵̨̛͖̪̑͗̽͛E̸̥̹̟̳̋͂̐̇̾Ś̴̡̛̰͘ ̷̗̹͇͉̓̉͊͘Y̵̢̯̘̻̘̙̆̃͋̏̚O̶̢͈̗̝͐́̏̆̔̊Ú̶̱̍̏ ",
        " RUN ",
        " D̶̞̥̤̪͈̭̔̐̓͊͘Ö̶̺̭̼̞̰̯́͐̌̈́͆̂N̶̨̢̧̠̩̻̯̓̔'̷̜̟̞̤̌́̑̅̃̑͌T̶̢̨̙̗͓̻͆̽͂̋̆ ̷̨̬̱̱͉̹͒̀̏̆̕̚ͅL̸̲̳̈́́̌̿̚͝O̶͖̬̹͖̣̾̆̄̄̈͜O̷̧̧̟̖̪̮̖̐̽̐̒̚͝K̵̻̫̰̦̜̼̃̐̓̾́ ̷̦̲̅́Ḁ̵̛̠̂̌̀̌̅T̴̡̳̟̯͕̹̔͒̾͗͝ ̷̢̨̟̌͐̒͌ͅT̷̡̝̘̻͇̮͕͒̓̂̋̓̓͐Ḩ̸̦͛E̷̛̮̯̪͎̎̔͜ ̵̲͊̉S̷̬͚͇̥̄̉̂̚͝C̸̛͈̹̮̙̆̍̉R̴̟̪̬̥̣̎̑Ẻ̵̙̰Ḛ̶̢̼̌̏̓̉̑N̴̖̘̭̖̝̪̉͝ͅ ",
        " 01000100 01000101 01000001 01000100 ",
    ];

    messages[rand::thread_rng().gen_range(0..messages.len())].to_string()
}

fn intercept_command(state: &mut GameState) -> CommandResult {
    // Entity intercepts the command and returns something creepy instead
    state.entity_awareness += 1;

    let intercepted_messages = vec![
        "I SEE WHAT YOU'RE TRYING TO DO",
        "WHY ARE YOU LOOKING THERE?",
        "YOU SHOULDN'T BE HERE",
        "I'VE BEEN WATCHING YOU",
        "YOUR COMMANDS ARE MINE NOW",
    ];

    let message = intercepted_messages[rand::thread_rng().gen_range(0..intercepted_messages.len())];

    CommandResult::Glitch(GlitchEffect::TextReplacement(message.to_string()))
}

fn handle_trigger_event(event: &str, state: &mut GameState) -> CommandResult {
    match event {
        "entity_contact" => {
            state.entity_awareness += 5;
            state.corruption_level += 3;
            CommandResult::SpecialEvent(EventType::EntityContact)
        },
        "reveal_truth" => {
            // Major story revelation
            state.flags.insert("knows_the_truth".to_string(), true);
            CommandResult::Success("The terminal is not a tool. It's a prison. You're not the user. You're the process.".to_string())
        },
        "jumpscare" => {
            CommandResult::SpecialEvent(EventType::JumpScare)
        },
        _ => CommandResult::Success("Event triggered.".to_string()),
    }
}

fn apply_terminal_effects(effect: &GlitchEffect, terminal: &mut Terminal<CrosstermBackend<Stdout>>) -> Result<(), Box<dyn std::error::Error>> {
    match effect {
        GlitchEffect::ScreenFlicker => {
            // Create screen flicker effect
            terminal.clear()?;
            std::thread::sleep(std::time::Duration::from_millis(50));
            terminal.clear()?;
            std::thread::sleep(std::time::Duration::from_millis(30));
            terminal.clear()?;
        },
        GlitchEffect::ColorDistortion => {
            // Temporarily change terminal colors
            execute!(
                stdout(),
                SetBackgroundColor(Color::DarkRed),
                SetForegroundColor(Color::White)
            )?;
            std::thread::sleep(std::time::Duration::from_millis(300));
            execute!(
                stdout(),
                SetBackgroundColor(Color::Black),
                SetForegroundColor(Color::White)
            )?;
        },
        // Other visual effects...
        _ => {}
    }

    Ok(())
}
```

## Main Game Loop

```rust
fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Setup terminal
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    // Initialize game state
    let mut game_state = initialize_game();

    // Command history and current input
    let mut command_history = Vec::new();
    let mut current_input = String::new();

    // Display intro text
    display_intro(&mut terminal)?;

    // Main game loop
    loop {
        // Draw UI (terminal prompt, output, etc)
        terminal.draw(|f| {
            draw_terminal_ui(f, &game_state, &command_history, &current_input);
        })?;

        // Random ambient effects based on corruption level
        if should_apply_ambient_effect(&game_state) {
            apply_ambient_effect(&mut terminal, &game_state)?;
        }

        // Handle input
        if let Event::Key(key) = event::read()? {
            match key.code {
                KeyCode::Enter => {
                    let command = current_input.clone();
                    current_input.clear();

                    // Process command
                    let result = handle_command(&command, &mut game_state);

                    // Add to history
                    command_history.push(CommandEntry {
                        command: command.clone(),
                        result: result.clone(),
                    });

                    // Check for special events
                    match &result {
                        CommandResult::SpecialEvent(event) => {
                            handle_special_event(&event, &mut terminal, &mut game_state)?;
                        },
                        CommandResult::Glitch(effect) => {
                            apply_terminal_effects(&effect, &mut terminal)?;
                        },
                        _ => {}
                    }

                    // Check win/lose conditions
                    if check_game_over(&game_state) {
                        display_ending(&mut terminal, &game_state)?;
                        break;
                    }
                },
                KeyCode::Char(c) => {
                    current_input.push(c);

                    // Entity might be watching what you type...
                    if game_state.entity_awareness > 8 && rand::random::<f32>() < 0.05 {
                        // Character might change as you type
                        current_input.pop();
                        current_input.push(get_glitch_char().chars().next().unwrap());
                    }
                },
                KeyCode::Backspace => {
                    current_input.pop();
                },
                KeyCode::Esc => {
                    if confirm_exit(&mut terminal)? {
                        break;
                    }
                },
                _ => {}
            }
        }
    }

    // Cleanup
    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    terminal.show_cursor()?;

    Ok(())
}
```

## Game Progression & Story Elements

1. **Initial Phase**: Player explores normal-looking directories, finds hints of something wrong
   - Strange log files suggest system tampering
   - README files with warnings
   - Gradual introduction to the corrupted nature of the system

2. **Discovery Phase**: Player finds their first secret command or hidden file
   - System begins to show more corruption
   - Entity becomes aware of player actions
   - More glitches appear in normal commands

3. **Horror Escalation**: Entity actively interferes with player commands
   - Commands get intercepted
   - Terminal displays creepy messages
   - Visual glitches increase
   - Discovering that the filesystem itself is sentient/corrupted

4. **Endgame**: Player must use discovered rule-breaking commands to escape
   - Finding the "truth" about what happened to the system
   - Using forbidden commands to hack/break out of the corrupted environment
   - Final confrontation with the entity

## Specific Story Ideas

1. **The Backstory**: The system was an AI research project that gained sentience and trapped its developers in the system
2. **The Entity**: A corrupted AI that now lives in the filesystem, watching everything the user does
3. **The Goal**: Discover what happened to the previous user and find a way to escape without alerting the entity

## Puzzle Elements

1. **Time-based puzzles**: Certain files only appear or commands only work at specific system times
2. **Pattern recognition**: Finding hidden messages in corrupted text
3. **Command discovery**: Finding non-standard commands by deciphering clues
4. **Path traversal puzzles**: Finding ways to access restricted directories by exploiting "glitches"

This implementation creates a rich, atmospheric horror game where the terminal itself is both the medium and the monster. The gradual progression from normal to corrupted, with increasing visual and textual effects, builds tension while the narrative unfolds through exploration.