def coins():
#randomly generated amount of coins, can throw them
global num_coins
print 'You have', num_coins, 'coins left.'
opt = yon('You could throw a coin if you wanted too. Y/N')
if opt == 'Y' and num_coins >0 :
print 'You throw a coin. It clutters around the ground.'
num_coins = int(num_coins)
num_coins -= 1
num_coins = str(num_coins)
print 'You have', num_coins, 'coins left.'
else:
'You decide to keep your change for later.'
if num_coins == 1:
inventory['coins'] = inventory['coin']
if num_coins == 0:
del inventory['coin']
return num_coins
return options()
amount = random.randrange(5, 12)
num_coins = str(amount)
inventory = ['Lighter', 'Phone', num_coins + ' Coins', 'Empty', 'Empty']
大家好,制作基于文字的游戏。我有一段时间试图让我的代码工作。当我调用函数coins()时,选择投掷硬币。它不会从全局变量num_coins中带走任何硬币。我有一个单独的函数,它调用我的代码中的所有函数,(options())。它也不会将我返回到函数选项()。非常感谢任何帮助,谢谢。
答案 0 :(得分:2)
无需在int
和str
之间切换。您可以使用str.format
将值包含在字符串中:
print "You have {0} coins left.".format(num_coins)
不是使用global
,而是使num_coins
成为一个参数,然后再return
:
def coins(num_coins):
...
return num_coins
现在,当您致电coins
时,请执行:
num_coins = coins(num_coins)
现在发生的事情要清楚得多。