在Pygam中创建矩形网格

2024-06-28 19:46:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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

显然,我的解决方案太静态了。 那么,我怎么能做到这一点呢?


Tags: posrecteventgetifdisplaywidthscreen
2条回答

简单的“人类”颜色:

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)

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

rectangles = (rect1, rect2, ...)

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

尝试某事

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

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

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

相关问题 更多 >