石头剪刀布python代码
时间: 2023-10-28 08:58:57 浏览: 58
当然,我可以为您提供石头剪刀布的Python代码。以下是一个简单的示例:
```python
import random
def get_user_choice():
choice = input("请选择:1. 石头, 2.剪刀, 3.布\n")
while choice not in ["1", "2", "3"]:
choice = input("请选择有效选项:1. 石头, 2.剪刀, 3.布\n")
return int(choice)
def get_computer_choice():
return random.randint(1, 3)
def determine_winner(user_choice, computer_choice):
if user_choice == computer_choice:
return "平局!"
elif (user_choice == 1 and computer_choice == 2) or \
(user_choice == 2 and computer_choice == 3) or \
(user_choice == 3 and computer_choice == 1):
return "恭喜,您赢了!"
else:
return "很遗憾,您输了!"
def play_game():
user_choice = get_user_choice()
computer_choice = get_computer_choice()
print("您的选择:")
print(get_choice_text(user_choice))
print("电脑的选择:")
print(get_choice_text(computer_choice))
print(determine_winner(user_choice, computer_choice))
def get_choice_text(choice):
if choice == 1:
return "石头"
elif choice == 2:
return "剪刀"
elif choice == 3:
return "布"
else:
return ""
play_game()
```
这个代码中,用户通过输入数字来选择石头、剪刀或布(分别对应1、2、3)。计算机会随机生成一个选择。然后根据用户和计算机的选择来判断胜负关系并输出结果。希望对您有所帮助!