簡體   English   中英

在pygame中用鼠標畫一條直線?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM