水波纹算法没有产生准确的结果

Water ripple algorithm not producing accurate results

我用来编写这段代码的来源是https://web.archive.org/web/20160418004149/http://freespace.virgin.net/hugo.elias/graphics/x_water.htm and https://www.youtube.com/watch?v=BZUdGqeOD0w。我遇到的算法问题是它经常产生负数,这对颜色无效。这是我的代码(我知道我不应该使用 PyGame 进行像素推送,我计划将来使用 OpenGL):

import pygame
pygame.init()

cols = 200
rows = 200

window = pygame.display.set_mode((cols, rows))

buffer1 = [[0 for _ in range(rows)] for _ in range(cols)]
buffer2 = buffer1.copy()

buffer1[100][100] = 255         #Raindrop


dampening = 0.97


running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

    for i in range(1, cols - 1):
        for j in range(1, rows - 1):
            buffer2[i][j] = ((buffer1[i+1][j] + buffer1[i-1][j] + buffer1[i][j+1] + buffer1[i][j-1]) / 2) - buffer2[i][j]
            buffer2[i][j] = buffer2[i][j] * dampening

    #Displaying the buffer
    for i in range(cols):
        for j in range(rows):
            window.fill((buffer2[i][j], buffer2[i][j], buffer2[i][j]), (i, j, 1, 1))

    #Swapping the buffers
    buffer1, buffer2 = buffer2, buffer1

    pygame.display.update()

pygame.display.quit()
pygame.quit()

我已经为此苦苦挣扎了一段时间,现在终于向您寻求帮助。 提前致谢。

The problem I'm having with the algorithm is that it often produces negative numbers, which are not valid for colour.

我建议将颜色值限制在 [0, 255] 范围内。例如:

c = max(0, min(255, buffer2[i][j]))
window.fill((c, c, c), (i, j, 1, 1))