I have a class with different methods inside it. In this project, I have to read in the input and call the methods according to what I receive in input. Here is my code
import sys
MIN_SIZE = 5
MAX_SIZE = 20
INFO = 'name="FabienLeGenie", version="1.0", author="TheBoss", country="Reu"'
AI = "X"
MANAGER = "O"
class Protocol:
def __init__(self):
self.size = 0
self.board = []
def startGame(self, size):
self.size = size
if self.size > MAX_SIZE or self.size < MIN_SIZE:
print("ERROR message - {} is not a valid size".format(self.size), flush=True)
sys.exit(84)
self.board = [[0 for x in range(self.size)] for y in range(self.size)]
print("OK - everything is good", flush=True)
def getBoard(self) -> list:
return self.board
def aboutGame(self):
print(INFO, flush=True)
def endGame(self):
sys.exit(0)
def turnGame(self, pos):
self.board[pos[0]][pos[1]] = MANAGER
print(self.board)
def begin():
jb = Protocol()
jb.startGame(20)
jb.aboutGame()
jb.turnGame((3, 3))
a = jb.getBoard()
jb.endGame()
print(a)
# while True:
# data = sys.stdin.readline()
# protocol = data.strip().split(" ")
# print(protocol[1])
# print(protocol[2])
if __name__ == "__main__":
begin()
So for example, if I receive BEGIN
in input, I have to execute startGame
.
I'm trying to find a solution to make my method calls dynamic avoiding the if
statement abuse.
I thought of using an array or a dictionnary for it but I don't know how to manage to send arguments in it because as you may have seen, some of my methods take arguments and other not. Is it possible to create a dictionnary with methods from a class like that ?
It could look something like that:
dict = {
"BEGIN": jb.startGame,
"END": jb.endGame,
"TURN": jb.turnGame, # <- how to send arguments here ?
}
dict["TURN"](myArgs) # <- is it like that ?
in the case the dictionnary I made up their is good, does that mean that I have to pass unused arguments to all my methods to be able to use it ?