I'm a beginner trying to write a text based game, something like Monopoly. Since I learned about functions I thought the best way would be to define a function for each square. Then, I would put the functions in a list and randomly call them. The problem is the functions might require different number of arguments or no argument.
from random import randrange
def foo1(arg_of_foo1):
x = arg_of_foo1 + 1
print "x is:", x
def foo2(arg_of_foo2):
y = arg_of_foo2 + 2
print "y is:", y
def foo3(useless_arg):
print "I have an argument but I don't really need it..."
list_of_foo = [foo1, foo2, foo3]
arg = 0
function_index = randrange(0,3)
print "Function index is:", function_index
if function_index == 0:
arg = 4
elif function_index == 1:
arg = 10
list_of_foo [function_index](arg)
As you can see this seems to work but it is not an elegant solution. I don't like that I had to define the third function with an argument even if it doesn't need it, of course. And I also don't like that I have to specify a condition for some functions to let them know what they should use as arguments. Surely there must be a better way to do this. There always is. Thank you and sorry if this is stupid or it has already been asked. I couldn't find an answer.
Aucun commentaire:
Enregistrer un commentaire