pygame显示屏上的发光面取决于鼠标位置

时间:2019-08-26 08:57:47

标签: python-3.x pygame

在此程序中,我的表面上有网格。我正在尝试编写一个程序来检测鼠标在表面上的位置,并且如果我的鼠标在正方形之一中,则正方形变为绿色。问题是我设法只工作了1个正方形。我希望所有正方形都像左上角的正方形一样工作。有人可以帮忙吗?

import pygame
pygame.init()

WIDTH = 540
TILESIZE = 60
RED = (255, 0, 0)
BLACK = (0, 0, 0)
GREY = (211, 211, 211)
GREEN = (0, 255, 0)


win = pygame.display.set_mode((WIDTH+1, WIDTH+1))
win.fill(GREY)
surface = pygame.Surface((TILESIZE-1, TILESIZE-1))
surface.fill(RED)

def mouse_pos():
    surface_place = (1, 1)
    for x in range(0, 9, TILESIZE):
        for y in range(x):
            surface_place = list(surface_place)
            surface_place[0] += TILESIZE
            surface_place[1] += TILESIZE
            surface_place = tuple(surface_place)
            win.blit(surface, surface_place)

    if surface.get_rect().collidepoint(pygame.mouse.get_pos()):
        win.blit(surface, surface_place)
        surface.fill(GREEN)
    else:
        win.blit(surface, surface_place)
        surface.fill(RED)

def draw_grid():
    for x in range(0, WIDTH+1, TILESIZE):
        pygame.draw.line(win, BLACK, (x, 0), (x, WIDTH))
    for y in range(0, WIDTH+1, TILESIZE):
        pygame.draw.line(win, BLACK, (0, y), (WIDTH, y))

clicked = False
while not clicked:
    draw_grid()
    mouse_pos()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            clicked = True

    pygame.display.update()

1 个答案:

答案 0 :(得分:3)

当然有多种解决方案。

一种方法是在WIDTH上进行范围/循环,就像绘制网格一样,并使用一些Rect魔术师将瓷砖绘制为绿色或红色,如下所示:

def mouse_pos():
    for x in range(1, WIDTH+1, TILESIZE):
        for y in range(1, WIDTH+1, TILESIZE):
            rect = pygame.Rect(x, y, TILESIZE, TILESIZE).inflate(-1, -1)
            win.fill(GREEN if rect.collidepoint(pygame.mouse.get_pos()) else RED, rect)

在这里,我们从1而不是0开始循环,并使用1将矩形缩小inflate像素,因此我们不会在网格线上绘制

但是哪种解决方案适合您,最终取决于您要实现的目标。就像,您是否需要在代码中逻辑表示网格?您需要使用Surfaces而不只是填充纯色吗?