python - Pygame点击改变多个矩形的颜色
问题描述
当我单击一个矩形时,颜色会发生变化。但我不能同时改变它周围的矩形。如何访问我单击的矩形周围的 x 和 y?
import pygame
import sys
width = 600
height = 600
size = 120
white = (255,255,255)
pygame.init()
screen = pygame.display.set_mode((width, height))
# create list with all rects
all_rects = []
for y in range(0, width, height):
row = []
for x in range(0, width, height):
rect = pygame.Rect(x, y, size-1, size-1)
row.append([rect, (0, 255, 0)])
all_rects.append(row)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
# check which rect was clicked and change its color on list
for row in all_rects:
for item in row:
rect, color = item
if rect.collidepoint(event.pos):
if color == (0, 255, 0):
item[1] = (255, 0, 0)
else:
item[1] = (0, 255, 0)
# draw all in every loop
screen.fill(white)
for row in all_rects:
for item in row:
rect, color = item
pygame.draw.rect(screen, color, rect)
pygame.display.flip()
解决方案
您应该像这样修改第 15、17 行;
for y in range(0, width, size):
row = []
for x in range(0, width, size):
在您当前的代码中, all_rects 仅包含 1 个矩形。
完整代码:
import pygame
import sys
width = 600
height = 600
size = 120
white = (255,255,255)
pygame.init()
screen = pygame.display.set_mode((width, height))
# create list with all rects
all_rects = []
for y in range(0, width, size):
row = []
for x in range(0, width, size):
rect = pygame.Rect(x, y, size-1, size-1)
row.append([rect, (0, 255, 0)])
all_rects.append(row)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
# check which rect was clicked and change its color on list
for row in all_rects:
for item in row:
rect, color = item
if rect.collidepoint(event.pos):
if color == (0, 255, 0):
item[1] = (255, 0, 0)
else:
item[1] = (0, 255, 0)
# draw all in every loop
screen.fill(white)
for row in all_rects:
for item in row:
rect, color = item
pygame.draw.rect(screen, color, rect)
pygame.display.flip()
推荐阅读
- python - 将输入与答案进行比较,无论顺序如何
- haskell - Haskell - 如何对反斜杠字符进行模式匹配?
- html - 如果元素没有尾随兄弟,有没有办法只删除它?
- json - 我需要帮助来构建自己的 json 架构
- java - Android 6-7 中的内部阴影颜色不正确
- sass - TypeError:“原始”参数必须是函数类型 - SASS
- c++ - 正确使用 C++ STL set_symmetric_difference?
- r - 当函数依赖于继承的 datafame 的参数时,如何将一组函数叠加到 ggplot2 图形上?
- lua - 运行同时重复循环 Lua 脚本 Logitech GHUB
- windows - Groovy java.sql.SQLException:找不到适合 jdbc:sqlserver:// 的驱动程序