File: api.py

package info (click to toggle)
0ad 0.28.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 182,352 kB
  • sloc: cpp: 201,989; javascript: 19,730; ansic: 15,057; python: 6,597; sh: 2,046; perl: 1,232; xml: 543; java: 533; makefile: 105
file content (33 lines) | stat: -rw-r--r-- 1,029 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import json
from urllib import request


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"))  # noqa: S310
        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"), strict=False)

    def evaluate(self, code):
        response = self.post("evaluate", code)
        return json.loads(response.decode())