Skip to content

Instantly share code, notes, and snippets.

@nuqz
Last active September 16, 2018 00:45
Show Gist options
  • Save nuqz/8a36bddae4e415586b80609d904bf9e6 to your computer and use it in GitHub Desktop.
Save nuqz/8a36bddae4e415586b80609d904bf9e6 to your computer and use it in GitHub Desktop.
import io
import json
from socket import socket, AF_INET, SOCK_STREAM
class SocketIO(io.RawIOBase):
def __init__(self, sock):
self.sock = sock
def read(self, sz=-1):
if (sz == -1): sz=0x7FFFFFFF
return self.sock.recv(sz)
def seekable(self):
return False
class TcpClient:
def __init__(self, addr=('127.0.0.1', 8000)):
self.host, self.port = addr
self.sock = None
self.buf = None
def new_game(self, solution_id):
self.sock = socket(AF_INET, SOCK_STREAM)
self.sock.connect((self.host, self.port))
self.sock.settimeout(5)
self.buf = SocketIO(self.sock)
return self.sock.sendall(json.dumps({"solution_id": solution_id}) + '\n')
def tick(self):
if self.buf is None: return None
return json.loads(self.buf.readline().decode('utf-8'))
def command(self, command, debug=None):
if self.sock is None: return None
return self.sock.sendall(json.dumps({ "command": command,
"debug": debug }) + '\n')
def end_game(self):
self.sock.close()
self.buf = None
self.sock = None
if __name__ == '__main__':
c = TcpClient()
c.new_game(12345)
while True:
try:
data = c.tick()
c.command("right")
except ValueError:
c.end_game()
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment