1

使用 pygame 模块,我在屏幕上绘制了一个黑色矩形。当我将鼠标悬停在矩形上时,我编写了一个代码,通过在矩形周围绘制另一个(绿色)矩形(宽度 = 4)来“突出显示”矩形。它可以工作,但前提是鼠标在它上面移动。如果它静止在黑色矩形的表面上,则不会出现绿色矩形。这是我的代码:

import random, pygame, sys
from pygame.locals import *

pygame.init()
done = False
clock = pygame.time.Clock()
white = (255,255,255) # COLLORS
black = (0,0,0)
red = (255,0,0)
green = (0,100,0)
display_width = 800 # SCREEN DIMMENSION
display_height = 600
game_display = pygame.display.set_mode((display_width,display_height)) # SCREEN

def draw_rect(x,y):
    rect = pygame.Rect(x, y, 40, 40)
    pygame.draw.rect(game_display, black, rect)
    if rect.collidepoint(mousex,mousey):
           box_hightlight(x,y)
def box_hightlight(x,y):
    pygame.draw.rect(game_display,green,(x-5,y-5,50,50),4)

while done != True:

    x = (display_width - 40) / 2
    y = (display_height - 40) / 2

    mousex = 0  # used to store x coordinate of mouse event
    mousey = 0 # used to store y coordinate of mouse event

    for event in pygame.event.get():  # PRESSED KEYS EFFECTS
        if event.type == pygame.QUIT:
            done = True
        elif event.type == MOUSEMOTION :
            mousex, mousey = event.pos
        elif event.type == MOUSEBUTTONUP:
            mousex, mousey = event.pos
            mouseClicked = True

    game_display.fill(white)
    draw_rect(x,y)
    pygame.display.update()
    clock.tick(60)

我错过了什么?

4

1 回答 1

1

draw_rect中,您检查位置mousex, mousey是否在内部rect

但是在您的主循环中,您设置mousex, mousey为,并且仅在发生(或)事件时0, 0将其设置为鼠标位置。MOUSEMOTIONMOUSEBUTTONUP

这解释了你的它的工作原理,但前提是鼠标在它上面移动

不要使用事件,而只是使用pygame.mouse.get_pos来获取鼠标位置。

于 2016-12-12T10:02:11.407 回答