generated from dgomes/ia-tetris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
74 lines (58 loc) · 2.68 KB
/
client.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 websockets
# Next 4 lines are not needed for AI agents, please remove them from your code!
import pygame
pygame.init()
program_icon = pygame.image.load("data/icon2.png")
pygame.display.set_icon(program_icon)
async def agent_loop(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}))
# Next 3 lines are not needed for AI agent
SCREEN = pygame.display.set_mode((299, 123))
SPRITES = pygame.image.load("data/pad.png").convert_alpha()
SCREEN.blit(SPRITES, (0, 0))
while True:
try:
state = json.loads(
await websocket.recv()
) # receive game update, this must be called timely or your game will get out of sync with the server
print(state)
# Next lines are only for the Human Agent, the key values are nonetheless the correct ones!
key = ""
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
key = "w"
elif event.key == pygame.K_LEFT:
key = "a"
elif event.key == pygame.K_DOWN:
key = "s"
elif event.key == pygame.K_RIGHT:
key = "d"
elif event.key == pygame.K_d:
import pprint
pprint.pprint(state)
await websocket.send(
json.dumps({"cmd": "key", "key": key})
) # send key command to server - you must implement this send in the AI agent
break
except websockets.exceptions.ConnectionClosedOK:
print("Server has cleanly disconnected us")
return
# Next line is not needed for AI agent
pygame.display.flip()
# 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())
loop.run_until_complete(agent_loop(f"{SERVER}:{PORT}", NAME))