Решение на Морски шах от Александър Димитров

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

Към профила на Александър Димитров

Резултати

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

Код

import re
class InvalidMove(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidKey(Exception):
pass
class NotYourTurn(Exception):
pass
class TicTacToeBoard:
def __init__(self):
self.board = {}
self.last_player = ''
self.status = 'Game in progress.'
self.steps = 0
def game_status(self):
return self.status
def __setitem__(self, key, value):
if re.search('^[ABC][123]$', key) is None:
raise InvalidKey
if value != 'X' and value != 'O':
raise InvalidValue
if key in self.board:
raise InvalidMove
if self.last_player == value:
raise NotYourTurn
self.board[key] = value
self.last_player = value
self.steps += 1
if self.status == 'Game in progress.':
if self.board.get('A1', '') == self.board.get('A2', '')\
== self.board.get('A3', '') and self.board.get('A1', ''):
self.status = self.board['A1'] + ' wins!'
if self.board.get('B1', '') == self.board.get('B2', '')\
== self.board.get('B3', '') and self.board.get('B1', ''):
self.status = self.board['B1'] + ' wins!'
if self.board.get('C1', '') == self.board.get('C2', '')\
== self.board.get('C3', '') and self.board.get('C1', ''):
self.status = self.board['C1'] + ' wins!'
if self.board.get('A1', '') == self.board.get('B1', '')\
== self.board.get('C1', '') and self.board.get('A1', ''):
self.status = self.board['A1'] + ' wins!'
if self.board.get('A2', '') == self.board.get('B2', '')\
== self.board.get('C2', '') and self.board.get('A2', ''):
self.status = self.board['A2'] + ' wins!'
if self.board.get('A3', '') == self.board.get('B3', '')\
== self.board.get('C3', '') and self.board.get('A3', ''):
self.status = self.board['A3'] + ' wins!'
if self.board.get('A1', '') == self.board.get('B2', '')\
== self.board.get('C3', '') and self.board.get('A1', ''):
self.status = self.board['A1'] + ' wins!'
if self.board.get('C1', '') == self.board.get('B2', '')\
== self.board.get('A3', '') and self.board.get('C1', ''):
self.status = self.board['C1'] + ' wins!'
if self.status == 'Game in progress.' and self.steps == 9:
self.status = 'Draw!'
def __getitem__(self, key):
return self.board[key]
def __str__(self):
result = '\n -------------\n'
for row in ['3', '2', '1']:
result += row + ' |'
for col in ['A', 'B', 'C']:
result += ' ' + self.board.get(col+row, ' ') + ' |'
result += '\n -------------\n'
result += ' A B C \n'
return result

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

........
----------------------------------------------------------------------
Ran 8 tests in 0.165s

OK

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

Александър обнови решението на 12.04.2013 23:47 (преди над 11 години)

+import re
+
+
+class InvalidMove(Exception):
+ pass
+
+
+class InvalidValue(Exception):
+ pass
+
+
+class InvalidKey(Exception):
+ pass
+
+
+class NotYourTurn(Exception):
+ pass
+
+
+class TicTacToeBoard:
+
+ def __init__(self):
+ self.board = {}
+ self.last_player = ''
+ self.status = 'Game in progress.'
+ self.steps = 0
+
+ def game_status(self):
+ return self.status
+
+ def __setitem__(self, key, value):
+ match = re.search('[ABC][123]', key)
+
+ if match is None:
+ raise InvalidKey
+
+ start, end = match.span()
+
+ if key[start:end] != key:
+ raise InvalidKey
+
+ if value != 'X' and value != 'O':
+ raise InvalidValue
+
+ if key in self.board:
+ raise InvalidMove
+
+ if self.last_player == value:
+ raise NotYourTurn
+
+ self.board[key] = value
+ self.last_player = value
+ self.steps += 1
+
+ if self.status == 'Game in progress.':
+ board_string = ''
+
+ for col in ['A', 'B', 'C']:
+ for row in ['1', '2', '3']:
+ board_string += self.board.get(col+row, ' ')
+
+ win_regex = ['ppp......', '...ppp...', '......ppp',
+ 'p..p..p', 'p...p...p', '..p.p.p..']
+
+ for player in ['X', 'O']:
+ for regex in win_regex:
+ pattern = re.sub('p', player, regex)
+ if re.search(pattern, board_string):
+ self.status = player + ' wins!'
+
+ if self.status == 'Game in progress.' and self.steps == 9:
+ self.status = 'Draw!'
+
+ def __getitem__(self, key):
+ return self.board[key]
+
+ def __str__(self):
+ result = '\n -------------\n'
+ for row in ['3', '2', '1']:
+ result += row + ' |'
+ for col in ['A', 'B', 'C']:
+ result += ' ' + self.board.get(col+row, ' ') + ' |'
+ result += '\n -------------\n'
+ result += ' A B C \n'
+ return result

Александър обнови решението на 13.04.2013 08:01 (преди над 11 години)

import re
class InvalidMove(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidKey(Exception):
pass
class NotYourTurn(Exception):
pass
class TicTacToeBoard:
def __init__(self):
self.board = {}
self.last_player = ''
self.status = 'Game in progress.'
self.steps = 0
def game_status(self):
return self.status
def __setitem__(self, key, value):
match = re.search('[ABC][123]', key)
if match is None:
raise InvalidKey
start, end = match.span()
if key[start:end] != key:
raise InvalidKey
if value != 'X' and value != 'O':
raise InvalidValue
if key in self.board:
raise InvalidMove
if self.last_player == value:
raise NotYourTurn
self.board[key] = value
self.last_player = value
self.steps += 1
if self.status == 'Game in progress.':
board_string = ''
for col in ['A', 'B', 'C']:
for row in ['1', '2', '3']:
board_string += self.board.get(col+row, ' ')
- win_regex = ['ppp......', '...ppp...', '......ppp',
- 'p..p..p', 'p...p...p', '..p.p.p..']
+ win_regex = '(^(...)*ppp(...)*$)|(p...p...p)|(p..p..p)|(..p.p.p..)'
for player in ['X', 'O']:
- for regex in win_regex:
- pattern = re.sub('p', player, regex)
- if re.search(pattern, board_string):
- self.status = player + ' wins!'
+ pattern = re.sub('p', player, win_regex)
+ if re.search(pattern, board_string):
+ self.status = player + ' wins!'
if self.status == 'Game in progress.' and self.steps == 9:
self.status = 'Draw!'
def __getitem__(self, key):
return self.board[key]
def __str__(self):
result = '\n -------------\n'
for row in ['3', '2', '1']:
result += row + ' |'
for col in ['A', 'B', 'C']:
result += ' ' + self.board.get(col+row, ' ') + ' |'
result += '\n -------------\n'
result += ' A B C \n'
return result

Александър обнови решението на 13.04.2013 15:52 (преди над 11 години)

import re
class InvalidMove(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidKey(Exception):
pass
class NotYourTurn(Exception):
pass
class TicTacToeBoard:
def __init__(self):
self.board = {}
self.last_player = ''
self.status = 'Game in progress.'
self.steps = 0
def game_status(self):
return self.status
def __setitem__(self, key, value):
- match = re.search('[ABC][123]', key)
-
- if match is None:
- raise InvalidKey
-
- start, end = match.span()
-
- if key[start:end] != key:
+ if re.search('^[ABC][123]$', key) is None:
raise InvalidKey
if value != 'X' and value != 'O':
raise InvalidValue
if key in self.board:
raise InvalidMove
if self.last_player == value:
raise NotYourTurn
self.board[key] = value
self.last_player = value
self.steps += 1
if self.status == 'Game in progress.':
board_string = ''
for col in ['A', 'B', 'C']:
for row in ['1', '2', '3']:
board_string += self.board.get(col+row, ' ')
win_regex = '(^(...)*ppp(...)*$)|(p...p...p)|(p..p..p)|(..p.p.p..)'
for player in ['X', 'O']:
pattern = re.sub('p', player, win_regex)
if re.search(pattern, board_string):
self.status = player + ' wins!'
if self.status == 'Game in progress.' and self.steps == 9:
self.status = 'Draw!'
def __getitem__(self, key):
return self.board[key]
def __str__(self):
result = '\n -------------\n'
for row in ['3', '2', '1']:
result += row + ' |'
for col in ['A', 'B', 'C']:
result += ' ' + self.board.get(col+row, ' ') + ' |'
result += '\n -------------\n'
result += ' A B C \n'
return result

Готин regex, но щеше да е по-добре да напишеш тази логика на Питон. Така ти се усложнява кода малко повече.

Добра практика е да използваш регулярните изрази само за четене или валидиране на данни които по принцип са само в низов формат. Иначе кодът става доста по-труден за четене.

Александър обнови решението на 14.04.2013 21:14 (преди над 11 години)

import re
class InvalidMove(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidKey(Exception):
pass
class NotYourTurn(Exception):
pass
class TicTacToeBoard:
def __init__(self):
self.board = {}
self.last_player = ''
self.status = 'Game in progress.'
self.steps = 0
def game_status(self):
return self.status
def __setitem__(self, key, value):
if re.search('^[ABC][123]$', key) is None:
raise InvalidKey
if value != 'X' and value != 'O':
raise InvalidValue
if key in self.board:
raise InvalidMove
if self.last_player == value:
raise NotYourTurn
self.board[key] = value
self.last_player = value
self.steps += 1
if self.status == 'Game in progress.':
- board_string = ''
+ if self.board.get('A1', '') == self.board.get('A2', '')\
+ == self.board.get('A3', '') and self.board.get('A1', ''):
+ self.status = self.board['A1'] + ' wins!'
- for col in ['A', 'B', 'C']:
- for row in ['1', '2', '3']:
- board_string += self.board.get(col+row, ' ')
+ if self.board.get('B1', '') == self.board.get('B2', '')\
+ == self.board.get('B3', '') and self.board.get('B1', ''):
+ self.status = self.board['B1'] + ' wins!'
- win_regex = '(^(...)*ppp(...)*$)|(p...p...p)|(p..p..p)|(..p.p.p..)'
+ if self.board.get('C1', '') == self.board.get('C2', '')\
+ == self.board.get('C3', '') and self.board.get('C1', ''):
+ self.status = self.board['C1'] + ' wins!'
- for player in ['X', 'O']:
- pattern = re.sub('p', player, win_regex)
- if re.search(pattern, board_string):
- self.status = player + ' wins!'
+ if self.board.get('A1', '') == self.board.get('B1', '')\
+ == self.board.get('C1', '') and self.board.get('A1', ''):
+ self.status = self.board['A1'] + ' wins!'
+
+ if self.board.get('A2', '') == self.board.get('B2', '')\
+ == self.board.get('C2', '') and self.board.get('A2', ''):
+ self.status = self.board['A2'] + ' wins!'
+
+ if self.board.get('A3', '') == self.board.get('B3', '')\
+ == self.board.get('C3', '') and self.board.get('A3', ''):
+ self.status = self.board['A3'] + ' wins!'
+
+ if self.board.get('A1', '') == self.board.get('B2', '')\
+ == self.board.get('C3', '') and self.board.get('A1', ''):
+ self.status = self.board['A1'] + ' wins!'
+
+ if self.board.get('C1', '') == self.board.get('B2', '')\
+ == self.board.get('A3', '') and self.board.get('C1', ''):
+ self.status = self.board['C1'] + ' wins!'
if self.status == 'Game in progress.' and self.steps == 9:
self.status = 'Draw!'
def __getitem__(self, key):
return self.board[key]
def __str__(self):
result = '\n -------------\n'
for row in ['3', '2', '1']:
result += row + ' |'
for col in ['A', 'B', 'C']:
result += ' ' + self.board.get(col+row, ' ') + ' |'
result += '\n -------------\n'
result += ' A B C \n'
return result