我正在尝试学习Python(3),我想要去一些OOP。 我写了这个程序,其中两个计算机“玩家”玩“Rock Paper Scissors”。 它有效,但我想如果有人可以看看并告诉我是否犯了任何愚蠢的错误!
# 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()
答案 0 :(得分:0)
OOP的好处在于您可以根据角色,责任和关注点将程序划分为不同的对象/类。目前,Rock
类和Player
类都有太多责任。
具体来说,您应该分解打印,从控制台读取和游戏循环。我会将它们放在Game
类控制器中。
无论是否考虑因素,您还应将Rock
主循环放在名为run的方法中。它不应该从构造函数开始循环。
最后,您的模块级代码可能如下所示:
# Main
game = Game()
game.run()
print("Game ended.")