给我写一个猜拳的代码
时间: 2023-09-11 10:05:36 浏览: 115
猜拳游戏代码
### 回答1:
好的,我来帮你写一个简单的猜拳游戏代码。
```
import random
def game():
# 电脑出拳
computer_choice = random.randint(1, 3)
if computer_choice == 1:
computer_choice_str = "剪刀"
elif computer_choice == 2:
computer_choice_str = "石头"
else:
computer_choice_str = "布"
# 用户出拳
user_choice = int(input("请出拳:1.剪刀 2.石头 3.布\n"))
if user_choice == 1:
user_choice_str = "剪刀"
elif user_choice == 2:
user_choice_str = "石头"
else:
user_choice_str = "布"
# 判断胜负
if user_choice == computer_choice:
result = "平局"
elif (user_choice == 1 and computer_choice == 3) or (user_choice == 2 and computer_choice == 1) or (user_choice == 3 and computer_choice == 2):
result = "你赢了"
else:
result = "你输了"
# 输出结果
print("电脑出拳:" + computer_choice_str)
print("你出拳:" + user_choice_str)
print("结果:" + result)
game()
```
这个代码会让电脑随机出拳,然后提示用户输入出拳决定胜负,最后输出结果。
希望这个代码能帮到你!
### 回答2:
当然可以!以下是一个简单的猜拳游戏的代码:
```python
import random
def janken():
win_message = "你赢了!"
lose_message = "你输了!"
draw_message = "平局!"
error_message = "请输入有效的选择:1(石头)、2(剪刀)或3(布)。"
choices = ["石头", "剪刀", "布"]
user_choice = input("请选择:(1)石头 (2)剪刀 (3)布\n")
computer_choice = random.choice(choices)
if user_choice not in ["1", "2", "3"]:
return error_message
else:
user_choice = choices[int(user_choice) - 1]
print("你选择了:" + user_choice)
print("电脑选择了:" + computer_choice)
if user_choice == computer_choice:
return draw_message
elif (user_choice == "石头" and computer_choice == "剪刀") or (user_choice == "剪刀" and computer_choice == "布") or (user_choice == "布" and computer_choice == "石头"):
return win_message
else:
return lose_message
result = janken()
print(result)
```
你只需要运行这段代码,它会要求你做出你的选择(1代表石头,2代表剪刀,3代表布),然后显示电脑的选择和游戏的结果。玩得开心!
阅读全文