mercredi 1 avril 2020

Replace ending integer number of a function with another random integer number

I have a function that generates a random integer number between 1 and 6 and calls a function based on the number.

I have 6 other functions from another class which have names ending in numbers from 1 to 6.

I want to call the function corresponding to the random number I generate each time, because I want to reduce the repeating lines of if statements.

Is it possible to replace the ending number of a function with the random number?

Not sure if this will work though, I have imagined something like this:

sense.set_pixels(self.dice_(self.number)())

This is my current code:

def roll(self):
    sense = SenseHat()
    self.number = random.randint(1,6)

    if self.number == 1:
        sense.set_pixels(self.dice_1())
    elif self.number == 2:
        sense.set_pixels(self.dice_2())
    elif self.number == 3:
        sense.set_pixels(self.dice_3())
    elif self.number == 4:
        sense.set_pixels(self.dice_4())
    elif self.number == 5:
        sense.set_pixels(self.dice_5())
    elif self.number == 6:
        sense.set_pixels(self.dice_6())



Aucun commentaire:

Enregistrer un commentaire