This snippet shows how to make AI agents search a map in a hide&seek-like or RTS scouting-like behavior. While this example just shows it working on tiles, the algorithm could easily be applied to FPS games to make the AI characters search the level, looking for the player in a smart way. I plan to use something like this for the scouting AI in a RTS I'm making.
White tiles are the areas of the map the AI can see or has recently seen. It's sort of like the AI's memory. Tiles slowly fade to black, making the AI want to re-search previous places on the map after a while.
sync on
sync rate 0
cls
hide mouse
tilesize=10
gw=screen width()/tilesize
gh=screen height()/tilesize
dim grid(gw,gh) as float
global scout_amount
scout_amount=6
type scout_type
x as float
y as float
r as float
target_exist
targetx as float
targety as float
endtype
dim scout(scout_amount) as scout_type
for s=1 to scout_amount
scout(s).x=rnd(screen width())
scout(s).y=rnd(screen height())
scout(s).r=rnd(359)
next s
speed#=2
length#=4.0
sightrange=3
do
cls
gosub display_grid
gosub ai
sync
loop
ai:
for s=1 to scout_amount
gx=scout(s).x/tilesize
gy=scout(s).y/tilesize
for x=gx-sightrange to gx+sightrange
for y=gy-sightrange to gy+sightrange
if x>=0 and y>=0 and x<gw and y<gh
if (x-gx+0.0)^2+(y-gy+0.0)^2<=sightrange^2
grid(x,y)=255
endif
endif
next y
next x
if scout(s).target_exist=0
mostwanted#=0
for x=0 to gw-1
for y=0 to gh-1
if x<>gx and y<>gy
good=1
for s2=1 to scout_amount
if s2<>s
if abs(0.0+scout(s2).targetx/tilesize-x)<sightrange*1.5 and abs(0.0+scout(s2).targety/tilesize-y)<sightrange*1.5
good=0
endif
endif
next s2
if good=1
want#=(1.0/(grid(x,y)*5+0.1))/((0.0+x-gx)^2+(0.0+y-gy)^2+1000000.0)
if want#>mostwanted#
mostwanted#=want#
wantx=x
wanty=y
endif
endif
endif
next y
next x
scout(s).target_exist=1
scout(s).targetx=tilesize*wantx+tilesize*0.5
scout(s).targety=tilesize*wanty+tilesize*0.5
endif
if scout(s).target_exist=1
scout(s).r=atanfull(scout(s).targety-scout(s).y,scout(s).targetx-scout(s).x)
scout(s).x=scout(s).x+speed#*cos(scout(s).r)
scout(s).y=scout(s).y+speed#*sin(scout(s).r)
if sqrt((scout(s).targety-scout(s).y)^2+(scout(s).targetx-scout(s).x)^2)<0.5*tilesize
scout(s).target_exist=0
endif
endif
ink rgb(0,0,255),0
line scout(s).x,scout(s).y,scout(s).x+length#*cos(scout(s).r),scout(s).y+length#*sin(scout(s).r)
` line scout(s).x,scout(s).y,scout(s).targetx,scout(s).targety
next s
return
display_grid:
for x=0 to gw-1
for y=0 to gh-1
if grid(x,y)>0 then grid(x,y)=grid(x,y)-0.1
ink rgb(grid(x,y),grid(x,y),grid(x,y)),0
box x*tilesize,y*tilesize,x*tilesize+tilesize,y*tilesize+tilesize
next y
next x
return
Edit, another idea: If you combine this with A*, it could be used if you want a pet/animal AI character to find his way out of a maze, but want him to have to search around the maze and look for a way out. It would look like he's trying the dead ends and remembering where he's already searched.