|
| 1 | +import random |
| 2 | + |
| 3 | +# Dungeon size |
| 4 | +ROWS, COLS = 5, 5 |
| 5 | + |
| 6 | +# Symbols |
| 7 | +EMPTY, PLAYER, EXIT, TRAP = '.', 'P', 'E', 'X' |
| 8 | + |
| 9 | +def create_dungeon(): |
| 10 | + dungeon = [[EMPTY for _ in range(COLS)] for _ in range(ROWS)] |
| 11 | + exit_row, exit_col = random.randint(0, ROWS-1), random.randint(0, COLS-1) |
| 12 | + dungeon[exit_row][exit_col] = EXIT |
| 13 | + |
| 14 | + # Random traps |
| 15 | + for _ in range(5): |
| 16 | + r, c = random.randint(0, ROWS-1), random.randint(0, COLS-1) |
| 17 | + if dungeon[r][c] == EMPTY: |
| 18 | + dungeon[r][c] = TRAP |
| 19 | + |
| 20 | + # Place player |
| 21 | + while True: |
| 22 | + pr, pc = random.randint(0, ROWS-1), random.randint(0, COLS-1) |
| 23 | + if dungeon[pr][pc] == EMPTY: |
| 24 | + dungeon[pr][pc] = PLAYER |
| 25 | + break |
| 26 | + return dungeon, pr, pc |
| 27 | + |
| 28 | +def display_dungeon(dungeon): |
| 29 | + for row in dungeon: |
| 30 | + print(' '.join(row)) |
| 31 | + print() |
| 32 | + |
| 33 | +def move_player(dungeon, pr, pc, direction): |
| 34 | + dungeon[pr][pc] = EMPTY |
| 35 | + if direction == 'N': pr -= 1 |
| 36 | + elif direction == 'S': pr += 1 |
| 37 | + elif direction == 'E': pc += 1 |
| 38 | + elif direction == 'W': pc -= 1 |
| 39 | + pr, pc = max(0, min(ROWS-1, pr)), max(0, min(COLS-1, pc)) |
| 40 | + cell = dungeon[pr][pc] |
| 41 | + dungeon[pr][pc] = PLAYER |
| 42 | + return pr, pc, cell |
| 43 | + |
| 44 | +def play(): |
| 45 | + dungeon, pr, pc = create_dungeon() |
| 46 | + lives = 3 |
| 47 | + |
| 48 | + print("🏰 Welcome to Dungeon Escape!") |
| 49 | + print("Find the exit (E) and avoid traps (X). Move with N/S/E/W.\n") |
| 50 | + |
| 51 | + while True: |
| 52 | + display_dungeon(dungeon) |
| 53 | + move = input("Move (N/S/E/W): ").upper() |
| 54 | + if move not in ['N', 'S', 'E', 'W']: |
| 55 | + print("Invalid move. Try again.") |
| 56 | + continue |
| 57 | + |
| 58 | + pr, pc, cell = move_player(dungeon, pr, pc, move) |
| 59 | + |
| 60 | + if cell == EXIT: |
| 61 | + display_dungeon(dungeon) |
| 62 | + print("🎉 You escaped the dungeon! You win!") |
| 63 | + break |
| 64 | + elif cell == TRAP: |
| 65 | + lives -= 1 |
| 66 | + print(f"💀 You hit a trap! Lives left: {lives}") |
| 67 | + if lives == 0: |
| 68 | + print("Game Over! You couldn’t escape.") |
| 69 | + break |
| 70 | + |
| 71 | +if __name__ == "__main__": |
| 72 | + play() |
0 commit comments