2
2
import json
3
3
import time
4
4
from datetime import datetime , timedelta
5
-
5
+ import os
6
6
import websockets
7
7
import requests
8
8
from csv import writer
9
9
10
10
import config
11
11
12
+
13
+ MAX_ROUNDS = 100
14
+
15
+ def append_to_csv (file_name : str , elements ):
16
+ with open (file_name , 'a+' , newline = '' ) as write :
17
+ csv_writer = writer (write )
18
+ csv_writer .writerow (elements )
19
+
20
+
12
21
client_time = datetime .now ()
13
22
time_request_result = requests .get (config .TIME_URL )
14
23
28
37
def transform_to_server_time (time_value : datetime ):
29
38
return time_value + time_offset
30
39
40
+
31
41
async def play ():
42
+
43
+ if not os .path .exists (config .GAME_ANALYSIS_DIRECTORY_PATH ):
44
+ os .makedirs (config .GAME_ANALYSIS_DIRECTORY_PATH )
45
+
46
+ board_size_file_name = config .GAME_ANALYSIS_DIRECTORY_PATH + "sizes" + ".csv"
47
+ time_file_name = config .GAME_ANALYSIS_DIRECTORY_PATH + "times-" \
48
+ + datetime .now ().strftime ("%Y-%m-%d-%H-%M-%S" ) + ".csv"
49
+
32
50
url = config .URL
33
51
key = config .API_KEY
34
52
35
53
async with websockets .connect (f"{ url } ?key={ key } " ) as websocket :
36
- started = False
54
+ rounds = 0
37
55
print ("Waiting for initial state..." , flush = True )
38
56
39
57
while True :
40
58
state_json = await websocket .recv ()
41
59
state = json .loads (state_json )
42
60
43
- if not started :
61
+ if rounds == 0 :
44
62
print (f"board -- width: %d -- height: %d" % (state ["width" ], state ["height" ]))
45
- started = True
63
+ append_to_csv (board_size_file_name , [state ["width" ], state ["height" ]])
64
+ rounds += 1
46
65
47
- if not state ["running" ]:
66
+ if not state ["running" ] or rounds >= MAX_ROUNDS :
48
67
break
49
68
50
69
deadline = datetime .strptime (state ["deadline" ], '%Y-%m-%dT%H:%M:%SZ' )
51
70
available_millis = (deadline - transform_to_server_time (datetime .now ())) / timedelta (milliseconds = 1 )
52
-
53
71
print (f"\t available milliseconds: %d" % available_millis )
54
-
55
- time .sleep (0.5 )
72
+ append_to_csv (time_file_name , [available_millis ])
56
73
57
74
action_json = json .dumps ({"action" : "change_nothing" })
58
75
await websocket .send (action_json )
@@ -61,5 +78,6 @@ async def play():
61
78
while True :
62
79
try :
63
80
asyncio .get_event_loop ().run_until_complete (play ())
64
- except Exception :
81
+ except Exception as e :
82
+ print (e )
65
83
print ("Connection was interrupted!" )
0 commit comments