python写一个玩家和电脑石头剪刀布的代码
时间: 2024-09-13 09:18:00 浏览: 42
当然可以。Python编写一个简单的石头、剪刀、布游戏的基本步骤如下:
```python
import random
# 定义游戏中可供选择的选项
choices = ["石头", "剪刀", "布"]
def player_choice():
while True:
player_input = input("请输入你的选择(石头/剪刀/布),或输入'q'退出游戏:")
if player_input.lower() == 'q':
print("游戏结束,感谢参与!")
break
elif player_input.lower() in choices:
return player_input.lower()
else:
print("无效的选择,请重新输入。")
def computer_choice():
return random.choice(choices)
def play_round(player, computer):
print(f"玩家出{player},电脑出{computer}.")
# 判断输赢
if player == computer:
result = "平局"
elif (player == "石头" and computer == "剪刀") or \
(player == "剪刀" and computer == "布") or \
(player == "布" and computer == "石头"):
result = "玩家胜利"
else:
result = "电脑胜利"
print(f"结果:{result}")
def main():
rounds = 1
while rounds > 0:
player = player_choice()
computer = computer_choice()
play_round(player, computer)
rounds -= 1
continue_playing = input("还想再玩一局吗?(y/n): ")
if continue_playing.lower() != 'y':
break
if __name__ == "__main__":
main()
```
阅读全文