石头剪刀布用Python
时间: 2023-11-16 07:06:58 浏览: 105
以下是一个简单的石头剪刀布游戏的 Python 代码示例:
```
import random
# 定义游戏结果的常量
PLAYER_WIN = 1
COMPUTER_WIN = -1
TIE = 0
# 定义选项的常量
ROCK = 'rock'
PAPER = 'paper'
SCISSORS = 'scissors'
# 定义选项的列表
OPTIONS = [ROCK, PAPER, SCISSORS]
# 定义玩家输入函数
def get_player_choice():
while True:
choice = input("Enter your choice (rock/paper/scissors): ")
if choice in OPTIONS:
return choice
else:
print("Invalid choice. Please try again.")
# 定义电脑选择函数
def get_computer_choice():
return random.choice(OPTIONS)
# 定义判断胜负的函数
def get_result(player_choice, computer_choice):
if player_choice == computer_choice:
return TIE
elif player_choice == ROCK and computer_choice == SCISSORS:
return PLAYER_WIN
elif player_choice == PAPER and computer_choice == ROCK:
return PLAYER_WIN
elif player_choice == SCISSORS and computer_choice == PAPER:
return PLAYER_WIN
else:
return COMPUTER_WIN
# 主游戏循环
while True:
player_choice = get_player_choice()
computer_choice = get_computer_choice()
result = get_result(player_choice, computer_choice)
print("You chose:", player_choice)
print("Computer chose:", computer_choice)
if result == PLAYER_WIN:
print("You win!")
elif result == COMPUTER_WIN:
print("You lose!")
else:
print("It's a tie.")
play_again = input("Do you want to play again? (y/n): ")
if play_again.lower() != 'y':
break
print("Thanks for playing!")
```
运行上述代码,即可开始石头剪刀布游戏。
阅读全文