完成五局三胜石头剪刀布Python
时间: 2024-10-19 22:02:06 浏览: 40
在Python中实现“石头、剪刀、布”游戏的五局三胜规则,你可以创建一个简单的循环,让两个玩家轮流出拳(石头、剪刀、布),然后判断胜负并累计分数。以下是简化的代码示例:
```python
import random
def get_user_choice():
choices = ['石头', '剪刀', '布']
return input("请输入你的选择(石头、剪刀、布):").lower().strip() in choices
def compare_choices(player, computer):
if player == computer:
return "平局"
elif (player == '石头' and computer == '剪刀') or \
(player == '剪刀' and computer == '布') or \
(player == '布' and computer == '石头'):
return "你赢了"
else:
return "电脑赢了"
def game_rounds(user_score, computer_score, max_rounds):
while user_score < 3 and computer_score < 3:
player_choice = get_user_choice()
computer_choice = random.choice(['石头', '剪刀', '布'])
result = compare_choices(player_choice, computer_choice)
print(f"你出了{player_choice},电脑出了{computer_choice},结果是{result}")
if result == "你赢了":
user_score += 1
else:
computer_score += 1
return user_score, computer_score
def main():
user_score = 0
computer_score = 0
max_rounds = 5
for _ in range(max_rounds):
user_score, computer_score = game_rounds(user_score, computer_score, max_rounds)
print("\n游戏结束,最终得分:")
print("你", user_score, "比", computer_score, "分")
if __name__ == "__main__":
main()
阅读全文