pythontkinterzigzag

How to create zigzag movements in Python?


from tkinter import *

def move():
    global x1, y1, dx, dy, flag, n, z

    x1, y1 = x1 + dx, y1 + dy

    if x1 > 360: 
        x1, dx, dy = 360, -15, 5
        can1.itemconfig(oval1, fill = "purple")

    if x1 < 10:
        x1, dx, dy = 10, 15, 5
        can1.itemconfig(oval1, fill = "red")

    if y1 == 360:
        x1, dx, dy = 360, -15, -5
        can1.itemconfig(oval1, fill = "green")


    can1.coords(oval1, x1, y1, x1 + 30, y1 + 30)

    if flag > 0:
        abl1.after(50, move)

def stop():
    global flag
    flag = 0

def start():
    global flag
    if flag == 0:
        flag = 1
        move()

###

x1, y1 = 10, 10
dx, dy = 15, 5
n = 0


flag = 0

###

abl1 = Tk()
abl1.title("Animációs gyakorlat Tkinter-rel")

can1 = Canvas(abl1, bg = "dark grey", height = 400, width = 400)
can1.pack(side=LEFT)

oval1 = can1.create_oval(x1, y1, x1 + 30, y1 + 30, fill = "white")

but1 = Button(abl1, text = "Quit", command = abl1.destroy).pack(side=BOTTOM, padx = 3, pady = 5)
but2 = Button(abl1, text = "Start", command = start).pack(padx = 3, pady = 5)
but3 = Button(abl1, text = "Stop", command = stop).pack(padx = 3, pady = 5)

abl1.mainloop()

With this code the ball automatically goes to the bottom with zigzag moves, but when it reaches the bottom, it should go back to the top then back to the bottom again. I tried several attempts but I couldn't solve it.


Solution

  • Create new variable

    is_moving_down = True
    

    And new function for moving up and then

    if is_moving_down:
        move_down()
    else:
        move_up()
    

    Now you need to change direction

    if some_conditions:
        is_moving_down = True
    else:
        is_moving_down = False