编程,使用while循环的方法实现人机“石头、剪刀、布”游戏(玩家通过键盘输入数字的方式出拳,电脑随机出拳,判断胜负情况并将其进行输出,当输入无效时继续出拳)Python
时间: 2024-10-23 14:21:41 浏览: 22
Python石头剪刀布游戏编程教程
实现这样的游戏,你可以先定义三种状态(石头、剪刀、布),然后利用`random`模块来生成电脑的选择,同时用`while`循环来保证用户持续输入直到有效选择为止。下面是一个简单的示例:
```python
import random
# 定义游戏选项
choices = ['石头', '剪刀', '布']
player_choice = None
while True:
player_input = input("请输入1代表石头,2代表剪刀,3代表布(输入无效则重新开始):")
if player_input.isdigit() and int(player_input) in [1, 2, 3]:
player_choice = choices[int(player_input) - 1]
computer_choice = random.choice(choices)
print(f"你出了:{player_choice}, 电脑出了:{computer_choice}")
if player_choice == computer_choice:
result = "平局"
elif (player_choice == '石头' and computer_choice == '剪刀') or \
(player_choice == '剪刀' and computer_choice == '布') or \
(player_choice == '布' and computer_choice == '石头'):
result = "你赢了!"
else:
result = "你输了!"
print(f"结果是:{result}\n")
else:
print("无效输入,请重新开始!")
阅读全文