use atari

type 
    scrx:0..39 
    scry:0..23 
    cellx:1..38
    celly:1..22

;screens
s1@$8000:array(scrx,scry) of byte
s2@$8400:array(scrx,scry) of byte
header:array(scrx,0) of byte
footerRun:array(scrx,0) of byte
footerEdit:array(scrx,1) of byte

;Display Lists
const gr0s1:array of dl_command =
	2 times BLANK8,
	CHR0+LMS, header,
	BLANK1 
	CHR0+LMS, s1, 
	23 times CHR0,
	BLANK1,
	CHR0+LMS,footerRun, 
	NEXT, gr0s1

const gr0s2:array of dl_command =
	2 times BLANK8,
	CHR0+LMS, header,
	BLANK1 
	CHR0+LMS, s2, 
	23 times CHR0, 
	BLANK1,
	CHR0+LMS,footerRun, 
	NEXT, gr0s2

const gr0edit:array of dl_command =
	2 times BLANK8,
	CHR0+LMS, header,
	BLANK1 
	CHR0+LMS, s1, 
	23 times CHR0, 
	BLANK1,
	CHR0+LMS,footerEdit,
	CHR0 
	NEXT, gr0s2

;random screen initialisation
smear:proc(mask:byte = 1) =
	for x:cellx
	    for y:celly
	        s1(x,y) = RANDOM bitand mask

edit:proc =
	SDLSTL = gr0edit
	x:cellx = 20
	y:celly = 12
	CH = none
	until CH = ESC
		buf = s1(x,y)
		bCH:KEY = CH bitand $7F ;[CONTROL] key is ignored
		if bCH <> $7F
			if bCH = 6 ;left
				if x>1 dec x ;x = x - 1
			else if bCH = 7 ;right
				if x<38 inc x ;x = x + 1
			else if bCH = 14 ;up
				if y>1 dec y ;y = y - 1
			else if bCH = 15 ;down
				if y<22 inc y ;y = y +1
			else if bCH = SPACE
				s1(x,y) = 1-buf
			else if bCH = DEL
				smear 0;s1 = 0
			else if bCH = R
				smear 1
			CH = none
		else
			s1(x,y) = "*"
			s1(x,y) = buf

;--------------------------------------------------------------------
;The rules are:
;Any alive cell that is touching less than two alive neighbours dies.
;Any alive cell touching four or more alive neighbours dies.
;Any alive cell touching two or three alive neighbours does nothing.
;Any dead cell touching exactly three alive neighbours becomes alive.


header(0,0)=   " Atalife - simple Life by pirx/5oft.pl  "
footerRun(0,0)="       Press [[Esc]] /[[E]] to edit.       "
footerEdit(0,0)="  Use cursor keys and [[Space]] to edit.  "
footerEdit(0,1)="[[Del]]-clear, [[R]]-random, [[Esc]]-continue."

smear 1
CH = none

main@

SDLSTL = gr0s1
for x:cellx
	for y:celly
		;life making
		v=s1(x-1,y-1)+s1(x,y-1)+s1(x+1,y-1)+s1(x-1,y)+s1(x+1,y)+s1(x-1,y+1)+s1(x,y+1)+s1(x+1,y+1)
		if s1(x,y) = 0
			if v=3 s2(x,y)=1
			else s2(x,y)=0
		else 
			if v<2 or v>3 s2(x,y)=0
			else s2(x,y)=1

SDLSTL = gr0s2
for x:cellx
	for y:celly
		;life making
		v=s2(x-1,y-1)+s2(x,y-1)+s2(x+1,y-1)+s2(x-1,y)+s2(x+1,y)+s2(x-1,y+1)+s2(x,y+1)+s2(x+1,y+1)
		if s2(x,y) = 0
			if v=3 s1(x,y)=1
			else s1(x,y)=0
		else 
			if v<2 or v>3 s1(x,y)=0
			else s1(x,y)=1

if CH = ESC or CH = E 
	edit
	CH = none

goto main
