我在哪里分配我的作业?

时间:2015-09-22 23:47:25

标签: python variables integer variable-assignment currency

我创建了一个程序,您可以根据帐户的密码“破解”虚假的银行帐户。我将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。请帮忙,谢谢!!!

2 个答案:

答案 0 :(得分:0)

Python的功能是function scoped。因此,在引用它之前,您需要将生命放在函数定义中但在while循环之前。另一方面,您可以明确地声明它以引用程序中声明的生命的全局版本。或者您可以将游戏定义为具有传递的参数,然后将其指定为“生命”。

答案 1 :(得分:0)

您需要将全局变量移动到容器类中。在构造函数(下面的__init__方法)中初始化它们,而不是从内部调用game,创建一个外部循环,每次都创建一个新游戏。

class Game(object):
    def __init__(self):
        self.lives = 100
        self.money = 0

    def run(self):
        password = random.randint(100, 999)
        while self.lives < 100:
           ...
        ...
        time.sleep(2)
        # game()

while True:
    g = Game()
    g.run()