-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEnvironment.py
98 lines (88 loc) · 3.84 KB
/
Environment.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import random
import math
import asyncio
import websockets
import requests
import json
import numpy as np
from State import State
class Environment:
def __init__(self):
self.game_name = None
self.state = None
self.username = None
async def connect(self):
uri = 'ws://sim.smogon.com:8000/showdown/websocket'
self.websocket = await websockets.connect(uri, ping_interval=None)
# wait for challstr
greeting = ''
while not greeting.startswith('|challstr|'):
greeting = await self.websocket.recv()
# print(f'<<< {greeting}')
# parse login request
f = open('user.txt','r')
usname = f.readline()
self.username = usname
passwd = f.readline()
header = {'Content-type': 'application/x-www-form-urlencoded; encoding=UTF-8'}
content = {'act': 'login', 'name': usname[:-1],'pass': passwd, 'challstr': greeting[10:]}
# send the login request
url = 'https://play.pokemonshowdown.com/~~showdown/action.php'
r = requests.post(url,data=content,headers=header)
s = json.loads(r.text[1:])
l = '|/trn ' + usname[0:-1] +',0,' + s['assertion']
# print(f'>>> {l}')
await self.websocket.send(l)
print('Done Connecting')
async def start_game(self, use_ladder = False, start_challenge = True, user = 'Ruang'):
if self.game_name:
print('Game already in progress')
return
await self.websocket.send('|/challenge {}, gen1randombattle'.format(user))
while True:
greeting = await self.websocket.recv()
print(f'<<< {greeting}')
if greeting.startswith('|updatesearch|'):
s = json.loads(greeting[14:])
if s['games']: # this will exist if there is a game going on
self.game_name = list(s['games'].keys())[0]
self.state = State()
break
receivedRequest = False
receivedChange = False
while True:
greeting = await self.websocket.recv()
# print(f'<<< {greeting}')
if greeting.startswith('>battle'):
lines = greeting.split('\n')[1:]
if lines[0].startswith('|request|') and lines[0] != '|request|': # request for move
self.state.updateSelf(json.loads(lines[0][9:]))
receivedRequest = True
elif lines[0] == '|' or '|start' in lines: # battle update
self.state.parseChange(lines,self.username.strip())
receivedChange = True
if receivedRequest and receivedChange:
return
async def make_move(self, move):
await self.websocket.send('{}|/choose {}'.format(self.game_name, move))
print('Chose {}'.format(move))
receivedRequest = False
receivedChange = False
while True:
greeting = await self.websocket.recv()
print(f'<<< {greeting}')
if greeting.startswith('>battle'):
lines = greeting.split('\n')[1:]
if lines[-1].startswith('|win|'):
print(self.username,greeting,lines[-1])
self.game_name = None
self.state = None
return 1 if self.username.strip() in lines[-1] else -1
if lines[0].startswith('|request|') and lines[0] != '|request|': # request for move
self.state.updateSelf(json.loads(lines[0][9:]))
receivedRequest = True
elif lines[0] == '|' or '|start' in lines: # battle update
self.state.parseChange(lines,self.username.strip())
receivedChange = True
if receivedRequest and receivedChange:
return 0