0

我正在尝试学习 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()
4

1 回答 1

0

OOP 的好处是您可以根据角色、职责和关注点将程序划分为不同的对象/类。目前,Rock类和Player类都有太多的职责。

具体来说,您应该考虑打印从控制台读取游戏循环。我会把它们放在一个Game类控制器中。

不管你是否考虑它,你也应该把Rock主循环放在一个叫做 run 的方法中。它不应该从构造函数开始循环。

最后,您的模块级代码可能如下所示:

# Main
game = Game()
game.run()
print("Game ended.")
于 2012-08-08T13:11:47.553 回答