数据类型,用于存储多个玩家的累积得分

时间:2019-02-15 03:09:47

标签: python-3.x

我在这里有问题。我是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

1 个答案:

答案 0 :(得分:0)

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

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())))

我希望这会有所帮助。最高邮编将按值排序,并同时打印值和最大值的键。