如何用Python实现人机猜拳游戏
时间: 2024-02-10 19:10:36 浏览: 30
可以通过Python的随机数模块和条件语句来实现人机猜拳游戏。
以下是一个简单的实现方式:
```python
import random
print("欢迎来到猜拳游戏!")
print("请出拳:1.石头 2.剪刀 3.布")
player = int(input())
computer = random.randint(1, 3)
if (player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1):
print("你赢了!")
elif (player == 1 and computer == 3) or (player == 2 and computer == 1) or (player == 3 and computer == 2):
print("你输了!")
else:
print("平局!")
print("电脑出的是:", computer)
```
首先,使用 `random` 模块随机生成电脑出拳的数字,然后通过 `input()` 函数获取玩家输入的数字,再使用条件语句判断胜负并输出结果。最后,显示电脑出的拳头数字。
相关问题
python实现人机猜拳游戏
好的,以下是Python实现:
```python
import random
print("欢迎来到人机猜拳游戏!")
print("请出拳:1.石头 2.剪刀 3.布")
while True:
player = int(input("请出拳:"))
if player == 1:
print("玩家出拳:石头")
elif player == 2:
print("玩家出拳:剪刀")
elif player == 3:
print("玩家出拳:布")
else:
print("输入错误,请重新输入!")
continue
computer = random.randint(1, 3)
if computer == 1:
print("电脑出拳:石头")
elif computer == 2:
print("电脑出拳:剪刀")
else:
print("电脑出拳:布")
if (player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1):
print("玩家获胜!")
elif player == computer:
print("平局!")
else:
print("电脑获胜!")
play_again = input("再玩一局吗?(y/n)")
if play_again == "n":
print("游戏结束,再见!")
break
```
程序会进入一个循环,每次先让玩家输入出拳的数字,分别代表石头、剪刀和布,然后程序会随机生成电脑出拳的结果。接着,程序会判断出拳的结果,根据规则判断胜负,并输出相应的信息。最后询问玩家是否再玩一局,如果输入"n"则退出游戏,否则继续进行游戏。
python编写实现人机猜拳游戏
好的,以下是一个 Python 代码实现人机猜拳游戏:
```python
import random
def play_game():
gestures = ['rock', 'paper', 'scissors']
computer_gesture = random.choice(gestures)
user_gesture = input("Please enter your gesture (rock/paper/scissors): ")
print("Computer's gesture: " + computer_gesture)
if computer_gesture == user_gesture:
print("It's a tie!")
elif (computer_gesture == 'rock' and user_gesture == 'scissors') or \
(computer_gesture == 'paper' and user_gesture == 'rock') or \
(computer_gesture == 'scissors' and user_gesture == 'paper'):
print("You lose!")
else:
print("You win!")
play_game()
```
运行代码后,程序会让用户输入手势,然后随机生成计算机的手势,最后输出比赛结果。