因此,我正在开发一个可以与朋友共享的基于Python文本的游戏。我已经完成了大多数游戏的工作,但是当用户选择某些命令时,我会在游戏中挣扎。我没有为此使用pygame,因为我找不到64位版本。以下是我正在查看的内容。我应该在gameOver函数中放入什么内容才能真正退出游戏,或者如果玩家愿意,请重试?

import time
import random
import sys

def searchAreas():
    print("1. Area1")
    print("2. Area2")
    print("3. Area3")
    print("4. Just give up")

def badResponse():
    print("Sorry, I don't understand " + search_area)

def gameOver():
    print("You decide to give up because life is too hard.")
    print("Would you like to try again?")
    player_choice = input("> ")
    if player_choice == "Yes":
        mainGame()
    elif player_choice == "No":
        print("# what goes here to quit the game?")
    else:
        badResponse()

def mainGame():
    search_area_options = ["1","2","3"]
    search_area = ""
    while search_area not in search_area_options:
        print("Where do you want to start looking?")
        searchAreas()
        search_area = str(input("> "))
        if search_area == "1":
            print("Text here")
        elif search_area == "2":
            print("Text here")
        elif search_area == "3":
            print("text here")
        elif search_area == "4":
            gameOver()
        else:
            badResponse()

mainGame()



当输入除四个选项以外的任何内容时,或者进入gameOver函数时,我看到此错误:

Traceback (most recent call last):
  File "./test.py", line 45, in <module>
    mainGame()
  File "./test.py", line 43, in mainGame
    badResponse()
  File "./test.py", line 14, in badResponse
    print("Sorry, I don't understand " + search_area)
NameError: name 'search_area' is not defined

最佳答案

在设计游戏时,与传统的“后端” Python编码相比,我们发现需要这种模式:从内部函数到“跳转”再到外部函数。

因此,在游戏中,通常会发生以下情况:从mainloop调用的函数中,您会希望退出mainloop并转到代码设置下一个游戏阶段或显示游戏结束画面的地方,并且提供开始新游戏的机会。

Python具有“ sys.exit”调用,该调用会完全停止程序,因此,尽管您可以从检查游戏结束条件的代码中调用它,但它会完全退出您的程序,而不会为用户提供选择开始新的比赛。 (如果您的游戏是在图形UI上,而不是在控制台的“打印和输入”游戏上,那么本来就很糟糕的体验将变成灾难性的,因为游戏本身会突然关闭而没有任何痕迹)。

因此,尽管可以使用可由这些功能设置的“状态变量”进行管理,并由mainloop(在您的情况下为while函数中的mainGame语句)进行管理,但这种设计既繁琐又出错容易-可能是这样的:


def mainGame(...):
   ...
   game_over = False
   while not game_over:
       if search_area not in search_area_options:
            game_over = True
       ...
       if search_area == "4":
            game_over = True



因此,请注意,采用这种设计,如果将“ game_over”标志更改为True,
无论在哪里,在下一次迭代中,“ while”条件都会失败,并且
该程序自然会终止您的mainGame函数的执行-
是否没有外部功能处理“再次播放”?屏幕上,程序结束。

没关系,也许对于像这样的简单游戏来说,正确的做法是。

但是在更复杂的设计中,您在主循环中的选择会变得更加复杂-您可以调用可以自行实现迷你游戏的函数,否则检查可能就不那么简单了-最重要的是,
退出此主要功能可能不止一个“游戏结束”条件,例如,将导致游戏进入下一阶段的“获胜”条件。

在这些情况下,您可能不想使用Python的Exception机制来将游戏状态记录在变量中。
异常是一种在程序错误时自然发生的语言构造,它使程序可以停止或继续在发生异常的地方“上方”的函数中运行-如果程序员仅包括正确的“ try” -except”子句以捕获异常。

因此,可以进行复杂的游戏,可以处理任意comples游戏,并且仍然可以通过创建命名良好的异常并适当地放置try-except子句,很容易始终知道执行将导致-
使用此策略的更复杂游戏的框架可能是:

# start

class BaseGameException(BaseException): pass

class ProgramExit(BaseGameException): pass

class GameOver(BaseGameException): pass

class MiniGameOver(BaseGameException): pass

class NextStage(BaseGameException): pass


def minigame():
    while True:
        # code for game-within-game mini game
        ...
        if some_condition_for_winning_main_game_stage:
            raise NextStage
        ...


def main_game(stage):
    # get data, scenarios, and variables as appropriate for the current stage
    while True:
        ...
        if some_condition_for_minigame:
            minigame()
        ...
        if condition_for_death:
            raise GameOver
        ...

def query_play_again():
    # print and get messag reponse on whether to play again
    ...
    if player_decided_to_quit:
        # This takes execution to outsude the "main_game_menu" function;
        raise ProgramExit


def main_game_menu():
    """Handle game start/play again/leatherboard screens"""
    stage = 1
    while True:
        # print welcome message, and prompt for game start
        try:
            main_game(stage)
        except NextStage:
            # print congratulations message, and prepare for next stage
            stage += 1
        except GameOver:
            # player died - print proper messages, leatherboard
            query_play_again()
            stage = 1
            # if the program returns here, just let the "while" restart the game

if __name__ == "__main__":
    try:
        main_game_menu()
    except ProgramExit:
        print("Goodbye!")

关于python - 玩家死亡时退出游戏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58136445/

10-14 17:32
查看更多