gpt4 book ai didi

python - 在 Pygame 中创建一个矩形网格

转载 作者:太空狗 更新时间:2023-10-30 03:06:42 25 4
gpt4 key购买 nike

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

显然,我的解决方案过于静态。那么,我怎样才能做到这一点?

最佳答案

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

rectangles = (rect1, rect2, ...)

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

试一试

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

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

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

关于python - 在 Pygame 中创建一个矩形网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7415109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com