在Pygame中创建矩形网格

4 投票
2 回答
10415 浏览
提问于 2025-04-17 02:16

我需要在pygame中创建一个可以点击的8x8网格。
现在,我的代码大概是这样的:

#!/usr/bin/python2
#-------------------------------------------------------------------------------
# Imports & Inits
import pygame, sys
from pygame.locals import *
pygame.init()
#-------------------------------------------------------------------------------
# Settings
WIDTH = 105
HEIGHT = 105
FPS = 60
#-------------------------------------------------------------------------------
# Screen Setup
WINDOW = pygame.display.set_mode([WIDTH,HEIGHT])
CAPTION = pygame.display.set_caption('Test')
SCREEN = pygame.display.get_surface()
TRANSPARENT = pygame.Surface([WIDTH,HEIGHT])
TRANSPARENT.set_alpha(255)
TRANSPARENT.fill((255,255,255))
#-------------------------------------------------------------------------------
# Misc stuff
rect1 = pygame.draw.rect(SCREEN, (255, 255, 255), (0,0, 50, 50))
rect2 = pygame.draw.rect(SCREEN, (255, 255, 255), (0,55, 50, 50))
rect3 = pygame.draw.rect(SCREEN, (255, 255, 255), (55,0, 50, 50))
rect4 = pygame.draw.rect(SCREEN, (255, 255, 255), (55,55, 50, 50))

...

#-------------------------------------------------------------------------------
# Refresh Display
pygame.display.flip()
#-------------------------------------------------------------------------------
# Main Loop
while True: 
    pos = pygame.mouse.get_pos()
    mouse = pygame.draw.circle(TRANSPARENT, (0, 0, 0), pos , 0)
    # Event Detection---------------
    for event in pygame.event.get(): 
        if event.type == QUIT: 
            sys.exit() 
        elif event.type == MOUSEBUTTONDOWN:
            if rect1.contains(mouse):
                rect1 = pygame.draw.rect(SCREEN, (155, 155, 155), (0,0, 50, 50))
                pygame.display.flip()

现在,在我原来的代码中,我有很多矩形,我需要一种方法来做到像这样:

for i in rectangles:
    if i hasbeenclickedon:
          change color

显然,我的解决方案太死板了。
那么,我该怎么做才能实现这个呢?

2 个回答

0

简单的“人性化”颜色:

Color("red")
Color(255,255,255)
Color("#fefefe")

使用方法:

import pygame
# This makes event handling, rect, and colors simpler.
# Now you can refer to `Sprite` or `Rect()` vs `pygame.sprite.Sprite` or `pygame.Rect()`
from pygame.locals import *
from pygame import Color, Rect, Surface

pygame.draw.rect(screen, Color("blue"), Rect(10,10,200,200), width=0)
pygame.draw.rect(screen, Color("darkred"), Rect(210,210,400,400), width=0)
4

虽然你的解决方案确实有点麻烦,但我首先想说

rectangles = (rect1, rect2, ...)

然后你就可以像预期那样遍历它们。

试试这样的代码

pos = pygame.mouse.get_pos()
for rect in rectangles:
    if rect.collidepoint(pos):
        changecolor(rect)

当然,你需要实现一个叫做 changecolor 的方法。

一般来说,我建议你为可点击的字段创建一个类,并在里面定义一个 changecolor 方法。

撰写回答