Skip to content

Instantly share code, notes, and snippets.

@EndingCredits
Created July 22, 2019 13:30
Show Gist options
  • Save EndingCredits/31ca9a83ca5e00856f9adf818fe27da4 to your computer and use it in GitHub Desktop.
Save EndingCredits/31ca9a83ca5e00856f9adf818fe27da4 to your computer and use it in GitHub Desktop.
Ripples
# Import a library of functions called 'pygame'
import pygame
import numpy as np
# Width and height of display
WIDTH = 255>>0
HEIGHT = 65>>0
# Downscale to ripple grid
SHFT = 2
R_WIDTH = (WIDTH>>SHFT)+1
R_HEIGHT = (HEIGHT>>SHFT)+1
# Initialise front and back buffers
frontbuffer = np.random.randint(255,size=R_WIDTH*R_HEIGHT)
backbuffer = np.random.randint(255,size=R_WIDTH*R_HEIGHT)
print("Using {} bytes of memory".format(R_WIDTH*R_HEIGHT*2))
# Initialize the game engine
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT*2))
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
# get mouse position and translate to grid
x, y = pygame.mouse.get_pos()
x = min(x>>SHFT, R_WIDTH-1)
y = min(y>>SHFT, R_HEIGHT-1)
frontbuffer[x + R_WIDTH*y] = 255 # create ripple
# Draw screen based on backbuffer
for x in range(0, WIDTH):
for y in range(0, HEIGHT):
x_ = min(x>>SHFT, R_WIDTH-1)
y_ = min(y>>SHFT, R_HEIGHT-1)
color = backbuffer[x_ + R_WIDTH*y_]
try:
pygame.draw.rect(screen, (color,color,color), [x, y, 1, 1], 2)
except:
print(color)
for x in range(0, WIDTH):
for y in range(HEIGHT, HEIGHT*2):
x_ = min(x>>SHFT, R_WIDTH-1)
y_ = min((y-HEIGHT)>>SHFT, R_HEIGHT-1)
color = frontbuffer[x_ + R_WIDTH*y_]
try:
pygame.draw.rect(screen, (color,color,color), [x, y, 1, 1], 2)
except:
print(color)
# Calculate wave propogation as in
# https://web.archive.org/web/20160418004149/http://freespace.virgin.net/hugo.elias/graphics/x_water.htm
for x in range(0, R_WIDTH):
for y in range(0, R_HEIGHT):
x_n = x-1 if x != 0 else x+1
x_p = x+1 if x != R_WIDTH-1 else x-1
y_n = y-1 if y != 0 else y+1
y_p = y+1 if y != R_HEIGHT-1 else y-1
backbuffer[x + R_WIDTH*y] = min(max((frontbuffer[x_p + R_WIDTH*y] +
frontbuffer[x_n + R_WIDTH*y] +
frontbuffer[x + R_WIDTH*y_p] +
frontbuffer[x + R_WIDTH*y_n] ) // 2 - \
backbuffer[x + R_WIDTH*y], 0), 255)
backbuffer[x + R_WIDTH*y] -= int(backbuffer[x + R_WIDTH*y])>>5
# swap buffers
temp = frontbuffer
frontbuffer = backbuffer
backbuffer = temp
pygame.display.flip()
# Be IDLE friendly
pygame.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment