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

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

Към профила на Весела Бандова

Резултати

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

Код

class TicTacToeBoard:
def __init__(self):
self.board = {x + y: " " for x in "ABC" for y in "123"}
self.status = "Game in progress."
self.last_turn = None
def __setitem__(self, position, move):
if position not in self.board.keys():
raise InvalidKey
if self.board[position] != ' ':
raise InvalidMove
if move not in ('X', 'O'):
raise InvalidValue
if self.last_turn == move:
raise NotYourTurn
self.last_turn = move
self.board[position] = move
if self.status == "Game in progress.":
self.update_status(position, move)
def __getitem__(self, position):
if position not in self.board.keys():
raise InvalidKey
return self.board[position]
def __str__(self):
dash = " "*2 + "-"*13 + "\n"
row = "{num} "+"| {pos1} | {pos2} | {pos3} |"+"\n"
arr = []
arr.append("\n")
for i in "321":
arr.append(row.format(num=i, pos1=self.board["A" + i],
pos2=self.board["B" + i], pos3=self.board["C" + i]))
arr.append(' A B C \n')
draw_board = dash.join(arr)
return draw_board
def makeTriple(self, alphas, nums):
triple = ""
for x, y in zip(alphas, nums):
triple += self.board[x + y]
return triple
def game_status(self):
return self.status
def update_status(self, position, move):
row_num = position[1]
row_alpha = position[0]
winner_combo = move*3
if(winner_combo == self.makeTriple((row_alpha)*3, "123") or
winner_combo == self.makeTriple("ABC", row_num*3) or
winner_combo == self.makeTriple("ABC", "123") or
winner_combo == self.makeTriple("ABC", "321")):
self.status = move + " wins!"
elif " " not in self.board.values():
self.status = "Draw!"
class InvalidMove(Exception):
pass
class InvalidKey(Exception):
pass
class InvalidValue(Exception):
pass
class NotYourTurn(Exception):
pass

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

........
----------------------------------------------------------------------
Ran 8 tests in 0.005s

OK

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

Весела обнови решението на 15.04.2013 12:24 (преди над 11 години)

+
+
+class TicTacToeBoard:
+
+ def __init__(self):
+ self.board = {x + y: " " for x in "ABC" for y in "123"}
+ self.status = "Game in progress."
+ self.last_turn = None
+
+ def __setitem__(self, position, move):
+ if(position not in self.board.keys()):
+ raise InvalidKey
+ if(self.board[position] != ' '):
+ raise InvalidMove
+ if(move not in ('X', 'O')):
+ raise InvalidValue
+ if(self.last_turn == move):
+ raise NotYourTurn
+ self.last_turn = move
+ self.board[position] = move
+ if self.status == "Game in progress.":
+ self.update_status(position, move)
+
+ def __getitem__(self, position):
+ if(position not in self.board.keys()):
+ raise InvalidKey
+ return self.board[position]
+
+ def __str__(self):
+ draw_board = '\n' + ' '+'-'*13 + '\n' + '3 | ' +\
+ self.board["A3"] + ' | ' + self.board["B3"] +\
+ ' | ' + self.board["C3"] + ' |\n' +\
+ ' '+'-'*13 + '\n' + '2 | ' + self.board["A2"] +\
+ ' | ' + self.board["B2"] + ' | '+self.board["C2"] +\
+ ' |\n' + ' ' + '-'*13 + '\n' + '1 | ' + self.board["A1"] +\
+ ' | ' + self.board["B1"] + ' | ' + self.board["C1"] +\
+ ' |\n'+' A B C \n'
+ return draw_board
+
+ def game_status(self):
+ return self.status
+
+ def update_status(self, position, move):
+ row_win = True
+ col_win = True
+ diag_win = True
+ board = self.board
+ for i in "123":
+ a = position[0] + i
+ if board[a] == ' ' or board[a] != move:
+ col_win = False
+ for i in "ABC":
+ a = i + position[1]
+ if board[a] == ' ' or board[a] != move:
+ row_win = False
+ diag1 = board["A1"] + board["B2"] + board["C3"]
+ diag2 = board["A3"] + board["B2"] + board["C1"]
+ diag_win = move*3 == diag1 or move*3 == diag2
+ if col_win or row_win or diag_win:
+ self.status = move + " wins!"
+ elif " " not in board.values():
+ self.status = "Draw!"
+
+
+class InvalidMove(Exception):
+ def __init__(self):
+ pass
+
+
+class InvalidKey(Exception):
+ def __init__(self):
+ pass
+
+
+class InvalidValue(Exception):
+ def __init__(self):
+ pass
+
+
+class NotYourTurn(Exception):
+ def __init__(self):
+ pass

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

Покрай условията в условен оператор нямаш нужда от скоби(гледа се лошо на тях). Употребата им е допустима само, когато става дума за определяне на приоритет или да направиш неявен такъв малко по-лесно четим.

__str__ метода ти може да се възползва от малко форматиране на низове.

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

Весела обнови решението на 15.04.2013 12:38 (преди над 11 години)

class TicTacToeBoard:
def __init__(self):
self.board = {x + y: " " for x in "ABC" for y in "123"}
self.status = "Game in progress."
self.last_turn = None
def __setitem__(self, position, move):
if(position not in self.board.keys()):
raise InvalidKey
if(self.board[position] != ' '):
raise InvalidMove
if(move not in ('X', 'O')):
raise InvalidValue
if(self.last_turn == move):
raise NotYourTurn
self.last_turn = move
self.board[position] = move
if self.status == "Game in progress.":
self.update_status(position, move)
def __getitem__(self, position):
if(position not in self.board.keys()):
raise InvalidKey
return self.board[position]
def __str__(self):
draw_board = '\n' + ' '+'-'*13 + '\n' + '3 | ' +\
self.board["A3"] + ' | ' + self.board["B3"] +\
' | ' + self.board["C3"] + ' |\n' +\
' '+'-'*13 + '\n' + '2 | ' + self.board["A2"] +\
' | ' + self.board["B2"] + ' | '+self.board["C2"] +\
' |\n' + ' ' + '-'*13 + '\n' + '1 | ' + self.board["A1"] +\
- ' | ' + self.board["B1"] + ' | ' + self.board["C1"] +\
- ' |\n'+' A B C \n'
+ ' | ' + self.board["B1"] + ' | ' + self.board["C1"] + ' |\n' +\
+ ' ' + '-'*13 + '\n' +\
+ ' A B C \n'
return draw_board
def game_status(self):
return self.status
def update_status(self, position, move):
row_win = True
col_win = True
diag_win = True
board = self.board
for i in "123":
a = position[0] + i
if board[a] == ' ' or board[a] != move:
col_win = False
for i in "ABC":
a = i + position[1]
if board[a] == ' ' or board[a] != move:
row_win = False
diag1 = board["A1"] + board["B2"] + board["C3"]
diag2 = board["A3"] + board["B2"] + board["C1"]
diag_win = move*3 == diag1 or move*3 == diag2
if col_win or row_win or diag_win:
self.status = move + " wins!"
elif " " not in board.values():
self.status = "Draw!"
class InvalidMove(Exception):
def __init__(self):
pass
class InvalidKey(Exception):
def __init__(self):
pass
class InvalidValue(Exception):
def __init__(self):
pass
class NotYourTurn(Exception):
def __init__(self):
pass

Весела обнови решението на 15.04.2013 13:39 (преди над 11 години)

class TicTacToeBoard:
def __init__(self):
self.board = {x + y: " " for x in "ABC" for y in "123"}
self.status = "Game in progress."
self.last_turn = None
def __setitem__(self, position, move):
- if(position not in self.board.keys()):
+ if position not in self.board.keys():
raise InvalidKey
- if(self.board[position] != ' '):
+ if self.board[position] != ' ':
raise InvalidMove
- if(move not in ('X', 'O')):
+ if move not in ('X', 'O'):
raise InvalidValue
- if(self.last_turn == move):
+ if self.last_turn == move:
raise NotYourTurn
self.last_turn = move
self.board[position] = move
if self.status == "Game in progress.":
self.update_status(position, move)
def __getitem__(self, position):
if(position not in self.board.keys()):
raise InvalidKey
return self.board[position]
def __str__(self):
draw_board = '\n' + ' '+'-'*13 + '\n' + '3 | ' +\
self.board["A3"] + ' | ' + self.board["B3"] +\
' | ' + self.board["C3"] + ' |\n' +\
' '+'-'*13 + '\n' + '2 | ' + self.board["A2"] +\
' | ' + self.board["B2"] + ' | '+self.board["C2"] +\
' |\n' + ' ' + '-'*13 + '\n' + '1 | ' + self.board["A1"] +\
' | ' + self.board["B1"] + ' | ' + self.board["C1"] + ' |\n' +\
' ' + '-'*13 + '\n' +\
' A B C \n'
return draw_board
+ def makeTriple(self, alphas, nums):
+ triple = ""
+ for x, y in zip(alphas, nums):
+ triple += self.board[x + y]
+ return triple
+
def game_status(self):
return self.status
def update_status(self, position, move):
- row_win = True
- col_win = True
- diag_win = True
- board = self.board
- for i in "123":
- a = position[0] + i
- if board[a] == ' ' or board[a] != move:
- col_win = False
- for i in "ABC":
- a = i + position[1]
- if board[a] == ' ' or board[a] != move:
- row_win = False
- diag1 = board["A1"] + board["B2"] + board["C3"]
- diag2 = board["A3"] + board["B2"] + board["C1"]
- diag_win = move*3 == diag1 or move*3 == diag2
- if col_win or row_win or diag_win:
+ row_num = position[1]
+ row_alpha = position[0]
+ winner_combo = move*3
+ if(winner_combo == self.makeTriple((row_alpha)*3, "123") or
+ winner_combo == self.makeTriple("ABC", row_num*3) or
+ winner_combo == self.makeTriple("ABC", "123") or
+ winner_combo == self.makeTriple("ABC", "321")):
self.status = move + " wins!"
- elif " " not in board.values():
+ elif " " not in self.board.values():
self.status = "Draw!"
class InvalidMove(Exception):
- def __init__(self):
- pass
+ pass
class InvalidKey(Exception):
- def __init__(self):
- pass
+ pass
class InvalidValue(Exception):
- def __init__(self):
- pass
+ pass
class NotYourTurn(Exception):
- def __init__(self):
- pass
+ pass

Весела обнови решението на 15.04.2013 13:46 (преди над 11 години)

class TicTacToeBoard:
def __init__(self):
self.board = {x + y: " " for x in "ABC" for y in "123"}
self.status = "Game in progress."
self.last_turn = None
def __setitem__(self, position, move):
if position not in self.board.keys():
raise InvalidKey
if self.board[position] != ' ':
raise InvalidMove
if move not in ('X', 'O'):
raise InvalidValue
if self.last_turn == move:
raise NotYourTurn
self.last_turn = move
self.board[position] = move
if self.status == "Game in progress.":
self.update_status(position, move)
def __getitem__(self, position):
- if(position not in self.board.keys()):
+ if position not in self.board.keys():
raise InvalidKey
return self.board[position]
def __str__(self):
draw_board = '\n' + ' '+'-'*13 + '\n' + '3 | ' +\
self.board["A3"] + ' | ' + self.board["B3"] +\
' | ' + self.board["C3"] + ' |\n' +\
' '+'-'*13 + '\n' + '2 | ' + self.board["A2"] +\
' | ' + self.board["B2"] + ' | '+self.board["C2"] +\
' |\n' + ' ' + '-'*13 + '\n' + '1 | ' + self.board["A1"] +\
' | ' + self.board["B1"] + ' | ' + self.board["C1"] + ' |\n' +\
' ' + '-'*13 + '\n' +\
' A B C \n'
return draw_board
def makeTriple(self, alphas, nums):
triple = ""
for x, y in zip(alphas, nums):
triple += self.board[x + y]
return triple
def game_status(self):
return self.status
def update_status(self, position, move):
row_num = position[1]
row_alpha = position[0]
winner_combo = move*3
if(winner_combo == self.makeTriple((row_alpha)*3, "123") or
winner_combo == self.makeTriple("ABC", row_num*3) or
winner_combo == self.makeTriple("ABC", "123") or
winner_combo == self.makeTriple("ABC", "321")):
self.status = move + " wins!"
elif " " not in self.board.values():
self.status = "Draw!"
class InvalidMove(Exception):
pass
class InvalidKey(Exception):
pass
class InvalidValue(Exception):
pass
class NotYourTurn(Exception):
pass

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

class TicTacToeBoard:
def __init__(self):
self.board = {x + y: " " for x in "ABC" for y in "123"}
self.status = "Game in progress."
self.last_turn = None
def __setitem__(self, position, move):
if position not in self.board.keys():
raise InvalidKey
if self.board[position] != ' ':
raise InvalidMove
if move not in ('X', 'O'):
raise InvalidValue
if self.last_turn == move:
raise NotYourTurn
self.last_turn = move
self.board[position] = move
if self.status == "Game in progress.":
self.update_status(position, move)
def __getitem__(self, position):
if position not in self.board.keys():
raise InvalidKey
return self.board[position]
def __str__(self):
- draw_board = '\n' + ' '+'-'*13 + '\n' + '3 | ' +\
- self.board["A3"] + ' | ' + self.board["B3"] +\
- ' | ' + self.board["C3"] + ' |\n' +\
- ' '+'-'*13 + '\n' + '2 | ' + self.board["A2"] +\
- ' | ' + self.board["B2"] + ' | '+self.board["C2"] +\
- ' |\n' + ' ' + '-'*13 + '\n' + '1 | ' + self.board["A1"] +\
- ' | ' + self.board["B1"] + ' | ' + self.board["C1"] + ' |\n' +\
- ' ' + '-'*13 + '\n' +\
- ' A B C \n'
+ dash = " "*2 + "-"*13 + "\n"
+ row = "{num} "+"| {pos1} | {pos2} | {pos3} |"+"\n"
+ arr = []
+ arr.append("\n")
+ for i in "321":
+ arr.append(row.format(num=i, pos1=self.board["A" + i],
+ pos2=self.board["B" + i], pos3=self.board["C" + i]))
+ arr.append(' A B C \n')
+ draw_board = dash.join(arr)
return draw_board
def makeTriple(self, alphas, nums):
triple = ""
for x, y in zip(alphas, nums):
triple += self.board[x + y]
return triple
def game_status(self):
return self.status
def update_status(self, position, move):
row_num = position[1]
row_alpha = position[0]
winner_combo = move*3
if(winner_combo == self.makeTriple((row_alpha)*3, "123") or
winner_combo == self.makeTriple("ABC", row_num*3) or
winner_combo == self.makeTriple("ABC", "123") or
winner_combo == self.makeTriple("ABC", "321")):
self.status = move + " wins!"
elif " " not in self.board.values():
self.status = "Draw!"
class InvalidMove(Exception):
pass
class InvalidKey(Exception):
pass
class InvalidValue(Exception):
pass
class NotYourTurn(Exception):
- pass
+ pass
+