I was trying to make my own solution for 8 puzzle game. Online I found mostly solutions with return statements. Is it wrong practice to code this way ?
import numpy as np
class Game(object):
def __init__(self, n, config):
array = np.array(config)
self.board = array.reshape((n, n))
blank = np.where(self.board == 0)
self.blanky = int(blank[0])
self.blankx = int(blank[1])
self.n = n
def move_up(self):
if self.blanky - 1 < 0:
return None
ay, ax = self.blanky, self.blankx
by, bx = self.blanky - 1, self.blankx
self.board[ay, ax], self.board[by, bx] = self.board[by, bx], self.board[ay, ax]
self.blanky = self.blanky - 1
def move_down(self):
if self.blanky + 1 > n:
return None
ay, ax = self.blanky, self.blankx
by, bx = self.blanky + 1, self.blankx
self.board[ay, ax], self.board[by, bx] = self.board[by, bx], self.board[ay, ax]
self.blanky = self.blanky + 1
def move_left(self):
if self.blankx - 1 < 0:
return None
ay, ax = self.blanky, self.blankx
by, bx = self.blanky, self.blankx - 1
self.board[ay, ax], self.board[by, bx] = self.board[by, bx], self.board[ay, ax]
self.blankx = self.blankx - 1
def move_right(self):
if self.blankx - 1 < 0:
return None
ay, ax = self.blanky, self.blankx
by, bx = self.blanky, self.blankx + 1
self.board[ay, ax], self.board[by, bx] = self.board[by, bx], self.board[ay, ax]
self.blankx = self.blankx + 1
def visualise(self):
return(self.board)
Within the world of object-oriented programming, you are using classes as they are designed. All the instance variables (self.blanky
and so on) are there to keep track of the state of the class.
However, you are on to something if you are thinking about other methodologies of coding, particularly functional coding. In functional coding, we want to avoid all side effects. They can modify variables within the function and return a value, but the shouldn't modify anything from the outside world (so you wouldn't be using classes if you were doing functional programming). See this article for some details: https://dzone.com/articles/side-effects-1
However, for the type of coding you are doing, there's no issue with a class method modifying the state of the class.