我正在尝试制作一个由块组成的小游戏,该块在单击时应与玩家互动。为了进行这项工作,我制作了一个矩阵来存储块,以便可以轻松访问它们。我知道它可以在所有类型的对象的普通python中工作,如本Creating a list of objects in Python中所述 问题(python矩阵是列表的列表)。
问题在于该对象的方法未正确检测到单击。有谁知道这是为什么?这是处理上的错误吗?
以下是您需要的代码:
class Block():#creates an object that senses clicking input by the user
def __init__(self,position=(),dimentions=(),rgb=(0,0,0)):
#set variables
self.x=position[0]
self.y=position[1]
self.w=dimentions[0]
self.h=dimentions[1]
#draw on screen:
fill(rgb[0],rgb[1],rgb[2])
rect(position[0],position[1],dimentions[0],dimentions[1])
def IsPressed(self):# senses if mouse is within the block and if it is pressed, if both are true output is true, else it´s false
if mouseX in range(self.x,self.x+self.w) and mouseY in range(self.y, self.y+self.h) and mousePressed==True:
return True
else:
return False
def createMatrix(matrix):#for loop function to create the matrix and give all blocks a location
r=-1#int for rows, required for the location assignment to work properly
c=-1#int for columns (items in row)rows, required for the location assignment to work properly
#nested loop:
for row in matrix:
r=r+1
c=-1
for item in row:
c=c+1
matrix[r][c]=Block((r*10,c*10),(10,10),(255,30,200))
def setup():
global blockgrid #allows usage of the blockgrid in the draw function
blockgrid=[[0]*3]*3 #creates the matrix in which blocks are stored
createMatrix(blockgrid)
print(blockgrid)
def draw():
#test to see if sensing works:
if blockgrid[1][1].IsPressed():
#blockgrid[1] [1] is the center one!!
print(True)
else:
print(False)
答案 0 :(得分:2)
blockgrid=[[0]*3]*3
是well-known bug。您尚未创建3x3矩阵。相反,您创建了一个长度为3的列表,其中包含3个对长度相同的相同列表的3个引用。无论您做什么,blockgrid[0][i] = blockgrid[1][i] = blockgrid[2][i]
(对于i = 0,1,2
),因此您会不断覆盖一些块。
使用blockgrid=[[0]*3 for _ in range(3)]
之类的东西。
出于测试目的,我建议使用例如size(300,300)
中的setup()
,使块变大,这样您就可以确定要单击的块。您当前的块不超过鼠标光标的尖端。更笼统地说,为什么不按照草图width
和height
来计算它们呢?