欢迎访问宙启技术站
智能推送

Pythoncurses实现终端迷宫游戏

发布时间:2024-01-14 08:48:08

Pythoncurses是一个Python模块,用于创建基于终端的用户界面。通过使用Pythoncurses,我们可以在终端环境中创建交互式的文本图形界面。

以下是一个使用Pythoncurses实现的简单终端迷宫游戏的例子:

import curses

def draw_maze():
    # 绘制迷宫地图
    maze = [
        "+-+-+-+-+-+-+-+-+-+",
        "|                 |",
        "+-+-+-+ +-+-+-+ +-+",
        "|     | |       | |",
        "+ +-+ + + +-+-+ + +",
        "| |   |   |   | | |",
        "+-+ +-+-+ + + + + +",
        "|     |   | |   | |",
        "+ +-+-+ +-+-+ +-+-+",
        "| |     |   |     |",
        "+ +-+-+ +-+-+-+-+ +",
        "|     |         | |",
        "+-+-+ +-+-+ +-+ + +",
        "|     |   | |   | |",
        "+ +-+ +-+ + +-+ + +",
        "| |       |       |",
        "+-+-+-+-+-+-+-+-+-+",
    ]

    stdscr.addstr(0, 0, "
".join(maze))

def main(stdscr):
    # 初始化终端
    curses.curs_set(0)  # 隐藏光标
    stdscr.nodelay(1)  # 非阻塞输入
    stdscr.timeout(100)  # 设置输入超时时间

    height, width = stdscr.getmaxyx()

    # 绘制迷宫
    draw_maze()

    # 设置起始位置
    y, x = 1, 1

    while True:
        stdscr.refresh()

        # 处理输入
        key = stdscr.getch()
        if key == ord("q"):
            break
        elif key == ord("w"):
            if y > 1 and stdscr.inch(y - 1, x) == ord(" "):
                y -= 1
        elif key == ord("s"):
            if y < height - 2 and stdscr.inch(y + 1, x) == ord(" "):
                y += 1
        elif key == ord("a"):
            if x > 1 and stdscr.inch(y, x - 1) == ord(" "):
                x -= 1
        elif key == ord("d"):
            if x < width - 2 and stdscr.inch(y, x + 1) == ord(" "):
                x += 1

        # 绘制角色
        stdscr.addch(y, x, "X", curses.A_BOLD)

if __name__ == "__main__":
    curses.wrapper(main)

在这个例子中,我们首先导入了Pythoncurses模块。然后定义了一个draw_maze()函数,用于绘制迷宫地图。在main()函数中,我们对终端进行了初始化,并设置了起始位置。然后,通过一个无限循环,在每次循环中处理用户的输入,并根据输入来移动角色的位置。最后,通过curses.wrapper()函数运行整个程序。

要运行这个例子,需要在终端中执行python filename.py命令,其中filename.py是你保存上述代码的文件名。

这个例子只是一个简单的演示,你可以根据自己的需求扩展它。你可以添加更复杂的地图、更多的角色操作等。希望这个例子对你有所帮助!