Python使用for循环创建累积分数计数器

2024-05-15 08:14:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个囚徒困境游戏,两个(变量)玩家一起工作。如果一个玩家背叛,另一个合作,背叛的玩家得5分,另一个得0分。如果他们一起工作,他们都得3分,如果他们都背叛对方,他们每人得1分

我如何以for循环的形式为两个玩家创建累积分数计数器?游戏应该可以玩几次(直到玩家退出)。我如何最好地设置这个?到目前为止,我已经能够为每一场比赛制作一个计数器,但无法跟踪几轮的分数

迄今为止的代码:

def game():
#Task 1
player_1 = input('Name of player 1 ')
player_2 = input('Name of player 2 ')

#Set up options for prisoners dilemma for players + give them choice
print(player_1)
choice_player_1 = input('betray or cooperate? ')
print(player_2)
choice_player_2 = input('betray or cooperate? ')


#Establish a score count
count1 = 0
count2 = 0



#If statement som skiller de ulike kombinasjonene som kan oppstå
if choice_player_1 == 'cooperate' and choice_player_2 == 'betray':
    count2 += 5

elif choice_player_1 ==  'cooperate' and choice_player_2 == 'betray':
    count1 += 5

elif choice_player_1 == 'cooperate' and choice_player_2 == 'betray':
    count1 += 3
    count2 += 3

elif choice_player_1 == 'betray' and choice_player_2 == 'betray':
    count1 += 1
    count2 += 1

    #Tally the points 
print(player_1, 'you got', count1, 'points', player_2, 'you got', count2, 'points')

print('Start the program again if you want to play another round ')

Tags: andyou游戏forinput玩家pointsplayer
2条回答

你可以创建新的变量,在每一场比赛后,它都会出现单个游戏的结果。这有意义吗?还是我不理解你的问题

您可以比较tuples,而不是单独比较每个值。如果将这些元组映射到作为元组的结果分数,您将获得一个简短但可读的代码段,如下所示:

points_table = {
    ("cooperate", "betray"   ): (0, 5),
    ("betray"   , "cooperate"): (5, 0),
    ("cooperate", "cooperate"): (3, 3),
    ("betray",    "betray"   ): (1, 1),
}

count1 = 0
count2 = 0
while running:
    choice_player_1 = input('betray or cooperate? ')
    choice_player_2 = input('betray or cooperate? ')
    round_count1, round_count2 = points_table[(choice_player_1, choice_player_2)]
    count1 += round_count1
    count2 += round_count2

相关问题 更多 >