我是pygame的新手,我正在编写一个程序,允许用户在pygame窗口周围单击并拖动一个矩形,然后通过一个套接字发送坐标。我可以通过鼠标点击来移动矩形,但我已经在它周围乱搞了一段时间,仍然不知道如何实现点击和拖动。任何帮助都将不胜感激。以下是相关代码:
from pygame.locals import *
import socket, pygame, time
#define variables
x = y = 0
screen = pygame.display.set_mode((430, 410))
targetRectangle = pygame.draw.rect(screen, (255, 0, 0), (176, 134, 7, 7))
pygame.display.flip()
#define smaller functions
#define function to start pygame window
def startPygame():
pygame.display.set_caption(option + " Tracking System")
pygame.mouse.set_visible(True)
screen.fill((255, 255, 255))
targetRectangle = pygame.draw.rect(screen, (255, 0, 0), (176, 134, 7, 7))
pygame.display.flip()
#define function to update pygame window
def updateWindow():
screen.fill((255, 255, 255))
global targetRectangle
global xPosition
global yPosition
targetRectangle = pygame.draw.rect(screen, (255, 0, 0), (xPosition, yPosition, 7, 7))
pygame.display.flip()
#define main functions
def collectMouseData():
startPygame()
print "\n"
print "mouse tracking system"
#wait until a mouse button is clicked
running = 1
while running == 1:
event = pygame.event.poll()
if event.type == pygame.QUIT:
c.send("quit")
pygame.quit()
running = 0
#see if a mousebutton is down
elif event.type == pygame.MOUSEBUTTONDOWN:
xMouse = event.pos[0]
yMouse = event.pos[1]
#see if mouse click collides with targetRectangle
if targetRectangle.collidepoint(xMouse, yMouse):
global xPosition
xPosition = event.pos[0]
global yPosition
yPosition = event.pos[1]
updateWindow()
global targetRectangle
sendData(targetRectangle)
你必须使用
MOUSEBUTTONDOWN
检查是否单击了对象并设置drag = True
(并记住鼠标位置与左上角矩形之间的偏移)MOUSEBUTTONUP
设置drag = False
MOUSEMOTION
在使用鼠标位置和偏移量drag == True
时移动对象。工作实例
编辑:GitHub上有许多矩形或圆和按钮的其他示例:
furas/python-examples/pygame/drag-rectangles-circles
相关问题 更多 >
编程相关推荐