과제를 위해 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()
"이미 경기장을 반복하면서 모든 필드가 꽉 차 있지만 성공하지 못했는지 확인하려고했습니다." 이것은 유효한 접근 방법입니다. * 어떻게 작동하지 않았습니까? – timgeb
여기에 멋진 [tic-tac-toe 참조] (https://inventwithpython.com/chapter10.html) – GiantsLoveDeathMetal
이 있습니다. 유효한 "전체 게시판"을 하드 코딩하는 대신 check_won에 대한 재귀 솔루션을 고려해야합니다. 귀하의 솔루션은 크기 N x N의 보드에 맞게 확장되지 않습니다. n-queens 문제를 확인하십시오. tic-tac-toe 보드를 해결하는 것과 비슷한 논리를 가지고 있습니다. – chukkwagon