This repository was archived by the owner on Dec 19, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
146 lines (111 loc) · 3.87 KB
/
client.py
File metadata and controls
146 lines (111 loc) · 3.87 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import requests
import ConfigParser
from bot import Bot
TIMEOUT = 15
BASE_URL = "http://game.blitz.codes:8080"
SECTION = "Game"
def get_new_game_state(session, server_url, key, mode='training', game_id=''):
"""Get a JSON from the server containing the current state of the game.
Args:
session: A request session.
server_url (str): The URL of the API.
key (str): A valid key.
mode (str): 'training' or 'competition'.
game_id (str): A valide game id.
Returns:
dict: The new game state.
"""
if mode == 'training':
# Don't pass the 'map' parameter if you want a random map
params = { 'key': key, 'map': 'm5'}
# params = {'key': key}
api_endpoint = '/api/training'
elif mode == 'competition':
params = {'key': key}
api_endpoint = '/api/arena?gameId='+game_id
# Wait for 10 minutes
print(server_url + api_endpoint)
r = session.post(server_url + api_endpoint, params, timeout=10*60)
if r.status_code == 200:
return r.json()
else:
print("Error when creating the game")
print(r.text)
def move(session, url, direction):
"""Send a move to the server.
Args:
session: A request session.
url: The url where to post the move.
direction: The direction to send to the server. One of 'Stay', 'North', 'South', 'East' or 'West'.
Returns:
dict: A dictionary containing the game state.
"""
try:
r = session.post(url, {'dir': direction}, timeout=TIMEOUT)
if r.status_code == 200:
return r.json()
else:
print("Error HTTP %d\n%s\n" % (r.status_code, r.text))
return {'game': {'finished': True}}
except requests.exceptions.RequestException as e:
print(e)
return {'game': {'finished': True}}
def is_finished(state):
"""Verify if a game is finished or not.
Args:
state (dict): A game state.
"""
return state['game']['finished']
def start(server_url, key, mode, game_id, bot):
"""Start a game with all the required parameters.
Args:
server_url (str): The server's URL.
key (str): A valid API key.
mode (str): The game mode, "training" or "competition".
game_id (str): a valid game id, when playing in competition mode.
bot (Bot): The bot that will play the game.
"""
# Create a requests session that will be used throughout the game
session = requests.session()
if mode == 'arena':
print(u'Connected and waiting for other players to join…')
# Get the initial state
state = get_new_game_state(session, server_url, key, mode, game_id)
print("Playing at: " + state['viewUrl'])
while not is_finished(state):
# Choose a move
direction = bot.move(state)
sys.stdout.write("Going to {}.\n".format(direction))
sys.stdout.flush()
# Send the move and receive the updated game state
url = state['playUrl']
state = move(session, url, direction)
# Clean up the session
session.close()
def main():
if len(sys.argv) < 3:
config = ConfigParser.ConfigParser()
config.read("config.ini")
key = config.get(SECTION, "Secret")
mode = config.get(SECTION, "Mode")
if mode == "competition":
game_id = config.get(SECTION, "GameId")
else:
game_id = ""
else:
key = sys.argv[1]
mode = sys.argv[2]
if len(sys.argv) == 4:
game_id = sys.argv[3]
else:
game_id = ""
if mode != "training" and mode != "competition":
print("Invalid game mode. Please use 'training' or 'competition'.")
else:
start(BASE_URL, key, mode, game_id, Bot())
print("\nGame finished!")
if __name__ == "__main__":
main()