[英]python pygame mouse events not working and not raising errors
我是 python 的新手,我正在嘗試用 pygame 制作國際象棋游戲,我將棋盤和各種棋子作為對象放置在上面。 這是 class 的零件:
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新手)
所以,問題是 click 事件有效並且它修改了dragging
,但是當涉及到 drag 事件時 object 不再有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]
編輯:
用於測試和調試的完整程序
拖動算法確實有效。 但是,在每一幀中都會調用defBoardPieces()
。 因此,游戲每幀都會重置。 並且拖動沒有效果。
從drawBoardPieces
function 中刪除defBoardPieces()
調用,但在應用程序循環之前調用一次:
#renders board pieces
def drawBoardPieces(win):
# defBoardPieces() <--- DELETE
for i in pieceslist:
if not i == "none":
i.draw(win)
pieceslist = []
startsquare = []
defBoardPieces() # <--- INSERT
run = True
while run:
# [...]
在reset
中也調用defBoardPieces()
:
def reset():
global position
position = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR"
defBoardPieces()
使用 mouse.get_pressed()[0] 拖動。 0 是左鍵。
if event.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pressed()[0]:
... drag code here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.