Enemy A.I. Code???

Blitz3D Forums/Blitz3D Programming/Enemy A.I. Code???

The forum is locked. These are the original blitzbasic.com forums, kept so they can still be read. No new topics, replies or edits can be made here. To join in, head over to the Blitz3D+ forums.

Just put together a very basic snippet to demonstrate state based AI, use the arrow keys to move around, you're the P!

The enemy has roam, chase and attack states, and will show it's state with it's colour and a R,C, or A.

Graphics 640,480,32,2

; simplistic ai
; Rob Farley 2004

px#=320
py#=240
pspd#=1


Const roam=1
Const chase=2
Const attack=3


ex#=Rand(0,640)
ey#=Rand(0,480)
espd#=.5
estate=roam
echasedis = 100
eattackdis = 20

roamx=Rand(0,640)
roamy=Rand(0,480)


kup = 200
kdown = 208
kleft = 203
kright = 205

SetBuffer BackBuffer()

Repeat
Cls

; player control
If KeyDown(kup) Then py=py-pspd
If KeyDown(kdown) Then py=py+pspd
If KeyDown(kleft) Then px=px-pspd
If KeyDown(kright) Then px=px+pspd

; find the distance from the player to the enemy
dis# = Sqr(((px-ex)*(px-ex)) + ((py-ey)*(py-ey)))

; enemy AI
If estate=roam And dis<echasedis Then estate=chase
If estate=chase And dis>echasedis Then estate=roam
If estate=chase And dis<eattackdis Then estate=attack
If estate=attack And dis>eattackdis Then estate=chase

If estate=roam ; go to a random place on the screen
	If ex<roamx Then ex=ex+espd
	If ex>roamx Then ex=ex-espd
	If ey>roamy Then ey=ey-espd
	If ey<roamy Then ey=ey+espd
	dis# = Sqr(((roamx-ex)*(roamx-ex)) + ((roamy-ey)*(roamy-ey)))
	If dis<50 Then 
		roamx=Rand(0,640)
		roamy=Rand(0,480)
		EndIf
	EndIf


If estate=chase	; chase the player
	If ex<px Then ex=ex+espd
	If ex>px Then ex=ex-espd
	If ey>py Then ey=ey-espd
	If ey<py Then ey=ey+espd
	EndIf
	
If estate=attack ; erm... chase the player hacking 'n' slashing
	If ex<px Then ex=ex+espd
	If ex>px Then ex=ex-espd
	If ey>py Then ey=ey-espd
	If ey<py Then ey=ey+espd
	EndIf



; draw advanced graphics

Color 0,255,0
Oval px-10,py-10,21,21,False
Text px,py,"P",True,True

If estate=roam Then Color 255,255,0
If estate=chase Then Color 255,160,0
If estate=attack Then Color 255,0,0
Oval ex-10,ey-10,21,21,False
If estate=roam Then Text ex,ey,"R",True,True
If estate=chase Then Text ex,ey,"C",True,True
If estate=attack Then Text ex,ey,"A",True,True


Flip
Until KeyHit(1)