// Written by James "Anthem" Costlow
// Released without license, free for all purposes.

function LandControlAll
locals
	rock
	town
	villager
	sex
	count
endl
begin
	blk	lbl0

// create the rock
	pshi	0x8
	pshi	0x5
	pshf	2266.000000
	crd	
	pshf	60.000000
	crd	
	pshf	2470.000000
	crd	
	sys	0x1B
	popf	rock

// initialize town, temp villager object, villager sex, villager count
	pshi	0x0
	popf	town

	pshi	0x0
	popf	villager

	pshi	0x31
	popf	sex

	pshf	0.000000
	popf	count

// done initializing
	free

// fade in. without this, some people's screens stay black
	pshf	0.000000
	sys	0xF2

// load player's creature at coordinate
	pshf	2013.310059
	crd	
	pshf	2372.659912
	crd	
	pshc
	swp
	sys	0xFA

// main loop, never exits

	blk	lbl1
lbl10:
	pshb	1
	jz	lbl2   // infinite loop (always true)


// loop: check if rock clicked, if not, keep rock in sight
	blk	lbl3
lbl7:
	pshf	[rock]
	sys	0x10
	not
	jz	lbl4    // if rock was clicked, exit this loop

// check if rock fell out of existence
	pshf	[rock]
	sys	0x100
	not
	jz	lbl5

// it did, so recreate it
	pshi	0x8
	pshi	0x5
	sys	0x6
	sys	0x1B
	popf	rock
	jmp	lbl5
lbl5:

// else, rock exists. check if it's more than 100 units from player
	sys	0x5
	pshf	[rock]
	sys	0x17
	sys	0x19
	pshf	100.000000
	gt
	jz	lbl6
	pshf	[rock]
// get player's coordinates
	sys	0x6
// move rock to player
	sys	0x18
	jmp	lbl6
lbl6:

	jmp	lbl7 // go back to rock-check loop

lbl4:
// rock was clicked, exit rock-check loop
	endb
	jmp	lbl8
lbl3:
	iter
lbl8:
// rock clicked, so create villagers
// set first villager's sex
	pshi	0x31
	popf	sex

// reset villager counter
	pshf	0.000000
	popf	count

// find town nearest to rock within 1000 units
	pshi	0x9
	pshi	0x1388
	pshf	[rock]
	sys	0x17
	pshf	1000.000000
	pshb	0
	sys	0x33
	popf	town


// loop: create 8 villagers of alternating sex
	blk	lbl9
lblE:
// check if 8 villagers created already. if so, exit loop
	pshf	[count]
	pshf	8.000000
	lt
	jz	lblA

// create villager near the rock
	pshi	0x4
	pshf	[sex]
	pshf	[rock]
	sys	0x17
	pshf	5.000000
	crd	
	pshf	5.000000
	crd	
	pshc
	swp
	addc
	sys	0x1B
	popf	villager

// make villager a citizen of the nearest town
	pshf	[villager]
	pshf	[town]
	pshb	0
	sys	0x25
	popo	
	zero	villager

// increment villager count
	pshi	[count]
	pshf	1.000000
	add
	popf	count

// switch sex for next villager
	pshi	0x31
	pshf	[sex]
	eq
	jz	lblB
	pshi	0x34
	popf	sex
	jmp	lblC
lblB:
	pshb	1
	jz	lblD
	pshi	0x31
	popf	sex

lblC:
	jmp	lblD

lblD:
	jmp	lblE  // repeat villager-create loop

lblA:
	endb         // end villager-create loop
	jmp	lblF

lbl9:
	iter
lblF:
// clear "clicked" state to get ready for next rock click
	sys	0x9C
	jmp	lbl10 // repeat main loop
lbl2:
	endb           // main loop is infinite, never gets here
	jmp	lbl11
lbl1:
	iter

// end function

lbl11:
	endb
	jmp	lbl12
lbl0:
	iter
lbl12:
	ret
end


