: AyaanScript+ — Perlin noise terrain
: Generates a heightmap once using noise() and renders it with colored cells.

const W = 800
const H = 600
gui_native "AyaanScript+ — Perlin Terrain" W H
gui_fps 30

: precompute terrain palette
list pal = ["#0a1a40", "#0d3a78", "#0f6bb8", "#5fa8d8", "#e8d893", "#5fa848", "#3a7a30", "#2a5a20", "#5a5a5a", "#9a9a9a", "#ffffff"]

set running = 1
set t = 0

while running == 1
    gui_open running
    if running == 0
        break
    endif

    gui_clear "#000010"

    : render a 40x30 cell grid using perlin noise + time offset
    set cy = 0
    repeat 30 cy
        set cx = 0
        repeat 40 cx
            set fx = {(cx - 1) * 0.15}
            set fy = {(cy - 1) * 0.15}
            : add a second octave for detail
            noise fx fy -> n1
            set fx2 = {fx * 2}
            set fy2 = {fy * 2}
            noise fx2 fy2 -> n2
            set h = {(n1 + n2 * 0.5) / 1.5}
            : map [-1,1] to palette index 0..10
            set idx = {int((h + 1) * 5)}
            if idx < 0
                set idx = 0
            endif
            if idx > 10
                set idx = 10
            endif
            list_at pal idx -> col
            set px = {(cx - 1) * 20}
            set py = {(cy - 1) * 20}
            gui_fill_rect px py 20 20 col
        endrepeat
    endrepeat

    gui_text_big 20 20 "PERLIN TERRAIN" "white" 2
    gui_text 20 55 "ESC quits" "lightgray"

    gui_key_down "esc" -> esc
    if esc == 1
        set running = 0
    endif

    gui_update
endwhile

gui_close
