3
\$\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.

AlexV
7,3532 gold badges24 silver badges47 bronze badges
asked Jun 23, 2019 at 0:23
\$\endgroup\$

1 Answer 1

3
\$\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.

AlexV
7,3532 gold badges24 silver badges47 bronze badges
answered Jun 23, 2019 at 1:00
\$\endgroup\$
1
  • \$\begingroup\$ I appreciate the feedback. I agree but wasn't paying attention, I really shouldn't manipulate the data coming in. thanks \$\endgroup\$ Commented Jun 23, 2019 at 1:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.