用python创建桌面应用(三)

来源:互联网 发布:淘宝情趣珍珠内裤评论 编辑:程序博客网 时间:2024/06/16 16:59

          这次让我们来创建一个用户界面,这里的用户界面和GUI是有区别的,这里只是和用户一个简单的交互而已,并不是图形化GUI。在前面的文章中,我们已经知道游戏是怎么的运行,它的操作流程。这一篇文章就是根据这些流程来创建用户界面。

''' CLI User Interface for Tic-Tac-Toie game.    Use as the main program, no reusable functions'''import oxo_logicmenu = ["Start new game",        "Resume saved game",        "Display help",        "Quit"]def getMenuChoice(aMenu):    ''' getMenuChoice(aMenu) -> int        takes a list of strings as input,        displays as a numbered menu and        loops until user selects a valid number'''        if not aMenu: raise ValueError('No menu content')    while True:        for index, item in enumerate(aMenu, start=1):#enumerate函数用来生成菜单项数字,开始于1.并不是每个人都是程序员,从0开始数数            print(index, "\t", item)        try:            choice = int(input("\nChoose a menu option: "))            if 1 <= choice <= len(aMenu):                return choice            else: print("Choose a number between 1 and", len(aMenu))        except ValueError:            print("Choose the number of a menu option")def startGame():    return oxo_logic.newGame()def resumeGame():    return oxo_logic.restoreGame()def displayHelp():    print('''    Start new game:  starts a new game of tic-tac-toe    Resume saved game: restores the last saved game and commences play    Display help: shows this page    Quit: quits the application    ''')def quit():#退出    print("Goodbye...")    raise SystemExitdef executeChoice(choice):#处理用户的选择    ''' executeChoice(int) -> None        Execute whichever option the user selected.    If the choice produces a valid game then    play the game until it completes.'''        dispatch = [startGame, resumeGame, displayHelp, quit]    game = dispatch[choice-1]()    if game:        playGame(game)def printGame(game):#该函数把游戏数据格式化后展现出来    display = '''      1 | 2 | 3      {} | {} | {}     ----------     -----------      4 | 5 | 6      {} | {} | {}      ---------     -----------      7 | 8 | 9      {} | {} | {}      '''    print(display.format(*game))# *表示扩展到列表的每个单独的元素def playGame(game):#用户界面提示    result = ""    while not result:        printGame(game)        choice = input("Cell[1-9 or q to quit]: ")        if choice.lower()[0] == 'q':            save = input("Save game before quitting?[y/n] ")            if save.lower()[0] == 'y':                oxo_logic.saveGame(game)             quit()        else:            try:                cell = int(choice)-1                if not (0 <= cell <= 8):  # check range                    raise ValueError            except ValueError:                print("Choose a number between 1 and 9 or 'q' to quit ")                continue            try:                result = oxo_logic.userMove(game,cell) #面板传入usrGame            except ValueError:                print("Choose an empty cell")                continue            if not result:                result = oxo_logic.computerMove(game) #面板传入computerGame            if not result:                continue            elif result == 'D':                printGame(game)                print("Its a draw")                            else:                printGame(game)                print("Winner is", result, '\n')def main():    while True:       choice = getMenuChoice(menu)       executeChoice(choice)if __name__ == "__main__": main()
    上面的文件名是:oxo_ui.py
   在将面板传入usrGame和computerGame函数中时,函数并没有返回跟新后的面板,这是因为面板对象是一个可变列表,它可以被函数更改,函数对初始变量的改变将会在面板上反应出来

0 0
原创粉丝点击