python - 在 Pygame 中的点击条件下显示一个矩形
问题描述
嗨,我正在用 pygame 写一个国际象棋游戏。我遇到的问题是,当我想在单击时突出显示(用红色矩形)一个图形时,它只会发生一小会儿,即单击鼠标时。然后刷新发生,红色矩形消失。负责的代码是:
def window_redrawing():
# Drawing the background and chess board
win.fill(bg_col)
win.blit(chess_board, (53, 50))
initial_positions()
mouse_x, mouse_y = pygame.mouse.get_pos()
for objPawn in pawn_list:
if objPawn.start_x <= mouse_x <= objPawn.start_x + 86 and objPawn.start_y + 84 >= mouse_y >= objPawn.start_y:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
b = pygame.draw.rect(win, (255, 0, 0), objPawn.clickbox, 2)
pygame.display.update(b)
pygame.display.update()
我的问题:单击鼠标时如何绘制矩形以使其停留更长时间?(假设再次单击鼠标)
我还尝试了其他一些方法,例如win.blit()
,如下:
def window_redrawing():
# Drawing the background and chess board
win.fill(bg_col)
win.blit(chess_board, (53, 50))
initial_positions()
mouse_x, mouse_y = pygame.mouse.get_pos()
for objPawn in pawn_list:
if objPawn.start_x <= mouse_x <= objPawn.start_x + 86 and objPawn.start_y + 84 >= mouse_y >= objPawn.start_y:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
win.blit(objPawn.clickbox, (objPawn.start_x, objPawn.start_y))
但后来我收到以下错误:TypeError: argument 1 must be pygame.Surface, not tuple
感谢所有帮助,谢谢!!!
解决方案
clicked
在实例的类中添加一个属性pawn_list
(我不知道该类的实际名称)
class Pawn: # I don't kow the actual name
def __init__(self)_
# [...]
self.clicked = False
设置单击对象时的状态 ( objPawn.clicked = True
)。如果设置了状态,则遍历列表中的对象并绘制矩形clicked
:
def window_redrawing():
mouse_x, mouse_y = pygame.mouse.get_pos()
for objPawn in pawn_list:
if objPawn.start_x <= mouse_x <= objPawn.start_x + 86 and objPawn.start_y + 84 >= mouse_y >= objPawn.start_y:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
objPawn.clicked = True
# Drawing the background and chess board
win.fill(bg_col)
win.blit(chess_board, (53, 50))
for objPawn in pawn_list:
if objPawn.clicked:
pygame.draw.rect(win, (255, 0, 0), objPawn.clickbox, 2)
pygame.display.update()
推荐阅读
- c# - BlogEngine.NET - 在应用程序级别之外使用注册为 allowDefinition='MachineToApplication' 的部分是错误的
- java - AEM-6.3 构建失败,Java-1.8.0_211 和 Maven-3.3.9
- r - 如果列存在或不存在于R中,如何进行计算?
- c# - 如何在 C# 中验证图片子句?
- python - 错误:TypeError:参数 1 必须是字符串或 unicode 对象
- durandal - Durandal.js 的所有版本是否都支持响应式网站开发
- html - Strange whitespace appears on specific resolutions
- c++ - 多变量初始化编译器支持
- angular - Angular Twilio 视频通话仅适用于野生动物园
- javascript - 由于路由器,我有两个不同的标题