1

I need some help for an assignment, I asked a question related to it this evening, but I recognize it was very poorly stated and written. I'll try to be a little more specific this time.

I have the following piece of code, it's inside a Game class (that inherits from the Canvas class):

def move_ball(self):
        if self.balldir==0:
                self.move(self.ball,0,-10)
        elif self.balldir==1:
                self.move(self.ball,0,10)
    root.after(20,self.move_ball)

This method is supossed to move a ball on the canvas, according to self.balldir. If it's 0, it moves up, if it's 1, it moves down.

It works just fine for a few seconds, but then it just makes the game slower and slower until it completely stops. I've tried with time.sleep as well, but It doesn't work well with Tkinter (as you probably already know).

I think the problems resides in the use of root.after() , but I really don't know any other way to move an object for an indefinite amount of time.

msw
  • 42,753
  • 9
  • 87
  • 112
dhcarmona
  • 402
  • 2
  • 10
  • 29
  • possible duplicate of [Code a timer in a python GUI in TKinter](http://stackoverflow.com/questions/2400262/code-a-timer-in-a-python-gui-in-tkinter) – msw Jun 13 '11 at 01:52
  • I want to retract my close vote, but cannot. Oops. – msw Jun 13 '11 at 02:11
  • 1
    This code all by itself won't make your program slower and slower and slower. I posted an answer to your other question that explains why your program gets slower. The code you posted here is fine, and is more-or-less ok, assuming `self.move` properly adjusts the coordinates of the ball object. – Bryan Oakley Jun 13 '11 at 14:57

1 Answers1

0

Twenty milliseconds seems like a short schedule time which might tweak some platform dependency that I don't know of. It is also not clear from your code snippet what values balldir may be assigned. If you expect balldir to only ever be 0 or 1 you might find this helpful:

def move_ball(self):
    assert 0 <= self.balldir <= 1
    self.move(self.ball, 0, 10 * (-1 * self.balldir))
    root.after(...

In your code snippet, if balldir is not in [0, 1] the ball will stop moving and give you no indication of why. To program defensively, especially when beginning never leave an else-less if:

if name == "dhcarmona":
    pass
elif name == "msw":
    pass
else
    raise ValueError, "name is not as expected"

Where the ValueError will keep your program from silently breaking.

msw
  • 42,753
  • 9
  • 87
  • 112