[英]Drawing a straight line with the mouse in pygame?
我正在创建与Flow类似的游戏。 如果您熟悉它,则要求用户通过网格上相同颜色的线将相同的圆圈匹配在一起。 我遇到一个问题,无论哪里发生鼠标移动事件,我都希望用户只能画直线(左,右,上,下)。 当前用户可以在任何地方绘制图形,我有一个函数可以在发生鼠标移动事件时绘制圆形图形,尽管我使用了一些if语句来尝试限制用户可以绘制图形的位置,但仍然无法正常工作。 也许有比使用鼠标移动事件更好的方法了? 不确定,但是任何帮助将不胜感激!
这是一些代码:
''' *** IN PROGRESS *** '''
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True # Closes the game and exits the loop
elif event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
pygame.mouse.set_visible(True)
''' If the user clicks down on the left button the mouse coordinates at that point are assigned to variables
x and y which are used to check the condition of the click_detection function'''
elif event.type == pygame.MOUSEBUTTONUP:
pygame.mouse.set_visible(True)
# Makes the cursor visible to choose a new circle easily
elif event.type == pygame.MOUSEMOTION:
''' State is assigned to an array for each of three mouse buttons
at state[0] it checks the left mouse button'''
state = pygame.mouse.get_pressed()
for circle in circle_grid_list:
# Checks following conditions for every circle in that Sprite group
if ClickDetection.click_detection(circle) == True:
''' Checks whether a circle is being clicked
- If so then variable colour is assigned to the colour of the clicked circle
- This is used so that the move method from circle_line class can be called using the colour of the clicked circle'''
colour = circle.colour
# *** WORK IN PROGRESS ***
if MovementChecker.check() != False:
print("can draw")
if state[0] == 1:
# Checking the left mouse button state, if 1 then button is being clicked or held down
moving_line_mouse.Move()
elif MovementChecker.check() == False:
# Used to stop the move method for the moving_line object from being called if movement checker is false
print("Can't draw")
因此,与其以“这是我的鼠标所在的位置”来思考,不如以“我的鼠标位于哪个盒子中?”来思考。 如果是,则为该框上色。 这可能有助于
例如,如果每个正方形均为100x100像素,并且鼠标位于坐标424和651,则可以通过执行int(424 / 100)
和int(651 / 100)
int(424 / 100)
来计算网格位置-鼠标为位于网格上4x6的位置(请注意,我们从零开始计数,因此左上角的正方形位于位置0x0)。
然后,您可以检查网格4x6是否已填充,检查网格4x6是否已填充不同的颜色,并根据此处理所有逻辑。
Flow还具有一项功能,可以绘制一条线连接您输入的位置和离开的位置。 如果您用另一种颜色“切穿”它,它还将删除现有行的一半。
一种实现方法是创建一个“正方形”对象,该对象跟踪其当前颜色,对您所来自的正方形的引用以及对您最终选择的正方形的引用。
这样,您可以在网格内部创建一种“链接列表”-每个正方形都指向它所连接的下一个正方形,因此您知道是需要绘制垂直条,水平条还是拐角。 如果您切过已经设置颜色的正方形,则可以继续遵循参考链,以查找先前颜色流过的下一个正方形,然后将其设置为空,然后继续。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.