石头剪刀布用Python
时间: 2023-11-16 18:12:04 浏览: 23
好的,以下是一个石头剪刀布游戏的 Python 实现:
```python
import random
# 定义石头剪刀布的三种状态
ROCK = 1
SCISSORS = 2
PAPER = 3
# 定义石头剪刀布的胜负规则
RULES = {
(ROCK, SCISSORS): 1,
(SCISSORS, ROCK): -1,
(SCISSORS, PAPER): 1,
(PAPER, SCISSORS): -1,
(PAPER, ROCK): 1,
(ROCK, PAPER): -1,
(ROCK, ROCK): 0,
(SCISSORS, SCISSORS): 0,
(PAPER, PAPER): 0
}
# 定义石头剪刀布的玩家类
class Player:
def __init__(self, name):
self.name = name
self.score = 0
def choose(self):
print("%s, please choose (1: rock, 2: scissors, 3: paper):" % self.name)
choice = int(input())
while choice not in [ROCK, SCISSORS, PAPER]:
print("Invalid input, please choose again:")
choice = int(input())
return choice
# 定义石头剪刀布的游戏类
class RockScissorsPaperGame:
def __init__(self, player1, player2):
self.player1 = player1
self.player2 = player2
def play(self):
for i in range(3):
print("Round %d:" % (i+1))
choice1 = self.player1.choose()
choice2 = self.player2.choose()
result = RULES[(choice1, choice2)]
if result == 1:
print("%s wins!" % self.player1.name)
self.player1.score += 1
elif result == -1:
print("%s wins!" % self.player2.name)
self.player2.score += 1
else:
print("Draw!")
print("%s: %d, %s: %d" % (self.player1.name, self.player1.score, self.player2.name, self.player2.score))
if self.player1.score > self.player2.score:
print("%s wins the game!" % self.player1.name)
elif self.player1.score < self.player2.score:
print("%s wins the game!" % self.player2.name)
else:
print("The game is a draw.")
# 创建两个玩家对象并开始游戏
player1 = Player("Player 1")
player2 = Player("Player 2")
game = RockScissorsPaperGame(player1, player2)
game.play()
```
玩家可以通过控制台输入 1、2、3 来选择石头、剪刀或布。游戏进行 3 轮,最后输出胜利者或者平局。