为uni编写一个非常基本的基于文本的游戏... 试图拥有一个全局变量或“密钥”,允许访问某些区域,如果已“找到” 即。找到key = 1时。尝试使用以下代码尝试访问房间时确定结果的所有权(或其他): (我只会包含相关的代码部分)
def playGame():
key = 0
location = "Porch"
showIntroduction()
while not (location == "Exit") :
showRoom(location)
direction = requestString("Which direction?")
location = pickRoom(direction , location)
def showRoom(location):
if location == "Porch":
showPorch()
if location == "Entryway":
showEntryway()
if location == "Kitchen":
if direction == "north":
return "DiningRoom"
if direction == "west":
if key == 1:
return "Stairs"
else:
printNow("You do not possess the Skeleton Key!")
return "Kitchen"
if direction == "south":
return "Entryway"
def showLR():
if key == 0:
printNow("...")
printNow("You enter the living room; dust covers the fireplace.")
printNow("Cobwebs shield a great armchair and it's contents from view.")
printNow("You spot an object glinting on the mantle, the dim light casting flickering shadows all around.")
printNow("The only exit lies behind, to the west")
printNow("...")
if key == 1:
printNow("...")
printNow("The living room shimmers in the dappled light.")
printNow("Cobwebs shield a great armchair and it's contents from view.")
printNow("The key in your pocket feels warm, or is it just your imagination?")
printNow("The only exit lies behind, to the west")
printNow("...")
希望以上内容有意义,大多数函数(showEntryway()showPorch())都被省略,但它们对showLR()做了类似的事情。
每次进入LivingRoom并运行时,我都试图让“键”作为变量工作:
if key == 0:
我收到一个错误,说找不到变量,初始值不是从playGame()传递的...... \
希望这是可以理解的,任何帮助都会感激不尽!谢谢 TG
答案 0 :(得分:2)
您有两个选项:将密钥设为global
变量,或将其作为第二个参数传递。
对于全局样式,您需要在函数中添加global key
行,您还需要更新它(即找到密钥)。
全球风格:
key = 0
def playGame():
global key
key = 0
location = "Porch"
showIntroduction()
while not (location == "Exit") :
showRoom(location)
direction = requestString("Which direction?")
location = pickRoom(direction , location)
def showRoom(location):
if location == "Porch":
showPorch()
if location == "Entryway":
showEntryway()
if location == "Kitchen":
if direction == "north":
return "DiningRoom"
if direction == "west":
if key == 1:
return "Stairs"
else:
printNow("You do not possess the Skeleton Key!")
return "Kitchen"
if direction == "south":
return "Entryway"
def showLR():
if key == 0:
printNow("...")
printNow("You enter the living room; dust covers the fireplace.")
printNow("Cobwebs shield a great armchair and it's contents from view.")
printNow("You spot an object glinting on the mantle, the dim light casting flickering shadows all around.")
printNow("The only exit lies behind, to the west")
printNow("...")
if key == 1:
printNow("...")
printNow("The living room shimmers in the dappled light.")
printNow("Cobwebs shield a great armchair and it's contents from view.")
printNow("The key in your pocket feels warm, or is it just your imagination?")
printNow("The only exit lies behind, to the west")
printNow("...")
或者,您可以维护一个关键变量,并将其传递给每个函数(“查找”键是一个不同的野兽)。想想如果key
变量不是全局的,你将如何更新它。我会留下这个练习。