我这里有问题。我是Python的新手。我想创建一个迷你游戏名称骰子卷。规则是这样的:
这是我的代码,我目前停留在第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中,我们有一个称为字典的数据类型,它存储名称/分数等键/值对,非常适合您的程序。我在你的代码中添加了一个名为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将按值排序并打印最大值的值和键。