Amazing-Python-Scripts

Форк
0
72 строки · 2.0 Кб
1
import random
2

3

4
def create_grid(size):
5
    return [[' ' for _ in range(size)] for _ in range(size)]
6

7

8
def place_treasure(grid, size):
9
    row = random.randint(0, size - 1)
10
    col = random.randint(0, size - 1)
11
    grid[row][col] = 'T'
12
    return row, col
13

14

15
def display_grid(grid):
16
    size = len(grid)
17
    for row in grid:
18
        print(' | '.join(cell.center(3) for cell in row))
19
        print('-' * (size * 5 - 1))
20

21

22
def move_explorer(grid, row, col, direction):
23
    size = len(grid)
24
    if direction == 'up' and row > 0:
25
        row -= 1
26
    elif direction == 'down' and row < size - 1:
27
        row += 1
28
    elif direction == 'left' and col > 0:
29
        col -= 1
30
    elif direction == 'right' and col < size - 1:
31
        col += 1
32
    return row, col
33

34

35
def grid_explorer(size):
36
    grid = create_grid(size)
37
    explorer_row, explorer_col = random.randint(
38
        0, size - 1), random.randint(0, size - 1)
39
    treasure_row, treasure_col = place_treasure(grid, size)
40

41
    print("Welcome to Grid Explorer!")
42
    print("Find the treasure (T) on the grid by navigating in the up, down, left, or right direction.")
43
    print("Enter 'quit' to exit the game.\n")
44

45
    while True:
46
        display_grid(grid)
47
        print(f"Explorer position: ({explorer_row}, {explorer_col})")
48
        move = input("Enter your move (up/down/left/right): ").lower()
49

50
        if move == 'quit':
51
            print("Exiting the game...")
52
            break
53

54
        if move not in ['up', 'down', 'left', 'right']:
55
            print("Invalid move. Try again.")
56
            continue
57

58
        new_explorer_row, new_explorer_col = move_explorer(
59
            grid, explorer_row, explorer_col, move)
60

61
        if grid[new_explorer_row][new_explorer_col] == 'T':
62
            display_grid(grid)
63
            print("Congratulations! You found the treasure!")
64
            break
65
        else:
66
            grid[explorer_row][explorer_col] = ' '
67
            explorer_row, explorer_col = new_explorer_row, new_explorer_col
68
            grid[explorer_row][explorer_col] = 'E'
69

70

71
if __name__ == "__main__":
72
    grid_explorer(5)
73

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.