jeck猫
使用 dict 来记录每个玩家名称的分数,切换一个turn持有当前掷骰子的玩家。实现了一些逻辑,即何时turn从一种更改为另一种:import randomdef score(players): for k in players: print("{} has {} points".format(k,players[k]))def hold(player): if input("Does {} want to hold? [y or anything]".format(player)).lower().strip() == "y": return "y" return "n"def main(): dice = range(1,7) players = {"p1":0, "p2":0} turn = "" change_player = "y" print("Welcome to the Two Dice Pig Game. You are Player 1!") while all(x < 100 for x in players.values()): # initially changePlayer is if change_player == "y": # print both scores on player changed score(players) turn = "p1" if turn != "p1" else "p2" dice1, dice2 = random.choices(dice,k=2) print("{} threw {} and {} for a total of {}".format(turn,d1,d2,d1+d2)) if dice1 + dice2 == 2: players[turn] = 0 print("Two 1 - you're done for now. Your points go back to 0.") change_player = "y" elif dice1 == 1 or dice2 == 1: print("One 1 - you're done for now.") change_player = "y" else: # only case where we need to add values and print new score players[turn] += dice1 + dice2 print("Your score: {}".format(players[turn])) if turn == "p1": change_player = hold(turn) else: change_player = "n" # computer is greedy, never stops winner, points = max(players.items(),key=lambda x: x[1]) print("The winner is {} with {} points.".format(winner,points))main() 输出:Welcome to the Two Dice Pig Game. You are Player 1!p1 has 0 pointsp2 has 0 pointsp1 threw 5 and 1 for a total of 6One 1 - you're done for now.p1 has 0 pointsp2 has 0 pointsp2 threw 3 and 6 for a total of 9Your score: 9p2 threw 6 and 2 for a total of 8Your score: 17p2 threw 4 and 1 for a total of 5One 1 - you're done for now.p1 has 0 pointsp2 has 17 pointsp1 threw 4 and 5 for a total of 9Your score: 9Does p1 want to hold? [y or anything]p1 threw 2 and 6 for a total of 8Your score: 17Does p1 want to hold? [y or anything]p1 threw 4 and 6 for a total of 10Your score: 27[snipp]One 1 - you're done for now.p1 has 91 pointsp2 has 51 pointsp1 threw 6 and 4 for a total of 10Your score: 101Does p1 want to hold? [y or anything]The winner is p1 with 101 points.