Решение на Морски шах от Нели Хатева

Обратно към всички решения

Към профила на Нели Хатева

Резултати

  • 6 точки от тестове
  • 0 бонус точки
  • 6 точки общо
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)

Код

class TicTacToeBoard:
def __init__(self):
self.board = {'A1': ' ', 'A2': ' ', 'A3': ' ',
'B1': ' ', 'B2': ' ', 'B3': ' ',
'C1': ' ', 'C2': ' ', 'C3': ' '}
self.valid_keys = ('A1', 'A2', 'A3',
'B1', 'B2', 'B3',
'C1', 'C2', 'C3')
self.valid_values = ('X', 'O')
self.filled_cells = 0
self.turn = 'unknown'
def __setitem__(self, index, item):
if index not in self.valid_keys:
raise InvalidKey('Invalid key!')
if item not in self.valid_values:
raise InvalidValue('Invalid value!')
if self.board[index] != ' ':
raise InvalidMove('Invalid move!')
if self.turn == 'unknown':
self.turn = item
elif self.turn == item:
raise NotYourTurn("It's not your turn!")
self.board[index] = item
self.turn = item
self.filled_cells += 1
def __getitem__(self, index):
if index not in self.valid_keys:
raise InvalidKey('Invalid key!')
return self.board[index]
def __str__(self):
line = ['', '', '']
for i in range(1, 4):
line[i - 1] = \
"{} | {} | {} | {} |\n".format(str(i),
self.board['A' + str(i)],
self.board['B' + str(i)],
self.board['C' + str(i)])
dashes = ' -------------\n'
return "\n{d}{}{d}{}{d}{}{d} A B C \n".format(*line[::-1],
d=dashes)
def game_status(self):
if self.wins('X'):
return 'X wins!'
elif self.wins('O'):
return 'O wins!'
elif self.filled_cells == 9:
return 'Draw!'
else:
return 'Game in progress.'
def wins(self, gamer):
winning_triples = (('A1', 'A2', 'A3'), ('B1', 'B2', 'B3'),
('C1', 'C2', 'C3'), ('A1', 'B1', 'C1'),
('A2', 'B2', 'C2'), ('A3', 'B3', 'C3'),
('A1', 'B2', 'C3'), ('A3', 'B2', 'C1'))
for triple in iter(winning_triples):
first, second, third = triple
if self.board[first] == self.board[second] == \
self.board[third] == gamer:
return True
return False
class InvalidKey(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidMove(Exception):
pass
class NotYourTurn(Exception):
pass

Лог от изпълнението

........
----------------------------------------------------------------------
Ran 8 tests in 0.097s

OK

История (9 версии и 5 коментара)

Нели обнови решението на 08.04.2013 16:11 (преди над 11 години)

+class TicTacToeBoard:
+
+ def __init__(self):
+ self.board = {'A1': ' ', 'A2': ' ', 'A3': ' ',
+ 'B1': ' ', 'B2': ' ', 'B3': ' ',
+ 'C1': ' ', 'C2': ' ', 'C3': ' '}
+ self.status = ''
+ self.filled_cells = 0
+
+ def __setitem__(self, index, item):
+ if index not in ('A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3'):
+ raise InvalidKey
+ if item not in ('X', 'O'):
+ raise InvalidValue
+ if self.board[index] != ' ':
+ raise InvalidMove
+ self.board[index] = item
+ self.filled_cells += 1
+
+ def __getitem__(self, index):
+ if index not in ('A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3'):
+ raise InvalidKey
+ return self.board[index]
+
+ def __str__(self):
+ line = ['', '', '', '']
+ for i in range(1, 4):
+ line[i] = str(i) + ' | ' + self.board['A' + str(i)] +\
+ ' | ' + self.board['B' + str(i)] +\
+ ' | ' + self.board['C' + str(i)] + ' |\n'
+ return '\n -------------\n' +\
+ line[3] +\
+ ' -------------\n' +\
+ line[2] +\
+ ' -------------\n' +\
+ line[1] +\
+ ' -------------\n' +\
+ ' A B C \n'
+
+ def game_status(self):
+ if self.filled_cells == 9:
+ return 'Draw!'
+ else:
+ return 'Game in progress.'
+
+
+class InvalidKey(Exception):
+ def __init__(self):
+ super().__init__()
+ self.message = 'Invalid key!'
+
+
+class InvalidValue(Exception):
+ def __init__(self):
+ super().__init__()
+ self.message = 'Invalid value!'
+
+
+class InvalidMove(Exception):
+ def __init__(self):
+ super().__init__()
+ self.message = 'Invalid move!'
+
+
+class NotYourTurn(Exception):
+ def __init__(self):
+ super().__init__()
+ self.message = 'Not your turn!'

Нели обнови решението на 08.04.2013 16:35 (преди над 11 години)

class TicTacToeBoard:
def __init__(self):
self.board = {'A1': ' ', 'A2': ' ', 'A3': ' ',
'B1': ' ', 'B2': ' ', 'B3': ' ',
'C1': ' ', 'C2': ' ', 'C3': ' '}
- self.status = ''
self.filled_cells = 0
def __setitem__(self, index, item):
if index not in ('A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3'):
raise InvalidKey
if item not in ('X', 'O'):
raise InvalidValue
if self.board[index] != ' ':
raise InvalidMove
self.board[index] = item
self.filled_cells += 1
def __getitem__(self, index):
if index not in ('A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3'):
raise InvalidKey
return self.board[index]
def __str__(self):
line = ['', '', '', '']
for i in range(1, 4):
line[i] = str(i) + ' | ' + self.board['A' + str(i)] +\
' | ' + self.board['B' + str(i)] +\
' | ' + self.board['C' + str(i)] + ' |\n'
return '\n -------------\n' +\
line[3] +\
' -------------\n' +\
line[2] +\
' -------------\n' +\
line[1] +\
' -------------\n' +\
' A B C \n'
def game_status(self):
- if self.filled_cells == 9:
+ if self.wins('X'):
+ return 'X wins!'
+ elif self.wins('O'):
+ return 'O wins!'
+ elif self.filled_cells == 9:
return 'Draw!'
else:
return 'Game in progress.'
+
+ def wins(self, gamer):
+ if self.board['A1'] == self.board['A2'] == self.board['A3'] == gamer:
+ return True
+ elif self.board['B1'] == self.board['B2'] == self.board['B3'] == gamer:
+ return True
+ elif self.board['C1'] == self.board['C2'] == self.board['C3'] == gamer:
+ return True
+ elif self.board['A1'] == self.board['B1'] == self.board['C1'] == gamer:
+ return True
+ elif self.board['A2'] == self.board['B2'] == self.board['C2'] == gamer:
+ return True
+ elif self.board['A3'] == self.board['B3'] == self.board['C3'] == gamer:
+ return True
+ else:
+ return False
class InvalidKey(Exception):
def __init__(self):
super().__init__()
self.message = 'Invalid key!'
class InvalidValue(Exception):
def __init__(self):
super().__init__()
self.message = 'Invalid value!'
class InvalidMove(Exception):
def __init__(self):
super().__init__()
self.message = 'Invalid move!'
class NotYourTurn(Exception):
def __init__(self):
super().__init__()
self.message = 'Not your turn!'

Нели обнови решението на 08.04.2013 16:39 (преди над 11 години)

class TicTacToeBoard:
def __init__(self):
self.board = {'A1': ' ', 'A2': ' ', 'A3': ' ',
'B1': ' ', 'B2': ' ', 'B3': ' ',
'C1': ' ', 'C2': ' ', 'C3': ' '}
+ self.valid_keys = ('A1', 'A2', 'A3',
+ 'B1', 'B2', 'B3',
+ 'C1', 'C2', 'C3')
+ self.valid_values = ('X', 'O')
self.filled_cells = 0
def __setitem__(self, index, item):
- if index not in ('A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3'):
+ if index not in self.valid_keys:
raise InvalidKey
- if item not in ('X', 'O'):
+ if item not in self.valid_values:
raise InvalidValue
if self.board[index] != ' ':
raise InvalidMove
self.board[index] = item
self.filled_cells += 1
def __getitem__(self, index):
- if index not in ('A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3'):
+ if index not in self.valid_keys:
raise InvalidKey
return self.board[index]
def __str__(self):
line = ['', '', '', '']
for i in range(1, 4):
line[i] = str(i) + ' | ' + self.board['A' + str(i)] +\
' | ' + self.board['B' + str(i)] +\
' | ' + self.board['C' + str(i)] + ' |\n'
return '\n -------------\n' +\
line[3] +\
' -------------\n' +\
line[2] +\
' -------------\n' +\
line[1] +\
' -------------\n' +\
' A B C \n'
def game_status(self):
if self.wins('X'):
return 'X wins!'
elif self.wins('O'):
return 'O wins!'
elif self.filled_cells == 9:
return 'Draw!'
else:
return 'Game in progress.'
def wins(self, gamer):
if self.board['A1'] == self.board['A2'] == self.board['A3'] == gamer:
return True
elif self.board['B1'] == self.board['B2'] == self.board['B3'] == gamer:
return True
elif self.board['C1'] == self.board['C2'] == self.board['C3'] == gamer:
return True
elif self.board['A1'] == self.board['B1'] == self.board['C1'] == gamer:
return True
elif self.board['A2'] == self.board['B2'] == self.board['C2'] == gamer:
return True
elif self.board['A3'] == self.board['B3'] == self.board['C3'] == gamer:
return True
else:
return False
class InvalidKey(Exception):
def __init__(self):
super().__init__()
self.message = 'Invalid key!'
class InvalidValue(Exception):
def __init__(self):
super().__init__()
self.message = 'Invalid value!'
class InvalidMove(Exception):
def __init__(self):
super().__init__()
self.message = 'Invalid move!'
class NotYourTurn(Exception):
def __init__(self):
super().__init__()
self.message = 'Not your turn!'

по-добрата практика е съобщението при изключение е да се подава като аргумент:

raise NotYourTurn("It's not your turn!")

Ако наследяваш Exception не е нужно да добавяш message атрибут. Неговия конструктор има атрибут args и str(exception) връща първият аргумент подаден на конструктора.

Накратко -- по-добре направи изключенията си така:

class NotYourTurn(Exception):
    pass

и ги извиквай както ти показах.

Изпускаш случаи, в които играч е победител.

Също изпускаш един от случаите, когато би трябвало да възбудиш изключение.

Помисли дали не можеш да направиш метода __str__ чрез форматиране на низ(ове).

Нели обнови решението на 09.04.2013 00:45 (преди над 11 години)

class TicTacToeBoard:
def __init__(self):
self.board = {'A1': ' ', 'A2': ' ', 'A3': ' ',
'B1': ' ', 'B2': ' ', 'B3': ' ',
'C1': ' ', 'C2': ' ', 'C3': ' '}
self.valid_keys = ('A1', 'A2', 'A3',
- 'B1', 'B2', 'B3',
- 'C1', 'C2', 'C3')
+ 'B1', 'B2', 'B3',
+ 'C1', 'C2', 'C3')
self.valid_values = ('X', 'O')
self.filled_cells = 0
def __setitem__(self, index, item):
if index not in self.valid_keys:
- raise InvalidKey
+ raise InvalidKey("Invalid key!")
if item not in self.valid_values:
- raise InvalidValue
+ raise InvalidValue("Invalid value!")
if self.board[index] != ' ':
- raise InvalidMove
+ raise InvalidMove("Invalid move!")
self.board[index] = item
self.filled_cells += 1
def __getitem__(self, index):
if index not in self.valid_keys:
- raise InvalidKey
+ raise InvalidKey("Invalid key!")
return self.board[index]
def __str__(self):
line = ['', '', '', '']
for i in range(1, 4):
line[i] = str(i) + ' | ' + self.board['A' + str(i)] +\
' | ' + self.board['B' + str(i)] +\
' | ' + self.board['C' + str(i)] + ' |\n'
return '\n -------------\n' +\
line[3] +\
' -------------\n' +\
line[2] +\
' -------------\n' +\
line[1] +\
' -------------\n' +\
' A B C \n'
def game_status(self):
if self.wins('X'):
return 'X wins!'
elif self.wins('O'):
return 'O wins!'
elif self.filled_cells == 9:
return 'Draw!'
else:
return 'Game in progress.'
def wins(self, gamer):
if self.board['A1'] == self.board['A2'] == self.board['A3'] == gamer:
return True
elif self.board['B1'] == self.board['B2'] == self.board['B3'] == gamer:
return True
elif self.board['C1'] == self.board['C2'] == self.board['C3'] == gamer:
return True
elif self.board['A1'] == self.board['B1'] == self.board['C1'] == gamer:
return True
elif self.board['A2'] == self.board['B2'] == self.board['C2'] == gamer:
return True
elif self.board['A3'] == self.board['B3'] == self.board['C3'] == gamer:
return True
+ elif self.board['A1'] == self.board['B2'] == self.board['C3'] == gamer:
+ return True
+ elif self.board['A3'] == self.board['B2'] == self.board['C1'] == gamer:
+ return True
else:
return False
class InvalidKey(Exception):
- def __init__(self):
- super().__init__()
- self.message = 'Invalid key!'
+ pass
class InvalidValue(Exception):
- def __init__(self):
- super().__init__()
- self.message = 'Invalid value!'
+ pass
class InvalidMove(Exception):
- def __init__(self):
- super().__init__()
- self.message = 'Invalid move!'
+ pass
class NotYourTurn(Exception):
- def __init__(self):
- super().__init__()
+ pass
- self.message = 'Not your turn!'

Нели обнови решението на 09.04.2013 01:06 (преди над 11 години)

class TicTacToeBoard:
def __init__(self):
self.board = {'A1': ' ', 'A2': ' ', 'A3': ' ',
'B1': ' ', 'B2': ' ', 'B3': ' ',
'C1': ' ', 'C2': ' ', 'C3': ' '}
self.valid_keys = ('A1', 'A2', 'A3',
'B1', 'B2', 'B3',
'C1', 'C2', 'C3')
self.valid_values = ('X', 'O')
self.filled_cells = 0
def __setitem__(self, index, item):
if index not in self.valid_keys:
raise InvalidKey("Invalid key!")
if item not in self.valid_values:
raise InvalidValue("Invalid value!")
if self.board[index] != ' ':
raise InvalidMove("Invalid move!")
self.board[index] = item
self.filled_cells += 1
def __getitem__(self, index):
if index not in self.valid_keys:
raise InvalidKey("Invalid key!")
return self.board[index]
def __str__(self):
- line = ['', '', '', '']
+ line = ['', '', '']
for i in range(1, 4):
- line[i] = str(i) + ' | ' + self.board['A' + str(i)] +\
- ' | ' + self.board['B' + str(i)] +\
- ' | ' + self.board['C' + str(i)] + ' |\n'
- return '\n -------------\n' +\
- line[3] +\
- ' -------------\n' +\
- line[2] +\
- ' -------------\n' +\
- line[1] +\
- ' -------------\n' +\
- ' A B C \n'
+ line[i - 1] = \
+ '{} | {} | {} | {} |\n'.format(str(i),
+ self.board['A' + str(i)],
+ self.board['B' + str(i)],
+ self.board['C' + str(i)])
+ dashes = ' -------------\n'
+ return '\n{}{}{}{}{}{}{} A B C \n'.format(dashes, line[2],
+ dashes, line[1],
+ dashes, line[0],
+ dashes)
def game_status(self):
if self.wins('X'):
return 'X wins!'
elif self.wins('O'):
return 'O wins!'
elif self.filled_cells == 9:
return 'Draw!'
else:
return 'Game in progress.'
def wins(self, gamer):
if self.board['A1'] == self.board['A2'] == self.board['A3'] == gamer:
return True
elif self.board['B1'] == self.board['B2'] == self.board['B3'] == gamer:
return True
elif self.board['C1'] == self.board['C2'] == self.board['C3'] == gamer:
return True
elif self.board['A1'] == self.board['B1'] == self.board['C1'] == gamer:
return True
elif self.board['A2'] == self.board['B2'] == self.board['C2'] == gamer:
return True
elif self.board['A3'] == self.board['B3'] == self.board['C3'] == gamer:
return True
elif self.board['A1'] == self.board['B2'] == self.board['C3'] == gamer:
return True
elif self.board['A3'] == self.board['B2'] == self.board['C1'] == gamer:
return True
else:
return False
class InvalidKey(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidMove(Exception):
pass
class NotYourTurn(Exception):
pass

Нели обнови решението на 09.04.2013 01:20 (преди над 11 години)

class TicTacToeBoard:
def __init__(self):
self.board = {'A1': ' ', 'A2': ' ', 'A3': ' ',
'B1': ' ', 'B2': ' ', 'B3': ' ',
'C1': ' ', 'C2': ' ', 'C3': ' '}
self.valid_keys = ('A1', 'A2', 'A3',
'B1', 'B2', 'B3',
'C1', 'C2', 'C3')
self.valid_values = ('X', 'O')
self.filled_cells = 0
+ self.turn = 'О'
def __setitem__(self, index, item):
if index not in self.valid_keys:
- raise InvalidKey("Invalid key!")
+ raise InvalidKey('Invalid key!')
if item not in self.valid_values:
- raise InvalidValue("Invalid value!")
+ raise InvalidValue('Invalid value!')
if self.board[index] != ' ':
- raise InvalidMove("Invalid move!")
+ raise InvalidMove('Invalid move!')
+ if self.turn == item:
+ raise NotYourTurn("It's not your turn!")
self.board[index] = item
+ self.turn = item
self.filled_cells += 1
def __getitem__(self, index):
if index not in self.valid_keys:
- raise InvalidKey("Invalid key!")
+ raise InvalidKey('Invalid key!')
return self.board[index]
def __str__(self):
line = ['', '', '']
for i in range(1, 4):
line[i - 1] = \
'{} | {} | {} | {} |\n'.format(str(i),
self.board['A' + str(i)],
self.board['B' + str(i)],
self.board['C' + str(i)])
dashes = ' -------------\n'
return '\n{}{}{}{}{}{}{} A B C \n'.format(dashes, line[2],
dashes, line[1],
dashes, line[0],
dashes)
def game_status(self):
if self.wins('X'):
return 'X wins!'
elif self.wins('O'):
return 'O wins!'
elif self.filled_cells == 9:
return 'Draw!'
else:
return 'Game in progress.'
def wins(self, gamer):
if self.board['A1'] == self.board['A2'] == self.board['A3'] == gamer:
return True
elif self.board['B1'] == self.board['B2'] == self.board['B3'] == gamer:
return True
elif self.board['C1'] == self.board['C2'] == self.board['C3'] == gamer:
return True
elif self.board['A1'] == self.board['B1'] == self.board['C1'] == gamer:
return True
elif self.board['A2'] == self.board['B2'] == self.board['C2'] == gamer:
return True
elif self.board['A3'] == self.board['B3'] == self.board['C3'] == gamer:
return True
elif self.board['A1'] == self.board['B2'] == self.board['C3'] == gamer:
return True
elif self.board['A3'] == self.board['B2'] == self.board['C1'] == gamer:
return True
else:
return False
class InvalidKey(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidMove(Exception):
pass
class NotYourTurn(Exception):
pass

Нели обнови решението на 10.04.2013 17:19 (преди над 11 години)

class TicTacToeBoard:
def __init__(self):
self.board = {'A1': ' ', 'A2': ' ', 'A3': ' ',
'B1': ' ', 'B2': ' ', 'B3': ' ',
'C1': ' ', 'C2': ' ', 'C3': ' '}
self.valid_keys = ('A1', 'A2', 'A3',
'B1', 'B2', 'B3',
'C1', 'C2', 'C3')
self.valid_values = ('X', 'O')
self.filled_cells = 0
- self.turn = 'О'
+ self.turn = 'unknown'
def __setitem__(self, index, item):
if index not in self.valid_keys:
raise InvalidKey('Invalid key!')
if item not in self.valid_values:
raise InvalidValue('Invalid value!')
if self.board[index] != ' ':
raise InvalidMove('Invalid move!')
- if self.turn == item:
+ if self.turn == 'unknown':
+ self.turn = item
+ elif self.turn == item:
raise NotYourTurn("It's not your turn!")
self.board[index] = item
self.turn = item
self.filled_cells += 1
def __getitem__(self, index):
if index not in self.valid_keys:
raise InvalidKey('Invalid key!')
return self.board[index]
def __str__(self):
line = ['', '', '']
for i in range(1, 4):
line[i - 1] = \
'{} | {} | {} | {} |\n'.format(str(i),
self.board['A' + str(i)],
self.board['B' + str(i)],
self.board['C' + str(i)])
dashes = ' -------------\n'
return '\n{}{}{}{}{}{}{} A B C \n'.format(dashes, line[2],
dashes, line[1],
dashes, line[0],
dashes)
def game_status(self):
if self.wins('X'):
return 'X wins!'
elif self.wins('O'):
return 'O wins!'
elif self.filled_cells == 9:
return 'Draw!'
else:
return 'Game in progress.'
def wins(self, gamer):
if self.board['A1'] == self.board['A2'] == self.board['A3'] == gamer:
return True
elif self.board['B1'] == self.board['B2'] == self.board['B3'] == gamer:
return True
elif self.board['C1'] == self.board['C2'] == self.board['C3'] == gamer:
return True
elif self.board['A1'] == self.board['B1'] == self.board['C1'] == gamer:
return True
elif self.board['A2'] == self.board['B2'] == self.board['C2'] == gamer:
return True
elif self.board['A3'] == self.board['B3'] == self.board['C3'] == gamer:
return True
elif self.board['A1'] == self.board['B2'] == self.board['C3'] == gamer:
return True
elif self.board['A3'] == self.board['B2'] == self.board['C1'] == gamer:
return True
else:
return False
class InvalidKey(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidMove(Exception):
pass
class NotYourTurn(Exception):
pass

Нели обнови решението на 15.04.2013 00:17 (преди над 11 години)

class TicTacToeBoard:
def __init__(self):
self.board = {'A1': ' ', 'A2': ' ', 'A3': ' ',
'B1': ' ', 'B2': ' ', 'B3': ' ',
'C1': ' ', 'C2': ' ', 'C3': ' '}
self.valid_keys = ('A1', 'A2', 'A3',
'B1', 'B2', 'B3',
'C1', 'C2', 'C3')
self.valid_values = ('X', 'O')
self.filled_cells = 0
self.turn = 'unknown'
def __setitem__(self, index, item):
if index not in self.valid_keys:
raise InvalidKey('Invalid key!')
if item not in self.valid_values:
raise InvalidValue('Invalid value!')
if self.board[index] != ' ':
raise InvalidMove('Invalid move!')
if self.turn == 'unknown':
self.turn = item
elif self.turn == item:
raise NotYourTurn("It's not your turn!")
self.board[index] = item
self.turn = item
self.filled_cells += 1
def __getitem__(self, index):
if index not in self.valid_keys:
raise InvalidKey('Invalid key!')
return self.board[index]
def __str__(self):
line = ['', '', '']
for i in range(1, 4):
line[i - 1] = \
- '{} | {} | {} | {} |\n'.format(str(i),
+ "{} | {} | {} | {} |\n".format(str(i),
self.board['A' + str(i)],
self.board['B' + str(i)],
self.board['C' + str(i)])
- dashes = ' -------------\n'
- return '\n{}{}{}{}{}{}{} A B C \n'.format(dashes, line[2],
+ dashes = ' -------------\n'
+ return "\n{}{}{}{}{}{}{} A B C \n".format(dashes, line[2],
dashes, line[1],
dashes, line[0],
dashes)
def game_status(self):
if self.wins('X'):
return 'X wins!'
elif self.wins('O'):
return 'O wins!'
elif self.filled_cells == 9:
return 'Draw!'
else:
return 'Game in progress.'
def wins(self, gamer):
if self.board['A1'] == self.board['A2'] == self.board['A3'] == gamer:
return True
elif self.board['B1'] == self.board['B2'] == self.board['B3'] == gamer:
return True
elif self.board['C1'] == self.board['C2'] == self.board['C3'] == gamer:
return True
elif self.board['A1'] == self.board['B1'] == self.board['C1'] == gamer:
return True
elif self.board['A2'] == self.board['B2'] == self.board['C2'] == gamer:
return True
elif self.board['A3'] == self.board['B3'] == self.board['C3'] == gamer:
return True
elif self.board['A1'] == self.board['B2'] == self.board['C3'] == gamer:
return True
elif self.board['A3'] == self.board['B2'] == self.board['C1'] == gamer:
return True
else:
return False
class InvalidKey(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidMove(Exception):
pass
class NotYourTurn(Exception):
pass

Само отбелязвам:

1) "\n{border}{}{border}{}{border}{}{border} A B C \n".format(*line[::-1], border=dashes)

2) В wins имаш не малко повторения, които лесно можеш да избегнеш като направиш някаква абстракция по тройка_победни_полета.

Нели обнови решението на 15.04.2013 14:56 (преди над 11 години)

class TicTacToeBoard:
def __init__(self):
self.board = {'A1': ' ', 'A2': ' ', 'A3': ' ',
'B1': ' ', 'B2': ' ', 'B3': ' ',
'C1': ' ', 'C2': ' ', 'C3': ' '}
self.valid_keys = ('A1', 'A2', 'A3',
'B1', 'B2', 'B3',
'C1', 'C2', 'C3')
self.valid_values = ('X', 'O')
self.filled_cells = 0
self.turn = 'unknown'
def __setitem__(self, index, item):
if index not in self.valid_keys:
raise InvalidKey('Invalid key!')
if item not in self.valid_values:
raise InvalidValue('Invalid value!')
if self.board[index] != ' ':
raise InvalidMove('Invalid move!')
if self.turn == 'unknown':
self.turn = item
elif self.turn == item:
raise NotYourTurn("It's not your turn!")
self.board[index] = item
self.turn = item
self.filled_cells += 1
def __getitem__(self, index):
if index not in self.valid_keys:
raise InvalidKey('Invalid key!')
return self.board[index]
def __str__(self):
line = ['', '', '']
for i in range(1, 4):
line[i - 1] = \
"{} | {} | {} | {} |\n".format(str(i),
self.board['A' + str(i)],
self.board['B' + str(i)],
self.board['C' + str(i)])
dashes = ' -------------\n'
- return "\n{}{}{}{}{}{}{} A B C \n".format(dashes, line[2],
- dashes, line[1],
- dashes, line[0],
- dashes)
+ return "\n{d}{}{d}{}{d}{}{d} A B C \n".format(*line[::-1],
+ d=dashes)
def game_status(self):
if self.wins('X'):
return 'X wins!'
elif self.wins('O'):
return 'O wins!'
elif self.filled_cells == 9:
return 'Draw!'
else:
return 'Game in progress.'
def wins(self, gamer):
- if self.board['A1'] == self.board['A2'] == self.board['A3'] == gamer:
- return True
- elif self.board['B1'] == self.board['B2'] == self.board['B3'] == gamer:
- return True
- elif self.board['C1'] == self.board['C2'] == self.board['C3'] == gamer:
- return True
- elif self.board['A1'] == self.board['B1'] == self.board['C1'] == gamer:
- return True
- elif self.board['A2'] == self.board['B2'] == self.board['C2'] == gamer:
- return True
- elif self.board['A3'] == self.board['B3'] == self.board['C3'] == gamer:
- return True
- elif self.board['A1'] == self.board['B2'] == self.board['C3'] == gamer:
- return True
- elif self.board['A3'] == self.board['B2'] == self.board['C1'] == gamer:
- return True
- else:
- return False
+ winning_triples = (('A1', 'A2', 'A3'), ('B1', 'B2', 'B3'),
+ ('C1', 'C2', 'C3'), ('A1', 'B1', 'C1'),
+ ('A2', 'B2', 'C2'), ('A3', 'B3', 'C3'),
+ ('A1', 'B2', 'C3'), ('A3', 'B2', 'C1'))
+ for triple in iter(winning_triples):
+ first, second, third = triple
+ if self.board[first] == self.board[second] == \
+ self.board[third] == gamer:
+ return True
+ return False
class InvalidKey(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidMove(Exception):
pass
class NotYourTurn(Exception):
pass