Sample Code

Download this example Python script to see how to use the API. This basic AI always checks/calls.

import argparse
import logging
import re
import sys

import requests

logging.getLogger("urllib3").setLevel(logging.WARNING)

BIG_BLIND = 2
WEB_API_URL = 'https://gtoking.com/api/play'


# If |bet| is None, we just read the current hand state. It is useful at
# the hand's start, as GTO King might play first (and we want to know his move).
# Note that we need to pass |initial_stack| everytime because a same bot can
# play in different formats.
def play(token, initial_stack, bet):
    data = {
        'token': token,
        'initialStacks': [initial_stack, initial_stack],
        'game_format': 'hu',
    }
    if bet is not None:
        data['bet'] = bet
    response = requests.post(WEB_API_URL, headers={}, json=data)
    success = getattr(response, 'status_code') == 200
    if not success:
        print('Status code: %s' % repr(response.status_code))
        try:
            print('Error response: %s' % repr(response.json()))
        except ValueError:
            pass
        sys.exit(-1)
    try:
        r = response.json()
    except ValueError:
        print('Could not get JSON from response')
        sys.exit(-1)
    if 'error' in r:
        print('Error: %s' % r['error'])
        sys.exit(-1)
    return r


# Check/call until hand's end.
def play_hand(token, initial_stack):
    r = play(token, initial_stack, None)
    #  print(r)
    #  position = r.get('position')
    #  hole_cards = r.get('hole_cards')
    while True:
        history = r.get('history')
        print(history)
        if 'outcome' in r:
            return r['outcome'], r['avg_outcome']
        street = history.count('/') / 2
        last_street_bets = r.get('history').split('/')[-1]
        last_bets = re.findall(r'b(\d+)', last_street_bets)
        bet = None
        if not last_bets:
            # Call the big blind when being SB preflop, check otherwise.
            bet = BIG_BLIND if street == 0 else 0
        else:
            # Call, or check if villain checked.
            bet = int(last_bets[-1])
        r = play(token, initial_stack, bet)
    # Not reached.


def main():
    parser = argparse.ArgumentParser(description='Play versus GTO King')
    parser.add_argument('--token', type=str, required=True)
    args = parser.parse_args()
    token = args.token

    initial_stack = 50
    num_hands = 10
    session_result = 0
    for hand in range(num_hands):
        print('\n----------------- HAND %i -----------------' % (hand + 1))
        hand_result, lifetime_result = play_hand(token, initial_stack)
        session_result += hand_result
    print('Total session:', session_result)
    print('Total lifetime:', lifetime_result)


if __name__ == '__main__':
    main()