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