[英]Pygame not detecting mouse clicks
#The induvidual squares
class Square():
def __init__(self,x,y):
self.x = x
self.y = y
#The grid as a whole
class Grid():
def __init__(self,width,height):
self.squares = []
self.objects = []
self.width = width
self.height = height
def populate(self):
for i in range(1,self.height + 1):
for j in range(1,self.width + 1):
self.squares.append(Square(j,i))
grid = Grid(10,10)
grid.populate()
for i in grid.squares:
grid.objects.append(pygame.Rect((i.x -1) * 50,(i.y - 1) * 50,50,50))
While True:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN :
print("HELLO") #Testing to see if it worked
(x,y) = pygame.mouse.get_pos()
for i in grid.objects:
if i.x*50 <= (x) < (i.x+1)*50:
if i.y*50 <= (y) < (i.y+1)*50:
print("hi") #Testing to see if it worked
我一直在嘗試創建網格並使用它們來制作游戲。 我正在考慮能夠單擊網格的某個正方形,這會導致該正方形發生變化。
這是我試圖讓它注冊我是否點擊了任何方塊但它沒有注冊我是否點擊過的地方。 我查看了有關該主題的其他討論,但沒有一個有效。
pygame.Rect
object 的.x
和.y
組件包含矩形的實際左上角 position。 乘以 50 是錯誤的:
while True:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN :
print("HELLO") #Testing to see if it worked
x, y = pygame.mouse.get_pos()
for obj_rect in grid.objects:
if obj_rect.x <= x < obj_rect.x+50:
if obj_rect.y <= y < obj_rect.y+50:
print("hi") #Testing to see if it worked
無論如何,我建議簡化代碼並使用collidepoint
x, y = pygame.mouse.get_pos()
for obj_rect in grid.objects:
if obj_rect.collidepoint((x, y)):
print("hi") #Testing to see if it worked
我找到了一個與我有另一個相關的修復
對於pygame.event.get()
中的事件
在同一個while循環中。 此事件檢查用於檢測我是否嘗試退出 window。 似乎 pygame 在同一個循環中有兩個事件檢查存在問題,可能與它們使用相同的變量名有關,無論哪種方式,我將我的檢查移到同一個 for 循環中,它現在可以工作了
while True:
for event in pygame.event.get():
print(event)
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN :
print("HELLO")
x, y = pygame.mouse.get_pos()
for obj_rect in grid.objects:
if obj_rect.collidepoint((x, y)):
print("hi") #Testing to see if it worked
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.