【问题标题】:Quitting to Game Over when player dies玩家死亡时退出游戏结束
【发布时间】:2019-09-27 14:21:42
【问题描述】:

所以,我正在开发一个基于 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

【问题讨论】:

  • 为什么不直接退出(0)?

标签: python python-3.x macos adventure


【解决方案1】:

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

因此,在游戏中,您通常希望从主循环调用的函数中跳出主循环并转到代码设置下一个游戏阶段的地方,或者显示游戏结束的地方屏幕,并提议开始新游戏。

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

因此,虽然这可以通过可以由这些函数设置并由主循环管理的“状态变量”进行管理(在您的情况下,mainGame 函数中的 while 语句),但该设计是乏味且容易出错 - 类似于:


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 的异常机制,而不是将游戏状态记录在变量中。 异常是在程序错误时自然发生的语言结构,它使程序能够停止或继续在发生异常的位置“上方”的函数中运行 - 如果程序员只包含正确的“尝试” -except" 子句来捕获异常。

因此,一个复杂的游戏可以发生,它可以处理任意复杂的游戏,并且仍然通过创建名称良好的异常并适当地放置 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!")

【讨论】:

    【解决方案2】:

    要退出脚本,可以使用

    import sys
    sys.exit()
    

    至于你的 badResponse 错误:你试图在 bad-response 函数中使用变量 search_area ,但该变量是在另一个函数中定义的,这意味着它无法访问它。您要么必须将 search_area 作为参数传递给 badResponse,要么将 search_area 设为全局变量(在顶部定义,在任何函数之外)。

    【讨论】:

      【解决方案3】:

      在你的函数中 search_area 不存在。

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

      您需要将 search_area 传递给您的函数:

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

      当你想调用函数时使用:

      badResponce(search_area)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        • 1970-01-01
        • 2021-06-15
        相关资源
        最近更新 更多