+ 2

How do i prevent my Action class from executing my action_method when i create an Action object and then run Invoke_action()?

https://code.sololearn.com/cbKQ2eqr5pqo/?ref=app

21st Jul 2021, 5:30 PM
Koen Tonkes
Koen Tonkes - avatar
4 Réponses
+ 3
You probably want to pass a function to your Action object, without actually executing it, because you are storing the actions in a list. You can do this by passing a parameterized lambda as argument. So in your World class when you instantiate the actions, you could do something like: self.add_action(Action("You fell in a ravine and you are looking for a way out.", "You lost 50 health to fall damage", 40, lambda: self.player.take_fall_damage(50))) and in the invoke_action method you would actually run the lambda by adding parentheses: if self.action_method != 0: print("i execute the action method") return self.action_method() Not sure if this will work flawlessly with the rest of the code, but this is the principle.
21st Jul 2021, 6:03 PM
Tibor Santa
Tibor Santa - avatar
+ 2
Tibor Santa ty for your solution, it works like a charm.
21st Jul 2021, 6:11 PM
Koen Tonkes
Koen Tonkes - avatar
0
I tried adding a boolean but that does not work.
21st Jul 2021, 5:30 PM
Koen Tonkes
Koen Tonkes - avatar
0
Here i define my action, i want the function to not execute from the constructor but if i call the invoke function i want to execute the method (see Action class at the bottom): self.add_action(Action("You fell in a ravine and you are looking for a way out.", "You lost 50 health to fall damage", 40, self.player.take_fall_damage(50))) class Action: def __init__(self, action_sentence, action_response, action_probability, action_method = 0): self.action_sentence = action_sentence self.action_response = action_response self.action_probability = action_probability self.action_method = action_method def invoke_action(self): rand_percentage = random.randrange(100) if rand_percentage <= self.action_probability: print(self.action_sentence) print(self.action_response) if self.action_method != 0: print("i execute the action method") return self.action_metho
21st Jul 2021, 6:02 PM
Koen Tonkes
Koen Tonkes - avatar