#!/usr/bin/python

import gtp
import ishi
import goban
import strength
import re
import string
import sys

def sign(n):
	if n<0:
		return -1
	elif n>0:
		return 1
	else:
		return 0

# B+17.0 (upper bound: -17.0, lower: -17.0)
def parse_result(s):
	if s[0:1] == 'B':
		return -1
	if s[0:1] == 'W':
		return 1
	else:
		sys.stderr.write('color is not B or W in parse_result\n')
		sys.stderr.write(s+'\n')
		sys.exit(1)
#	r = re.compile('^([BW])\+([0-9\.]) ')
#	m = r.match(s)
#	if not m:
#		sys.stderr.write('bad result string\n')
#		sys.stderr.write(s+'\n')
#		sys.exit(1)
#	if m.group(1) == 'B':
#		return string.atoi(m.group(2))
#	if m.group(2) == 'W':
#		return -string.atoi(m.group(2))
#	sys.stderr.write('color is not B or W in parse_result\n')
#	sys.stderr.write(s+'\n')
#	sys.exit(1)

# return negative for black stronger
# return positive for white stronger
# n is trial strength difference
def match(black,white,n):
	(flip,handicap,komi) = strength.n_to_fhk(n)
	samples = 3
	if flip:
		b,w = white,black
	else:
		b,w = black,white
	player = [0,0]
	boardsize=7
	player[ishi.black] = gtp.gtp(b,boardsize,0)
	player[ishi.white] = gtp.gtp(w,boardsize,0)
	board = goban.board(boardsize,handicap)
#	print board
#	print
	list = []
	for sample in range(0,samples):
		passcount = 0
		while 1:
			for state in [ishi.black,ishi.white]:
				move = player[state].get_input(state,board)
				#print 'got move',move,'from',ishi.description(state)
				if move == 'PASS':
					passcount += 1
				else:
					passcount = 0
				player[ishi.invert(state)].feed_move(state,move)
				if move != 'PASS':
					board.move(move,state)
				#print board
				#print
				if passcount == 2:
					break
			if passcount == 2:
				break
		result = parse_result(player[ishi.black].get_result())
#		if result == 1:
#			print
#			print
#			print 'Black won'
#			print
#		else:
#			print
#			print
#			print 'White won'
#			print
		# just a 1 or -1 for now.  Actually, that's probably better, so that
		# the size of a win doesn't matter
		list.append(result)
	total = 0
	for sample in range(samples):
		total += list[sample]
	return float(total)/samples
	return 0

def main():
	n = 0
	d = {}
	black='gnugo --mode gtp'
	white='gnugo --mode gtp'
	r = match(black,white,0)
	if r < 0:
		r = -r
		black,white = white,black
	print r
	n = 0
	while 1:
		prev = r
		r = match(black,white,n)
		print prev,r
		if sign(prev) != sign(r):
			print 'strength difference for',black,white,'is between',prev,n
			sys.exit(0)
		if r<0:
			n += 1
		

main()