在Pygame中创建矩形网格

4

我需要在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个回答

4
虽然你的解决方案有点繁琐,但首先我要说
rectangles = (rect1, rect2, ...)

然后您可以按预期迭代它们。 尝试类似以下方式:
pos = pygame.mouse.get_pos()
for rect in rectangles:
    if rect.collidepoint(pos):
        changecolor(rect)

当然,你需要实现changecolor方法。

通常,我建议创建一个类来定义可点击字段,并且该类应该包含一个changecolor方法。


哈哈,现在你指出来了,这真是显而易见。非常感谢。 :) - user937839
不客气。顺便说一下,既然我看到你实际上正在绘制64个矩形,我强烈建议你使用循环绘制它们,并同时将它们添加到“rectangles”列表中。 - Johannes Charra
如果答案有帮助并且您不需要更多的帮助,您可以接受该答案。 ;) - Johannes Charra

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接