在Pygame中创建一个rect网格

时间:2011-09-14 10:49:43

标签: python pygame

我需要在pygame中创建一个可点击的8 x 8网格。 现在我有这样的事情:

#!/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 :(得分:4)

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

rectangles = (rect1, rect2, ...)

然后你可以按照预期迭代它们。

试试......

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

当然,您必须实施changecolor方法。

通常,我建议为您定义方法changecolor的可点击字段创建一个类。

答案 1 :(得分: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)