!falling_speed = $30
!tile1 = $80	;first frame, walking
!tile2 = $82	;second frame, walking
!tile3 = $84	;first frame, in shell
!tile4 = $86	;second frame, in shell
!tile5 = $88	;third frame, in shell
!yxppccct = $0D

incsrc subroutinedefs_xkas.asm

print "INIT ",pc
			phb : phk : plb
			jsl !SubHorizPos
			tya
			sta $157C,x
			stz $1510,x
			plb : rtl
print "MAIN ",pc
			phb : phk : plb
			jsr Code
			plb : rtl
skip: 		stz $AA,x
			stz $B6,x
			jmp Code_updatesp
Code:		jsl !SubOffscreenX0
			lda $9D
			bne skip
			lda $1588,x
			and #$04
			beq +
			jsr SpawnBuzzy
+ : 		JSL $81A7DC
			bcc +
			rep #$20
			lda $14D4,x
			and #$00FF
			xba
			ora $D8,x
			cmp $96
			sep #$20
			bcc .hurtmario
			lda #$13 : sta $1DF9
			lda $D8,x
			clc
			adc #$08
			sta $D8,x
			lda $14D4,x
			adc #$00
			sta $14D4,x
			jsr SpawnBuzzy
+ : 		lda $1588,x
			and #$03
			beq .flipsk
			lda $157C,x
			eor #$01
			sta $157C,x	
.flipsk :  	jsr CheckProximity
			beq .notnear
			lda #$01 : sta $1510,x
.notnear : 	lda $1510,x			;fall flag
			beq +
			lda #!falling_speed
			sta $AA,x
			stz $B6,x
			bra .updatesp
+ : 		ldy $157C,x
			lda .xspeed,y
			sta $B6,x
			stz $AA,x
.updatesp : JSL $81801A
			JSL $818022
			JSL $819138
			JSL $818032	
			jsr Graphics
			rts
.hurtmario : 
			JSL $80F5B7
			bra .flipsk
.xspeed : db $08 : db $08^$FF+1
Graphics:	JSL $8190B2
			lda $7f1234
			ldy $15EA,x
			lda $157C,x
			eor #$01
			clc
			ror A : ror A : ror A
			ora.b #!yxppccct|$80
			sta $0303,y
			lda $1510,x
			asl #2
			sta $02
			lda $14
			lsr #3
			and #$03
			clc : adc $02
			phx
			tax
			lda .tiles,x
			plx
			sta $0302,y
			rts
.tiles
db !tile1,!tile2,!tile1,!tile2
db !tile3,!tile4,!tile5,!tile4
SpawnBuzzy:
			lda #$11
			sta $9E,x
			lda #$08
			sta $14C8,x
			JSL $87F7D2
			rts
			

CheckProximity:
Proximity:		; If sprite is TOO close to Mario, return.
	LDA $14E0,x
	XBA
	LDA $E4,x
	REP #$20 ; Get sprite's X position.
	SEC
	SBC $94	; Subtract Mario's to get the difference range.
	SEP #$20
	PHA
	JSL !SubHorizPos; Determine sprite range.
	PLA
	EOR InvertAbility,y ; Apply inversion based on direction.
	CMP #$09 ; Range.
	BCS OutofRange
	LDA #$01
	RTS
OutofRange:
	LDA $E4,x
	CMP $94
	BNE RangeOut
	LDA #$01
	RTS
RangeOut:
	LDA #$00
	RTS
InvertAbility:
	db $FF,$00

