Решение на Морски шах от Светлана Величкова

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

Към профила на Светлана Величкова

Резултати

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

Код

class TicTacToeBoard:
def __init__(self):
self.board = {"A1": " ", "A2": " ", "A3": " ",
"B1": " ", "B2": " ", "B3": " ",
"C1": " ", "C2": " ", "C3": " "}
self.status = "Game in progress."
self.last_played = None
self.winner = None
def __getitem__(self, key):
if key not in self.board:
raise InvalidKey("There is no such field.")
return self.board[key]
def __setitem__(self, key, value):
if value != "X" and value != "O":
raise InvalidValue("This is not a proper mark")
if key not in self.board:
raise InvalidKey("There is no such field.")
if self.board[key] != " ":
raise InvalidMove("This field is already filled.")
if value == self.last_played:
raise NotYourTurn("The other player hasn't made his move yet")
self.last_played = value
self.board[key] = value
self.check_status()
def check_status(self):
if self.winner:
return
lines = list(map(lambda x: x[1], sorted(self.board.items())))
lines = (lines[:3] + lines[3:6] + lines[6:9] +
lines[::3] + lines[1::3] + lines[2::3])
for i, v in enumerate(lines):
if i % 3 == 0 and i < 18:
if lines[i] == lines[i + 1] == lines[i + 2] != " ":
self.winner = v
if self.winner:
self.status = self.winner + " wins!"
if " " not in self.board.values() and not self.winner:
self.status = "Draw!"
self.winner = "Draw"
def __str__(self):
return ("\n -------------\n"
"3 | {0[A3]} | {0[B3]} | {0[C3]} |\n"
" -------------\n"
"2 | {0[A2]} | {0[B2]} | {0[C2]} |\n"
" -------------\n"
"1 | {0[A1]} | {0[B1]} | {0[C1]} |\n"
" -------------\n"
" A B C \n").format(self.board)
def game_status(self):
return self.status
class TicTacToeError(Exception):
pass
class InvalidMove(TicTacToeError):
pass
class InvalidKey(TicTacToeError):
pass
class InvalidValue(TicTacToeError):
pass
class NotYourTurn(TicTacToeError):
pass

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

...F...F
======================================================================
FAIL: 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-1297ejd/test.py", line 130, in test_o_wins
    self.assertEqual('O wins!', d.game_status())
AssertionError: 'O wins!' != 'Game in progress.'
- O wins!
+ Game in progress.


======================================================================
FAIL: 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-1297ejd/test.py", line 99, in test_x_wins
    self.assertEqual('X wins!', d.game_status())
AssertionError: 'X wins!' != 'Game in progress.'
- X wins!
+ Game in progress.


----------------------------------------------------------------------
Ran 8 tests in 0.149s

FAILED (failures=2)

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

Светлана обнови решението на 14.04.2013 23:43 (преди над 11 години)

+class TicTacToeError(Exception):
+ pass
+
+
+class InvalidMove(TicTacToeError):
+
+ def __init__(self):
+ self.message = "This field is already filled."
+
+
+class InvalidKey(TicTacToeError):
+
+ def __init__(self):
+ self.message = "There is no such field."
+
+
+class InvalidValue(TicTacToeError):
+
+ def __init__(self):
+ self.message = "This is not a proper mark"
+
+
+class NotYourTurn(TicTacToeError):
+
+ def __init__(self):
+ self.message = "The other player hasn't made his move yet"
+
+
+class TicTacToeBoard:
+
+ def __init__(self):
+ self.board = {"A1": " ", "A2": " ", "A3": " ",
+ "B1": " ", "B2": " ", "B3": " ",
+ "C1": " ", "C2": " ", "C3": " "}
+ self.status = "Game in progress."
+ self.last_played = None
+ self.winner = None
+
+ def __getitem__(self, key):
+ if key not in self.board:
+ raise InvalidKey
+ return self.board[key]
+
+ def __setitem__(self, key, value):
+ if value != "X" and value != "O":
+ raise InvalidValue
+ if key not in self.board:
+ raise InvalidKey
+ if self.board[key] != " ":
+ raise InvalidMove
+ if value == self.last_played:
+ raise NotYourTurn
+ self.last_played = value
+ self.board[key] = value
+ self.check_status()
+
+ def check_status(self):
+ if self.winner:
+ return
+ for row in ["1", "2", "3"]:
+ if (self.board["A" + row] == self.board["B" + row] ==
+ self.board["C" + row] != " "):
+ self.winner = self.board["A" + row]
+ for column in ["A", "B", "C"]:
+ if (self.board[column + "1"] == self.board[column + "2"] ==
+ self.board[column + "3"] != " "):
+ self.winner = self.board[column + "1"]
+ if self.board["A3"] == self.board["B2"] == self.board["C1"] != " ":
+ self.winner = self.board["A3"]
+ if self.board["A1"] == self.board["B2"] == self.board["C3"] != " ":
+ self.winner = self.board["A3"]
+ if self.winner:
+ self.status = self.winner + " wins!"
+ if " " not in self.board.values() and not self.winner:
+ self.status = "Draw!"
+ self.winner = "Draw"
+
+ def __str__(self):
+ return ("\n -------------\n"
+ "3 | {0[A3]} | {0[B3]} | {0[C3]} |\n"
+ " -------------\n"
+ "2 | {0[A2]} | {0[B2]} | {0[C2]} |\n"
+ " -------------\n"
+ "1 | {0[A1]} | {0[B1]} | {0[C1]} |\n"
+ " -------------\n"
+ " A B C \n").format(self.board)
+
+ def game_status(self):
+ return self.status

Светлана обнови решението на 14.04.2013 23:48 (преди над 11 години)

-class TicTacToeError(Exception):
- pass
-
-
-class InvalidMove(TicTacToeError):
-
- def __init__(self):
- self.message = "This field is already filled."
-
-
-class InvalidKey(TicTacToeError):
-
- def __init__(self):
- self.message = "There is no such field."
-
-
-class InvalidValue(TicTacToeError):
-
- def __init__(self):
- self.message = "This is not a proper mark"
-
-
-class NotYourTurn(TicTacToeError):
-
- def __init__(self):
- self.message = "The other player hasn't made his move yet"
-
-
class TicTacToeBoard:
def __init__(self):
self.board = {"A1": " ", "A2": " ", "A3": " ",
"B1": " ", "B2": " ", "B3": " ",
"C1": " ", "C2": " ", "C3": " "}
self.status = "Game in progress."
self.last_played = None
self.winner = None
def __getitem__(self, key):
if key not in self.board:
raise InvalidKey
return self.board[key]
def __setitem__(self, key, value):
if value != "X" and value != "O":
raise InvalidValue
if key not in self.board:
raise InvalidKey
if self.board[key] != " ":
raise InvalidMove
if value == self.last_played:
raise NotYourTurn
self.last_played = value
self.board[key] = value
self.check_status()
def check_status(self):
if self.winner:
return
for row in ["1", "2", "3"]:
- if (self.board["A" + row] == self.board["B" + row] ==
- self.board["C" + row] != " "):
- self.winner = self.board["A" + row]
+ if (self["A" + row] == self["B" + row] == self["C" + row] != " "):
+ self.winner = self["A" + row]
for column in ["A", "B", "C"]:
- if (self.board[column + "1"] == self.board[column + "2"] ==
- self.board[column + "3"] != " "):
- self.winner = self.board[column + "1"]
- if self.board["A3"] == self.board["B2"] == self.board["C1"] != " ":
- self.winner = self.board["A3"]
- if self.board["A1"] == self.board["B2"] == self.board["C3"] != " ":
- self.winner = self.board["A3"]
+ if (self[column + "1"] == self[column + "2"] ==
+ self[column + "3"] != " "):
+ self.winner = self[column + "1"]
+ if self["A3"] == self["B2"] == self["C1"] != " ":
+ self.winner = self["A3"]
+ if self["A1"] == self["B2"] == self["C3"] != " ":
+ self.winner = self["A3"]
if self.winner:
self.status = self.winner + " wins!"
if " " not in self.board.values() and not self.winner:
self.status = "Draw!"
self.winner = "Draw"
def __str__(self):
return ("\n -------------\n"
"3 | {0[A3]} | {0[B3]} | {0[C3]} |\n"
" -------------\n"
"2 | {0[A2]} | {0[B2]} | {0[C2]} |\n"
" -------------\n"
"1 | {0[A1]} | {0[B1]} | {0[C1]} |\n"
" -------------\n"
" A B C \n").format(self.board)
def game_status(self):
return self.status
+
+
+class TicTacToeError(Exception):
+ pass
+
+
+class InvalidMove(TicTacToeError):
+
+ def __init__(self):
+ self.message = "This field is already filled."
+
+
+class InvalidKey(TicTacToeError):
+
+ def __init__(self):
+ self.message = "There is no such field."
+
+
+class InvalidValue(TicTacToeError):
+
+ def __init__(self):
+ self.message = "This is not a proper mark"
+
+
+class NotYourTurn(TicTacToeError):
+
+ def __init__(self):
+ self.message = "The other player hasn't made his move yet"

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

Помисли дали не можеш да преработиш check_status да обхожда някаква структура така, че този код self[field1] == self[field2] == self[field3] != " ": self.winner = self[field1] да се среща само веднъж.

Светлана обнови решението на 15.04.2013 15:31 (преди над 11 години)

class TicTacToeBoard:
def __init__(self):
self.board = {"A1": " ", "A2": " ", "A3": " ",
"B1": " ", "B2": " ", "B3": " ",
"C1": " ", "C2": " ", "C3": " "}
self.status = "Game in progress."
self.last_played = None
self.winner = None
def __getitem__(self, key):
if key not in self.board:
- raise InvalidKey
+ raise InvalidKey("There is no such field.")
return self.board[key]
def __setitem__(self, key, value):
if value != "X" and value != "O":
- raise InvalidValue
+ raise InvalidValue("This is not a proper mark")
if key not in self.board:
- raise InvalidKey
+ raise InvalidKey("There is no such field.")
if self.board[key] != " ":
- raise InvalidMove
+ raise InvalidMove("This field is already filled.")
if value == self.last_played:
- raise NotYourTurn
+ raise NotYourTurn("The other player hasn't made his move yet")
self.last_played = value
self.board[key] = value
self.check_status()
def check_status(self):
if self.winner:
return
- for row in ["1", "2", "3"]:
- if (self["A" + row] == self["B" + row] == self["C" + row] != " "):
- self.winner = self["A" + row]
- for column in ["A", "B", "C"]:
- if (self[column + "1"] == self[column + "2"] ==
- self[column + "3"] != " "):
- self.winner = self[column + "1"]
- if self["A3"] == self["B2"] == self["C1"] != " ":
- self.winner = self["A3"]
- if self["A1"] == self["B2"] == self["C3"] != " ":
- self.winner = self["A3"]
+ lines = list(map(lambda x: x[1], sorted(self.board.items())))
+ lines = (lines[:3] + lines[3:6] + lines[6:9] +
+ lines[::3] + lines[1::3] + lines[2::3])
+ for i, v in enumerate(lines):
+ if i % 3 == 0 and i < 18:
+ if lines[i] == lines[i + 1] == lines[i + 2] != " ":
+ self.winner = v
if self.winner:
self.status = self.winner + " wins!"
if " " not in self.board.values() and not self.winner:
self.status = "Draw!"
self.winner = "Draw"
def __str__(self):
return ("\n -------------\n"
"3 | {0[A3]} | {0[B3]} | {0[C3]} |\n"
" -------------\n"
"2 | {0[A2]} | {0[B2]} | {0[C2]} |\n"
" -------------\n"
"1 | {0[A1]} | {0[B1]} | {0[C1]} |\n"
" -------------\n"
" A B C \n").format(self.board)
def game_status(self):
return self.status
class TicTacToeError(Exception):
pass
class InvalidMove(TicTacToeError):
+ pass
- def __init__(self):
- self.message = "This field is already filled."
-
class InvalidKey(TicTacToeError):
+ pass
- def __init__(self):
- self.message = "There is no such field."
-
class InvalidValue(TicTacToeError):
+ pass
- def __init__(self):
- self.message = "This is not a proper mark"
-
class NotYourTurn(TicTacToeError):
-
- def __init__(self):
+ pass
- self.message = "The other player hasn't made his move yet"