Как перемещать объекты в петлях? - PullRequest
1 голос
/ 22 апреля 2019

Я хочу переместить трубы и землю моего "Flappy Bird" в петле, но это не работает. Что мне нужно сделать? Я пытался переместить трубы и землю с «если», но это не работает. Я ожидаю, что трубы и земля будут двигаться петлей.

def deplacement():
    global tuyx,tuyx2,h,H,oisx,oisy,solx,sol2x

    x0, y0, x1, y1 = canvas.bbox(image_oiseau)
    if y1 < 510:
        canvas.move(image_oiseau, 0, DY)

    canvas.coords(image_sol,solx,512)  
    if solx >= -144:
        solx=solx-5
    else:
        solx=144

    canvas.coords(image_sol2,sol2x,512)
    if sol2x >= -144:
        sol2x=sol2x-5
    else:
        sol2x=432

    canvas.coords(image_tuyau_haut,tuyx,h)
    canvas.coords(image_tuyau_bas,tuyx,h-241)
    h = randint(128,385)
    if tuyx>=-28:
        tuyx=tuyx-5
    else:
        tuyx=316

    canvas.coords(image_tuyau_haut2,tuyx2,H)
    canvas.coords(image_tuyau_bas2,tuyx2,H-241)
    H = randint(128,385)
    if tuyx2>=-28:
        tuyx2=tuyx-5
    else:
        tuyx2=488

    canvas.after(40,deplacement)

1 Ответ

1 голос
/ 22 апреля 2019

Вы можете использовать метод canvas.move, чтобы изменить положение canvas item на dx, dy; С помощью after этот move можно вызывать повторно, создавая непрерывное движение.

Вот пример, где изображения, которые вы не предоставили, были заменены на элемент холста, но принцип перемещения объектов на холсте остается тем же:

import random
import tkinter as tk


WIDTH, HEIGHT = 500, 500


def create_pipes():
    pipes = []
    for x in range(0, WIDTH, 40):
        y1 = random.randrange(50, HEIGHT - 50)
        y0 = y1 + 50
        pipes.append(canvas.create_line(x, 0, x, y1))
        pipes.append(canvas.create_line(x, y0, x, HEIGHT))
    return pipes

def move_pipes():
    for pipe in pipes:
        canvas.move(pipe, -2, 0)
        x, y0, _, y1 = canvas.coords(pipe)
        if x < 0:   # reset pipe to the right of the canvas
            canvas.coords(pipe, WIDTH+20, y0, WIDTH+20, y1)
    root.after(40, move_pipes)


root = tk.Tk()
tk.Button(root, text='start', command=move_pipes).pack()
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="cyan")
canvas.pack()

pipes = create_pipes()

root.mainloop()
...