python人机猜拳游戏代码且统计胜率局数
时间: 2023-07-09 08:42:42 浏览: 70
好的,下面是一个增加了统计胜率和局数的Python人机猜拳游戏代码:
```python
import random
valid_inputs = ["rock", "paper", "scissors"]
total_rounds = 0
win_rounds = 0
while True:
# 人出拳
user_input = input("Please choose 'rock', 'paper', or 'scissors': ")
user_input = user_input.lower().strip()
# 判断人出拳是否合法
if user_input not in valid_inputs:
print("Invalid input, please try again.")
continue
# AI出拳
ai_input = random.choice(valid_inputs)
print(f"AI chose {ai_input}.")
# 判断胜负
if user_input == ai_input:
print("Tie!")
elif user_input == "rock" and ai_input == "scissors":
print("You win!")
win_rounds += 1
elif user_input == "paper" and ai_input == "rock":
print("You win!")
win_rounds += 1
elif user_input == "scissors" and ai_input == "paper":
print("You win!")
win_rounds += 1
else:
print("AI wins!")
total_rounds += 1
win_rate = win_rounds / total_rounds
print(f"Win rate: {win_rate:.2%} ({win_rounds}/{total_rounds})")
# 判断是否继续游戏
play_again = input("Do you want to play again? (y/n): ")
if play_again.lower().strip() != "y":
break
```
代码在原有的基础上增加了两个变量:`total_rounds`和`win_rounds`,用于分别统计总共进行的局数和赢的局数。在每轮游戏结束时,程序都会更新这两个变量,并计算胜率,输出对应的结果。另外,程序还会询问人是否继续游戏,如果不继续,则退出游戏循环。