Skip to content

Commit

Permalink
Cleaning up python code. (RLBot#335)
Browse files Browse the repository at this point in the history
* Cleaning up python files.

* Move python version check to rlbot.runner

* Consistent f-string usage.

* Remove duplicated code.
  • Loading branch information
RLMarvin authored and tarehart committed Jan 4, 2019
1 parent f463c2b commit 4b8dc89
Show file tree
Hide file tree
Showing 41 changed files with 251 additions and 168 deletions.
5 changes: 2 additions & 3 deletions runner.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import sys
import os.path
sys.path.insert(0, os.path.realpath(os.path.dirname(os.path.abspath(__file__)) + '/src/main/python/'))
from rlbot.utils import python_version_check
from rlbot import runner as framework_runner

if __name__ == '__main__':
framework_runner.main()

from rlbot import runner as framework_runner

framework_runner.main()
1 change: 0 additions & 1 deletion src/main/python/rlbot/agents/base_agent.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import flatbuffers
from rlbot.botmanager.helper_process_request import HelperProcessRequest
from rlbot.parsing.custom_config import ConfigObject, ConfigHeader
from rlbot.utils.game_state_util import GameState
Expand Down
17 changes: 8 additions & 9 deletions src/main/python/rlbot/agents/base_dotnet_agent.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import os
import msvcrt
import socket
import time

Expand All @@ -21,8 +20,7 @@ def __init__(self, name, team, index):
def run_independently(self, terminate_request_event):

while not terminate_request_event.is_set():
message = "add\n{0}\n{1}\n{2}\n{3}".format(self.name, self.team, self.index, game_interface.get_dll_directory())

message = f"add\n{self.name}\n{self.team,}\n{self.index}\n{game_interface.get_dll_directory()}"
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", self.port))
Expand Down Expand Up @@ -52,20 +50,21 @@ def get_extra_pids(self):
for proc in psutil.process_iter():
for conn in proc.connections():
if conn.laddr.port == self.port:
self.logger.debug('.NET socket server for {} appears to have pid {}'.format(self.name, proc.pid))
self.logger.debug(f".NET socket server for {self.name} appears to have pid {proc.pid}")
return [proc.pid]
if self.is_executable_configured():
return []
time.sleep(1)
if self.dotnet_executable_path is None:
self.logger.info(
"Can't auto-start .NET executable because no executable is configured. Please start the .NET bot manually!")
self.logger.info("Can't auto-start .NET executable because no executable is configured. "
"Please start the .NET bot manually!")
else:
self.logger.info("Can't auto-start .NET executable because {} is not found. Please start the .NET bot manually!".format(self.dotnet_executable_path))
self.logger.info(f"Can't auto-start .NET executable because {self.dotnet_executable_path} "
"is not found. Please start the .NET bot manually!")

def retire(self):
port = self.read_port_from_file()
message = "remove\n{0}".format(self.index)
message = f"remove\n{self.index}"

try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Expand All @@ -75,7 +74,7 @@ def retire(self):
except ConnectionRefusedError:
self.logger.warn("Could not connect to server!")
self.is_retired = True

def read_port_from_file(self):
try:
location = self.get_port_file_path()
Expand Down
8 changes: 3 additions & 5 deletions src/main/python/rlbot/agents/base_java_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@
import psutil
from py4j.java_gateway import GatewayParameters
from py4j.java_gateway import JavaGateway
from rlbot.agents.base_agent import BOT_CONFIG_AGENT_HEADER, BOT_CONFIG_MODULE_HEADER

from rlbot.agents.base_independent_agent import BaseIndependentAgent
from rlbot.botmanager.helper_process_request import HelperProcessRequest
from rlbot.parsing.custom_config import ConfigHeader, ConfigObject
from rlbot.utils.logging_utils import get_logger
from rlbot.utils.structures import game_interface

Expand Down Expand Up @@ -69,7 +67,7 @@ def get_extra_pids(self):
for proc in psutil.process_iter():
for conn in proc.connections():
if conn.laddr.port == self.port:
self.logger.debug('py4j server for {} appears to have pid {}'.format(self.name, proc.pid))
self.logger.debug(f'py4j server for {self.name} appears to have pid {proc.pid}')
return [proc.pid]
if self.is_executable_configured():
# The helper process will start java and report the PID. Nothing to do here.
Expand All @@ -79,8 +77,8 @@ def get_extra_pids(self):
self.logger.info(
"Can't auto-start java because no executable is configured. Please start java manually!")
else:
self.logger.info("Can't auto-start java because {} is not found. Please start java manually!"
.format(self.java_executable_path))
self.logger.info(f"Can't auto-start java because {self.java_executable_path} is not found. "
"Please start java manually!")

def retire(self):
try:
Expand Down
32 changes: 22 additions & 10 deletions src/main/python/rlbot/agents/human/controller_input.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from inputs import get_gamepad # pip install inputs
import threading


def deadzone(normalized_axis):
if abs(normalized_axis) < 0.1: return 0.0
if abs(normalized_axis) < 0.1:
return 0.0
return normalized_axis


class ControllerInput:
def __init__(self):
# self.throttle = 0.0
Expand All @@ -28,15 +31,24 @@ def main_poll_loop(self):
events = get_gamepad() # Blocking
for event in events:
# print(repr((event.ev_type, event.code, event.state)))
if False: pass
elif event.ev_type=='Absolute' and event.code=='ABS_RZ': self._gas_pedal = deadzone(event.state / 255.0)
elif event.ev_type=='Absolute' and event.code=='ABS_Z': self._brake_pedal = deadzone(event.state / 255.0)
elif event.ev_type=='Absolute' and event.code=='ABS_X': self.steer = self.yaw = deadzone(event.state / 32768.0)
elif event.ev_type=='Absolute' and event.code=='ABS_Y': self.pitch = deadzone(-event.state / 32768.0)
elif event.ev_type=='Key' and event.code=='BTN_THUMBL': self.roll = -event.state
elif event.ev_type=='Key' and event.code=='BTN_SOUTH': self.jump = event.state
elif event.ev_type=='Key' and event.code=='BTN_TR': self.boost = event.state
elif event.ev_type=='Key' and event.code=='BTN_WEST': self.handbrake = event.state
if False:
pass
elif event.ev_type == 'Absolute' and event.code == 'ABS_RZ':
self._gas_pedal = deadzone(event.state / 255.0)
elif event.ev_type == 'Absolute' and event.code == 'ABS_Z':
self._brake_pedal = deadzone(event.state / 255.0)
elif event.ev_type == 'Absolute' and event.code == 'ABS_X':
self.steer = self.yaw = deadzone(event.state / 32768.0)
elif event.ev_type == 'Absolute' and event.code == 'ABS_Y':
self.pitch = deadzone(-event.state / 32768.0)
elif event.ev_type == 'Key' and event.code == 'BTN_THUMBL':
self.roll = -event.state
elif event.ev_type == 'Key' and event.code == 'BTN_SOUTH':
self.jump = event.state
elif event.ev_type == 'Key' and event.code == 'BTN_TR':
self.boost = event.state
elif event.ev_type == 'Key' and event.code == 'BTN_WEST':
self.handbrake = event.state


controller = ControllerInput()
Expand Down
2 changes: 1 addition & 1 deletion src/main/python/rlbot/botmanager/bot_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ def run(self):
last_module_modification_time = new_module_modification_time
agent, agent_class_file = self.reload_agent(agent, agent_class_file)
except FileNotFoundError:
self.logger.error("Agent file {} was not found. Will try again.".format(agent_class_file))
self.logger.error(f"Agent file {agent_class_file} was not found. Will try again.")
time.sleep(0.5)
except Exception:
self.logger.error("Reloading the agent failed:\n" + traceback.format_exc())
Expand Down
2 changes: 1 addition & 1 deletion src/main/python/rlbot/botmanager/bot_manager_flatbuffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def call_agent(self, agent, agent_class):
agent.set_flatbuffer_binary(self.game_tick_flat_binary)
player_input = agent.get_output_flatbuffer(self.game_tick_flat)
if not player_input:
raise Exception('Agent "{}" did not return a player input.'.format(agent_class.__name__))
raise Exception(f'Agent "{agent_class.__name__}" did not return a player input.')

self.game_interface.update_player_input_flat(player_input)

Expand Down
3 changes: 2 additions & 1 deletion src/main/python/rlbot/botmanager/bot_manager_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ def prepare_for_run(self):
# Set up shared memory map (offset makes it so bot only writes to its own input!) and map to buffer
self.bot_input = PlayerInput()
# Set up shared memory for game data
self.game_tick_packet = gd.GameTickPacket() # We want to do a deep copy for game inputs so people don't mess with em
# We want to do a deep copy for game inputs so people don't mess with em
self.game_tick_packet = gd.GameTickPacket()
# Set up shared memory for Ball prediction
self.ball_prediction = bp.BallPrediction()
# Set up shared memory for rigid body tick
Expand Down
2 changes: 1 addition & 1 deletion src/main/python/rlbot/gui/gui_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def get_agent_preset(self):

def get_agent_config_path(self):
return os.path.realpath(self.overall_config.getpath(PARTICIPANT_CONFIGURATION_HEADER,
PARTICIPANT_CONFIG_KEY, self.overall_index))
PARTICIPANT_CONFIG_KEY, self.overall_index))

def set_agent_config_path(self, config_path: str):
self.overall_config.set_value(PARTICIPANT_CONFIGURATION_HEADER, PARTICIPANT_CONFIG_KEY,
Expand Down
1 change: 1 addition & 0 deletions src/main/python/rlbot/gui/index_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ class IndexManager:
"""
Handles the indices for agents, some useful methods for handling the overall indices
"""

def __init__(self, size):
self.numbers = set()
self.size = size
Expand Down
4 changes: 2 additions & 2 deletions src/main/python/rlbot/gui/mutator_editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def create_linking_dicts(self):

self.mutator_widget_to_config_name = {}
for config_name, widget in self.config_name_to_mutator_widget.items():
self.mutator_widget_to_config_name[widget] = config_name
self.mutator_widget_to_config_name[widget] = config_name

self.config_name_to_options_list = {
MUTATOR_MATCH_LENGTH: match_length_types,
Expand All @@ -85,4 +85,4 @@ def create_linking_dicts(self):
MUTATOR_GRAVITY: gravity_mutator_types,
MUTATOR_DEMOLISH: demolish_mutator_types,
MUTATOR_RESPAWN_TIME: respawn_time_mutator_types
}
}
4 changes: 2 additions & 2 deletions src/main/python/rlbot/gui/preset_editors.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,6 @@ def add_new_preset(self):
if list_item.data(Qt.UserRole) == preset:
self.presets_listwidget.setCurrentRow(i)


def load_preset_cfg(self):
file_path = QtWidgets.QFileDialog.getOpenFileName(self, 'Load Config', '', 'Config Files (*.cfg)')[0]
if not os.path.isfile(file_path):
Expand Down Expand Up @@ -170,7 +169,7 @@ def save_preset_cfg(self, time_out=0):
else:
preset.save_config(time_out=time_out, message_out=self.statusbar.showMessage)

def validate_name(self, name, preset, copy_index = None):
def validate_name(self, name, preset, copy_index=None):

value = name
if copy_index is not None:
Expand Down Expand Up @@ -198,6 +197,7 @@ class CarCustomisationDialog(BasePresetEditor, Ui_LoadoutPresetCustomiser):
"""
The class extending BasePresetEditor to allow some loadout preset specific preset editing, like handling item names
"""

def __init__(self, qt_gui):
super().__init__(qt_gui, qt_gui.loadout_presets, qt_gui.loadout_preset_combobox, LoadoutPreset)

Expand Down
8 changes: 6 additions & 2 deletions src/main/python/rlbot/gui/presets.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class Preset:
"""
Stores a config, the config path, a preset name and has methods to save/load the preset
"""

def __init__(self, config, file_path, name):
self.config = config
self.config_path = file_path
Expand Down Expand Up @@ -72,6 +73,7 @@ class LoadoutPreset(Preset):
"""
A class extending Preset to handle a LoadoutPreset, which is based on the looks configurations file
"""

def __init__(self, name, file_path=None):
super().__init__(BaseAgent._create_looks_configurations(), file_path, name)

Expand All @@ -81,8 +83,10 @@ def get_required_sections(self):

class AgentPreset(Preset):
"""
A class extending Preset to handle an AgentPreset, which is based on the agent configuration file and which also contains the Agent class
A class extending Preset to handle an AgentPreset
which is based on the agent configuration file and which also contains the Agent class
"""

def __init__(self, name, file_path=None):

self.looks_path = None
Expand All @@ -98,7 +102,7 @@ def __init__(self, name, file_path=None):
try:
self.agent_class = import_agent(python_file_path).get_loaded_class()
except (ValueError, ModuleNotFoundError, FileNotFoundError) as e:
raise ValueError("Problem when processing {}: {}".format(file_path, str(e)))
raise ValueError(f"Problem when processing {file_path}: {str(e)}")

super().__init__(self.agent_class.base_create_agent_configurations(), file_path, name)
# Make sure the path to the python file actually gets set to that path, even if there was no config at file_path
Expand Down
Loading

0 comments on commit 4b8dc89

Please sign in to comment.