Вы не можете использовать is_hover()
для назначения изображения в __init__
и ожидать, что оно изменит изображение при наведении курсора мыши.
Вы должны загрузить оба изображения в __init__
и использовать self.hoverd
в draw()
для отображения другого изображения.
И вы должны использовать draw()
в while True
, чтобы нарисовать все поля после всех тестов.
class Box:
def __init__(self, height, width, x, y):
self.height = height
self.width = width
self.x = x
self.y = y
self.hoverd = False
self.img = pygame.image.load(os.path.join(resource_dir, "box.png"))
self.img_hovered = pygame.image.load(os.path.join(resource_dir, "box_hover.png"))
def draw(self, window):
if self.hoverd:
window.blit(self.img_hovered, (self.x, self.y))
else
window.blit(self.img, (self.x, self.y))
# create object without drawing
board_boxes = []
for y in (0, 100, 200):
for x in (0, 100, 200):
box = Box(100, 100, x, y)
board_boxes.append(box)
# mainloop
run = True
while run:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# --- changes/moves ---
pos = pygame.mouse.get_pos()
for box in board_boxes:
if pos[0] > box.x and pos[0] < box.x + box.width:
if pos[1] > box.y and pos[1] < box.y + box.height:
box.hoverd = True
else:
box.hoverd = False
# --- draws ---
# pygame.screen.fill( (0,0,0) ) # clear screen with black color
for box in board_boxes:
box.draw(window)
pygame.display.update()
# end
pygame.quit()
Используя pygame.Rect()
, вы можете написать его короче ...
class Box:
def __init__(self, height, width, x, y):
self.rect = pygame.Rect(x, y, width, height)
self.hoverd = False
self.img = pygame.image.load(os.path.join(resource_dir, "box.png"))
self.img_hovered = pygame.image.load(os.path.join(resource_dir, "box_hover.png"))
def draw(self, window):
if self.hoverd:
window.blit(self.img_hovered, self.rect)
else
window.blit(self.img, self.rect)
# create object without drawing
board_boxes = []
for y in (0, 100, 200):
for x in (0, 100, 200):
box = Box(100, 100, x, y)
board_boxes.append(box)
# mainloop
run = True
while run:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# --- changes/moves ---
pos = pygame.mouse.get_pos()
for box in board_boxes:
box.hoverd = box.rect.collidepoint(pos)
# --- draws ---
# pygame.screen.fill( (0,0,0) ) # clear screen with black color
for box in board_boxes:
box.draw(window)
pygame.display.update()
# end
pygame.quit()