我刚刚开始学习Python作为我的第一语言,并且在尝试制作游戏时遇到了一些麻烦。这是我坚持的部分: 主要关注点:我想让它随机生成物体和门。 次要问题:即使我离开房间后,我也需要每个房间都能记住这些物品(花盆是可破坏的)
问题:我希望程序吐出罐子,箱子,内阁和门的数量,但变量仍然是空的。很抱歉没有更具体地构思这个问题,但我刚刚开始,水在这里有点模糊D:
def random_room(pot, chest, schest, ldoor, rdoor, fdoor):
import random
loop = 0
pot = 0
chest = 0
schest = 0
ldoor = 0
rdoor = 0
fdoor = 0
while loop < 6:
rand = random.randint(0, 30)
if rand in range(1, 3, 1):
chest += 1
loop += 2
return chest
if rand in range(4,10, 1):
schest -= 1
return schest
if rand == 16:
schest += 1
loop += 3
return schest
if rand > 16:
pot += 1
loop +=1
return pot
if rand in range(10,12, 1):
ldoor = 1
return ldoor
if rand in range(12,14, 1):
fdoor = 1
return fdoor
if rand in range(14, 16, 1):
rdoor = 1
return rdoor
if schest < 0:
schest = 0
if rdoor + fdoor + ldoor == 0:
rand = random.randint(1,3)
if rand == 1:
rdoor += 1
if rand == 2:
ldoor += 1
if rand == 3:
fdoor += 1
random_room(pot, chest, schest, ldoor, rdoor, fdoor)
print pot
print ldoor
print rdoor
print fdoor
print chest
print schest
room = 2
while room == 2:
left_door = ""
right_door = ""
front_door = ""
print "You enter a room."
if chest == 1:
print "There is one CHEST in the room."
if chest > 1:
print "There are", chest, "CHESTs in the room."
if pot == 1:
print "There is one POT in the room."
if pot > 1:
print "THere are", pot, "POTs in the room."
if ldoor == 1:
left_door = "a door to the LEFT"
if rdoor == 1:
right_door = "a door to the RIGHT"
if fdoor == 1:
front_door = "a door in the FRONT"
if True:
print "There's", left_door, ",", right_door, ", and", front_door
break
答案 0 :(得分:3)
Daniel,您发布的代码存在许多问题。我会尝试尽可能多地概述它们。
首先,传递给函数的参数通常提供了一种将信息转换为函数的方法,而不是函数。 Python确实允许您从函数返回多个值,因此不是这样:
random_room(pot, chest, schest, ldoor, rdoor, fdoor)
你想这样说:
pot, chest, schest, ldoor, rdoor, fdoor = random_room()
下一个大问题是return
会立即退出某个函数,因此当您在random_room
函数内部时,您会说:
while loop < 6:
rand = random.randint(0, 30)
if rand in range(1, 3, 1):
chest += 1
loop += 2
return chest
return chest
会立即退出该函数,并仅返回变量chest
中的值,该值将赋予变量pot
。但是,如果删除while
循环内的所有return语句,循环将完成执行,最后,您可以说:
return pot, chest, schest, ldoor, rdoor, fdoor
并且所有值都将返回到调用random_room
函数的代码。
最后,这段代码:
room = 2
while room == 2:
实际上没有意义,只会导致无限循环。由于while
循环中没有代码可以更改变量room
的值,因此它将继续反复打印。我想你可能想要让循环运行几次并打印出几次调用random_room
的值?
如果是这种情况,您可能希望代码看起来像这样:
room = 0
while room < 5: # Print five calls to random room
pot, chest, schest, ldoor, rdoor, fdoor = random_room()
# Code to print out values returned from random_room
# ...
room += 1
正如我在上面的评论中所说,你需要对Python和面向对象的Python做更多的阅读。 Python可能是一种非常宽容的语言,因为当您尝试运行语法合法但根本没有多大意义的代码时,它可能不会给您带来明确的错误。幸运的是,python是非常流行的语言,网上有一些无数的有用资源,你可以利用它们。
祝你好运。
答案 1 :(得分:0)
我不确定我明白你在问什么,但这个帖子可能有所帮助: