Move a ball inside Tkinter Canvas Widget (simple Arkanoid game)

后端 未结 2 1223
春和景丽
春和景丽 2020-12-10 22:46

I\'m trying to write a simple Arkanoid with the help of Python and Tkinter. The goal is to make the ball reflect from the top, right and left sides. And if the player misses

相关标签:
2条回答
  • 2020-12-10 23:01

    here is a simple hack for this problem:

    delta_x = delta_y = 3
    while True:
          objects = canv.find_overlapping(canv.coords(ball)[0], canv.coords(ball)[1], canv.coords(ball)[2], canv.coords(ball)[3])
          for obj in objects:
            if obj == 1:
                delta_y = -delta_y
            if obj == 2:
                delta_x = -delta_x
            if obj == 3:
                delta_x = -delta_x
            if obj == 4:
                delta_y = -delta_y
    
          new_x, new_y = delta_x, delta_y
          canv.move(ball, new_x, new_y)
          canv.update()
          time.sleep(0.025)
    
          root.bind('<Right>', move_right)
          root.bind('<Left>', move_left)
    
    0 讨论(0)
  • 2020-12-10 23:23

    To move an object you need to use the coords method or the move method, which changes the coordinates of the object. You can use the coords method to get the current coordinates.

    To do the animation you can use after. Call a function, then have it use after to call itself again a short time in the future. How far in the future will determine your frame rate (ie: every 10ms means roughly 100 frames per second)

    For example:

    def moveit(self):
    
        # move the object
        <get the existing coordinates using the coords method>
        <adjust the coordinates relative to the direction of travel>
        <give the object new coordinates using the coords method>
    
        # cause this movement to happen again in 10 milliseconds
        self.after(10, self.moveit)
    

    Once you call moveit() just once, the cycle begins. That same method can be used to update more than one object, or you can have different methods for different objects.

    edit: You've completely changed your question from "how do I move something on a canvas?" to "why does it move in the wrong direction?". The answer to the latter is simple: you're telling it to move in the wrong direction. Use a debugger or some print statements to see where and how you are calculating delta_y.

    0 讨论(0)
提交回复
热议问题