Python老虎机

时间:2019-06-10 20:04:53

标签: python

我无法使此python老虎机正常运行。另外,如何添加一个计数器来跟踪和显示用户玩的次数,以及一个累加器来跟踪和显示所赢取的总金额。的  带有前哨值的外循环,该值提示用户是否希望继续播放不起作用。

import random

words = ["Cherries", "Oranges", "Plums","Melons", "Bells"]


rand1 = random.randint(0,4)
rand2 = random.randint(0,4)
rand3 = random.randint(0,4)


word1 = words[rand1]
word2 = words[rand2]
word3 = words[rand3]

def random_calculate (calculate):

    print(word1, " ", word2, " ", word3)
    if (rand1 == rand2 or rand2 == rand3 or rand1 == rand3):
        if (rand1 == rand2 and rand2 == rand3):
            if(ranrand1=="Bells"):
                win=50           

        else:
            win = 10

    else:
         win = 5










def display_menue():
    print ("Welcome to the Slot Machine!")
    print ("    Match 2 of any kind to win $5")
    print ("    Match 3 of any fruit to win $10")
    print ("    Match 3 BELLS to win $50!")



def main():
    display_menue()
    calculate = random_calculate 

    choice = "y"
    while choice.lower() == "y":


        choice = input("Do you want to play? (y or n):  ")
        print("OK, pull the lever!")
        print()
        print("You have won $" + str(win))   





if __name__ == "__main__":
    main()

2 个答案:

答案 0 :(得分:0)

Python 2.7在类型检查方面做得不好。因此,当您将integerstring进行比较时,它什么也没说:) 试试看,让那台老虎机正常工作:

print(word1, " ", word2, " ", word3)
    if rand1 == rand2 == rand3:
        if rand1 == 4:
            win = 50
        else:
            win = 10
    elif rand1 == rand2 or rand2 == rand3 or rand1 == rand3:
        win = 5
    else:
         win = 0

要添加计数器和累加器,可以将它们添加为外部变量。

计数器= 0 total_winnings = 0

random_calculate函数中,您可以在最后添加这两行:

count + = 1 total_winnings + =胜利

答案 1 :(得分:0)

首先,很抱歉,如果我的回答格式不正确,这是我第一次回答。其次,我将为您提供我更正的代码和一些详细信息。

因此,我假设您的random_calculate()方法已被调用,以便它将重新生成插槽。为此,您必须将数字生成包含在该方法中,以便每次调用它时都会重新生成。同样在此函数中,由于您没有将任何变量传递到方法中,因此应从此处删除该“ calculate”。另外,为什么要存储随机生成的数字,一次只能调用它们,然后将字符串彼此进行比较,从而使用较少的变量呢?另外,如果应该将变量“ win”返回给main()函数,那么如果未将其声明为全局变量which you shouldn't do,则必须返回该变量。我还改变了打印字符串的方式,因为我个人更喜欢.format()而不是串联but I might not be the only one

这是random_calculate()方法的修改代码:

def random_calculate():
    word1 = words[random.randint(0, 4)]
    word2 = words[random.randint(0, 4)]
    word3 = words[random.randint(0, 4)]

    print("{} {} {}".format(word1, word2, word3))
    if word1 == word2 or word2 == word3 or word1 == word3:
        if word1 == word2 and word2 == word3:
            if word1 == "Bells":
                win = 50
        else:
            win = 10
    else:
        win = 5

    return win

对于main()函数,我添加了两个计数器:一个用于迭代次数(num_of_plays),另一个用于跟踪游戏中所有收益的变量({{1} }。另外,我将变量sum_of_winswin移到循环的核心。

这是random_calculate()方法的修改代码:

main()

希望这对您有帮助!