问题描述
我想创建一个简单的程序,当你点击屏幕时,盒子会永远移动。看起来很简单,而且可能很简单,但我似乎无法让它发挥作用。
代码:
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,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)
但这完全冻结了一切
解决方法
您必须在事件循环中处理事件。单击鼠标并根据变量的状态移动对象时,设置一个布尔变量(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,0],blast)
pygame.display.flip()
clock.tick(30)
,
你可以在 if event.tpye == pygame.MOUSEBUTTONDOWN 中加入一个 if 语句,然后从那里移动