Skip to content

Instantly share code, notes, and snippets.

@gynvael
Created March 19, 2023 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gynvael/754b1a7a3f5f8d797e6c9398d6317cec to your computer and use it in GitHub Desktop.
Save gynvael/754b1a7a3f5f8d797e6c9398d6317cec to your computer and use it in GitHub Desktop.
GPT-4 output 2 metaball script
import pygame
import sys
import math
import time
# Constants
WIDTH, HEIGHT = 800, 600
BG_COLOR = (0, 0, 0)
THRESHOLD = 0.5
def handle_exit_event():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
def add_metaball(x, y, vx, vy, r, g, b, metaballs):
metaballs.append({"x": x, "y": y, "vx": vx, "vy": vy, "r": r, "g": g, "b": b})
def draw_scene(screen, metaballs):
for x in range(WIDTH):
for y in range(HEIGHT):
total_influence = 0
color_r, color_g, color_b = 0, 0, 0
for metaball in metaballs:
dx = x - metaball["x"]
dy = y - metaball["y"]
distance_sq = dx * dx + dy * dy
influence = 1 / max(distance_sq, 1)
total_influence += influence
color_r += metaball["r"] * influence
color_g += metaball["g"] * influence
color_b += metaball["b"] * influence
norm = math.sqrt(color_r * color_r + color_g * color_g + color_b * color_b)
color_r /= max(norm, 1)
color_g /= max(norm, 1)
color_b /= max(norm, 1)
intensity = 255 if total_influence >= THRESHOLD else 128
color = (int(color_r * intensity), int(color_g * intensity), int(color_b * intensity))
screen.set_at((x, y), color)
pygame.display.flip()
def update_metaball_positions(metaballs):
for metaball in metaballs:
metaball["x"] += metaball["vx"]
metaball["y"] += metaball["vy"]
if metaball["x"] < 0 or metaball["x"] > WIDTH:
metaball["vx"] = -metaball["vx"]
if metaball["y"] < 0 or metaball["y"] > HEIGHT:
metaball["vy"] = -metaball["vy"]
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Metaballs Simulation")
metaballs = []
add_metaball(250, 250, -1, -1, 255, 0, 0, metaballs)
add_metaball(200, 200, 1, 1, 0, 255, 0, metaballs)
while True:
start_time = time.time()
handle_exit_event()
draw_scene(screen, metaballs)
update_metaball_positions(metaballs)
iteration_time = time.time() - start_time
print(f"Time taken for iteration: {iteration_time:.4f} seconds")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment