I have this function for checking which way we are facing when traveling through a coordinate system, by looking at how the values in a tuple increase, or decrease in comparison to the next value in a list of waypoints. Looking at the code, it feels convoluted and clumsy:
a.facing = self.direction(a.travel_list[0], a.travel_list[1])
def direction(self, start, end):
s_width = start[0]
s_height = start[1]
e_width = end[0]
e_height = end[1]
# check directions
if s_height < e_height:
if s_width < e_width:
return 'right'
elif s_width > e_width:
return 'up'
else:
return 'up_right'
elif s_height > e_height:
if s_width < e_width:
return 'down'
elif s_width > e_width:
return 'left'
else:
return 'down_left'
elif s_height == e_height and s_width < e_width:
return 'down_right'
else:
return 'up_left'
The return values are adjusted to be rotated one step clockwise. My question is, how can we change the code to make the function shorter and more efficient?
Edit: Note that movement can only happen in the 8 directions specified.
Use a dictionary based on the cmp() return values:
Build the dictionary to summarize your current logic:
If you’re using Python 3, you will need define your own cmp() function as: