0ad/source/tools/rlclient/python/zero_ad/api.py
wraitii 5473393e30 Add an interface for Reinforcement Learning.
Implement a simple HTTP server to start games, receive the gamestate and
pass commands to the simulation.
This is mainly intended for training reinforcement learning agents in 0
AD. As such, a python client and a small example are included.

This option can be enabled using the -rl-interface flag.

Patch by: irishninja
Reviewed By: wraitii, Itms
Fixes #5548

Differential Revision: https://code.wildfiregames.com/D2199
This was SVN commit r23917.
2020-08-01 10:52:59 +00:00

29 lines
895 B
Python

import urllib
from urllib import request
import json
class RLAPI():
def __init__(self, url):
self.url = url
def post(self, route, data):
response = request.urlopen(url=f'{self.url}/{route}', data=bytes(data, 'utf8'))
return response.read()
def step(self, commands):
post_data = '\n'.join((f'{player};{json.dumps(action)}' for (player, action) in commands))
return self.post('step', post_data)
def reset(self, scenario_config, player_id, save_replay):
path = 'reset?'
if save_replay:
path += 'saveReplay=1&'
if player_id:
path += f'playerID={player_id}&'
return self.post(path, scenario_config)
def get_templates(self, names):
post_data = '\n'.join(names)
response = self.post('templates', post_data)
return zip(names, response.decode().split('\n'))