perlinnoise.py

Created by lex-kimmel

Created on October 18, 2023

1.7 KB

Perlin Noise generator using Numpy Module


import kandinsky as kd
import random
import time

# Generate a random gradient grid
def generate_gradient_grid(width, height):
    gradient_grid = []
    for x in range(width):
        row = []
        for y in range(height):
            angle = random.uniform(0, 2 * 3.14159265359)
            row.append([random.uniform(-1, 1), random.uniform(-1, 1)])
        gradient_grid.append(row)
    return gradient_grid

# Interpolation function
def interpolate(t, a, b):
    return a + t * (b - a)

# Smoothstep function
def smoothstep(t):
    return t * t * (3 - 2 * t)

# Perlin noise function
def perlin_noise(x, y, gradient_grid, width, height):
    x0, y0 = int(x), int(y)
    x1, y1 = x0 + 1, y0 + 1
    tx, ty = x - x0, y - y0

    gx0, gy0 = gradient_grid[x0][y0]
    gx1, gy1 = gradient_grid[x1][y0]
    gx2, gy2 = gradient_grid[x0][y1]
    gx3, gy3 = gradient_grid[x1][y1]

    dx0 = x - x0
    dx1 = x - x1
    dy0 = y - y0
    dy1 = y - y1

    n0 = gx0 * dx0 + gy0 * dy0
    n1 = gx1 * dx1 + gy1 * dy0
    n2 = gx2 * dx0 + gy2 * dy1
    n3 = gx3 * dx1 + gy3 * dy1

    ix0 = interpolate(smoothstep(tx), n0, n1)
    ix1 = interpolate(smoothstep(tx), n2, n3)

    return interpolate(smoothstep(ty), ix0, ix1)

# Set the size of the Perlin noise grid
width = 160
height = 120

# Generate a gradient grid
gradient_grid = generate_gradient_grid(width, height)

# Display Perlin noise on the Numworks calculator
for x in range(width):
    for y in range(height):
        value = perlin_noise(x / 10, y / 10, gradient_grid, width, height)
        color = int((value + 1) * 127)
        kd.set_pixel(x, y, color, color, color)

# Refresh the screen
kd.display()

# Delay to view the image (adjust as needed)
time.sleep(10)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.