gpt4 book ai didi

Python 游戏逻辑

转载 作者:行者123 更新时间:2023-12-01 05:04:53 25 4
gpt4 key购买 nike

正如本网站上许多其他提问者所做的那样,我正在使用“艰难的方式学习 Python”来学习 Python。

我正在学习第 36 课,其中我们根据他在第 35 课中带领我们完成的游戏创建了自己的 BBS 风格文本游戏。

http://learnpythonthehardway.org/book/ex36.html

http://learnpythonthehardway.org/book/ex35.html

我想提高游戏的“难度”,所以我让迷宫变得更复杂一些。有些房间有多个门,而不是每个房间只有一个入口和一个导出。其中一些门不会通向任何东西,但有些房间可以从 map 内的多个房间进入。

所以,在monster_room中,玩家可以通过monkey_room或empty_room进入。问题是,无论玩家从哪里进入,monster_room 都会运行相同的代码。由于我首先构建了empty_room,所以门的选择和结果都是基于该房间的。

这是 monster_room 代码:​​

def monster_room():
print "You have stumbled into a dark room with a giant, but friendly, monster."
print "There are four doors:"
print "One straight ahead, one to your right, one to your left, and the one you just entered through."
print "Which door would you like to choose?"

door = raw_input("> ")

if "left" in door:
dead("The door magically recedes into the wall behind you and you find yourself forever trapped in a black room with no doors, no windows, and no hope of escape.")
elif "right" in door:
monkey_room()
elif "straight" in door:
dead("You step into the abyss and fall through nothingness to your certain death.")
else:
print "You found a magical shortcut to the Treasure Room!"
treasure_room()

好吧,非常简单,对吧?但是,如果有人从猴房进入,门的位置就不一样了。向左通向空荡荡的房间,向右通向深渊,直通则永远被困,而回到你来时的路仍然是一条神奇的捷径。

我知道我可以创建一个 Monster_room_2 或只能从 Monkey_room 进入的东西,并将所有门都放在“正确的位置”,但我认为可能有一种方法可以让游戏根据将它们发送到那里的函数。这有道理吗?

任何帮助将不胜感激。

最佳答案

您可以为当前房间设置一个全局值,然后使用它。

CURRENT_ROOM = "whatever"

def monster_room():
global CURRENT_ROOM
if CURRENT_ROOM = "monkey":
"""Display monkey room choices"""
else:
"""display other room choices"""
# don't forget to set your global to the room selected:
CURRENT_ROOM = new_room

如果您愿意,您当然可以使用函数而不是字符串:

CURRENT_ROOM = monkey_room

但是,全局变量是一种代码味道。您最好使用类,和/或将当前房间作为变量传递。

我会做这样的事情:

class Game:
def __init__(self):
self.current_room = self.initial_room

def initial_room(self):
...

def monster_room(self):
...

def monkey_room(self):
...

def display_room(self):
self.current_room()

因此,在游戏“循环”中,您将创建一个 Game 实例,并使用它来帮助跟踪您当前所在的位置以及类似的事情。

关于Python 游戏逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25249933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com