Skip to content

Commit

Permalink
Correction of the pylint tests
Browse files Browse the repository at this point in the history
Why this change was necessary:

* Norms are important
* Camel case instead of dash
* for loops instead of enumerate
* change some file names
* import grouped and ordered correctly
* warning about spacing and hyphens
  • Loading branch information
Edouard360 committed Oct 6, 2017
1 parent fe1e101 commit 66c32a4
Show file tree
Hide file tree
Showing 31 changed files with 429 additions and 334 deletions.
2 changes: 1 addition & 1 deletion .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ enable=indexing-exception,old-raise-syntax
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W"
disable=design,similarities,no-self-use,attribute-defined-outside-init,locally-disabled,star-args,pointless-except,bad-option-value,global-statement,fixme,suppressed-message,useless-suppression,locally-enabled,no-member,no-name-in-module,import-error,unsubscriptable-object,unbalanced-tuple-unpacking,undefined-variable,not-context-manager
disable=invalid-unary-operand-type,design,similarities,no-self-use,attribute-defined-outside-init,locally-disabled,star-args,pointless-except,bad-option-value,global-statement,fixme,suppressed-message,useless-suppression,locally-enabled,no-member,no-name-in-module,import-error,unsubscriptable-object,unbalanced-tuple-unpacking,undefined-variable,not-context-manager


# Set the cache size for astng objects.
Expand Down
4 changes: 1 addition & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ install:
script:
# Tests
- python -m unittest discover -v
# Style checks
# Temporary workaround
- for i in `cat pylint_checks.txt` ; do pylint $i ;done
- find . -iname "*.py" | xargs pylint

# Coverage checks
- py.test --cov=train tests/
Expand Down
28 changes: 15 additions & 13 deletions networking/hlt_networking.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,40 @@
"""The HLT class to handle the connection"""
import socket

from public.hlt import GameMap, translate_cardinal


class HLT:
"""The HLT class to handle the connection"""
def __init__(self, port):
_connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
_connection.connect(('localhost', port))
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.connect(('localhost', port))
print('Connected to intermediary on port #' + str(port))
self._connection = _connection
self.connection = connection

def get_string(self):
newString = ""
new_string = ""
buffer = '\0'
while True:
buffer = self._connection.recv(1).decode('ascii')
buffer = self.connection.recv(1).decode('ascii')
if buffer != '\n':
newString += str(buffer)
new_string += str(buffer)
else:
return newString
return new_string

def sendString(self, s):
def send_string(self, s):
s += '\n'
self._connection.sendall(bytes(s, 'ascii'))
self.connection.sendall(bytes(s, 'ascii'))

def get_init(self):
myID = int(self.get_string())
my_id = int(self.get_string())
game_map = GameMap(self.get_string(), self.get_string(), self.get_string())
return myID, game_map
return my_id, game_map

def send_init(self, name):
self.sendString(name)
self.send_string(name)

def send_frame(self, moves):
self.sendString(' '.join(
self.send_string(' '.join(
str(move.square.x) + ' ' + str(move.square.y) + ' ' + str(translate_cardinal(move.direction)) for move in
moves))
57 changes: 27 additions & 30 deletions networking/pipe_socket_translator.py
Original file line number Diff line number Diff line change
@@ -1,62 +1,59 @@
"""
To be launched by the Halite program as an intermediary,
in order to enable a pipe player to join.
"""
import socket
import sys

# logging.basicConfig(filename='example.log', level=logging.DEBUG)

try:
# Connect
# logging.warning("connecting")
socket_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
socket_.bind(('localhost', int(sys.argv[1]))) # This is where the port is selected
socket_.listen(1)
connection, _ = socket_.accept()


# IO Functions
def sendStringPipe(toBeSent):
sys.stdout.write(toBeSent + '\n')
def send_string_pipe(to_be_sent):
sys.stdout.write(to_be_sent + '\n')
sys.stdout.flush()


def getStringPipe():
str = sys.stdin.readline().rstrip('\n')
return (str)
def get_string_pipe():
str_pipe = sys.stdin.readline().rstrip('\n')
return str_pipe


def sendStringSocket(toBeSent):
global connection
toBeSent += '\n'
connection.sendall(bytes(toBeSent, 'ascii'))
def send_string_socket(to_be_sent):
to_be_sent += '\n'
connection.sendall(bytes(to_be_sent, 'ascii'))


def getStringSocket():
global connection
newString = ""
def get_string_socket():
new_string = ""
buffer = '\0'
while True:
buffer = connection.recv(1).decode('ascii')
if buffer != '\n':
newString += str(buffer)
new_string += str(buffer)
else:
return newString
return new_string


while True:
# Handle Init IO
sendStringSocket(getStringPipe()) # Player ID
sendStringSocket(getStringPipe()) # Map Dimensions
sendStringSocket(getStringPipe()) # Productions
sendStringSocket(getStringPipe()) # Starting Map
sendStringPipe(getStringSocket()) # Player Name / Ready Response
send_string_socket(get_string_pipe()) # Player ID
send_string_socket(get_string_pipe()) # Map Dimensions
send_string_socket(get_string_pipe()) # Productions
send_string_socket(get_string_pipe()) # Starting Map
send_string_pipe(get_string_socket()) # Player Name / Ready Response

# Run Frame Loop
while (getStringPipe() == 'Get map and play!'): # while True:
sendStringSocket('Get map and play!')
sendStringSocket(getStringPipe()) # Frame Map
sendStringPipe(getStringSocket()) # Move List
sendStringSocket('Stop playing!')
while get_string_pipe() == 'Get map and play!': # while True:
send_string_socket('Get map and play!')
send_string_socket(get_string_pipe()) # Frame Map
send_string_pipe(get_string_socket()) # Move List
send_string_socket('Stop playing!')

except Exception as e:
except ConnectionError as e:
# logging.warning(traceback.format_exc())
pass
53 changes: 38 additions & 15 deletions networking/start_game.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
"""The start_game function to launch the halite.exe"""
import subprocess
import argparse
import os


def start_game(port=2000, width=10,height=10, max_strength=25, max_turn=25, max_game=1, silent_bool=True, timeout=True, quiet=True,
n_pipe_players=1, slave_players=[]):
def start_game(port=2000, width=10, height=10, max_strength=25, max_turn=25, max_game=1,
silent_bool=True, timeout=True, quiet=True,
n_pipe_players=1, slave_players=None):
"""
The start_game function to launch the halite.exe.
Execute with the -h option for help.
"""
path_to_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
for i in range(n_pipe_players):
subprocess.call([path_to_root + "/networking/kill.sh", str(port + i)]) # Free the necessary ports
Expand All @@ -24,7 +30,7 @@ def start_game(port=2000, width=10,height=10, max_strength=25, max_turn=25, max_
]
slave_players = [
"python3 " + path_to_root + "/public/" + slave_player + ' slave' for slave_player in slave_players
] # slave is the slave argument
] if slave_players is not None else [] # slave is the slave argument
players = pipe_players + slave_players
# "python3 " + path_to_root + "/networking/pipe_socket_translator.py " + str(port+1)
n_player = '' if len(players) > 1 else '-n 1 '
Expand All @@ -40,19 +46,36 @@ def start_game(port=2000, width=10,height=10, max_strength=25, max_turn=25, max_

if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--port", type=int, help="the port for the simulation - Useless if there are no pipe_players", default=2000)
parser.add_argument("-t", "--timeout", help="Doens't timeout if you set this flag is set", action="store_true", default=False)
parser.add_argument("-j", "--silent", help="Doesn't print *.hlt file", action="store_true", default=False)
parser.add_argument("-q", "--quiet", help="Doesn't output information to the console", action="store_true", default=False)
parser.add_argument("-s", "--strength", help="The max strength of the squares, if needed", type=int, default=25)
parser.add_argument("-dw", "--width", help="The width of the game", type=int, default=10)
parser.add_argument("-dh", "--height", help="The height of the game", type=int, default=10)
parser.add_argument("-m", "--maxturn", help="The total number of turns per game (maximum)", type=int, default=25)
parser.add_argument("-g", "--maxgame", help="The total number of games to play", type=int, default=1) # -1 for infinite game
parser.add_argument("-pp", "--n_pipe_players",help="The number of pipe players. You need to handle these players yourself. Each of them has a port assigned.", type=int, default=0)
parser.add_argument("-sp", "--slave_players", help="The slave players. Handled by the halite.exe. You should write one of these two strings: 'MyBot.py' or 'OpponentBot.py' (multiple time if desired) ",nargs='+', default=[])
parser.add_argument("-p", "--port", type=int,
help="the port for the simulation - Useless if there are no pipe_players",
default=2000)
parser.add_argument("-t", "--timeout", help="Doens't timeout if you set this flag is set",
action="store_true", default=False)
parser.add_argument("-j", "--silent", help="Doesn't print *.hlt file",
action="store_true", default=False)
parser.add_argument("-q", "--quiet", help="Doesn't output information to the console",
action="store_true", default=False)
parser.add_argument("-s", "--strength", help="The max strength of the squares, if needed",
type=int, default=25)
parser.add_argument("-dw", "--width", help="The width of the game",
type=int, default=10)
parser.add_argument("-dh", "--height", help="The height of the game",
type=int, default=10)
parser.add_argument("-m", "--maxturn", help="The total number of turns per game (maximum)",
type=int, default=25)
parser.add_argument("-g", "--maxgame", help="The total number of games to play",
type=int, default=1) # -1 for infinite game
parser.add_argument("-pp", "--n_pipe_players",
help="The number of pipe players. You need to handle these players yourself. "
"Each of them has a port assigned.",
type=int, default=0)
parser.add_argument("-sp", "--slave_players",
help="The slave players. Handled by the halite.exe. "
"You should write one of these two strings: "
"'MyBot.py' or 'OpponentBot.py' (multiple time if desired) ",
nargs='+', default=[])
args = parser.parse_args()
start_game(port=args.port, width=args.width,height=args.height, max_strength=args.strength, max_turn=args.maxturn,
start_game(port=args.port, width=args.width, height=args.height, max_strength=args.strength, max_turn=args.maxturn,
silent_bool=args.silent, timeout=args.timeout, max_game=args.maxgame, quiet=args.quiet,
n_pipe_players=args.n_pipe_players,
slave_players=args.slave_players)
24 changes: 13 additions & 11 deletions public/MyBot.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,29 @@
import sys
"""The MyBot.py file that executes the TrainedBot.py"""
import os
import sys

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
try:
from public.models.bot.TrainedBot import TrainedBot
from networking.hlt_networking import HLT
except:
raise

mode = 'server' if (len(sys.argv) == 1) else 'local'

if mode == 'server' or sys.argv[1]=='slave': # 'server' mode
if mode == 'server' or sys.argv[1] == 'slave': # 'server' mode
import hlt
else: # 'local' mode
import context

port = int(sys.argv[1]) if len(sys.argv) > 1 else 2000
hlt = context.HLT(port=port)

from public.models.bot.trainedBot import TrainedBot
hlt = HLT(port=port)

bot = TrainedBot()

while True:
myID, game_map = hlt.get_init()
my_id, game_map = hlt.get_init()
hlt.send_init("MyBot")
bot.setID(myID)
bot.set_id(my_id)

while (mode == 'server' or hlt.get_string() == 'Get map and play!'):
while mode == 'server' or hlt.get_string() == 'Get map and play!':
game_map.get_frame(hlt.get_string())
moves = bot.compute_moves(game_map)
hlt.send_frame(moves)
24 changes: 13 additions & 11 deletions public/OpponentBot.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,29 @@
import sys
"""The Opponent.py file that executes the ImprovedBot.py"""
import os
import sys

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
try:
from public.models.bot.ImprovedBot import ImprovedBot
from networking.hlt_networking import HLT
except:
raise

mode = 'server' if (len(sys.argv) == 1) else 'local'

if mode == 'server' or sys.argv[1]=='slave': # 'server' mode
if mode == 'server' or sys.argv[1] == 'slave': # 'server' mode
import hlt
else: # 'local' mode
import context

port = int(sys.argv[1]) if len(sys.argv) > 1 else 2000
hlt = context.HLT(port=port)

from public.models.bot.improvedBot import ImprovedBot
hlt = HLT(port=port)

bot = ImprovedBot()

while True:
myID, game_map = hlt.get_init()
my_id, game_map = hlt.get_init()
hlt.send_init("OpponentBot")
bot.setID(myID)
bot.set_id(my_id)

while (mode == 'server' or hlt.get_string() == 'Get map and play!'):
while mode == 'server' or hlt.get_string() == 'Get map and play!':
game_map.get_frame(hlt.get_string())
moves = bot.compute_moves(game_map)
hlt.send_frame(moves)
5 changes: 0 additions & 5 deletions public/context.py

This file was deleted.

17 changes: 11 additions & 6 deletions public/hlt.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
"""The original but corrected hlt.py file for communication with halite."""
import sys
from collections import namedtuple
from itertools import chain, zip_longest
Expand All @@ -24,6 +25,8 @@ def opposite_cardinal(direction):


class GameMap:
"""The GameMap on which to play."""

def __init__(self, size_string, production_string, map_string=None):
self.width, self.height = tuple(map(int, size_string.split()))
self.production = tuple(
Expand Down Expand Up @@ -57,12 +60,14 @@ def __iter__(self):
return chain.from_iterable(self.contents)

def neighbors(self, square, n=1, include_self=False):
"Iterable over the n-distance neighbors of a given square. For single-step neighbors, the enumeration index provides the direction associated with the neighbor."
"""Iterable over the n-distance neighbors of a given square.
For single-step neighbors, the enumeration index provides
the direction associated with the neighbor.
"""
assert isinstance(include_self, bool)
assert isinstance(n, int) and n > 0
if n == 1:
combos = ((0, -1), (1, 0), (0, 1), (-1, 0), (0,
0)) # NORTH, EAST, SOUTH, WEST, STILL ... matches indices provided by enumerate(game_map.neighbors(square))
combos = ((0, -1), (1, 0), (0, 1), (-1, 0), (0, 0))
else:
combos = ((dx, dy) for dy in range(-n, n + 1) for dx in range(-n, n + 1) if abs(dx) + abs(dy) <= n)
return (self.contents[(square.y + dy) % self.height][(square.x + dx) % self.width] for dx, dy in combos if
Expand Down Expand Up @@ -96,17 +101,17 @@ def get_string():


def get_init():
playerID = int(get_string())
player_id = int(get_string())
m = GameMap(get_string(), get_string())
return playerID, m
return player_id, m


def send_init(name):
send_string(name)


def translate_cardinal(direction):
"Translate direction constants used by this Python-based bot framework to that used by the official Halite game environment."
"Beware the direction are changed! Important for visualization"
return (direction + 1) % 5


Expand Down
Loading

0 comments on commit 66c32a4

Please sign in to comment.