【发布时间】:2023-03-22 04:35:01
【问题描述】:
我创建了一个程序,您可以在其中根据帐户密码“破解”虚假银行帐户以获取资金。我将money 指定为 0(因为游戏是每次打开时都会重新启动的游戏类型),将lives 指定为 100,因为您有 100 条生命来获得尽可能多的钱。代码如下:
#PASSWORD GUESSING MONEY GAME
#
#
#
#
import random
import time
print('Hello, please enter a name for your bank account.')
bank_acc = input()
print('Welcome to your bank account: ' + bank_acc)
print("$$$: 0")
print('Just press ENTER when ready.')
print('At the press of a button, you will have access to hundreds of millions of bank accounts.')
print('But do not be so quick, you will be required to hack the password of each bank account.')
print('Each and every password is a 3-digit code.')
print('You have 100 lives to do so. Each time you get the password wrong, subtracts a life')
print('After you use up all 100 lives, your bank account will be reset.')
print('Good luck')
money = 0
lives = 100
def game():
passwords = random.randint(100, 999)
while lives <= 100:
print('Take a guess')
guess = input()
guess = int(guess)
if guess < passwords:
print('Password incorrect. Number too low.')
lives = lives - 1
if guess > passwords:
print('Password incorrect. Number too high')
lives = lives -1
if guess == passwords:
break
if guess == passwords:
money = money + passwords
print('Hacking account...')
time.sleep(1)
print('.')
time.sleep(1)
print('.')
time.sleep(1)
print('.')
print('Account hacked.')
print('...Adding money to account...')
print('Your Account:')
print('$$$: ' + str(money))
print('Lives: ' + str(lives))
print('...NEXT ACCOUNT...')
print('')
print('')
time.sleep(2)
game()
game()
当它说在分配之前引用了lives。我知道,由于lives 没有在具有while lives <= 100: 的代码块中分配,但是我可以在哪里放置分配以在引用它之前进行分配。我知道你可以把它放在哪里,但是......如果有人猜对了密码,我不想在进入下一个帐户时将钱重置回 0 并且将生命重置回 100。请帮忙,谢谢!!!
【问题讨论】:
-
作为
def game():之后的第一行添加以下内容:global live- 如果您希望能够引用它,您应该将其声明为全局!旁注:最好避免使用全局变量。仔细考虑是否真的需要 - 或者是否可以将其传递给函数! -
@alfasin 不会让 live 变量在所有范围内都可用吗?
-
@PatrickBassut 它已经是(通过在函数之外声明它)
-
@alfasin 没看到。我以为它根本没有声明
-
@alfasin 非常感谢!!!成功了!
标签: python variables integer variable-assignment currency