This repository has been archived by the owner on Aug 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstudent.py
74 lines (57 loc) · 2.29 KB
/
student.py
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
import asyncio
import getpass
import json
import os
import random
import websockets
from mapa import Map
from tree_search import SearchNode, SearchTree
async def solver(puzzle, solution):
while True:
game_properties = await puzzle.get()
mapa = Map(game_properties["map"])
#print(mapa)
search_tree = SearchTree(mapa)
r = await search_tree.search()
#print(r)
await solution.put(r)
#await asyncio.sleep(0)
async def agent_loop(puzzle, solution, server_address="localhost:8000", agent_name="student"):
async with websockets.connect(f"ws://{server_address}/player") as websocket:
# Receive information about static game properties
await websocket.send(json.dumps({"cmd": "join", "name": agent_name}))
while True:
try:
update = json.loads(
await websocket.recv()
) # receive game update, this must be called timely or your game will get out of sync with the server
if "map" in update:
# we got a new level
game_properties = update
keys = ""
await puzzle.put(game_properties)
if not solution.empty():
keys = await solution.get()
key = ""
if len(keys): # we got a solution!
key = keys[0]
keys = keys[1:]
await websocket.send(
json.dumps({"cmd": "key", "key": key})
)
except websockets.exceptions.ConnectionClosedOK:
print("Server has cleanly disconnected us")
return
# DO NOT CHANGE THE LINES BELLOW
# You can change the default values using the command line, example:
# $ NAME='arrumador' python3 client.py
loop = asyncio.get_event_loop()
SERVER = os.environ.get("SERVER", "localhost")
PORT = os.environ.get("PORT", "8000")
NAME = os.environ.get("NAME", getpass.getuser())
puzzle = asyncio.Queue(loop=loop)
solution = asyncio.Queue(loop=loop)
net_task = loop.create_task(agent_loop(puzzle, solution, f"{SERVER}:{PORT}", NAME))
solver_task = loop.create_task(solver(puzzle, solution))
loop.run_until_complete(asyncio.gather(net_task, solver_task))
loop.close()