I made this class to eventually create a tic tac toe game. I used numpy which is a first for me. Here it is:
import numpy as np
class Grid():
def __init__(self, data, row_length, coloumn_length):
"""Represents a Grid of data as a matrix.
Args:
data(list): data to be placed in grid matrix
row_length(int): number of elements per row
coloumn_length(int): number of elements per column
"""
data_len = row_length*coloumn_length
if len(data) < data_len:
difference = data_len - len(data)
data += [0]*(difference)
self.grid_matrix = np.array(data, dtype=object).reshape(row_length, coloumn_length)
def __str__(self):
return str(self.grid_matrix)
def replace(self, position, value):
"""Replace a value in a grid"""
x,y = position
rows, coloumns = len(self.grid_matrix), len(self.grid_matrix[0])
if x < rows and y < coloumns:
self.grid_matrix[x,y] = value
Note the goal is to make a generic grid class to make it easier to make different games with different tools so the actual rendering will be done in the game class.