对于一个班级项目,我必须用 python 制作这个骰子游戏,我无法解决的一件事是,total_score 变量在每个玩家回合开始时重新设置为 0。我相信这是因为该值没有正确存储,但找不到解决方案。
import math, random
def print_instructions():
print("""Welcome to Pig Dice. Get 2 to 10 players and one 6 sided die. During a player's turn, they may roll the die as many times as they wish. At the end of their turn, add all of their points together and pass the die to the next person. However, if they roll a one, they lose all points gained, and that turn ends. First one to score 100 points wins.""")
def get_Player_names ():
print("You will need 2 to 10 players!")
done = False
players = []
while not done:
player = input("Names of players(hit enter to quit): ")
if len(player)>0:
players.append(player)
else:
done=True
print()
return players
def process_player_turn(player_name,total_score,turn_score):
choice = input(f"{player_name} would you like to roll or pass? ")
while choice == ("roll"):
player_value = random.randint(1,6)
print(f"{player_name} rolled a {player_value}")
turn_score = turn_score + player_value
if player_value == 1:
turn_score = 0
print(f"{player_name} rolled a 1! Turn over!")
print("Total score:", total_score)
break
if total_score >= 100:
print(f"{player_name}'s score:", total_score, f"{player_name} Wins!")
return True
choice = input(f"{player_name} would you like to roll again? ")
else:
total_score = total_score + turn_score
print("Total score:", total_score, "Turn ended.")
turn_score = 0
print()
return False
def main():
total_score = 0
turn_score = 0
print_instructions()
player_names = get_Player_names()
done = False
while not done:
for player_name in player_names:
done = process_player_turn(player_name,total_score,turn_score)
if done:
break
if __name__=="__main__":
main()
为了简单起见,您可以将所有功能合并为一个。那么你就不需要考虑变量的可访问性:
import random
MAX_SCORE = 100
print(f"""Welcome to Pig Dice. Get 2 to 10 players and one 6 sided die.
During a player's turn, they may roll the die as many times as they wish.
At the end of their turn, add all of their points together and pass the die to the next person.
However, if they roll a one, they lose all points gained, and that turn ends.
First one to score {MAX_SCORE} points wins.""")
players = []
while True:
name = input("Player name (hit enter to quit): ")
if name:
players.append(name)
else:
break
total_score = 0
while True:
for player in players:
turn_score = 0
while True:
choice = input(f"{player} would you like to roll or pass? ")
if choice == "roll":
value = random.randint(1, 6)
print(f"{player} rolled a {value}")
turn_score += value
if value == 1:
turn_score = 0
print(f"{player} rolled a 1! Turn over!")
print("Total score:", total_score)
break
else:
total_score += turn_score
print("Total score:", total_score, "Turn ended.")
break
if total_score >= MAX_SCORE:
print(f"{player}'s score:", total_score, f"{player} Wins!")
break