gpt4 book ai didi

python - 如何循环移动对象?

转载 作者:行者123 更新时间:2023-12-01 07:59:27 24 4
gpt4 key购买 nike

我想循环移动我的“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)

最佳答案

您可以使用canvas.move方法通过dxdy更改canvas项目的位置>;借助after,可以重复调用此move,从而创建连续的运动。

下面是一个示例,其中您未提供的图像被替换为 Canvas 项目,但在 Canvas 上移动对象的原理保持不变:

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()

关于python - 如何循环移动对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55789153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com