'Get the combination of two python functions
I'm writing a game based on a grid pattern where the player can move in all directions. The diagonal directions can be represented as two consecutive moves in a straight direction, e.g. the direction up-left is first up and then left. How could I then return a function that first executes the up-move and then the left-move on the result? Snippet of my current tile class:
class Tile():
def __init__(self,row,col):
self.row,self.col = row,col
def up(self):
return Tile(self.row+1,self.col)
def down(self):
return Tile(self.row-1,self.col)
def left(self):
return Tile(self.row,self.col-1)
def right(self):
return Tile(self.row,self.col+1)
and I have a method that returns all these functions:
def directions():
return [Tile.up,Tile.down,Tile.left,Tile.right]
How do I also add the diagonal functions to this list? I want to return the combined function, something along the lines of return Tile.up(Tile.left)
Thank you!
Solution 1:[1]
Seems like lambda x : Tile.up(Tile.left(x)) worked, so just wanted to leave an explanation here. By using lambda x : Tile.up(Tile.left(x)) you create an anonymous function on one line. And then you can easily add this function to your list.
def directions():
return [Tile.up,Tile.down,Tile.left,Tile.right, lambda x : Tile.up(Tile.left(x))]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jhanzaib Humayun |
