Решение на Морски шах от Десислава Добрева

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

Към профила на Десислава Добрева

Резултати

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

Код

class TicTacToeBoard(dict):
empty = []
def __init__(self, *args, **kwargs):
self['A1'] = " "
self['A2'] = " "
self['A3'] = " "
self['B1'] = " "
self['B2'] = " "
self['B3'] = " "
self['C1'] = " "
self['C2'] = " "
self['C3'] = " "
def turn(self):
if list(self.values()).count("X") > list(self.values()).count("O") + 1:
return "O"
if list(self.values()).count("X") < list(self.values()).count("O") - 1:
return "X"
return " "
def __setitem__(self, key, value):
super(TicTacToeBoard, self).__setitem__(key, value)
self.empty.append(key)
if value not in [" ", "X", "O"]:
super(TicTacToeBoard, self).__setitem__(key, " ")
raise InvalidValue
if key not in ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"]:
raise InvalidKey
if self.turn() != value and self.turn() != " ":
super(TicTacToeBoard, self).__setitem__(key, " ")
raise NotYourTurn
if self.empty.count(key) > 2:
super(TicTacToeBoard, self).__setitem__(key, " ")
raise InvalidMove
self.player = value
def __str__(self):
boardstr = "\n"
for x in ['0', "3", "2", "1"]:
if x == '0':
boardstr += " -------------\n"
else:
boardstr += x + " |"
for y in ["A", "B", "C"]:
a = y+x
b = str(self[a])
boardstr += " " + b + " |"
boardstr += "\n -------------\n"
boardstr += " A B C \n"
return boardstr
def win(self):
for i in ['A', 'B', 'C']:
if self[i+'1'] == self[i+'2'] == self[i+'3'] and not self[i+'1'] == " ":
self.player = self[i+'1']
return True
for i in ['1', '2', '3']:
if self['A'+i] == self['B'+i] == self['C'+i] and not self['B'+i] == " ":
self.player = self['B'+i]
return True
if self['A1'] == self['B2'] == self['C3'] and not self['A1'] == " ":
self.player = self['A1']
return True
if self['A3'] == self['B2'] == self['C1'] and not self['A3'] == " ":
self.player = self['A3']
return True
return False
def game_status(self):
if self.win():
return self.player + " wins!"
elif " " not in self.values() and not self.win():
return "Draw"
else:
return "Game in progress"
class InvalidMove(Exception):
def __init__(self):
self.message = "This cell has value! Try again"
class InvalidValue(Exception):
def __init__(self):
self.message = "Value must be in X or O"
class InvalidKey(Exception):
def __init__(self):
self.message = "Wrong board key"
class NotYourTurn(Exception):
def __init__(self):
self.message = "Not your turn"

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

FEEEEEEE
======================================================================
ERROR: test_game_in_progress (test.TicTacHomeworkTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20130415-29081-c7hh7k/test.py", line 147, in test_game_in_progress
    p = solution.TicTacToeBoard()
  File "/tmp/d20130415-29081-c7hh7k/solution.py", line 6, in __init__
    self['A1'] = " "
  File "/tmp/d20130415-29081-c7hh7k/solution.py", line 38, in __setitem__
    raise InvalidMove
solution.InvalidMove

======================================================================
ERROR: test_input_format (test.TicTacHomeworkTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20130415-29081-c7hh7k/test.py", line 43, in test_input_format
    o = solution.TicTacToeBoard()
  File "/tmp/d20130415-29081-c7hh7k/solution.py", line 6, in __init__
    self['A1'] = " "
  File "/tmp/d20130415-29081-c7hh7k/solution.py", line 38, in __setitem__
    raise InvalidMove
solution.InvalidMove

======================================================================
ERROR: test_o_wins (test.TicTacHomeworkTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20130415-29081-c7hh7k/test.py", line 102, in test_o_wins
    h = solution.TicTacToeBoard()
  File "/tmp/d20130415-29081-c7hh7k/solution.py", line 6, in __init__
    self['A1'] = " "
  File "/tmp/d20130415-29081-c7hh7k/solution.py", line 38, in __setitem__
    raise InvalidMove
solution.InvalidMove

======================================================================
ERROR: test_overwrite_move (test.TicTacHomeworkTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20130415-29081-c7hh7k/test.py", line 63, in test_overwrite_move
    o = solution.TicTacToeBoard()
  File "/tmp/d20130415-29081-c7hh7k/solution.py", line 6, in __init__
    self['A1'] = " "
  File "/tmp/d20130415-29081-c7hh7k/solution.py", line 38, in __setitem__
    raise InvalidMove
solution.InvalidMove

======================================================================
ERROR: test_tostring_empty (test.TicTacHomeworkTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20130415-29081-c7hh7k/test.py", line 8, in test_tostring_empty
    b = solution.TicTacToeBoard()
  File "/tmp/d20130415-29081-c7hh7k/solution.py", line 6, in __init__
    self['A1'] = " "
  File "/tmp/d20130415-29081-c7hh7k/solution.py", line 38, in __setitem__
    raise InvalidMove
solution.InvalidMove

======================================================================
ERROR: test_tostring_full (test.TicTacHomeworkTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20130415-29081-c7hh7k/test.py", line 20, in test_tostring_full
    d = solution.TicTacToeBoard()
  File "/tmp/d20130415-29081-c7hh7k/solution.py", line 6, in __init__
    self['A1'] = " "
  File "/tmp/d20130415-29081-c7hh7k/solution.py", line 38, in __setitem__
    raise InvalidMove
solution.InvalidMove

======================================================================
ERROR: test_x_wins (test.TicTacHomeworkTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20130415-29081-c7hh7k/test.py", line 71, in test_x_wins
    h = solution.TicTacToeBoard()
  File "/tmp/d20130415-29081-c7hh7k/solution.py", line 6, in __init__
    self['A1'] = " "
  File "/tmp/d20130415-29081-c7hh7k/solution.py", line 38, in __setitem__
    raise InvalidMove
solution.InvalidMove

======================================================================
FAIL: test_draw (test.TicTacHomeworkTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20130415-29081-c7hh7k/test.py", line 144, in test_draw
    self.assertEqual('Draw!', d.game_status())
AssertionError: 'Draw!' != 'Draw'
- Draw!
?     -
+ Draw


----------------------------------------------------------------------
Ran 8 tests in 0.010s

FAILED (failures=1, errors=7)

История (1 версия и 2 коментара)

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

+class TicTacToeBoard(dict):
+ empty = []
+
+
+ def __init__(self, *args, **kwargs):
+ self['A1'] = " "
+ self['A2'] = " "
+ self['A3'] = " "
+ self['B1'] = " "
+ self['B2'] = " "
+ self['B3'] = " "
+ self['C1'] = " "
+ self['C2'] = " "
+ self['C3'] = " "
+
+
+ def turn(self):
+ if list(self.values()).count("X") > list(self.values()).count("O") + 1:
+ return "O"
+ if list(self.values()).count("X") < list(self.values()).count("O") - 1:
+ return "X"
+ return " "
+
+
+ def __setitem__(self, key, value):
+ super(TicTacToeBoard, self).__setitem__(key, value)
+ self.empty.append(key)
+ if value not in [" ", "X", "O"]:
+ super(TicTacToeBoard, self).__setitem__(key, " ")
+ raise InvalidValue
+ if key not in ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"]:
+ raise InvalidKey
+ if self.turn() != value and self.turn() != " ":
+ super(TicTacToeBoard, self).__setitem__(key, " ")
+ raise NotYourTurn
+ if self.empty.count(key) > 2:
+ super(TicTacToeBoard, self).__setitem__(key, " ")
+ raise InvalidMove
+ self.player = value
+
+
+ def __str__(self):
+ boardstr = "\n"
+ for x in ['0', "3", "2", "1"]:
+ if x == '0':
+ boardstr += " -------------\n"
+ else:
+ boardstr += x + " |"
+ for y in ["A", "B", "C"]:
+ a = y+x
+ b = str(self[a])
+ boardstr += " " + b + " |"
+ boardstr += "\n -------------\n"
+ boardstr += " A B C \n"
+ return boardstr
+
+ def win(self):
+ for i in ['A', 'B', 'C']:
+ if self[i+'1'] == self[i+'2'] == self[i+'3'] and not self[i+'1'] == " ":
+ self.player = self[i+'1']
+ return True
+ for i in ['1', '2', '3']:
+ if self['A'+i] == self['B'+i] == self['C'+i] and not self['B'+i] == " ":
+ self.player = self['B'+i]
+ return True
+ if self['A1'] == self['B2'] == self['C3'] and not self['A1'] == " ":
+ self.player = self['A1']
+ return True
+ if self['A3'] == self['B2'] == self['C1'] and not self['A3'] == " ":
+ self.player = self['A3']
+ return True
+ return False
+
+
+ def game_status(self):
+ if self.win():
+ return self.player + " wins!"
+ elif " " not in self.values() and not self.win():
+ return "Draw"
+ else:
+ return "Game in progress"
+
+
+class InvalidMove(Exception):
+
+
+ def __init__(self):
+ self.message = "This cell has value! Try again"
+
+
+class InvalidValue(Exception):
+
+
+ def __init__(self):
+ self.message = "Value must be in X or O"
+
+
+class InvalidKey(Exception):
+
+
+ def __init__(self):
+ self.message = "Wrong board key"
+
+
+class NotYourTurn(Exception):
+
+
+ def __init__(self):
+ self.message = "Not your turn"

По-добре си направи изключенията така: MyException(Exception): pass и ги възбуждай така, ако настояваш за съобщение: raise MyException('my exceptional message')

Наследяването е зло! Предпочитай композиция всеки път, когато отговора на въпроса Дали [nаследникът] е [родителят] не е Категорично ДА!. В случая Дъската за морски шах не е речник.

В метода wins имаш много повторения. Помисли дали не можеш да ги избегнеш чрез дефинирането на някаква структура, която да описва всички победни варианти, предварително.

__str__ може да бъде много по-четим и лесен за разбиране(и редактиране).
Hint: str.format, multiline string са идеални за такива цели.

П.П. Задължително си пусни sample_test.py над решението!