shithub: chessfs

ref: 470f19bc73180395683aa1e14c96ea3c2d3a828f
dir: /rc/replay/

View raw version
#!/bin/rc

rfork e
flagfmt='s sleepamt, k skip, f fen, d delay, c:close, h:help'
args='chessdir'
eval `{aux/getflags $*}

chessdir=$1
gameid=()
gamedir=()
player=white

if(~ $help 1 || ! ~ $#* 1) {
	aux/usage
	exit usage
}

if(~ $#sleepamt 0)
	sleepamt=1.5
if(~ $#delay 0)
	delay=10

fn sighup sigint sigterm{
	exit
}

# create game
gameid=`{cat $chessdir/clone}
gamedir=$chessdir/games/$gameid
if(~ $#gameid 0)
	exit clone

echo 'created game' $gameid

# load fen if necessary
if(! ~ $#fen 0) {
	echo $"fen >$chessdir/fen
	if(! ~ $#status 0) {
		echo 'unable to load fen'
		exit fen
	}
	echo 'loaded FEN'
}

# start player process
echo 'starting game in 5 seconds'
sleep $delay

oifs=$ifs
line=()
finished=()
echo start >$gamedir/ctl
echo 'game started'

while(line=`{read | tr -d \xa} && ! ~ $line 1.*) {}
while(~ $#finished 0) {
	for(i in `{seq 1 $#line}) {
		move=$line($i)
		if(! ~ $move *.) {
			echo $player 'plays' $move
			echo $move >$gamedir/$player
			switch($player) {
			case white
				player=black
			case black
				player=white
			}
			sleep $sleepamt
		}
	}
	line=`{read | tr -d \xa}
	if(! ~ $#status 0)
		finished=yes
}

echo 'replay finished'

ifs=$oifs
rm /env/oifs
rm /env/chessdir
rm /env/gameid
rm /env/gamedir
rm /env/player
rm /env/line
rm /env/finished

if(! ~ $#close 0) {
	echo 'closing game'
	echo close >$gamedir/ctl
}