如何循环播放python游戏又能使其变得更干净?

时间:2019-03-21 02:53:29

标签: python-3.x

我在循环播放此游戏时遇到了麻烦,但同时也使其更加简洁。我对编码非常陌生,所以我对python知识不多。 在幸运七人制游戏中,玩家掷出一对骰子。如果点加起来等于7,则玩家赢得$ 4;否则,玩家将损失$ 1。假设为了吸引易受骗的人,赌场告诉玩家有很多获胜方法:(1、6),(2、5)以及很快。
    您面临的挑战是编写一个程序来演示游戏的无用性。您的Python程序应将玩家想要放入底池中的金额作为输入,并进行游戏直到底池为空。

The program should have at least TWO functions (Input validation and Sum of the dots of user’s two dice). Like the program 1, your code should be user-friendly and able to handle all possible user input. The game should be able to allow a user to ply several times.

The program should print a table as following:

Number of rolls     Win or Loss     Current value of the pot  
          1                Put          $10
          2                Win          $14
          3                Loss         $11

这是我到目前为止所得到的。我主要在restart()上遇到麻烦

import random

pot = 0
number_rolls = []
winloss = [0]
valuepot = []
rollcounter = 0
maxpot = 0

def confirmation():
    user_input = input ("How much would you like to add to the pot?")
    try:
        global pot
        pot = int(user_input)
        if(pot > 0):
            valuepot.append(pot)
    else:
        print("Please enter a positive number.")
        confirmation()
    except ValueError:
        print("Please enter an integer.")
        confirmation()

def dice_roll():
    global pot
    global rollcounter
    global number_rolls
    global winloss
    global maxpot
    dice1 = random.randint(1,6)
    dice2 = random.randint(1,6)
    dicetotal = dice1 + dice2
    if pot > 0:
        if dicetotal == 7:
            pot += 4
            rollcounter += 1
            number_rolls.append(rollcounter)
            valuepot.append(pot)
            winloss.append("Win")
            if pot > maxpot:
                maxpot = pot
        dice_roll()
    elif dicetotal != 7:
        pot -= 1
        rollcounter += 1
        number_rolls.append(rollcounter)
        valuepot.append(pot)
        winloss.append("Loss")
        if pot > maxpot:
            maxpot = pot
        dice_roll()
    else:
        print("Number of rolls", '\t', "Win or Loss", '\t', "Current Value of Pot")  
        for number_rolls in number_rolls:
            print(number_rolls, '\t\t\t\t\t\t', winloss[number_rolls], '\t\t\t', valuepot[number_rolls])

def restart():
    try:
        userinput =(input('Would you like to try again? Type "yes" or "no"'))
        if userinput == ('yes'):
            confirmation()
            dice_roll()
        if userinput == ('no'):
            print("Thank you for playing, Bye-bye!")
            exit()
        else:
            print('Please type "yes" or "no"')
            return
    except ValueError:
        print('Please type "yes" or "no"')

confirmation()
dice_roll()
print('You lost your money after', rollcounter,'rolls of plays')
print('The maximum amount of money in the pot during the playing is $', maxpot)
restart()

我明白了
        追溯(最近一次通话):       在第77行的文件“ XXXXX”中         重新开始()       重新启动文件“ XXXXX”,第62行         dice_roll()       在dice_roll中,文件“ XXXXX”,第46行         number_rolls.append(rollcounter)     AttributeError:“ int”对象没有属性“ append”

1 个答案:

答案 0 :(得分:0)

晚上好,我在写了少量伪代码后重新编写了程序。这可以帮助程序员甚至在编写代码之前就整理好思想。将其视为代码的概述,如果您是视觉学习者,则伪代码的流程图可以帮助可视化代码。如果您想查看伪代码,请在评论中告诉我,我将其添加为编辑内容。
这应该可以提供您所需要的内容,但是请仔细阅读注释,因为它们解释了代码内部的情况。随着该代码更接近于编程的功能范例,Python被认为既适用于面向对象编程又适用于功能编程。两者都有其优点和缺点,但是强烈建议您理解该概念,因为它将使大多数代码的逻辑流程易于理解。祝您有个美好的夜晚,如果您有任何其他疑问,请随时发表评论,或者如果我忘记了什么,请尽快告诉我。 对于有经验的人,如果我在上面说错了,请纠正。谢谢您的帮助。

import random

def playRound(budget: int) -> tuple:
    """ 
        The values are calculated directly inside the params so
        that the Garabage Collector can know the memory is free. 
        While not import here, it is still an important thing to 
        be aware of in any program.    
    """
    sum = sumOfDice(random.randint(1,6), random.randint(1,6))
    if sum == 7:
        budget += 4
        return ("Win",budget)
    else:
        budget -= 1
        return ("Loss",budget)

def sumOfDice(die1: int, die2: int) -> int:
        return die1 + die2

def haveMoney(budget: int) -> bool:
    # This is a ternary expression it is an if statement in one line
    #     Truthy   Expression      Falsy
    return True if budget > 0 else False

def main():
    numRolls = 0

    """
        This is a template string, not to be confused with an F-String.
        The user may use str.format(args*,kwargs**) to unpack into it.
        In english, kwargs pass keyword with value and it will fill 
        respectively. For args, pass in order as each number represents 
        an index to fill the values respectively.
    """
    outputString = "\t{0}\t\t{1}\t\t{2}"

    # To prevent a type error, the string is explicitly converted to int
    budget = int(input("What is your gambling budget?"))

    # \t is the metacharacter representing a tab
    print("Number of rolls\t\tWin or Loss\tCurrent value of the pot")

    print(outputString.format(numRolls, "Put", budget))

    # The return value is a boolean type, thus the output is the expression
    while haveMoney(budget):
        # Python does not support the pre-increment or post-crement operator
        numRolls += 1
        output = playRound(budget)
        budget = output[1]
        print(outputString.format(numRolls, output[0], output[1]))

    print("Sorry you're out of money")    

# Entry point for a Python program
if __name__ == "__main__":
    main()
    # Your solution works but it does not need a dedicated funct
    while True:
        userIn = input("Would you like to play again?")
        if 'yes' == userIn:
            main()
        else:
            print("Goodbye")
            break

如果您想使用外部文件,这是一种方法:

import efficent_lucky_sevens

def main():
    while True:
        efficent_lucky_sevens.main()
        userIn = input("Would you like to play again?")
        if 'yes' == userIn:
            efficent_lucky_sevens.main()
        else:
            print("Goodbye")
            break

if __name__ == "__main__":
    main()