如何使用箭头键使菜单在Python中可导航

2024-10-01 09:24:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个基于文本的游戏,可以为他们的角色选择一个类。目前,玩家输入他们的选项,要么输入数字,要么输入类名。它工作得很好。在

不过,我想让玩家用箭头键导航菜单,并用“回车”键选择一个选项。为了明确他们将要选择哪个选项,我还想突出显示所选选项的文本。如果你玩过ASCII流氓游戏,你知道它是什么样子的。在

以下是我当前拥有的类代码:

def character():

    print "What is your class?"
    print "1. The sneaky thief."
    print "2. The smarty wizard."
    print "3. The proletariat."

    charclass = raw_input("> ")
        if charclass == "1" or "thief":
            charclass = thief
            print "You are a thief!"

        elif charclass == "2" or "wizard":
            charclass = wizard
            print "You are a wizard!"

        elif charclass == "3" or "prole":
            charclass = prole
            print "You are a prole!"

        else:
            print "I'm sorry, I didn't get that"

谢谢!在


Tags: orthe文本you游戏角色选项玩家
1条回答
网友
1楼 · 发布于 2024-10-01 09:24:38

正如评论中已经提到的,你可以使用诅咒。这里有一个小的工作菜单来实现你想要的

import curses

classes = ["The sneaky thief", "The smarty wizard", "The proletariat"]


def character(stdscr):
    attributes = {}
    curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)
    attributes['normal'] = curses.color_pair(1)

    curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_WHITE)
    attributes['highlighted'] = curses.color_pair(2)

    c = 0  # last character read
    option = 0  # the current option that is marked
    while c != 10:  # Enter in ascii
        stdscr.erase()
        stdscr.addstr("What is your class?\n", curses.A_UNDERLINE)
        for i in range(len(classes)):
            if i == option:
                attr = attributes['highlighted']
            else:
                attr = attributes['normal']
            stdscr.addstr("{0}. ".format(i + 1))
            stdscr.addstr(classes[i] + '\n', attr)
        c = stdscr.getch()
        if c == curses.KEY_UP and option > 0:
            option -= 1
        elif c == curses.KEY_DOWN and option < len(classes) - 1:
            option += 1

    stdscr.addstr("You chose {0}".format(classes[option]))
    stdscr.getch()


curses.wrapper(character)

getch的最后一次调用只是为了在程序终止之前看到结果

相关问题 更多 >