#!../expect -f
# Synopsis
#    robohunt player-name [-nodisplay]

# Plays hunt automatically.  Optional "-nodisplay" argument disables output.

# by Don Libes


trap exit SIGINT

set timeout 1

# given a direction and number, moves that many spaces in that direction
proc mv {dir num} {
	# first try firing a bullet (what the hell...open some walls to move!)
	send "f"
	for {set i 0} {$i<$num} {incr i} {
		send $dir
	}
}

# given a random character, generates/moves a distance/direction

# 31 is arbitrarily used as a max distance to move in any one direction
# this is a compromise between long horizontal and vertical moves
# but since excess movement is good for stabbing, this is reasonable
proc move {str} {
	scan $str "%c" num
	set mask [expr $num&3]
	set num [expr $num&31]
	if $mask==0 {send "H"; mv "h" $num; return}
	if $mask==1 {send "L"; mv "l" $num; return}
	if $mask==2 {send "K"; mv "k" $num; return}
		     send "J"; mv "j" $num; return
}

log_user 0
# output is turned off so that we can first strip out ^Gs before they
# are sent to the tty.  It seems to drive xterms crazy - because our
# rather stupid algorithm off not checking after every move can cause
# the game to send a lot of them.

if 3==[llength $argv] { set output 0 } {set output 1}
if 2>[llength $argv] { send_user "usage: robohunt name \[-nodisplay\]\n"; exit}
spawn hunt -b -c -n [lindex $argv 1]
expect "team"
send "\r"

set several_moves 15

set i -1;		# index into fortune buffer

for {} 1 {} {
	if $i==-1 {
		# get a new fortune to use for move data
		set fortune [split [exec /usr/games/fortune] ""]
		set i [expr [llength $fortune]-1]
	}

	# make several moves at a time, before checking to see if we are dead
	# this is a compromise between just ignoring our status after each move
	# and looking at our status after each move
	for {set j $several_moves} {$j>=0 && $i>=0} {incr i -1; incr j -1} {
		move [lindex $fortune $i]
	}
	expect {
		-re ^\007+ {continue -expect}
		-re "? " {send y}
		-re \[^\007\]+
	}	
	if $output {send_user $expect_out(buffer)}
}
