Решение на Морски шах от Рейхан Садък

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

Към профила на Рейхан Садък

Резултати

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

Код

class InvalidMove(Exception):
def __init__(self):
super().__init__()
def __str__(self):
return "Invalid Move Exception"
class InvalidValue(Exception):
def __init__(self):
super().__init__()
def __str__(self):
return "Invalid Value Exception"
class InvalidKey(Exception):
def __init__(self):
super().__init__()
def __str__(self):
return "Invalid Key Exception"
class NotYourTurn(Exception):
def __init__(self):
super().__init__()
def __str__(self):
return "Not Your Turn Exception"
class TicTacToeBoard:
def __init__(self):
self.listOfValidPositions = list()
self.board = dict()
self.emptyPos = " "
self.turn = " "
self.hasWinner = False
self.winnerSign = ""
if(len(self.listOfValidPositions) is 0):
self.listOfValidPositions.append("A1")
self.listOfValidPositions.append("A2")
self.listOfValidPositions.append("A3")
self.listOfValidPositions.append("B1")
self.listOfValidPositions.append("B2")
self.listOfValidPositions.append("B3")
self.listOfValidPositions.append("C1")
self.listOfValidPositions.append("C2")
self.listOfValidPositions.append("C3")
for pos in self.listOfValidPositions:
self.board[pos] = self.emptyPos
def __getitem__(self, key):
return self.board[key]
def __setitem__(self, key, value):
try:
if(key not in self.listOfValidPositions):
raise InvalidKey
elif(value is not "X" and value is not "O"):
raise InvalidValue
elif(self.board[key] is not self.emptyPos):
raise InvalidMove
elif(value is not self.turn and self.turn is not " "):
raise NotYourTurn
else:
self.board[key] = value
if(self.turn is " "):
self.turn = value
if(self.turn is "X"):
self.turn = "O"
elif(self.turn is "O"):
self.turn = "X"
if(self.xWins()):
self.hasWinner = True
self.winnerSign = "X"
elif(self.oWins()):
self.hasWinner = True
self.winnerSign = "O"
except (InvalidMove, InvalidValue, InvalidMove, NotYourTurn) as data:
print(data)
def __str__(self):
return "\n -------------\n3 | {0} | {1} | {2} |\n2 | {3} | {4} | {5} |\n1 | {6} | {7} | {8} |\n -------------\n A B C \n".format(self.board["A3"], self.board["B3"], self.board["C3"], self.board["A2"], self.board["B2"], self.board["C2"], self.board["A1"], self.board["B1"], self.board["C1"])
def playerWins(self, playerSign):
if(playerSign is not "X" and playerSign is not "O"):
return False
elif(self.board["A1"] is playerSign and self.board["A2"] is playerSign and self.board["A3"] is playerSign):
return True
elif(self.board["B1"] is playerSign and self.board["B2"] is playerSign and self.board["C3"] is playerSign):
return True
elif(self.board["C1"] is playerSign and self.board["C2"] is playerSign and self.board["C3"] is playerSign):
return True
elif(self.board["A1"] is playerSign and self.board["B1"] is playerSign and self.board["C1"] is playerSign):
return True
elif(self.board["A2"] is playerSign and self.board["B2"] is playerSign and self.board["C2"] is playerSign):
return True
elif(self.board["A3"] is playerSign and self.board["B3"] is playerSign and self.board["C3"] is playerSign):
return True
elif(self.board["A1"] is playerSign and self.board["B2"] is playerSign and self.board["C3"] is playerSign):
return True
elif(self.board["A3"] is playerSign and self.board["B2"] is playerSign and self.board["C1"] is playerSign):
return True
else:
return False
def xWins(self):
return self.playerWins("X")
def oWins(self):
return self.playerWins("O")
def isBoardFull(self):
for pos in self.listOfValidPositions:
if(self.board[pos] is self.emptyPos):
return False
return True
def game_status(self):
if(self.isBoardFull() and not self.hasWinner):
return "Draw!"
elif(self.xWins() and self.winnerSign is not "O"):
return "X wins!"
elif(self.oWins() and self.winnerSign is not "X"):
return "O wins!"
else:
return "In progress!"

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

FFF
Stdout:
Invalid Value Exception
.F
Stdout:
Not Your Turn Exception
FF.
======================================================================
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-14erx7b/test.py", line 144, in test_draw
    self.assertEqual('Draw!', d.game_status())
AssertionError: 'Draw!' != 'X wins!'
- Draw!
+ X wins!


======================================================================
FAIL: 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-14erx7b/test.py", line 151, in test_game_in_progress
    self.assertEqual('Game in progress.', p.game_status())
AssertionError: 'Game in progress.' != 'In progress!'
- Game in progress.
+ In progress!


======================================================================
FAIL: 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-14erx7b/test.py", line 54, in test_input_format
    o['A3'] = 'G'
AssertionError: InvalidValue not raised

Stdout:
Invalid Value Exception

======================================================================
FAIL: 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-14erx7b/test.py", line 68, in test_overwrite_move
    o["A2"] = 'X'
AssertionError: NotYourTurn not raised

Stdout:
Not Your Turn Exception

======================================================================
FAIL: 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-14erx7b/test.py", line 17, in test_tostring_empty
    self.assertEqual(empty_board, b.__str__())
AssertionError: '\n  -------------\n3 |   |   |   |\n  -------------\n2 |   |   |   |\n  ------- [truncated]... != '\n  -------------\n3 |   |   |   |\n2 |   |   |   |\n1 |   |   |   |\n  ------- [truncated]...
  
    -------------
  3 |   |   |   |
-   -------------
  2 |   |   |   |
-   -------------
  1 |   |   |   |
    -------------
      A   B   C  


======================================================================
FAIL: 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-14erx7b/test.py", line 40, in test_tostring_full
    self.assertEqual(full_board, d.__str__())
AssertionError: '\n  -------------\n3 | O | O | X |\n  -------------\n2 | X | X | O |\n  ------- [truncated]... != '\n  -------------\n3 | O | O | X |\n2 | X | X | O |\n1 | O | X | O |\n  ------- [truncated]...
  
    -------------
  3 | O | O | X |
-   -------------
  2 | X | X | O |
-   -------------
  1 | O | X | O |
    -------------
      A   B   C  


----------------------------------------------------------------------
Ran 8 tests in 0.086s

FAILED (failures=6)

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

Рейхан обнови решението на 15.04.2013 00:32 (преди над 11 години)

+class InvalidMove(Exception):
+ def __init__(self):
+ super().__init__()
+
+ def __str__(self):
+ return "Invalid Move Exception"
+
+class InvalidValue(Exception):
+ def __init__(self):
+ super().__init__()
+
+ def __str__(self):
+ return "Invalid Value Exception"
+
+class InvalidKey(Exception):
+ def __init__(self):
+ super().__init__()
+
+ def __str__(self):
+ return "Invalid Key Exception"
+
+class NotYourTurn(Exception):
+ def __init__(self):
+ super().__init__()
+
+ def __str__(self):
+ return "Not Your Turn Exception"
+
+class TicTacToeBoard:
+ def __init__(self):
+ self.listOfValidPositions = list()
+ self.board = dict()
+ self.emptyPos = " "
+ self.turn = " "
+ self.hasWinner = False
+ self.winnerSign = ""
+ if(len(self.listOfValidPositions) is 0):
+ self.listOfValidPositions.append("A1")
+ self.listOfValidPositions.append("A2")
+ self.listOfValidPositions.append("A3")
+ self.listOfValidPositions.append("B1")
+ self.listOfValidPositions.append("B2")
+ self.listOfValidPositions.append("B3")
+ self.listOfValidPositions.append("C1")
+ self.listOfValidPositions.append("C2")
+ self.listOfValidPositions.append("C3")
+ for pos in self.listOfValidPositions:
+ self.board[pos] = self.emptyPos
+
+ def __getitem__(self, key):
+ return self.board[key]
+
+ def __setitem__(self, key, value):
+ try:
+ if(key not in self.listOfValidPositions):
+ raise InvalidKey
+ elif(value is not "X" and value is not "O"):
+ raise InvalidValue
+ elif(self.board[key] is not self.emptyPos):
+ raise InvalidMove
+ elif(value is not self.turn and self.turn is not " "):
+ raise NotYourTurn
+ else:
+ self.board[key] = value
+ if(self.turn is " "):
+ self.turn = value
+ if(self.turn is "X"):
+ self.turn = "O"
+ elif(self.turn is "O"):
+ self.turn = "X"
+ if(self.xWins()):
+ self.hasWinner = True
+ self.winnerSign = "X"
+ elif(self.oWins()):
+ self.hasWinner = True
+ self.winnerSign = "O"
+ except (InvalidMove, InvalidValue, InvalidMove, NotYourTurn) as data:
+ print(data)
+
+ def __str__(self):
+ return "\n -------------\n3 | {0} | {1} | {2} |\n2 | {3} | {4} | {5} |\n1 | {6} | {7} | {8} |\n -------------\n A B C \n".format(self.board["A3"], self.board["B3"], self.board["C3"], self.board["A2"], self.board["B2"], self.board["C2"], self.board["A1"], self.board["B1"], self.board["C1"])
+
+ def playerWins(self, playerSign):
+ if(playerSign is not "X" and playerSign is not "O"):
+ return False
+ elif(self.board["A1"] is playerSign and self.board["A2"] is playerSign and self.board["A3"] is playerSign):
+ return True
+ elif(self.board["B1"] is playerSign and self.board["B2"] is playerSign and self.board["C3"] is playerSign):
+ return True
+ elif(self.board["C1"] is playerSign and self.board["C2"] is playerSign and self.board["C3"] is playerSign):
+ return True
+ elif(self.board["A1"] is playerSign and self.board["B1"] is playerSign and self.board["C1"] is playerSign):
+ return True
+ elif(self.board["A2"] is playerSign and self.board["B2"] is playerSign and self.board["C2"] is playerSign):
+ return True
+ elif(self.board["A3"] is playerSign and self.board["B3"] is playerSign and self.board["C3"] is playerSign):
+ return True
+ elif(self.board["A1"] is playerSign and self.board["B2"] is playerSign and self.board["C3"] is playerSign):
+ return True
+ elif(self.board["A3"] is playerSign and self.board["B2"] is playerSign and self.board["C1"] is playerSign):
+ return True
+ else:
+ return False
+
+ def xWins(self):
+ return self.playerWins("X")
+
+ def oWins(self):
+ return self.playerWins("O")
+
+ def isBoardFull(self):
+ for pos in self.listOfValidPositions:
+ if(self.board[pos] is self.emptyPos):
+ return False
+ return True
+
+ def game_status(self):
+ if(self.isBoardFull() and not self.hasWinner):
+ return "Draw!"
+ elif(self.xWins() and self.winnerSign is not "O"):
+ return "X wins!"
+ elif(self.oWins() and self.winnerSign is not "X"):
+ return "O wins!"
+ else:
+ return "In progress!"

Когато форматираш низ и подредбата е естествена няма нужда да номерираш. str.format е достатъчно умно написан ;)

Прегледай PEP8. И по-точно конвенцията за именуване! А също и за дължината на всеки ред..

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

След като преименуваш playerWins помисли дали не можеш да използваш някаква структура и да избегнеш еднотипното използване на толкова условни оператори с подозрително дублиращ се код.

В __str__ можеш да използваш multiline string, за да избегнеш този дълъг ред

Да заглушаваш собствените си изключение в името на печатането им може да ти се струва като добра идея докато пишеш кода, но не забравяй да махаш try: ... except: блоковете.
Hint: малко е грозно, но ако настояваш да си ги печаташ без да ги заглушаваш можеш на края на except блока да добавиш едно raise. Това ще ескалира изключението изрично по същия начин, по който това щеше да стане, ако не го хващаше, с тази разлика, че можеш да свършиш нещо и на това ниво.. Това в този случай не е особено добра идея.

П.П. Пусни си sample_test.py над решението