我在pygame上制作了一个网格,我想知道如何才能做到这一点,以便从网格上的某个点开始,颜色随着您离该点的增加而改变,例如,当一个正方形时,颜色从深蓝色变为离开十个正方形时变成浅蓝色。我真的不确定如何执行此操作,任何帮助都会很棒。
使用以下方法创建网格:
grid = []
for y in range(grid_size):
row = []
for x in range(grid_size):
row.append([x * (grid_width + grid_margin) + distance_from_left, y * (grid_height + grid_margin) + distance_from_top, white])
grid.append(row)
使用以下方法绘制网格:
for row in grid:
for x, y, colour in row:
pygame.draw.rect(screen, colour, (x, y, grid_width, grid_height))
我还有一个函数可以计算出网格上每个节点的所有子节点(围绕它的所有节点(上,下,侧面和对角线),我觉得这可能对确定与选定对象的距离很有用节点。
答案 0 :(得分:2)
一种颜色由3个颜色通道(reg,绿色,蓝色)组成。参见RGB color model。在这种情况下,颜色不过是[0,255]范围内的3个值的元组。
深蓝色例如(0,0,63),浅蓝色是(127,191,255)。
您必须在这两个值之间进行插值。计算范围为[0.0,1.0]的因子,该因子表示颜色的色调。使用该因子对颜色通道进行插值:
例如f
是[0.0,1.0]的一个因素
blue = 63 + 192 * f # interpolate between 63 and 255 dependent of f
到两点之间的距离可以通过pygame.math.Vector2.
distance_to()
计算:
例如
pos = (x, y)
gx = (x + 0.5) * grid_size
gy = (y + 0.5) * grid_size
distance = pygame.math.Vector2(pos).distance_to((gx, gy))
例如在位置pos
附近设置浅蓝色,在远离位置的位置设置深蓝色:
pos = # (x, y) position
grid = []
for y in range(grid_size):
row = []
for x in range(grid_size):
gx = x * (grid_width + grid_margin) + distance_from_left
gy = y * (grid_height + grid_margin) + distance_from_top
distance = pygame.math.Vector2(pos).distance_to((gx + grid_width/2, gy + grid_height/2))
maxLen = grid_size * (grid_height + grid_margin)
f = max(0, 1 - distance / maxLen)
color = (127 * f, 191 * f, 63 + 192 * f)
row.append([gx, gy, color])
grid.append(row)
以上解决方案假定pos
是像素单位的窗口坐标。
如果pos
是“网格”坐标,则意味着pos
标识网格中的位置,则解决方案更加简单:
pos = # (x, y) position
grid = []
for y in range(grid_size):
row = []
for x in range(grid_size):
distance = pygame.math.Vector2(pos).distance_to((x, y))
f = max(0, 1 - distance / grid_size)
color = (127 * f, 191 * f, 63 + 192 * f)
gx = x * (grid_width + grid_margin) + distance_from_left
gy = y * (grid_height + grid_margin) + distance_from_top
row.append([gx, gy, color])
grid.append(row)