Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDanish Saleem
7,965 PointsMovement Challenge
Hello , i completed the movement challenge as below but the code looks very childish to me and i want to improve it , any suggestion ???
x, y, hp = player
a,b = direction
if a < 0:
x= x-abs(a)
else:
x = x+a
if b < 0:
y= y-abs(b)
else:
y = y+b
if x < 0:
x = 0
hp = hp-5
elif y < 0:
y = 0
hp = hp-5
elif x > 9:
x = 9
hp = hp-5
elif y > 9:
y = 9
hp = hp-5
return x,y,hp
[MOD: added ```python formatting -cf]
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsThere are some simplifications available:
# this
if a < 0:
x= x-abs(a)
else:
x = x+a
if b < 0:
y= y-abs(b)
else:
y = y+b
# is equivalent to
x += a
y += b
The rest is python's version of a case statement:
# case statement.
if x < 0:
x = 0
hp = hp-5
elif y < 0:
y = 0
hp = hp-5
elif x > 9:
x = 9
hp = hp-5
elif y > 9:
y = 9
hp = hp-5
# final return
return x,y,hp
The only other suggestion would be to improve on styling (see PEP8). Spaces after commas and around operators in assignments improve readability.