我正在做一个小的2D游戏,以学习python和pygame。我制作了一个菜单,上面有 2 个按钮(播放和退出(。播放按钮开始游戏 et 退出按钮离开游戏。
现在我想在鼠标经过按钮时显示一个红色圆圈。我正在使用MOUSEMOTION和collidepoint。
代码正在工作,当我将鼠标放在按钮上时会显示一个红色圆圈,但是当我将鼠标放在窗口的其他位置时,红色圆圈仍然存在。
def menu():
global Font, Xplay, Xquit, Yplay, Yquit, X_rect_play, Y_rect_play, X_rect_quit, Y_rect_quit, done, QUIT1, pos_quit, BLACK, WHITE, RECT_QUIT, RECT_PLAY, pos_play
pygame.font.init()
circle_play = False
circle_quit = False
while not done:
screen.fill(BLACK)
RECT_QUIT = pygame.draw.rect(screen, WHITE, (X_rect_quit,Y_rect_quit,250,50))
RECT_PLAY = pygame.draw.rect(screen, WHITE, (X_rect_play, Y_rect_play,250,50))
pos_play = (325,166)
PLAY1 = Font.render("PLAY", True, BLACK)
screen.blit(PLAY1,pos_play)
screen.blit(QUIT1, pos_quit)
if circle_play:
pygame.draw.circle(screen, RED, (310,174), 13)
if circle_quit:
pygame.draw.circle(screen, RED, (310,274), 13)
pygame.display.update()
for event in pygame.event.get():
if event.type == MOUSEMOTION:
circle_play = RECT_PLAY.collidepoint(pygame.mouse.get_pos())
circle_quit = RECT_QUIT.collidepoint(pygame.mouse.get_pos())
我希望在移动鼠标时删除红色圆圈。
我该如何解决这个问题?
感谢您的帮助。
只需在 while 循环中移动绘制按钮的代码,并确保每帧都清除屏幕。
要修复圆圈自动消失的问题,您需要创建一个变量来跟踪圆圈是否可见。
def menu():
global Font, Xplay, Xquit, Yplay, Yquit, X_rect_play, Y_rect_play, X_rect_quit, Y_rect_quit, done, QUIT1, pos_quit
circle_play = False # will be true when circle on the play button will be visible
circle_quit = False
while not done:
screen.fill(BLACK)
RECT_PLAY = pygame.draw.rect(screen, WHITE, (X_rect_play, Y_rect_play,250,50))
pos_play = (325,166)
PLAY1 = Font.render("PLAY", True, BLACK)
screen.blit(PLAY1,pos_play)
screen.blit(QUIT1, pos_quit)
if circle_play:
pygame.draw.circle(screen, RED, (310,174), 13)
if circle_quit:
pygame.draw.circle(screen, RED, (310,274), 13)
pygame.display.update()
for event in pygame.event.get():
if event.type == MOUSEMOTION:
circle_play = RECT_PLAY.collidepoint(pygame.mouse.get_pos())
circle_quit = RECT_QUIT.collidepoint(pygame.mouse.get_pos())
...