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

问题描述 投票:1回答:1

我这里有问题。我是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个回答
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())))

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

© www.soinside.com 2019 - 2024. All rights reserved.