python - 为什么当对象在矩阵中时python处理方法不起作用?
问题描述
我正在尝试制作一个由单击时应与玩家交互的块组成的小游戏。为了尝试完成这项工作,我制作了一个存储块的矩阵,以便可以轻松访问它们。我知道它适用于所有类型的对象的普通 python,如在 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)
解决方案
blockgrid=[[0]*3]*3
是一个众所周知的错误。您尚未创建 3x3 矩阵。相反,您创建了一个长度为 3 的列表,其中包含对完全相同的长度为 3 列表的 3 个引用。无论您做什么,blockgrid[0][i] = blockgrid[1][i] = blockgrid[2][i]
(for i = 0,1,2
) 所以您不断地覆盖您的一些块。
相反,使用类似blockgrid=[[0]*3 for _ in range(3)]
.
出于测试目的,我建议使用例如size(300,300)
in setup()
,使块更大,以便您可以确定您单击的是哪个块。您当前的块不比鼠标光标的尖端大多少。更一般地说 - 不是在块的大小上硬连线,为什么不根据草图来计算width
它们height
?
推荐阅读
- node.js - Electron 和 React 应用程序:从计算机或网络中查找和使用本地文件
- flutter - Flutter Toggle Button ListView,默认未选择任何内容
- javascript - 我收到无限制的资源分配或限制错误
- json - 使用 JSONB 列 postgresql 中的值连接表
- google-cloud-platform - Vertex AI Managed Notebook,获取子网/IP
- java - Java ArrayList removeAll
- simulink - 如何使用模拟连接动态负载(直流电机)与光伏系统?
- python - 在 django 中连接到 scss 文件时出错
- html - 对齐不同列中的元素
- reactjs - 构建脚本返回非零退出代码:1,我该怎么办