【问题标题】:Datatype to store accumulated scores for multiple players用于存储多个玩家的累积分数的数据类型
【发布时间】:2019-07-09 04:13:02
【问题描述】:

我这里有问题。我是 Python 新手。我想创建一个迷你游戏名称骰子。规则是这样的:

  1. 卷数不限

  2. 玩家人数不受限制 (无限意味着用户可以添加任意数量的玩家和滚动)

  3. 然后在每个玩家进行一定的尝试后,它会根据他们掷骰子的次数来计算总骰子

  4. 然后程序将计算总分最高的玩家并成为获胜者。

这是我的代码,我目前停留在第 4 点。

import random

numPlayer = int(input("Enter number of player:"))
numTest = int(input("Enter the number of test:"))

def dice_roll():
    total = 0
    for i in range(numTest):
        nana = random.randint(1 , 6)
        total = total + nana
    #print("TOTAL: " + str(total))
    return total

player = 0
for j in range(numPlayer):  # number of player
    print("\n")
    print("Player " + str(j + 1))
    print("-------")
    print(dice_roll())

# create a variable to store total for each player

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    在 python 中,我们有一种称为字典的数据类型,它存储键/值对,例如名称/分数,非常适合您的程序。我在您的代码中添加了一个名为 highScore 的字典,它现在工作得很好,并打印了 (score, player) 对,这样您就知道谁赢了,他们的得分是多少。它仍然会打印其他玩家,因此您可以检查它:

    import random
    
    
    def dice_roll(rolls):
        total = 0
        for i in range(rolls):
            nana = random.randint(1, 6)
            total = total + nana
        print("TOTAL :" + str(total))
        return total
    
    
    # gather user parameters
    numPlayer = int(input("Enter number of player:"))
    numTest = int(input("Enter the number of test:"))
    
    # initialize a dictionary to store the scores by player name
    highScore = {}
    
    player = 0
    for j in range(numPlayer):
        print("\n")
        name = ("Player "+str(j+1))  # assign the name to a string variable
        print(name)
        print("-------")
        score = dice_roll(numTest)   # store the value in an int variable
        print(str(score))
        highScore[name] = score      # store the name and score in a dictionary
    
    # prints the high score and the player (score, player)
    print(max(zip(highScore.values(), highScore.keys())))
    

    我希望这会有所帮助。 max zip 将按值排序并打印最大值的值和键。

    【讨论】:

    • 我将名称和分数放入变量中,然后打印这些变量以保持您当前的格式。以这种方式准备会更容易一些。
    猜你喜欢
    • 2014-06-29
    • 2019-07-08
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多