我想创建一个简单的程序,当你点击屏幕时,盒子会永远移动。这看起来很简单,而且可能很简单,但我似乎无法让它发挥作用。
代码:
import pygame
import sys
from pygame.locals import *
count = 0
def blast1():
global bl, blast
blast.y = bl
# ran = random.randint(0, 450)
pygame.init()
running = True
clock = pygame.time.Clock()
bl = 10
blast = pygame.Rect(300, 200 ,20,20)
screen = pygame.display.set_mode((500, 500))
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
blast1()
screen.fill((255, 255, 255)) #color
pygame.draw.ellipse(screen, [0, 255, 0], blast)
keys=pygame.key.get_pressed()
if event.type == pygame.MOUSEBUTTONDOWN and count != 1:
blast.x += bl
count = 1
pygame.display.flip()
clock.tick(30)
pygame.quit()
没有错误,但我希望它连续平稳地移动而不会停止。我怎样才能做到这一点?我试图放一个 for I in range(100)
但这只会使运动加倍,而且运动不顺畅。我也试过降低速度并放一个 pygame. time.sleep(100)
但这完全卡住了一切
最佳答案
您必须在事件循环中处理事件。当您单击鼠标并根据变量的状态移动对象时,设置一个 bool 变量 ( move
):
moving = False
count = 0
blast1()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN1:
moving = True
if moving and count < 100:
blast.x += 1
count += 1
screen.fill((255, 255, 255)) #color
pygame.draw.ellipse(screen, [0, 255, 0], blast)
pygame.display.flip()
clock.tick(30)
关于python - 单击鼠标按钮时如何连续移动字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67244425/