HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Character instance slowdown

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
instanceslowdowncharacter

Problem

I'm making a Mario clone in PyGame and I am writing a function that, after releasing the left and right button while Mario is moving horizontally, slows him down until he is at rest. As of right now, the code I am using is functional and works the way it should. Though, I am not sure if there is a way I can write the following code more efficiently:

self.deacc = 0.5 # Always a positive number, never changed anywhere in the code.

if self.horzDir == 'l': # if mario is moving left.
    self.x += self.dx
    self.dx += self.deacc

    # To ensure marios velocity doesnt go below zero.
    if self.dx > (self.deacc * -1): 
        self.dx = 0
else:
    self.x += self.dx
    self.dx -= self.deacc

    # Also to ensure marios velocity doesnt go below zero.
    if self.dx < self.deacc:
        self.dx = 0


Everything is working correctly, but I feel like it can be more efficient than this because the if and else statements are very similar, just with slightly different calculations. Any ideas?

Solution

The most important difference between your if and your else is this:

self.dx += self.deacc


vs.

self.dx -= self.deacc


The rest can work just fine without being in if or else.

Also, when you copy-paste code, which you apparently did to check the bounds on self.dx, you should change the comments. Both of your comments say "go below zero". It was a bit hard for me to understand the purpose of your if self.dx > (self.deacc * -1):.

If I understand your code correctly, and if my Python syntax skills are correct, I think it should work to do it like this:

self.x += self.dx
self.dx += (self.deacc if self.horzDir == 'l' else -self.deacc)

if Math.abs(self.dx) < self.deacc:
    self.dx = 0


If I understand your code correctly, you are stopping Mario whenever his velocity (self.dx) gets close enough to zero. This can be accomplished by taking the absolute value of self.dx (which will get rid of a possible negative sign) and check if it is below self.deacc. If it is, Mario should stop. I think describing this as "stop Mario if his speed is too slow" is more accurate than "ensure Mario's velocity doesn't go below zero."

Code Snippets

self.dx += self.deacc
self.dx -= self.deacc
self.x += self.dx
self.dx += (self.deacc if self.horzDir == 'l' else -self.deacc)

if Math.abs(self.dx) < self.deacc:
    self.dx = 0

Context

StackExchange Code Review Q#98056, answer score: 3

Revisions (0)

No revisions yet.