python3。7迷宫

易晨然 3周前 6浏览 0评论

Python3.7 迷宫 - 一个简单的控制台迷宫游戏。

import os

class Maze:
    def __init__(self, maze_file):
        self.maze_file = maze_file
        self.maze_list = []
        self.start_location = None
        self.end_location = None
        self.player_location = None
        self.load()

    def load(self):
        with open(self.maze_file, 'r') as file:
            for line in file:
                row = [char for char in line.rstrip()]
                if 'S' in row:
                    self.start_location = (len(self.maze_list), row.index('S'))
                if 'E' in row:
                    self.end_location = (len(self.maze_list), row.index('E'))
                self.maze_list.append(row)

    def draw(self):
        os.system('cls' if os.name == 'nt' else 'clear')
        for row in self.maze_list:
            print(''.join(row))

    def move_player(self, movement):
        row, col = self.player_location
        if movement == 'up':
            row -= 1
        elif movement == 'down':
            row += 1
        elif movement == 'left':
            col -= 1
        elif movement == 'right':
            col += 1

        if row < 0 or row >= len(self.maze_list) or col < 0 or col >= len(self.maze_list[0]) or self.maze_list[row][col] == '#':
            return

        self.maze_list[self.player_location[0]][self.player_location[1]] = ' '
        self.maze_list[row][col] = 'P'
        self.player_location = (row, col)

    def start(self):
        self.player_location = self.start_location
        while True:
            self.draw()
            movement = input('Move (up, down, left, right): ')
            self.move_player(movement)
            if self.player_location == self.end_location:
                self.draw()
                print('You won!')
                break

maze = Maze('maze.txt')
maze.start()

在这个 Python 3.7 迷宫游戏中,玩家需要帮助角色到达终点,避开了障碍物。

这个游戏在控制台上运行,并将地图存储在文本文件中。玩家使用控制台输入来进行移动,并且只能向上、下、左或右移动一个空间。

玩家的角色用一个字母 “P” 表示,地图上的起点用字母 “S” 表示,终点用字母 “E” 表示,障碍物用字符 “#” 表示。