Skip to content

Commit 0fb0fcf

Browse files
committed
Delinted
1 parent 9c7f376 commit 0fb0fcf

16 files changed

+48
-42
lines changed

.pre-commit-config.yaml

+27
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,34 @@ repos:
99
- id: check-executables-have-shebangs
1010
- id: check-shebang-scripts-are-executable
1111
- id: end-of-file-fixer
12+
- repo: https://github.com/asottile/pyupgrade
13+
rev: v3.15.0
14+
hooks:
15+
- id: pyupgrade
16+
args:
17+
- "--py38-plus"
1218
- repo: https://github.com/psf/black-pre-commit-mirror
1319
rev: 23.12.1
1420
hooks:
1521
- id: black
22+
- repo: https://github.com/PyCQA/isort
23+
rev: 5.13.2
24+
hooks:
25+
- id: isort
26+
- repo: https://github.com/PyCQA/flake8
27+
rev: 6.1.0
28+
hooks:
29+
- id: flake8
30+
additional_dependencies:
31+
- flake8-absolute-import
32+
# - flake8-annotations
33+
- flake8-builtins
34+
- flake8-comprehensions
35+
# - flake8-docstrings
36+
- flake8-future-annotations
37+
- flake8-no-implicit-concat
38+
# - flake8-print
39+
# - flake8-requirements
40+
- flake8-simplify
41+
- flake8-use-fstring
42+
- flake8-use-pathlib

environments/logging.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import contextlib
12
import json
23
import logging
34
from datetime import datetime
@@ -47,10 +48,8 @@ def upload(self, log_file):
4748
oc = owncloud.Client(self.url)
4849
oc.login(self.user, self.password)
4950

50-
try: # Create folder
51+
with contextlib.suppress(owncloud.HTTPResponseError):
5152
oc.mkdir(self.remote_dir)
52-
except owncloud.HTTPResponseError:
53-
pass
5453

5554
oc.put_file(self.remote_dir + log_file.name, str(log_file))
5655

environments/spe_ed_env.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,9 @@ def render(self, mode="human", screen_width=720, screen_height=720):
5454
def _validate_action(self, action):
5555
"""Change illegal actions to do nothing"""
5656
controlled_player = self.players[0]
57-
if controlled_player.speed >= 10 and action == "speed_up":
58-
action = "change_nothing"
59-
elif controlled_player.speed <= 1 and action == "slow_down":
57+
if (controlled_player.speed >= 10 and action == "speed_up") or (
58+
controlled_player.speed <= 1 and action == "slow_down"
59+
):
6060
action = "change_nothing"
6161
return action
6262

environments/websocketenv.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ async def send_action(self, action):
9191
"""Wait for send action."""
9292
await self.websocket.send(json.dumps({"action": action}))
9393
elapsed_time = time.time() + self.time_limit - self.deadline
94-
logging.info(f"Client sent action {action}, took {elapsed_time:.02f}s ({elapsed_time/self.time_limit:.02%})")
94+
logging.info(f"Client sent action {action}, took {elapsed_time:.02f}s ({elapsed_time / self.time_limit:.02%})")
9595

9696
def game_state(self):
9797
"""Get current game state as dict."""
@@ -119,7 +119,7 @@ def measure_server_time(time_url="https://msoll.de/spe_ed_time", n_probes=10):
119119
datetime.strptime(data["time"], "%Y-%m-%dT%H:%M:%S%z") + timedelta(milliseconds=int(data["milliseconds"]))
120120
).timestamp()
121121
if last_server_time is not None:
122-
time_deltas.append((server_time - last_server_time))
122+
time_deltas.append(server_time - last_server_time)
123123

124124
time_offsets.append(now - server_time)
125125
last_server_time = server_time

heuristics/opponentdistance_heuristic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ def __init__(self, dist_threshold=16):
1313
def score(self, cells, player, opponents, rounds, deadline):
1414
"""Computes the distance to all players."""
1515
min_opponent_dist = min(
16-
min(np.sum(np.abs((player.position - o.position))) for o in opponents if o.active), self.dist_threshold
16+
min(np.sum(np.abs(player.position - o.position)) for o in opponents if o.active), self.dist_threshold
1717
)
1818
return min_opponent_dist / np.sum(cells.shape)
1919

policies/circle_policy.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ class CirclePolicy(Policy):
77
Baseline strategy, smarter policies should be able to outperform this.
88
"""
99

10-
def act(self, cells, player, opponents, round, deadline):
10+
def act(self, cells, player, opponents, rounds, deadline):
1111
"""Choose action."""
1212
# directions - relative to player direction
1313
forward = player.direction

policies/mazewalker_policy.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ def __init__(self):
1111
"""Initialize MazeWalkerPolicy."""
1212
self.hit_wall = False
1313

14-
def act(self, cells, player, opponents, round, deadline):
14+
def act(self, cells, player, opponents, rounds, deadline):
1515
"""Choose action."""
1616

1717
def is_free(pos):

policies/policy.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@ class Policy(ABC):
77
"""Abstract base class for all policies."""
88

99
@abstractmethod
10-
def act(self, cells, you, opponents, rounds, deadline):
10+
def act(self, cells, player, opponents, rounds, deadline):
1111
"""Produce an action for a given game state.
1212
1313
Args:
1414
cells: binary ndarray of cell occupancies.
15-
you: Controlled player
15+
player: Controlled player
1616
opponents: List of other active players
1717
rounds: Number of this round. Starts with 1, thus `rounds % 6 == 0` indicates a jump.
1818
deadline: A deadline after which the policy must return immediately.

policies/random_policy.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,7 @@ def act(self, cells, player, opponents, rounds, deadline):
3030
action = self.rng.choice(actions, p=self.p)
3131

3232
# Check for illegal actions
33-
if player.speed >= 10 and action == "speed_up":
34-
action = "change_nothing"
35-
elif player.speed <= 1 and action == "slow_down":
33+
if (player.speed >= 10 and action == "speed_up") or (player.speed <= 1 and action == "slow_down"):
3634
action = "change_nothing"
3735

3836
return action

policies/spiral_policy.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ def __init__(self):
1111
"""Initialize MazeWalkerPolicy."""
1212
self.clockwise = True
1313

14-
def act(self, cells, player, opponents, round, deadline):
14+
def act(self, cells, player, opponents, rounds, deadline):
1515
"""Choose action."""
1616
# directions - relative to player direction
1717
forward = player.direction

setup.cfg

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[flake8]
2-
ignore = E265,E741,W504,D100
2+
ignore = E203,E741,W503,D100,D104,D105,PL123,ANN101,ANN102
33
max-line-length = 120
44
docstring-convention = google
55

statistics/stats.py

-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
from pathlib import Path
33
from statistics.log_files import get_log_files
44

5-
import numpy as np
65
import pandas as pd
76
from tqdm import tqdm
87

tests/websocket_test.py

+2-16
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,17 @@
11
import asyncio
22
import json
3-
import threading
43
import unittest
54

65
import websockets
76

8-
from environments import WebsocketEnv
9-
107

118
class DummyServer:
129
def __init__(self, url, port):
1310
self.url = url
1411
self.port = port
1512
self.step_counter = 0
16-
file = open("tests/spe_ed-1603124417603.json", "r")
17-
self.states = json.load(file)
18-
file.close()
13+
with open("tests/spe_ed-1603124417603.json") as file:
14+
self.states = json.load(file)
1915
# Start new thread from current loop
2016
self.__serving = asyncio.get_event_loop().run_in_executor(None, self.run)
2117
self.__starting = asyncio.get_event_loop().create_future()
@@ -54,7 +50,6 @@ def run(self): # Executed in new thread
5450
self.__starting.get_loop().call_soon_threadsafe(self.__starting.set_result, None)
5551

5652
loop.run_until_complete(self.serve()) # Run serve in loop until stopped
57-
# threading.Thread(target=loop.run_forever).start()
5853
loop.close()
5954
print("Server stopped")
6055

@@ -76,12 +71,3 @@ def setUp(self):
7671
def tearDown(self):
7772
print("Stop")
7873
self.server.stop()
79-
80-
# def test_connection(self):
81-
# env = WebsocketEnv(f"ws://{self.url}:{self.port}", self.key)
82-
# obs = env.reset()
83-
# done = False
84-
# while not done:
85-
# action = "change_nothing"
86-
# obs, reward, done, _ = env.step(action)
87-
# print(done)

tool_render_opponent_overview.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,13 @@ def easeOutCubic(t):
2020

2121
def names_to_codes(names):
2222
code_map = {}
23-
id = 0
23+
name_id = 0
2424

2525
codes = []
2626
for name in names:
2727
if name not in code_map:
28-
code_map[name] = id
29-
id += 1
28+
code_map[name] = name_id
29+
name_id += 1
3030

3131
codes.append(code_map[name])
3232

tournament/tournament_config.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from policies import RandomPolicy, SpiralPolicy, load_named_policy
1+
from policies import SpiralPolicy, load_named_policy
22

33
# participating policies with short nick names
44
policies = [

visualization/axes.py

-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
1-
import matplotlib.pyplot as plt
21
import numpy as np
32
import pandas as pd
43
from matplotlib.colors import ListedColormap
5-
from matplotlib.dates import AutoDateLocator
64

75
player_colors = [
86
(204.0 / 255, 7.0 / 255, 30.0 / 255, 1.0), # Player 1 - red
@@ -66,6 +64,5 @@ def __init__(self, fig, ax, date, won, groupby="D"):
6664
(line,) = ax.plot(date, mean, label="win rate", c=player_colors[0])
6765
c = line.get_color()
6866
ax.fill_between(date, low, high, facecolor=c, alpha=0.25, interpolate=True, label="confidence interval")
69-
# ax.xaxis.set_major_locator(AutoDateLocator(maxticks=6))
7067
ax.set_xlim(date[0], date[-1] + pd.offsets.Day(1))
7168
ax.set_ylim(0, 1)

0 commit comments

Comments
 (0)