2017-04-21 7 views
0

과제를 위해 tic-tac-toe 게임을 쓰고 있습니다. 객체 지향 프로그래밍을 사용해야합니다.Python - OOP Tic Tac Toe

내 문제는 보드가 꽉 찼는 지 확인하고 같은 플레이어로 게임을 다시 시작하는 방법을 구현하는 것입니다. 나는 이미 모든 필드가 꽉 차 있지만 성공하지 않았는지 확인하면서 경기장을 반복하려고했습니다.

나는 점령 된 플레이어를 홍보하고 점령 된 필드를 선택하면 이전 플레이어를 홍보하는 데 약간의 문제가 있습니다. 난 내 주요 기능에서 선수 또는 차례를 추적하기 위해 루프를 변경해야한다고 생각하지만 아무런 단서가 없습니다.

class Player(object): 
    def __init__(self, name, symbol, initial_score=0): 
     self.name= name 
     self.symbol= symbol 
     self.score= initial_score 

    def won_match(self): 
     self.score+= 100 

    def lost_match(self): 
     self.score-= 50 

    def show_score(self): 
     print('Player {}: {} points'.format(self.name, self.score)) 

class PlayingField(object): 
    def __init__(self): 
     self.field= [ 
        [None, None, None], 
        [None, None, None], 
        [None, None, None] 
        ] 

    def show_field(self): 
     for row in self.field: 
      for player in row: 
       print('_' if player is None else player.symbol,end=' ') 
      print() 

    def set_player(self, x, y, player): 
     if self.field[y][x] is not None: 
      return False 

     self.field[y][x]= player 

     return True 

    def full_board(self): 
    for row in self.field: 
     for col in row: 
      if col is None: 
       return False 
     return True 

    def check_won(self, x, y, player): 
    if self.field[0][x] == player and self.field[1][x] == player and self.field[2][x] == player: 
     return True 
    elif self.field[y][0] == player and self.field[y][1] == player and self.field[y][2] == player: 
     return True 
    elif self.field[0][0] == player and self.field[1][1] == player and self.field[2][2] == player: 
     return True 
    elif self.field[0][2] == player and self.field[1][1] == player and self.field[2][0] == player: 
     return True 
    else: 
     return False 


def main(): 
    name_1= input('Name of Player 1: ') 
    name_2= input('Name of Player 2: ') 

    players= [ 
       Player(name_1, 'X'), 
       Player(name_2, 'O') 
       ] 

    field= PlayingField() 

    while True: 
     for player in players: 
      field.show_field() 

      x= int(input('Player {} choose your column: '.format(player.name))) - 1 

      y= int(input('Player {} choose your row: '.format(player.name))) - 1 

      if not field.set_player(x, y, player): 
       print('That field is already occupied.') 

      elif field.full_board(): 
      field.show_field() 
      print('full board') 
      for player in players: 
       print('{}: {}'.format(player.name, player.score)) 
      field= PlayingField() 

      elif field.check_won(player): 
       field.show_field() 
       print('Player {} won the game.'.format(player.name)) 
       print('Score') 
       for player in players: 
        if field.check_won(player) == True: 
         player.won_match() 
        elif field.check_won(player) == False: 
         player.lost_match() 
        print('{}: {}'.format(player.name, player.score)) 
       field= PlayingField() 

if __name__ == '__main__': 
    main() 
+3

"이미 경기장을 반복하면서 모든 필드가 꽉 차 있지만 성공하지 못했는지 확인하려고했습니다." 이것은 유효한 접근 방법입니다. * 어떻게 작동하지 않았습니까? – timgeb

+0

여기에 멋진 [tic-tac-toe 참조] (https://inventwithpython.com/chapter10.html) – GiantsLoveDeathMetal

+0

이 있습니다. 유효한 "전체 게시판"을 하드 코딩하는 대신 check_won에 대한 재귀 솔루션을 고려해야합니다. 귀하의 솔루션은 크기 N x N의 보드에 맞게 확장되지 않습니다. n-queens 문제를 확인하십시오. tic-tac-toe 보드를 해결하는 것과 비슷한 논리를 가지고 있습니다. – chukkwagon

답변

0

보드가 가득 차 있는지 확인하려면 모든 요소를 ​​반복하고 비 - 없음 값을 확인하면됩니다.

은 현재

def full_board(self): 
    for row in self.field: 
     for col in self.field: 
      if col == '_': 
       return False 
      else: 
       return True 

기억이, self.field는 목록의 목록입니다. 우리가하고 싶은 일은 세 가지 목록 모두에서 모든 요소를 ​​검사하는 것입니다.

def full_board(self): 
    for row in self.field: # all good so far 
     for col in row: # <-- now we're iterating through each list in self.field 
     if col is None: 
      return False # the board is not full if there's at least one empty space 
    return True # we looked at every element and they were all occupied 

실수가 너무 일찍 돌아 왔습니다. 귀하의 버전에서 하나의 요소를 확인한 다음이를 기반으로 참/거짓 값을 결정하십시오. 모두을 확인하려면 for 루프 뒤에 True를 반환해야합니다.

선택한 위치의 유효성 확인은 위치가 유효 할 때까지 계속 묻습니다. 당신의 while 루프에서

, 당신이 여기이

x, y = prompt_for_position() 

while not pos_is_valid(x,y): 
    x, y = prompt_for_position() 

# now we can be sure that the chosen position is valid 

같은 것을 가질 수 prompt_for_position 그냥 X/Y의 사용자를 요청할 수 있으며, 그것의 경우 pos_is_valid 당신는 x와 y에 걸릴 알 수 있습니다 유효한 위치. (없음/비어있는 사각형)

잘하면이 도움이되었습니다.

+0

을 해결하는 방법을 얻지 못했습니다. 먼저 도움을 주셔서 감사합니다. 나는 코드를 편집했다. 나는 full_board 방법에서 내가 한 일을 이해하지만, 당신의 설명 아래에있는 부분을 이해하지 못한다. 나는 이해하지 못한다. 내 주요 기능에 메서드를 구현하려고했습니다. 그것은 어떻게 든 작동합니다. 그러나 첫 번째 행은 기호로 채워질 때마다 그는 True를 반환하고 왜 나에게 설명하지 않습니다. 필자는 2 주 전에 Python으로 코딩을 시작했으며 코드의 절반은 교사가 담당한다고 언급해야합니다. – Hans

+0

full_board 메서드의 들여 쓰기가 해제되었습니다. return True가 두 루프 외부에 있는지 확인하십시오.True 반환이 루프 중 하나에 있으면, 한 행/열을 반복하여 반환 할 것임을 의미합니다. – chatton