【发布时间】:2021-05-07 15:25:54
【问题描述】:
我是 python 新手,我正在尝试用 pygame 制作国际象棋游戏,我有棋盘和各种棋子作为对象放置在上面。这是碎片类:
class piece(object):
def __init__(self, x, y, which):
self.x = x
self.y = y
self.which = which
self.square = getsquare(x + PIECE/2, y + PIECE/2)
self.dragging = False
def drag(self, x, y):
limit = 720
if x >= limit:
x = limit
self.x = x - PIECE/2
self.y = y - PIECE/2
def draw(self, win):
win.blit(self.which, (self.x, self.y))
self.square = getsquare(self.x + PIECE/2, self.y + PIECE/2)
其中 PIECE 是带有碎片图像的精灵表的尺寸。我试图为碎片制作一个拖动系统(存储在一个 64 个元素的长列表中)并且只使用 1 件它可以工作,但是当我使用完整列表时它停止工作而没有任何错误。这是拖动系统:
"""event listeners"""
for event in pygame.event.get():
if event.type == pygame.QUIT: #quit event
run = False
"""mouse release"""
if event.type == pygame.MOUSEBUTTONUP:
clickpos = pygame.mouse.get_pos()
x = clickpos[0]
y = clickpos[1]
sqr = getsquare(x, y)
for i in pieceslist:
if not i == "none":
if i.dragging:
i.dragging = False
try:
i.x = squarepos(i.square[0], i.square[1])[1]
i.y = squarepos(i.square[0], i.square[1])[0]
except:
i.x = squarepos(originalsquare[0], originalsquare[1])[1]
i.y = squarepos(originalsquare[0], originalsquare[1])[0]
"""mouse click"""
if event.type == pygame.MOUSEBUTTONDOWN:
clickpos = pygame.mouse.get_pos()
x = clickpos[0]
y = clickpos[1]
#print("X: " + str(x) + ", Y: " + str(y))
sqr = getsquare(x, y)
for i in pieceslist:
if not i == "none":
if sqr == i.square:
originalsquare = sqr
i.dragging = True
"""mouse drag"""
if event.type == pygame.MOUSEMOTION:
clickpos = pygame.mouse.get_pos()
x = clickpos[0]
y = clickpos[1]
#print("X: " + str(x) + ", Y: " + str(y))
sqr = getsquare(x, y)
for i in pieceslist:
if not i == "none":
if i.dragging:
i.drag(x, y)
因为pieceslist 充满了piece 对象和"none" 字符串,所以我进行了if 检查(我知道肯定有更好的方法来做到这一点,但我是python 新手)
所以,问题在于点击事件有效并且它修改了dragging,但是当涉及到拖动事件时,对象不再具有dragging == True
编辑:
squarepos()返回放置spritesheet的坐标,getsquare()按行列返回坐标:
def getsquare(x, y):
if x <= BORDER or y <= BORDER or x >= squarepos(1, 9)[0] or y >= squarepos(9, 1)[1]:
pass #not on the board
else:
x -= BORDER
y -= BORDER
x /= SQUARE
y /= SQUARE
return [int(x) + 1, int(y) + 1]
编辑:
完整程序here用于测试和调试
【问题讨论】: