【发布时间】:2022-06-19 02:20:14
【问题描述】:
我正在尝试在 PYGAME 中对彩色单元格的动画进行编程,在每次迭代中,它们中的几个会交换各自的颜色。但是,我不太明白为什么,代码生成了单元格网格,但没有任何形式的移动。它只是保持静止。
import random
import pygame
import sys
colors = [(77,2,6),(180,5,180),(140,180,11)]
class CELL () :
def __init__ (self,x,y,ide):
self.color = random.choice(colors)
self.ide = ide
self.x = x
self.y = y
n, m = 10, 10
block_width, block_height = 50, 50
win_width, win_height = block_width*m, block_height*n
# Matrix : 10x10
# Cell size : 50x50
# Window size : 500x500
cells = {}
for i in range(n):
for j in range(m):
cells[i*n+j] = CELL(i,j,i*n+j)
# We create a cells dictionary in which keys are the
# ID attribute of each cell object stored.
class sprite_CELL (pygame.sprite.Sprite):
def __init__ (self,cell_obj):
pygame.sprite.Sprite.__init__(self)
self.cell = cell_obj
# Represents one of the cells.
self.image = pygame.Surface([block_width,block_height])
self.update_rect()
def update_rect (self):
self.image.fill(self.cell.color)
self.rect = self.image.get_rect()
# We update the rect according to the current color for the linked cell.
self.rect.topleft = [self.cell.x*block_width, self.cell.y*block_height]
sprites_group = pygame.sprite.Group()
for cell in cells.values():
sprites_group.add(sprite_CELL(cell))
# So far we have created a group of sprites containing sprites whose method
# "("update_rect" updates their graphical representation depending on the
# color of the cell to which the sprite is linked.
# API
pygame.init()
clock = pygame.time.Clock()
window = pygame.display.set_mode((win_width, win_height))
sprites_group.draw(window)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
rand_cell_a = random.choice(list(cells.values()))
rand_cell_b = random.choice(list(cells.values()))
# We randomly choose two cells.
color_a = cells[rand_cell_a.ide].color
color_b = cells[rand_cell_b.ide].color
# We extract the colors and...
cells[rand_cell_a.ide].color = color_b
cells[rand_cell_b.ide].color = color_a
# Swap the colors for the cells.
sprites_group.update()
# Updating the sprites should update their linked
# colors too.
pygame.display.flip()
clock.tick(60)
# And that's done iteratively.
如果有人能帮我解决这个问题,我将不胜感激。
【问题讨论】:
-
改变颜色属性是不够的。您还必须致电
update_rect。因为你必须用新颜色(self.image.fill(self.cell.color))填充图像。
标签: python pygame sprite pygame-surface