#!/usr/bin/env python
"""'Traditional' twogtp implementation.

This runs a single game between two local GTP engines and reports the result.

This demonstrates the gtp_games module.

"""

import shlex
import sys
from optparse import OptionParser, SUPPRESS_HELP

from gomill import ascii_boards
from gomill import gtp_games
from gomill.gtp_controller import GtpChannelError, BadGtpResponse
from gomill.common import format_vertex

def print_move(colour, move, board):
    print colour.upper(), format_vertex(move)

def print_board(colour, move, board):
    print colour.upper(), format_vertex(move)
    print ascii_boards.render_board(board)
    print

def main():
    usage = "%prog [options] --black='<command>' --white='<command>'"
    parser = OptionParser(usage=usage)
    parser.add_option("--black", help=SUPPRESS_HELP)
    parser.add_option("--white", help=SUPPRESS_HELP)
    parser.add_option("--komi", type="float", default=7.5)
    parser.add_option("--size", type="int", default=19)
    parser.add_option("--verbose", type="choice", choices=('0','1','2'),
                      default=0, metavar="0|1|2")

    (options, args) = parser.parse_args()
    if args:
        parser.error("too many arguments")
    if not options.black or not options.white:
        parser.error("players not specified")

    black_command = shlex.split(options.black)
    white_command = shlex.split(options.white)
    game = gtp_games.Game(
        board_size=options.size,
        komi=options.komi,
        move_limit=1000)
    if black_command[0] != white_command[0]:
        game.set_player_code('b', black_command[0])
        game.set_player_code('w', white_command[0])
    if options.verbose == '1':
        game.set_move_callback(print_move)
    elif options.verbose == '2':
        game.set_move_callback(print_board)

    game.allow_scorer('b')
    game.allow_scorer('w')

    try:
        game.set_player_subprocess('b', black_command)
        game.set_player_subprocess('w', white_command)
        game.ready()
        game.run()
    except (GtpChannelError, BadGtpResponse), e:
        sys.exit("aborting game due to error:\n%s\n" % e)
    finally:
        game.close_players()
    print game.result.describe()
    if game.late_errors:
        sys.exit("\n".join(game.late_errors))

if __name__ == "__main__":
    main()