Created
September 3, 2018 23:25
-
-
Save ltbringer/f27395e588f24d0578460cf87774cd00 to your computer and use it in GitHub Desktop.
reinforcement_tic_tac_toe_snippet_6.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def draw_char_for_item(self, item): | |
""" | |
Returns the string mapping of the integers in the matrix | |
which can be understood by, but is not equal to: | |
{ | |
0: ' ', | |
1: 'O', | |
2: 'X' | |
} | |
(The exact mapping is present in the constructor) | |
params: | |
- item int: One of (1, 2, 0) representing the mark of the player, bot or empty. | |
return: str | |
""" | |
if item == self.sym_x.get('value'): | |
# If item = 2 (value of symbol x, return mark of symbol x viz: 'X') | |
return self.sym_x.get('mark') | |
elif item == self.sym_o.get('value'): | |
# If item = 1 (value of symbol o, return mark of symbol o viz: 'O') | |
return self.sym_o.get('mark') | |
else: | |
# Otherwise the cell must be empty, as only 1, 2 have 'O','X' mapped onto them. | |
return self.sym_empty.get('mark') | |
def draw_board(self): | |
""" | |
Prints a human friendly representation of the tic-tac-toe board | |
""" | |
elements_in_board = self.board.size | |
# Calculate the elements in the board | |
items = [ | |
self.draw_char_for_item(self.board.item(item_idx)) | |
for item_idx in range(elements_in_board) | |
] | |
# For each integer cell/element in the matrix, find the character mapped to it | |
# and store in a list. | |
board = """ | |
{} | {} | {} | |
----------- | |
{} | {} | {} | |
----------- | |
{} | {} | {} | |
""".format(*items) | |
# The *items expand to N arguments where N is the number of elements in `items`, | |
# which is equal to the number of elements in the matrix, hence the string equivalent | |
# of the board | |
print(board) | |
def is_winning_move(self, player, item, item_x, item_y): | |
""" | |
Check if the last move was a winning move, which is defined by a row, column or diagonal having | |
the same values as the latest inserted integer `item`. | |
params | |
- item_x int: The row of the matrix in which item has been inserted. | |
- item_y int: The column of the matrix in which the item has been inserted. | |
- item int: The latest integer inserted into the matrix at row-index = item_x, and column-index = item_y. | |
""" | |
if self.is_game_over(player, item, item_x, item_y): | |
self.winner = player | |
return True | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment