2012-08-08 2 views
0

나는 Python (3)을 배우려고 노력 중이며 일부 OOP를 사용하고 싶었다. 두 대의 컴퓨터 "플레이어"가 "바위 종이 가위"를 연주하는이 프로그램을 작성했습니다. 그것은 바보 같은 실수를했는지 누군가가 외모를 가지고 말해 줄 수 있다면 좋겠다.이것은 Python에서 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() 
+8

이 더 http://codereview.stackexchange.com 후보처럼 보이는 당신은 대답 할 수있는 질문을하지 않는 한 [FAQ] (http://stackoverflow.com/faq)를 참조하십시오. –

+1

Rock 클래스와 Player 클래스 모두 너무 많은 책임이 있습니다. 특히, * 인쇄 *, * 콘솔에서 읽기 *, 게임 루프 *를 제외해야합니다. 아니면 최소한'Rock' 메인 루프를'run'이라는 메서드에 넣으십시오. 생성자에서 반복을 시작하면 안됩니다. – Deestan

+0

감사합니다. Deestan – antiloquax

답변

0

OOP의 장점은 역할, 맞는 책임과 관심에 따라 서로 다른 객체/클래스로 프로그램을 나눌 수 있다는 것입니다. 현재 Rock 클래스와 Player 클래스 모두 너무 많은 책임이 있습니다.

특히, 인쇄, 콘솔에서 읽기 및 게임 루프을 고려한다. 나는 그들을 Game 클래스 컨트롤러에 넣을 것이다.

주저하지 말고 Rock 주 루프를 실행이라는 메서드에 넣어야합니다. 생성자에서 반복을 시작하면 안됩니다. 결국

, 모듈 수준의 코드는 다음과 같을 수 있습니다 :

# Main 
game = Game() 
game.run() 
print("Game ended.") 
+1

다시 한번 감사드립니다. 초보자에게 매우 도움이됩니다! – antiloquax