python - Pygame没有检测到鼠标点击
问题描述
#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
我一直在尝试创建网格并使用它们来制作游戏。我正在考虑能够单击网格的某个正方形,这会导致该正方形发生变化。
这是我试图让它注册我是否点击了任何方块但它没有注册我是否点击过的地方。我查看了有关该主题的其他讨论,但没有一个有效。
解决方案
对象的.x
and.y
组件pygame.Rect
包含矩形的实际左上角位置。乘以 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
推荐阅读
- ios - 以下swift代码是什么意思?
- awk - 在 csv 文件的第二行中插入值,与 ksh 脚本中的第一行有关
- sql - 比较 Table_1 和 Table_2 并根据 Table_1 中更改的数据更新 Table_2 的存储过程
- java - SUN 次要代码 309 含义
- android - Android FCM - 如何为带有通知和数据有效负载的推送构建默认通知
- c# - UWP 动画列表项移动
- javascript - 如何在地图顶部浮动框
- c# - TPL Dataflow 从所有传入节点(多个生产者,1 个消费者)创建聚合结果数组
- javascript - 当我同时使用标头元素和 aurelia 路由器视图时,标头的渲染会延迟
- ionic-framework - 如何更新我的页面内容?