This is my attempt at making a class to represent a game board for tic tac toe. I normally hate while
loops but I used one because I cant seem to make the for
loop look nice for the display.
import numpy as np
class TicTacToeBoard():
"""Class to represent a board for a game of tic tac toe"""
def __init__(self):
"""Initialize the board data"""
self.dimension = 3,3
self.board_data = np.array(range(1,10), dtype=object).reshape(self.dimension)
self.space_to_coordinate = {}
self.last_marked_coordinate = None
for coord in np.ndindex(self.board_data.shape):
space = self.board_data[coord]
self.space_to_coordinate[space] = coord
def display(self):
"""Displays the game board to console
Example:
1 | 2 | 3
----------
4 | 5 | 6
----------
7 | 8 | 9
"""
count = 1
while count < 10:
coordinate = self.space_to_coordinate[count]
space_data = self.board_data[coordinate]
print(str(space_data)) if not count % 3 else print(str(space_data) + " |", end=' ')
print('----------') if not count % 3 and count != 9 else None
count += 1
print()
def is_marked(self, space):
"""Checks if space is marked returns false if not marked"""
coordinate = self.space_to_coordinate[space]
space_data = self.board_data[coordinate]
if space_data == "X" or space_data == "O":
return True
return False
def add_mark(self, space, mark):
"""If space is not marked, then add player mark and return true else return false"""
if not self.is_marked(space):
coordinate = self.space_to_coordinate[space]
self.board_data[coordinate] = mark
self.last_marked_coordinate = coordinate
return True
return False
def is_winner(self, mark):
"""Checks to see if mark has won the board by getting '3 in a row' """
if self.last_marked_coordinate == None:
return False
row_win, column_win, diag1_win, diag2_win = [True] * 4
fixed_row, fixed_column = self.last_marked_coordinate
for i in range(3):
#check row
if self.board_data[fixed_row, i] != mark:
row_win = False
#check column
if self.board_data[i, fixed_column] != mark:
column_win = False
#check diagnol 1
if self.board_data[i,i] != mark:
diag1_win = False
#check diagnol 2
if self.board_data[i, 2-i] != mark:
diag2_win = False
return any([row_win, column_win, diag1_win, diag2_win])
NOTE: just realized I forgot to test for a cats game.