gpt4 book ai didi

python - 如何在pygame中根据鼠标 Action 绘制矩形

转载 作者:行者123 更新时间:2023-12-01 05:15:28 24 4
gpt4 key购买 nike

我正在尝试在 pygame 中创建一个绘画程序。它要求用户能够通过单击并拖动在屏幕上绘制矩形。

pygame.draw.rect(screeny, (255,255,255), [posi[0], posi[1], e.pos[0]-posi[0], e.pos[1]-posi[1]], 1)
square = pygame.draw.rect(screeny, color, [posi[0], posi[1], e.pos[0]-posi[0], e.pos[1]-posi[1]], 1)

pygame.display.flip()

但是,矩形无法正确显示。我如何只从鼠标按钮按下点开始到鼠标按钮向上点绘制一个矩形?

最佳答案

我没有足够的代码来使用您的示例。但我能够编写一些代码来创建盒子并将其保留在屏幕上。

import pygame, sys
from pygame.locals import * //Allows MOUSEMOTION in stead of pygame.MOUSEMOTION

window_size = (800, 600)
clock = pygame.time.Clock()
FPS = 60
mousepos = None
boxes = []

screen = pygame.display.set_mode(window_size)

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

while 1:

screen.fill(WHITE)

events = pygame.event.get()

for event in events:
if event.type == QUIT:
pygame.quit()
sys.exit()

if event.type == MOUSEBUTTONDOWN:
mousepos = [event.pos[0], event.pos[1], 0, 0]

if event.type == MOUSEBUTTONUP:
boxes.append(mousepos)
mousepos = None

if event.type == MOUSEMOTION and mousepos != None:
mousepos = [mousepos[0], mousepos[1], event.pos[0] - mousepos[0], event.pos[1] - mousepos[1]]

for box in boxes:
pygame.draw.rect(screen, BLACK, box, 1)

if mousepos != None:
pygame.draw.rect(screen, BLACK, mousepos, 1)

pygame.display.update()
clock.tick(FPS)

我希望这会有所帮助。

注意:小心事件队列,它很危险。切勿使用它来检查按键情况。使用“pygame.key.get_pressed()[K_(此处为按键)]”。如果您需要防止触发两次,请创建一个包含先前值的列表,如下所示:

prev = pygame.key.get_pressed()

if prev[K_(key here)] != pygame.key.get_pressed()[K_(Key here)]
do your stuff...

关于python - 如何在pygame中根据鼠标 Action 绘制矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23313975/

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