2016-06-13 40 views
0

我一直在嘗試使用鼠標位置將圖像blit到我的屏幕。這是我的代碼。如何在屏幕上只在鼠標位置blit

#Placing the farm 
if farm: 


    if pygame.mouse.get_pressed()[0]: 
     hi = True 
    if hi: 
     screen.blit(farm_image,mouse_pos) 

所以基本上我希望它做塊的圖像在mouse_position只有一次屏幕點擊鼠標時,但它顯示的圖像不是一次,而是與mouse_pos移動。我該怎麼做才能讓圖像只在mouse_position上顯示一次。在這之前我有一個主循環。 我試過的是在圖像是blit後將hi設置爲False,但是後者會擦除圖像。謝謝你提供的任何答案!

+0

您可以在按下按鈕時將農場的位置定義爲(x,y)tulpe。然後使用True/False語句確保它是第一個clic,您只需設置一次農場位置。這將確保農場在每一幀都保持blitting。 – Sorade

回答

1

大廈PythonMaster的回答類似的東西可能工作,確保農場保持的情況下,在每一幀圖混合您每次刷新所有屏幕與背景:

#Placing the farm 
if farm: 

    if pygame.mouse.get_pressed()[0] == False: #resets the first_click to False everytime the button is released 
     first_click = False 

    if pygame.mouse.get_pressed()[0]: 
     if first_click == False: 
      first_click = True 
     else: 
      pass 
     if first_click == True: #set's the farm position it will keep updating the position of the farm as you drag the mouse, if you do not want that set first_click to False here. 
      farm_pos = mouse_pos 
    try: #using try here, prevents errors when farm_pos is not yet defined 
     screen.blit(farm_image,farm_pos) 
    except: 
     print 'farm position not defined yet, click to place' 
+0

它整理工作。謝謝 – abc1234

+0

有很好的答案 –

1

你可以嘗試使用另一個變量來檢查,看它是否是你的第一個點擊與否:

if pygame.mouse.get_pressed()[0]: 
    if first_click == False: 
     hi = true 
     first_click = True 
    else: 
     pass 

請確保您使用它之前定義first_click。此代碼使用first_click來查看您是否點擊過一次。它的起始值是False,並且一旦鼠標點擊,則更改爲True。這也將hi更改爲True,同時禁止再次點擊,因爲first_click不再是False。這導致elsepass聲明,幾乎沒有做任何事情。

+0

它沒有工作,圖像仍然只是休耕鼠標的位置,當你點擊沒有發生。 – abc1234

1

您還可以使用事件檢查,而不是狀態檢查,當你只需要一次點擊。這非常有用,因爲這意味着您不會錯過點擊(如果用戶在您的代碼未檢查用戶輸入時點擊並釋放鼠標,可能會發生這種情況)。 Pygame有事件MOUSEBUTTONDOWNMOUSEBUTTONUP,它們都給你鼠標的位置和被點擊的按鈕。

如何將其合併到您的代碼中取決於您的其他代碼,例如,如果你已經在其他地方使用了pygame事件隊列。小例子:

for event in pygame.event.get(): 
    if event.type == pygame.QUIT: 
     pygame.quit() 
     sys.exit() 
    if event.type == pygame.MOUSEBUTTONDOWN: 
     if farm: 
      screen.blit(farm_image,(event.pos[0], event.pos[1])) 

你可以使用一個變量來跟蹤狀態的一次通過PythonMaster和Sorade,或者更好的建議尚未農場已被放置,存放在一個農場農場的位置和可見狀態對象(Sprite),只要將其狀態設置爲可見,只需將其閃爍到其位置即可。

相關問題