Решение на Морски шах от Симеон Попов

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

Към профила на Симеон Попов

Резултати

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

Код

class InvalidMove(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidKey(Exception):
pass
class NotYourTurn(Exception):
pass
class TicTacToeBoard:
def __init__(self):
self.map = {"A1": " ", "A2": " ", "A3": " ",
"B1": " ", "B2": " ", "B3": " ",
"C1": " ", "C2": " ", "C3": " "}
self.last_turn = " "
def __getitem__(self, key):
return self.map[key]
def __setitem__(self, key, value):
if key not in self.map:
raise InvalidKey("Invalid Key")
if value != "O" and value != "X":
raise InvalidValue("Invalid Value")
if value == self.last_turn:
raise NotYourTurn("Not your turn")
if self.map[key] != " ":
raise InvalidMove("Invalid Move")
self.map[key] = value
self.last_turn = value
def __str__(self):
return ('\n -------------\n' +
(" |\n -------------\n").join([" | ".join(["3",
self.map["A3"],
self.map["B3"],
self.map["C3"]]),
" | ".join(["2",
self.map["A2"],
self.map["B2"],
self.map["C2"]]),
" | ".join(["1",
self.map["A1"],
self.map["B1"],
self.map["C1"]]),
" ".join([" ",
"A",
"B",
"C"]) + " \n"])
)
def game_status(self):
win_table = ((self.map["A1"], self.map["A2"], self.map["A3"]),
(self.map["B1"], self.map["B2"], self.map["B3"]),
(self.map["C1"], self.map["C2"], self.map["C3"]),
(self.map["A1"], self.map["B1"], self.map["C1"]),
(self.map["A2"], self.map["B2"], self.map["C2"]),
(self.map["A3"], self.map["B3"], self.map["C3"]),
(self.map["A1"], self.map["B2"], self.map["C3"]),
(self.map["A3"], self.map["B2"], self.map["C1"]))
for win_line in win_table:
if win_line[0] == win_line[1] == win_line[2] == "X":
return "X wins!"
elif win_line[0] == win_line[1] == win_line[2] == "O":
return "O wins!"
if " " not in self.map.values():
return "Draw!"
return "Game in progress."

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

........
----------------------------------------------------------------------
Ran 8 tests in 0.006s

OK

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

Симеон обнови решението на 08.04.2013 19:55 (преди над 11 години)

+class InvalidMove(Exception):
+ def __str__(self):
+ return "This field is already taken"
+
+
+class InvalidValue(Exception):
+ def __str__(self):
+ return "You value is different from 'X' or 'O'"
+
+
+class InvalidKey(Exception):
+ def __str__(self):
+ return "Coordinate is invalid"
+
+
+class NotYourTurn(Exception):
+ def __str__(self):
+ return "Not your turn"
+
+
+class TicTacToeBoard:
+ def __init__(self):
+ self.map = {"A1": " ", "A2": " ", "A3": " ",
+ "B1": " ", "B2": " ", "B3": " ",
+ "C1": " ", "C2": " ", "C3": " "}
+ self.last_turn = " "
+
+ def __getitem__(self, key):
+ return self.map[key]
+
+ def __setitem__(self, key, value):
+ if key not in self.map:
+ raise InvalidKey
+ if value != "O" and value != "X":
+ raise InvalidValue
+ if value == self.last_turn:
+ raise NotYourTurn
+ if self.map[key] != " ":
+ raise InvalidMove
+ self.map[key] = value
+ self.last_turn = value
+ return self.map[key]
+
+ def __str__(self):
+ returnStr = "---------\n"
+ returnStr = returnStr + "3 " + "|" +
+ self.map["A3"] + "|" + self.map["B3"] +
+ "|" + self.map["C3"] + "|" + "\n"
+ returnStr = returnStr + "---------\n"
+ returnStr = returnStr + "2 " + "|" +
+ self.map["A2"] + "|" + self.map["B2"] +
+ "|" + self.map["C2"] + "|" + "\n"
+ returnStr = returnStr + "---------\n"
+ returnStr = returnStr + "1 " + "|" +
+ self.map["A1"] + "|" + self.map["B1"] +
+ "|" + self.map["C1"] + "|" + "\n"
+ returnStr = returnStr + "---------\n"
+ returnStr = returnStr + " " + " " +
+ "A" + " " + "B" + " " + "C" + " " + "\n"
+ return returnStr
+
+ def game_status(self):
+ if " " in self.map.values():
+ return 'Game in progress.'
+
+ win_table = ((self.map["A1"], self.map["A2"], self.map["A3"]),
+ (self.map["B1"], self.map["B2"], self.map["B3"]),
+ (self.map["C1"], self.map["C2"], self.map["C3"]),
+ (self.map["A1"], self.map["B1"], self.map["C1"]),
+ (self.map["A2"], self.map["B2"], self.map["C2"]),
+ (self.map["A3"], self.map["B3"], self.map["C3"]),
+ (self.map["A1"], self.map["B2"], self.map["C3"]),
+ (self.map["A3"], self.map["B2"], self.map["C1"]))
+ for win_line in win_table:
+ for element in win_line:
+ if element == "X":
+ return "X wins"
+ elif element == "O":
+ return "O wins"
+ else:
+ return "Draw"

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

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

Конструкторът на Exception има атрибут args и str(exception) връща първият аргумент подаден на конструктора.

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

class NotYourTurn(Exception):
    pass

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

Освен това много внимателно виж как е форматирана дъската в описанието на задачата. На пръв поглед забелязвам че имаш 9 тиренца на ред вместо 13 както е в примера. Общо взето, на първият ред трябва да имаш два спейса отпред, след това 13 тирета и нов ред.

Симеон обнови решението на 08.04.2013 20:51 (преди над 11 години)

class InvalidMove(Exception):
def __str__(self):
return "This field is already taken"
class InvalidValue(Exception):
def __str__(self):
return "You value is different from 'X' or 'O'"
class InvalidKey(Exception):
def __str__(self):
return "Coordinate is invalid"
class NotYourTurn(Exception):
def __str__(self):
return "Not your turn"
class TicTacToeBoard:
def __init__(self):
self.map = {"A1": " ", "A2": " ", "A3": " ",
"B1": " ", "B2": " ", "B3": " ",
"C1": " ", "C2": " ", "C3": " "}
self.last_turn = " "
def __getitem__(self, key):
return self.map[key]
def __setitem__(self, key, value):
if key not in self.map:
raise InvalidKey
if value != "O" and value != "X":
raise InvalidValue
if value == self.last_turn:
raise NotYourTurn
if self.map[key] != " ":
raise InvalidMove
self.map[key] = value
self.last_turn = value
return self.map[key]
def __str__(self):
- returnStr = "---------\n"
- returnStr = returnStr + "3 " + "|" +
- self.map["A3"] + "|" + self.map["B3"] +
- "|" + self.map["C3"] + "|" + "\n"
- returnStr = returnStr + "---------\n"
- returnStr = returnStr + "2 " + "|" +
- self.map["A2"] + "|" + self.map["B2"] +
- "|" + self.map["C2"] + "|" + "\n"
- returnStr = returnStr + "---------\n"
- returnStr = returnStr + "1 " + "|" +
- self.map["A1"] + "|" + self.map["B1"] +
- "|" + self.map["C1"] + "|" + "\n"
- returnStr = returnStr + "---------\n"
- returnStr = returnStr + " " + " " +
- "A" + " " + "B" + " " + "C" + " " + "\n"
+ returnStr = '\n -------------\n'
+ returnStr = returnStr + "3" + " | "
+ returnStr = returnStr + self.map["A3"] + " | " + self.map["B3"]
+ returnStr = returnStr + " | " + self.map["C3"] + " |\n"
+ returnStr = returnStr + ' -------------\n'
+ returnStr = returnStr + "2" + " | "
+ returnStr = returnStr + self.map["A2"] + " | " + self.map["B2"]
+ returnStr = returnStr + " | " + self.map["C2"] + " |\n"
+ returnStr = returnStr + ' -------------\n'
+ returnStr = returnStr + "1" + " | "
+ returnStr = returnStr + self.map["A1"] + " | " + self.map["B1"]
+ returnStr = returnStr + " | " + self.map["C1"] + " |\n"
+ returnStr = returnStr + ' -------------\n'
+ returnStr = returnStr + " "
+ returnStr = returnStr + "A" + " " + "B" + " " + "C" + " " + "\n"
return returnStr
def game_status(self):
- if " " in self.map.values():
- return 'Game in progress.'
-
+ result = "Game in progress."
win_table = ((self.map["A1"], self.map["A2"], self.map["A3"]),
(self.map["B1"], self.map["B2"], self.map["B3"]),
(self.map["C1"], self.map["C2"], self.map["C3"]),
(self.map["A1"], self.map["B1"], self.map["C1"]),
(self.map["A2"], self.map["B2"], self.map["C2"]),
(self.map["A3"], self.map["B3"], self.map["C3"]),
(self.map["A1"], self.map["B2"], self.map["C3"]),
(self.map["A3"], self.map["B2"], self.map["C1"]))
+
for win_line in win_table:
- for element in win_line:
- if element == "X":
+ if win_line[0] == win_line[1] == win_line[2] == "X":
- return "X wins"
+ return "X wins!"
- elif element == "O":
+ elif win_line[0] == win_line[1] == win_line[2] == "O":
- return "O wins"
+ return "O wins!"
- else:
+
- return "Draw"
+ if " " not in self.map.values():
+ result = "Draw!"
+ return result

Да, да тези неща останаха за дооправяне, аз общо взето го качих за да мога да го пренеса, защото нали не можеше да ги качваме на публични места и понеже сега съм на работа, да мога да работя вкъщи после :)

Симеон обнови решението на 08.04.2013 20:56 (преди над 11 години)

class InvalidMove(Exception):
- def __str__(self):
- return "This field is already taken"
+ pass
class InvalidValue(Exception):
- def __str__(self):
- return "You value is different from 'X' or 'O'"
+ pass
class InvalidKey(Exception):
- def __str__(self):
- return "Coordinate is invalid"
+ pass
class NotYourTurn(Exception):
- def __str__(self):
- return "Not your turn"
+ pass
class TicTacToeBoard:
def __init__(self):
self.map = {"A1": " ", "A2": " ", "A3": " ",
"B1": " ", "B2": " ", "B3": " ",
"C1": " ", "C2": " ", "C3": " "}
self.last_turn = " "
def __getitem__(self, key):
return self.map[key]
def __setitem__(self, key, value):
if key not in self.map:
- raise InvalidKey
+ raise InvalidKey("Invalid Key")
if value != "O" and value != "X":
- raise InvalidValue
+ raise InvalidValue("Invalid Key")
if value == self.last_turn:
- raise NotYourTurn
+ raise NotYourTurn("Not your turn")
if self.map[key] != " ":
- raise InvalidMove
+ raise InvalidMove("Invalid Move")
self.map[key] = value
self.last_turn = value
return self.map[key]
def __str__(self):
returnStr = '\n -------------\n'
returnStr = returnStr + "3" + " | "
returnStr = returnStr + self.map["A3"] + " | " + self.map["B3"]
returnStr = returnStr + " | " + self.map["C3"] + " |\n"
returnStr = returnStr + ' -------------\n'
returnStr = returnStr + "2" + " | "
returnStr = returnStr + self.map["A2"] + " | " + self.map["B2"]
returnStr = returnStr + " | " + self.map["C2"] + " |\n"
returnStr = returnStr + ' -------------\n'
returnStr = returnStr + "1" + " | "
returnStr = returnStr + self.map["A1"] + " | " + self.map["B1"]
returnStr = returnStr + " | " + self.map["C1"] + " |\n"
returnStr = returnStr + ' -------------\n'
returnStr = returnStr + " "
returnStr = returnStr + "A" + " " + "B" + " " + "C" + " " + "\n"
return returnStr
def game_status(self):
result = "Game in progress."
win_table = ((self.map["A1"], self.map["A2"], self.map["A3"]),
(self.map["B1"], self.map["B2"], self.map["B3"]),
(self.map["C1"], self.map["C2"], self.map["C3"]),
(self.map["A1"], self.map["B1"], self.map["C1"]),
(self.map["A2"], self.map["B2"], self.map["C2"]),
(self.map["A3"], self.map["B3"], self.map["C3"]),
(self.map["A1"], self.map["B2"], self.map["C3"]),
(self.map["A3"], self.map["B2"], self.map["C1"]))
for win_line in win_table:
if win_line[0] == win_line[1] == win_line[2] == "X":
return "X wins!"
elif win_line[0] == win_line[1] == win_line[2] == "O":
return "O wins!"
if " " not in self.map.values():
result = "Draw!"
return result

Симеон обнови решението на 08.04.2013 22:46 (преди над 11 години)

class InvalidMove(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidKey(Exception):
pass
class NotYourTurn(Exception):
pass
class TicTacToeBoard:
def __init__(self):
self.map = {"A1": " ", "A2": " ", "A3": " ",
"B1": " ", "B2": " ", "B3": " ",
"C1": " ", "C2": " ", "C3": " "}
self.last_turn = " "
def __getitem__(self, key):
return self.map[key]
def __setitem__(self, key, value):
if key not in self.map:
raise InvalidKey("Invalid Key")
if value != "O" and value != "X":
- raise InvalidValue("Invalid Key")
+ raise InvalidValue("Invalid Value")
if value == self.last_turn:
raise NotYourTurn("Not your turn")
if self.map[key] != " ":
raise InvalidMove("Invalid Move")
self.map[key] = value
self.last_turn = value
return self.map[key]
def __str__(self):
returnStr = '\n -------------\n'
returnStr = returnStr + "3" + " | "
returnStr = returnStr + self.map["A3"] + " | " + self.map["B3"]
returnStr = returnStr + " | " + self.map["C3"] + " |\n"
returnStr = returnStr + ' -------------\n'
returnStr = returnStr + "2" + " | "
returnStr = returnStr + self.map["A2"] + " | " + self.map["B2"]
returnStr = returnStr + " | " + self.map["C2"] + " |\n"
returnStr = returnStr + ' -------------\n'
returnStr = returnStr + "1" + " | "
returnStr = returnStr + self.map["A1"] + " | " + self.map["B1"]
returnStr = returnStr + " | " + self.map["C1"] + " |\n"
returnStr = returnStr + ' -------------\n'
returnStr = returnStr + " "
returnStr = returnStr + "A" + " " + "B" + " " + "C" + " " + "\n"
return returnStr
def game_status(self):
result = "Game in progress."
win_table = ((self.map["A1"], self.map["A2"], self.map["A3"]),
(self.map["B1"], self.map["B2"], self.map["B3"]),
(self.map["C1"], self.map["C2"], self.map["C3"]),
(self.map["A1"], self.map["B1"], self.map["C1"]),
(self.map["A2"], self.map["B2"], self.map["C2"]),
(self.map["A3"], self.map["B3"], self.map["C3"]),
(self.map["A1"], self.map["B2"], self.map["C3"]),
(self.map["A3"], self.map["B2"], self.map["C1"]))
for win_line in win_table:
if win_line[0] == win_line[1] == win_line[2] == "X":
return "X wins!"
elif win_line[0] == win_line[1] == win_line[2] == "O":
return "O wins!"
if " " not in self.map.values():
result = "Draw!"
- return result
+ return result

Симеон обнови решението на 08.04.2013 23:18 (преди над 11 години)

class InvalidMove(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidKey(Exception):
pass
class NotYourTurn(Exception):
pass
class TicTacToeBoard:
def __init__(self):
self.map = {"A1": " ", "A2": " ", "A3": " ",
"B1": " ", "B2": " ", "B3": " ",
"C1": " ", "C2": " ", "C3": " "}
self.last_turn = " "
def __getitem__(self, key):
return self.map[key]
def __setitem__(self, key, value):
if key not in self.map:
raise InvalidKey("Invalid Key")
if value != "O" and value != "X":
raise InvalidValue("Invalid Value")
if value == self.last_turn:
raise NotYourTurn("Not your turn")
if self.map[key] != " ":
raise InvalidMove("Invalid Move")
self.map[key] = value
self.last_turn = value
return self.map[key]
def __str__(self):
- returnStr = '\n -------------\n'
- returnStr = returnStr + "3" + " | "
- returnStr = returnStr + self.map["A3"] + " | " + self.map["B3"]
- returnStr = returnStr + " | " + self.map["C3"] + " |\n"
- returnStr = returnStr + ' -------------\n'
- returnStr = returnStr + "2" + " | "
- returnStr = returnStr + self.map["A2"] + " | " + self.map["B2"]
- returnStr = returnStr + " | " + self.map["C2"] + " |\n"
- returnStr = returnStr + ' -------------\n'
- returnStr = returnStr + "1" + " | "
- returnStr = returnStr + self.map["A1"] + " | " + self.map["B1"]
- returnStr = returnStr + " | " + self.map["C1"] + " |\n"
- returnStr = returnStr + ' -------------\n'
- returnStr = returnStr + " "
- returnStr = returnStr + "A" + " " + "B" + " " + "C" + " " + "\n"
- return returnStr
+ board = '\n -------------\n'
+ board = board + "3" + " | "
+ board = board + self.map["A3"] + " | " + self.map["B3"]
+ board = board + " | " + self.map["C3"] + " |\n"
+ board = board + ' -------------\n'
+ board = board + "2" + " | "
+ board = board + self.map["A2"] + " | " + self.map["B2"]
+ board = board + " | " + self.map["C2"] + " |\n"
+ board = board + ' -------------\n'
+ board = board + "1" + " | "
+ board = board + self.map["A1"] + " | " + self.map["B1"]
+ board = board + " | " + self.map["C1"] + " |\n"
+ board = board + ' -------------\n'
+ board = board + " "
+ board = board + "A" + " " + "B" + " " + "C" + " " + "\n"
+ return board
def game_status(self):
- result = "Game in progress."
+ status = "Game in progress."
win_table = ((self.map["A1"], self.map["A2"], self.map["A3"]),
(self.map["B1"], self.map["B2"], self.map["B3"]),
(self.map["C1"], self.map["C2"], self.map["C3"]),
(self.map["A1"], self.map["B1"], self.map["C1"]),
(self.map["A2"], self.map["B2"], self.map["C2"]),
(self.map["A3"], self.map["B3"], self.map["C3"]),
(self.map["A1"], self.map["B2"], self.map["C3"]),
(self.map["A3"], self.map["B2"], self.map["C1"]))
for win_line in win_table:
if win_line[0] == win_line[1] == win_line[2] == "X":
return "X wins!"
elif win_line[0] == win_line[1] == win_line[2] == "O":
return "O wins!"
if " " not in self.map.values():
- result = "Draw!"
- return result
+ status = "Draw!"
+ return status

Симеон обнови решението на 09.04.2013 10:53 (преди над 11 години)

class InvalidMove(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidKey(Exception):
pass
class NotYourTurn(Exception):
pass
class TicTacToeBoard:
def __init__(self):
self.map = {"A1": " ", "A2": " ", "A3": " ",
"B1": " ", "B2": " ", "B3": " ",
"C1": " ", "C2": " ", "C3": " "}
self.last_turn = " "
def __getitem__(self, key):
return self.map[key]
def __setitem__(self, key, value):
if key not in self.map:
raise InvalidKey("Invalid Key")
if value != "O" and value != "X":
raise InvalidValue("Invalid Value")
if value == self.last_turn:
raise NotYourTurn("Not your turn")
if self.map[key] != " ":
raise InvalidMove("Invalid Move")
self.map[key] = value
self.last_turn = value
return self.map[key]
+ def print_board_line(self, numline, a, b, c, sec):
+ return numline + sec + a + sec + b + sec + c
+
+ def print_horizontal_line(self):
+ return ' -------------\n'
+
def __str__(self):
- board = '\n -------------\n'
- board = board + "3" + " | "
- board = board + self.map["A3"] + " | " + self.map["B3"]
- board = board + " | " + self.map["C3"] + " |\n"
- board = board + ' -------------\n'
- board = board + "2" + " | "
- board = board + self.map["A2"] + " | " + self.map["B2"]
- board = board + " | " + self.map["C2"] + " |\n"
- board = board + ' -------------\n'
- board = board + "1" + " | "
- board = board + self.map["A1"] + " | " + self.map["B1"]
- board = board + " | " + self.map["C1"] + " |\n"
- board = board + ' -------------\n'
- board = board + " "
- board = board + "A" + " " + "B" + " " + "C" + " " + "\n"
+ board = '\n'
+ board = board + self.print_horizontal_line()
+ board = board + self.print_board_line("3",
+ self.map["A3"],
+ self.map["B3"],
+ self.map["C3"],
+ " | ") + " |\n"
+ board = board + self.print_horizontal_line()
+ board = board + self.print_board_line("2",
+ self.map["A2"],
+ self.map["B2"],
+ self.map["C2"],
+ " | ") + " |\n"
+ board = board + self.print_horizontal_line()
+ board = board + self.print_board_line("1",
+ self.map["A1"],
+ self.map["B1"],
+ self.map["C1"],
+ " | ") + " |\n"
+ board = board + self.print_horizontal_line()
+ board = board + self.print_board_line(" ",
+ "A",
+ "B",
+ "C",
+ " ") + " \n"
return board
def game_status(self):
status = "Game in progress."
win_table = ((self.map["A1"], self.map["A2"], self.map["A3"]),
(self.map["B1"], self.map["B2"], self.map["B3"]),
(self.map["C1"], self.map["C2"], self.map["C3"]),
(self.map["A1"], self.map["B1"], self.map["C1"]),
(self.map["A2"], self.map["B2"], self.map["C2"]),
(self.map["A3"], self.map["B3"], self.map["C3"]),
(self.map["A1"], self.map["B2"], self.map["C3"]),
(self.map["A3"], self.map["B2"], self.map["C1"]))
for win_line in win_table:
if win_line[0] == win_line[1] == win_line[2] == "X":
return "X wins!"
elif win_line[0] == win_line[1] == win_line[2] == "O":
return "O wins!"
if " " not in self.map.values():
status = "Draw!"
return status

Това е перфектно решение... ако пишеш на асемблер.

Сериозно, имаш три едни и същи блока. Можеш да използваш оператора += и въобще може да не конкатенираш стрингове по този C-way.

Hints: mutli-line strings, format.

Така съм го направим с multi-line strings, но идеята за format не ме кефи в този конкретен случай, така че ще го оставя с "+"-ове. Надявам се, че няма да ме режете заради характера ми(т.е. отказа) при положение, че езика го позволява и работи :)

Симеон обнови решението на 09.04.2013 12:02 (преди над 11 години)

class InvalidMove(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidKey(Exception):
pass
class NotYourTurn(Exception):
pass
class TicTacToeBoard:
def __init__(self):
self.map = {"A1": " ", "A2": " ", "A3": " ",
"B1": " ", "B2": " ", "B3": " ",
"C1": " ", "C2": " ", "C3": " "}
self.last_turn = " "
def __getitem__(self, key):
return self.map[key]
def __setitem__(self, key, value):
if key not in self.map:
raise InvalidKey("Invalid Key")
if value != "O" and value != "X":
raise InvalidValue("Invalid Value")
if value == self.last_turn:
raise NotYourTurn("Not your turn")
if self.map[key] != " ":
raise InvalidMove("Invalid Move")
self.map[key] = value
self.last_turn = value
return self.map[key]
def print_board_line(self, numline, a, b, c, sec):
return numline + sec + a + sec + b + sec + c
def print_horizontal_line(self):
return ' -------------\n'
def __str__(self):
- board = '\n'
- board = board + self.print_horizontal_line()
- board = board + self.print_board_line("3",
- self.map["A3"],
- self.map["B3"],
- self.map["C3"],
- " | ") + " |\n"
- board = board + self.print_horizontal_line()
- board = board + self.print_board_line("2",
- self.map["A2"],
- self.map["B2"],
- self.map["C2"],
- " | ") + " |\n"
- board = board + self.print_horizontal_line()
- board = board + self.print_board_line("1",
- self.map["A1"],
- self.map["B1"],
- self.map["C1"],
- " | ") + " |\n"
- board = board + self.print_horizontal_line()
- board = board + self.print_board_line(" ",
- "A",
- "B",
- "C",
- " ") + " \n"
+ board = ('\n' +
+ self.print_horizontal_line() +
+ self.print_board_line("3",
+ self.map["A3"],
+ self.map["B3"],
+ self.map["C3"],
+ " | ") + " |\n" +
+ self.print_horizontal_line() +
+ self.print_board_line("2",
+ self.map["A2"],
+ self.map["B2"],
+ self.map["C2"],
+ " | ") + " |\n" +
+ self.print_horizontal_line() +
+ self.print_board_line("1",
+ self.map["A1"],
+ self.map["B1"],
+ self.map["C1"],
+ " | ") + " |\n" +
+ self.print_horizontal_line() +
+ self.print_board_line(" ",
+ "A",
+ "B",
+ "C",
+ " ") + " \n")
return board
def game_status(self):
status = "Game in progress."
win_table = ((self.map["A1"], self.map["A2"], self.map["A3"]),
(self.map["B1"], self.map["B2"], self.map["B3"]),
(self.map["C1"], self.map["C2"], self.map["C3"]),
(self.map["A1"], self.map["B1"], self.map["C1"]),
(self.map["A2"], self.map["B2"], self.map["C2"]),
(self.map["A3"], self.map["B3"], self.map["C3"]),
(self.map["A1"], self.map["B2"], self.map["C3"]),
(self.map["A3"], self.map["B2"], self.map["C1"]))
for win_line in win_table:
if win_line[0] == win_line[1] == win_line[2] == "X":
return "X wins!"
elif win_line[0] == win_line[1] == win_line[2] == "O":
return "O wins!"
if " " not in self.map.values():
status = "Draw!"
return status

Езикът позволява много неща и за много от тях сме казвали да не ги правите. Това не е аргумент ;) Иначе, да. Подозирам, че няма да те отрежем, но не обещавам :D

Ок съм да използваш конкатенацията на стрингове, ама 26 реда имплементация на __str__ ми идват в повече...

И двата print_... метода са излишни: 1) Имената им не са подходящи 2) Приличат много повече на самостоятелни функции, от колкото на методи на TicTacToeBoard 3) Нямат особен смисъл сами по себе си. Можеш да ги замениш чрез други способи: локални променливи и str.join например, ако толкова отказваш да използваш форматиране на низове.

В game_status използваш локална променлива за подготвянето на връщаната стойност и връщаш директно. Замисли се дали няма да е по-добре да се спреш на едното от двете.

Защо връщаш стойност от __setitem__ ?

Симеон обнови решението на 09.04.2013 17:20 (преди над 11 години)

class InvalidMove(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidKey(Exception):
pass
class NotYourTurn(Exception):
pass
class TicTacToeBoard:
def __init__(self):
self.map = {"A1": " ", "A2": " ", "A3": " ",
"B1": " ", "B2": " ", "B3": " ",
"C1": " ", "C2": " ", "C3": " "}
self.last_turn = " "
def __getitem__(self, key):
return self.map[key]
def __setitem__(self, key, value):
if key not in self.map:
raise InvalidKey("Invalid Key")
if value != "O" and value != "X":
raise InvalidValue("Invalid Value")
if value == self.last_turn:
raise NotYourTurn("Not your turn")
if self.map[key] != " ":
raise InvalidMove("Invalid Move")
self.map[key] = value
self.last_turn = value
- return self.map[key]
- def print_board_line(self, numline, a, b, c, sec):
- return numline + sec + a + sec + b + sec + c
-
- def print_horizontal_line(self):
- return ' -------------\n'
-
def __str__(self):
- board = ('\n' +
- self.print_horizontal_line() +
- self.print_board_line("3",
- self.map["A3"],
- self.map["B3"],
- self.map["C3"],
- " | ") + " |\n" +
- self.print_horizontal_line() +
- self.print_board_line("2",
- self.map["A2"],
- self.map["B2"],
- self.map["C2"],
- " | ") + " |\n" +
- self.print_horizontal_line() +
- self.print_board_line("1",
- self.map["A1"],
- self.map["B1"],
- self.map["C1"],
- " | ") + " |\n" +
- self.print_horizontal_line() +
- self.print_board_line(" ",
- "A",
- "B",
- "C",
- " ") + " \n")
- return board
+ return ('\n -------------\n' +
+ (" |\n -------------\n").join([" | ".join(["3",
+ self.map["A3"],
+ self.map["B3"],
+ self.map["C3"]]),
+ " | ".join(["2",
+ self.map["A2"],
+ self.map["B2"],
+ self.map["C2"]]),
+ " | ".join(["1",
+ self.map["A1"],
+ self.map["B1"],
+ self.map["C1"]]),
+ " ".join([" ",
+ "A",
+ "B",
+ "C"]) + " \n"])
+ )
def game_status(self):
- status = "Game in progress."
win_table = ((self.map["A1"], self.map["A2"], self.map["A3"]),
(self.map["B1"], self.map["B2"], self.map["B3"]),
(self.map["C1"], self.map["C2"], self.map["C3"]),
(self.map["A1"], self.map["B1"], self.map["C1"]),
(self.map["A2"], self.map["B2"], self.map["C2"]),
(self.map["A3"], self.map["B3"], self.map["C3"]),
(self.map["A1"], self.map["B2"], self.map["C3"]),
(self.map["A3"], self.map["B2"], self.map["C1"]))
for win_line in win_table:
if win_line[0] == win_line[1] == win_line[2] == "X":
return "X wins!"
elif win_line[0] == win_line[1] == win_line[2] == "O":
return "O wins!"
if " " not in self.map.values():
- status = "Draw!"
- return status
+ return "Draw!"
+ return "Game in progress."