python - 单击鼠标按钮时如何连续移动字符

标签 python python-3.x pygame

我想创建一个简单的程序,当你点击屏幕时,盒子会永远移动。这看起来很简单,而且可能很简单,但我似乎无法让它发挥作用。
代码:

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/

相关文章:

python - 如何从字节播放 mp3?

python - 这段代码背后的逻辑是如何运作的?

python - 在 Python 中实现对字符串中包含的整数求和的函数

python 3.3 : struct. pack 不接受字符串

python - 使用 python 静默捕获网络摄像头快照

python - 在 PyGame 中移动图像会隐藏所有其他图像

python - Pygame 组更新不带参数

python - 仅在数据框中向右移动某些列,而不覆盖现有列

python - Django 如何知道呈现表单字段的顺序?

python - 连续绿色日