我正在尝试学习 Python (3),并且想尝试一些 OOP。我编写了这个程序,其中两个计算机“玩家”玩“石头剪刀布”。它有效,但我希望有人可以看看并告诉我我是否犯了任何愚蠢的错误!
# rock.py
# example of OOP
import random
class Rock:
def main(self):
self.Make_players()
print("Best of Five - Let's play!\n")
done = False
while done == False:
self.p1.go_player()
self.p2.go_player()
print()
if self.p2.go == self.p1.go:
print("No winner!\n")
continue
else:
temp = self.check(self.p1, self.p2)
if temp == False:
temp = self.check(self.p2, self.p1)
print(self.message, end = " ")
print(temp.name + " won this round.")
temp.scored()
print(self.p1.name + ": " + str(self.p1.score))
print(self.p2.name + ": " + str(self.p2.score))
if self.p1.score == 3:
self.winner = self.p1
done = True
elif self.p2.score == 3:
self.winner = self.p2
done = True
else:
done = False
input()
print("The winner was " + self.winner.name + "!")
def __init__(self):
print("**** Welcome to Rock, Paper, Scissors!****\n")
self.winner = False
self.main()
def Make_players(self):
temp = (input("What shall we call Player 1? "))
self.p1 = Player(temp)
temp = (input("What shall we call Player 2? "))
self.p2 = Player(temp)
def check(self, p_a, p_b):
if p_a.go == "rock" and p_b.go == "scissors":
self.message = "Rock breaks scissors."
return p_a
elif p_a.go == "paper" and p_b.go == "rock":
self.message = "Paper wraps stone."
return p_a
elif p_a.go == "scissors" and p_b.go == "paper":
self.message = "Scissors cut paper."
return p_a
else:
return False
class Player:
def __init__(self, name):
self.choices = ["rock", "paper", "scissors"]
self.score = 0
self.name = name
print("Player:", self.name, "created!\n")
def go_player(self):
self.go = random.choice(self.choices)
print(self.name + " chose " + self.go, end = ". ")
return self.go
def scored(self):
self.score += 1
# Main
game = Rock()