Skip to content

Instantly share code, notes, and snippets.

@lidavidm
Created December 29, 2017 21:46
Show Gist options
  • Save lidavidm/2611852878d92e252fa875d4c54efc46 to your computer and use it in GitHub Desktop.
Save lidavidm/2611852878d92e252fa875d4c54efc46 to your computer and use it in GitHub Desktop.
Halite II remote debugging
import socket
import sys
# Connect
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind(('localhost', int(sys.argv[1])))
socket.listen(1)
connection, _ = socket.accept()
# IO Functions
def sendStringPipe(toBeSent):
sys.stdout.write(toBeSent+'\n')
sys.stdout.flush()
def getStringPipe():
s = sys.stdin.readline().rstrip('\n')
return(s)
def sendStringSocket(toBeSent):
global connection
toBeSent += '\n'
connection.sendall(bytes(toBeSent, 'ascii'))
def getStringSocket():
global connection
newString = ""
buf = '\0'
while True:
buf = connection.recv(1).decode('ascii')
if buf != '\n':
newString += str(buf)
else:
return newString
# Handle Init IO
sendStringSocket(getStringPipe()) # Player ID
sendStringSocket(getStringPipe()) # Map Dimensions
sendStringSocket(getStringPipe()) # Starting map
sendStringPipe(getStringSocket()) # Player Name / Ready Response
# Run Frame Loop
while True:
sendStringSocket(getStringPipe()) # Frame Map
sendStringPipe(getStringSocket()) # Move List
import socket
import sys
import hlt
class Game(hlt.Game):
def __init__(self, *args, **kwargs):
self._buf = []
self._connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = int(input("Enter the port on which to connect: "))
self._connection.connect(("localhost", port))
print("Connected to intermediary on port #", port)
super().__init__(*args, **kwargs)
def _send_string(self, s):
"""
Send data to the game. Call :function:`done_sending` once finished.
:param str s: String to send
:return: nothing
"""
self._buf.append(s)
def _done_sending(self):
"""
Finish sending commands to the game.
:return: nothing
"""
self._connection.sendall((''.join(self._buf) + "\n").encode("ascii"))
self._buf.clear()
def _get_string(self):
"""
Read input from the game.
:return: The input read from the Halite engine
:rtype: str
"""
buf = []
while True:
c = self._connection.recv(1).decode("ascii")
if c == "\n" or not c:
break
else:
buf.append(c)
if not c:
sys.exit()
return "".join(buf)
def send_command_queue(self, command_queue):
"""
Issue the given list of commands.
:param list[str] command_queue: List of commands to send the Halite engine
:return: nothing
"""
for command in command_queue:
self._send_string(command)
self._done_sending()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment