我创建了这个窗口,允许用户在窗口中创建点并将它们链接起来,我现在要做的是允许他在完成绘制点之后移动想要的任何点
在我的示例中,我允许他画五个点,然后我希望他移动他选择的点,我真的不知道该怎么做
这是我的代码:
import pygame
#Initialise pygame
pygame.init()
#Create the screen
screen = pygame.display.set_mode((1200, 700))
#Change the title and the icon
pygame.display.set_caption('The Thoughtful Minds')
icon = pygame.image.load('IA.png')
pygame.display.set_icon(icon)
#Dots
dot = pygame.image.load('point.png')
class Dot:
def __init__(self, pos):
self.cx, self.cy = pos
def draw(self):
screen.blit(dot,(self.cx-8 , self.cy-8))
def text_objects(text,font):
textSurface = font.render(text, True, (100,100,100))
return textSurface, textSurface.get_rect()
dots = []
#Running the window
i = 0
running = True
while running:
mx, my = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
for oPosition in dots:
if ((oPosition.cx - 8) < mx < (oPosition.cx + 8)) and ((oPosition.cy - 8) < my < (oPosition.cy + 8)):
'''
What should I put her to allow him to move the dot he clicked on
'''
if i<3:
# append a new dot at the current mouse position
dots.append(Dot((mx,my)))
i += 1
# clear the display
screen.fill((30,30,30))
# draw all the dots
if len(dots)>1:
for i in range(len(dots)-1):
pygame.draw.line(screen, (50, 50, 50), [dots[i].cx,dots[i].cy],[dots[i+1].cx,dots[i+1].cy],2 )
for d in dots:
d.draw()
if mx < 50 and my < 50:
pygame.draw.rect(screen,(24,24,24),(0,0,50,50))
else:
pygame.draw.rect(screen,(20,20,20),(0,0,50,50))
text = pygame.font.Font("freesansbold.ttf",25)
textSurf, textRect = text_objects('–', text)
textRect.center = (25,25)
screen.blit( textSurf, textRect )
if 52 < mx < 102 and my < 50:
pygame.draw.rect(screen,(24,24,24),(52,0,50,50))
else:
pygame.draw.rect(screen,(20,20,20),(52,0,50,50))
textSurf, textRect = text_objects('+', text)
textRect.center = (76,25)
screen.blit( textSurf, textRect )
# update the dispalay
pygame.display.flip()
谢谢。
pygame是一个低端工具,它没有任何预先实现的拖放方法。您必须自己构建它。
您必须使用各种事件类型。这是想法:
首先,dragged_dot = None
在主循环外创建一个变量。并在事件循环中检查以下事件:
pygame.MOUSEBUTTONDOWN
事件告诉您何时按下按钮。当您检测到此事件时,请检查鼠标是否在现有的点上单击。这就是for
循环的作用。如果没有,请像您已经做的那样添加一个新的点。否则,将点设置为拖动:dragged_dot = oPosition
。pygame.MOUSEMOTION
事件告诉您鼠标何时移动。当您检测到此事件时,请检查是否存在拖动的点:if dragged_dot is not None
。如果是这样,请编辑它的坐标并添加鼠标动作,以便可以在新位置重画它(记住要删除上一个位置的点的图像)。使用event.rel
要知道以前的鼠标位置和当前鼠标位置之间的差异。pygame.MOUSEBUTTONUP
事件告诉您何时释放按钮。只需设置dragged_dot = None
,即可删除该点,并且不再跟随鼠标移动。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句