2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

I am not sure why you do not just use numpys ndarray and instead have invented your own version. I would however suggest you make it derive from numpys ndarray, which will save you a lot of work, and it allow you to do all kinds of nice things with it. I would also use __setitem__ instead of replace, so you can use the grid[x,y] = value, notation. There are some problems with the padding of the start data. First off it has side effects (your input is actually changed), and secondly it will only work with actual lists, other numpy arrays and Grids will fail. I recommend generating the grid first, and then slicing in the data when the input does not fit perfectly. Consider whether it would make sense to move setting the grid to have a certain value based on some data (possibly different types) to some other method.

\$\endgroup\$
  • \$\begingroup\$ I appreciate the feedback. I agree but wasn't paying attention, I really shouldn't manipulate the data coming in. thanks \$\endgroup\$ – CE3601 Jun 23 at 1:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.