How to create zigzag movements in Python?

自古美人都是妖i 提交于 2021-01-29 22:41:24

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/24282937/how-to-create-zigzag-movements-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!