Compare commits

..

14 Commits

3 changed files with 197 additions and 97 deletions

View File

@ -1,10 +1,11 @@
{
"expansions":
{
"ShockColar1": {"players": ["Brosef"], "tags": ["shock"], "config": {"COM_port": "COM3", "shocker_ID": 24770}},
"RobotBarman": {"players": ["Tango", "TRS_MML"], "tags": ["drink"], "config": {}},
"ChallengeDB": {"players": ["TRS_MML"], "tags": ["challenge"], "config": {}},
"SourCandy": {"players": [], "tags": ["food"], "config": {}}
"ShockColar1": {"players": ["Brosef"], "tags": ["shock"], "class": "serialShocker", "config": {"COM_port": "COM3", "shocker_ID": 24770}},
"RobotBarman": {"players": ["Tango", "TRS_MML"], "tags": ["drink"], "class": "bar", "config": {}},
"ChallengeDB": {"players": ["TRS_MML"], "tags": ["challenge"], "class": "challenge", "config": {}},
"SourCandy": {"players": [], "tags": ["food"], "class": "candy", "config": {}},
"Simple": {"players": ["Brosef"], "tags": [], "class": "simplest", "config": {}}
},
"players": {
"Brosef": {"flags": [], "expansions": {"exampleExpansion": {"playerOption": 5}}, "gamesSave": {"gameID0": 2}},

View File

@ -6,7 +6,7 @@ import copy
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from NoPELib.player_settings import ExpansionsManager
from .player_settings import ExpansionsManager
class Hook:
@ -36,53 +36,69 @@ class Expansion:
Attributes:
players (tuple of str):
tags (tuple of flag):
config: The config of the expansion. Can't be modified during execution.
Methods:
__call__: Execute a given action with the expansion
Subclass methods:
step:
reset:
close:
Signals:
onError:
midStepError:
"""
def __init__(self, ID: str, expansionsManager):
"""
Initialise the creation of an expansion and raise an error if not
available.
"""
def __init__(self, ID: str, expansionsManager: "ExpansionsManager"):
self._ID = ID
self._closed = False
self._manager = expansionsManager
self.onError = Hook()
self.midStepError = Hook()
self.midStepError.connect(expansionsManager._midStepError)
def __call__(self, action):
try:
assert not self._closed, "Can't use an expansion that has been closed."
return self.step(action)
except Exception as e:
step_info = {
"expansionID": self._ID,
"showOnScreen": None,
"error": e,
"done": False
}
self.midStepError(self._ID)
return step_info
@property
def config(self):
"""
The config of the expansion.
Can't be modified during execution.
"""
return copy.deepcopy(self._manager.config[self._ID]["config"])
@property
def players(self):
""" Players that have access to this expansion. """
""" Players that have access to the expansion. """
return self._manager.config[self._ID]["players"]
@players.setter
def players(self, newPlayers):
""" Players that have access to this expansion. """
self._manager.config[self._ID]["players"] = tuple(newPlayers)
self._manager.expansionPlayersChanged(self._ID)
self._manager.expansionPlayersChange(self._ID, newPlayers)
@players.deleter
def players(self):
self._manager.config[self._ID]["players"] = ()
self._manager.expansionPlayersChanged(self._ID)
self._manager.expansionPlayersChange(self._ID, ())
@property
def tags(self):
""" Players that have access to this expansion. """
""" Tags of the expansion. """
return self._manager.config[self._ID]["tags"]
@tags.setter
def tags(self, newPlayers):
""" Players that have access to this expansion. """
self._manager.config[self._ID]["tags"] = tuple(newPlayers)
@tags.deleter
@ -91,9 +107,6 @@ class Expansion:
@abc.abstractmethod
def step(self, action):
"""
Call close if an error is thrown
"""
raise NotImplementedError
@abc.abstractmethod
@ -117,12 +130,12 @@ class serialShocker(Expansion):
super().__init__(ID, expansionsManager)
if self.config["COM_port"] not in serialShocker._api:
self._assignApi()
self.shocker = serialShocker._api[self.config["COM_port"]].shocker(["shocker_ID"])
self.shocker = serialShocker._api[self.config["COM_port"]].shocker(self.config["shocker_ID"])
def _assignApi(self):
from pishock import SerialAPI
serialShocker._api[self.config["COM_port"]] = SerialAPI(self.config["COM_port"])
def step(self, action):
"""
Arguments:
@ -131,15 +144,22 @@ class serialShocker(Expansion):
a positive float that defines the duration
a float within the range [0.0, 1.0] that defines the intensity
"""
# Execute the step
vibrateInstead, duration, intensity = action
if vibrateInstead:
self.shocker.vibrate(duration=duration, intensity=intensity)
else:
self.shocker.shock(duration=duration, intensity=intensity)
callFunc = self.shocker.vibrate if vibrateInstead else self.shocker.shock
callFunc(duration=duration, intensity=intensity)
# Return additionnal info
step_info = {
"expansionID": self._ID,
"showOnScreen": None,
"error": None,
"done": True
}
return step_info
def close(self):
pass
def reset(self):
if self.config["COM_port"] not in serialShocker._api:
serialShocker._api[self.config["COM_port"]].restart()
@ -161,12 +181,20 @@ class simplest(Expansion):
a positive float that defines the duration
a float within the range [0.0, 1.0] that defines the intensity
"""
# Execute the step
vibrateInstead, duration, intensity = action
values = f"duration={duration}, intensity={intensity}"
if vibrateInstead:
print(f"Vibrate with {values}")
else:
print(f"Shock with {values}")
interact_type = "Vibrate" if vibrateInstead else "Shock"
message = f"{interact_type} with {values}"
print(message)
# Return additionnal info
step_info = {
"expansionID": self._ID,
"showOnScreen": message,
"error": None,
"done": True
}
return step_info
def close(self):
print("Closing")

View File

@ -6,7 +6,7 @@ import copy
import json
import logging
from pathlib import Path
import NoPELib.expansionsLib as expansionsLib
from . import expansionsLib
_log = logging.getLogger('NoPE-Lib')
@ -227,58 +227,51 @@ class Player:
"games": self._gamesSave
}
def punish(self, value, preferedExpansion: str=None):
do_something = lambda value, preferedExpansion: value
additionalInfos = {
"expansionID": "challengeDB",
"balancedValue": 0.2,
"showOnScreen": "Do 100 push-up",
"error": None,
"done": False
}
# NOTE Make a result class instead and an error class
# TODO Implement a way to choose between the available expansions
additionalInfos = do_something(value, preferedExpansion)
return additionalInfos
class ExpansionsManager:
"""
Manager of the availability of the expansions.
Attributes:
includedExpansions: tuple of str
includeExpansions: tuple of str
Container of the expansions to try making available
activeExpansions: dict of Expansion
Container of the relevent expansions
Methods:
expansionPlayersChange: Change the assigned players of an expansion
lookupPlayer: Provide a list of expansion available to a player
"""
defaultExpansionConfig = {"players": (), "types": ()}
keysConvert2Tuple = ("players", "types")
keysConvert2Tuple = ("players", "tags")
tags = ["shock", "spice", "sour", "drink", "challenge"]
# (attributed players / types)
# TODO Allow to get a list of expansions with a specific tag/player
def __init__(self, playersManager: PlayersManager, includedExpansions: tuple[str]=None):
def __init__(self, playersManager: PlayersManager, includeExpansions: tuple[str]=None):
"""
Arguments:
tryInclude: bool=False, tryActivate: bool=False
"""
# Create the attributes
self.playersManager = playersManager
self._playersLookUp = {}
self._cfg = playersManager.config["expansions"]
if includedExpansions is not None:
self._includedExpansions = tuple(includedExpansions)
if includeExpansions is not None:
self._includeExpansions = tuple(includeExpansions)
else:
self._includedExpansions = ()
self._includeExpansions = ()
# Convert the required lists into tuples
for expansionID in self._cfg["expansions"]:
for expansionID in self._cfg:
for key in self.keysConvert2Tuple:
converted = tuple(self._cfg["expansions"][expansionID][key])
self._cfg["expansions"][expansionID][key] = converted
converted = tuple(self._cfg[expansionID][key])
self._cfg[expansionID][key] = converted
# Compute the active expansions
self._activeExpansions = {}
for expansionID in self._listPossiblyValidExpansions():
self._createExpansion(expansionID)
creation_out = self._createExpansion(expansionID)
if isinstance(creation_out, expansionsLib.Expansion):
self._activeExpansions[expansionID] = creation_out
else:
raise creation_out
# Connect the signals to the slots
playersManager.onMadePlayerActive.connect(self._activePlayerAdded)
@ -297,18 +290,18 @@ class ExpansionsManager:
return f"ExpansionsManager has {len(self._activeExpansions)} active expansions"
@property
def includedExpansions(self):
def includeExpansions(self):
""" Dictionnary of the included expansions. """
return self._includedExpansions
return self._includeExpansions
@includedExpansions.setter
def includedExpansions(self, newIncluded: tuple[str]):
self._includedExpansions = tuple(newIncluded)
@includeExpansions.setter
def includeExpansions(self, newIncluded: tuple[str]):
self._includeExpansions = tuple(newIncluded)
self._includeChanged()
@includedExpansions.deleter
def includedExpansions(self):
self._includedExpansions = ()
@includeExpansions.deleter
def includeExpansions(self):
self._includeExpansions = ()
@property
def config(self):
@ -316,33 +309,50 @@ class ExpansionsManager:
return self._cfg
def _getPlayersFillMissing(self, expansionID):
return set(self._cfg["expansions"].get(expansionID, {}).get("players", []))
return set(self._cfg.get(expansionID, {}).get("players", []))
def _getClassFillMissing(self, expansionID):
return self._cfg.get(expansionID, {}).get("class", "")
def _listPossiblyValidExpansions(self):
"""
List expansions that are included, defined in expansionsLib and are available
List expansions that are: included, defined in expansionsLib and available
to at least one active player.
"""
activePlayers = set(self.playersManager.keys())
possiblyValidExpansions = [
expansionID for expansionID in self._includedExpansions
if hasattr(expansionsLib, expansionID) and
expansionID for expansionID in self._includeExpansions
if hasattr(expansionsLib, self._getClassFillMissing(expansionID)) and
not self._getPlayersFillMissing(expansionID).isdisjoint(activePlayers)
]
return possiblyValidExpansions
def _createExpansion(self, expansionID):
terminalErrors = SystemExit, KeyboardInterrupt, GeneratorExit
try:
expansion = getattr(expansionsLib, expansionID)(expansionID, self)
except:
pass
else:
self._activeExpansions[expansionID] = expansion
# Create the expansion
expansionClass = self._getClassFillMissing(expansionID)
class_to_create = getattr(expansionsLib, expansionClass)
expansion = class_to_create(expansionID, self)
# Update the lookup
for player in self._getPlayersFillMissing(expansionID):
if player in self._playersLookUp:
self._playersLookUp[player].append(expansionID)
else:
self._playersLookUp[player] = [expansionID]
return expansion
except terminalErrors as e:
raise e
except Exception as e:
return e
def _removeExpansion(self, expansionID):
# Update the lookup
for player in self._getPlayersFillMissing(expansionID):
self._playersLookUp[player].pop(expansionID)
# Remove the expansion
expansion = self._activeExpansions.pop(expansionID)
expansion.close()
del expansion
def _includeChanged(self):
"""
@ -351,7 +361,7 @@ class ExpansionsManager:
# Compute the expansions involved in the modification
possiblyValidExpansions = set(self._listPossiblyValidExpansions())
previousExpansions = set(self._includedExpansions)
previousExpansions = set(self._includeExpansions)
# Remove irrelevant expansions
expansionsToRemove = previousExpansions.difference(possiblyValidExpansions)
for expansionID in expansionsToRemove:
@ -359,19 +369,27 @@ class ExpansionsManager:
# Add the new expansions
expansionsToAdd = possiblyValidExpansions.difference(previousExpansions)
for expansionID in expansionsToAdd:
self._createExpansion(expansionID)
creation_out = self._createExpansion(expansionID)
if isinstance(creation_out, expansionsLib.Expansion):
self._activeExpansions[expansionID] = creation_out
else:
raise creation_out
def _activePlayerAdded(self, playerName):
# Find the expansions that are to be created
possibleAddition = set(self._includedExpansions).difference(self._activeExpansions)
possibleAddition = set(self._includeExpansions).difference(self._activeExpansions)
filteredAddition = [
expansionID for expansionID in possibleAddition
if hasattr(expansionsLib, expansionID) and
if hasattr(expansionsLib, self._getClassFillMissing(expansionID)) and
playerName in self._getPlayersFillMissing(expansionID)
]
# Create the expansions
for expansionID in filteredAddition:
self._createExpansion(expansionID)
creation_out = self._createExpansion(expansionID)
if isinstance(creation_out, expansionsLib.Expansion):
self._activeExpansions[expansionID] = creation_out
else:
raise creation_out
def _activePlayerRemoved(self, playerName):
# Find the expansions that are to be removed
@ -383,32 +401,85 @@ class ExpansionsManager:
for expansionID in filteredRemoval:
self._removeExpansion(expansionID)
def _errorOccured(self, expansionID):
def _midStepError(self, expansionID):
self._removeExpansion(expansionID)
def expansionPlayersChanged(self, expansionID):
def expansionPlayersChange(self, expansionID, newPlayers):
"""
Method that allows changing the assigned players of an expansion.
Arguments:
expansionID (str):
newPlayers (tuple of str):
"""
# Save the change
previousPlayers = self._cfg[expansionID]["players"]
self._cfg[expansionID]["players"] = tuple(newPlayers)
# Check the state of the expansion
expansionIsActive = expansionID in self._activeExpansions
activePlayers = set(self.playersManager.keys())
expansionHasNoPlayers = self._getPlayersFillMissing(expansionID).isdisjoint(activePlayers)
expansionDefined = hasattr(expansionsLib, expansionID)
expansionDefined = hasattr(expansionsLib, self._getClassFillMissing(expansionID))
# Update the activation status
activeChanged = False
if expansionIsActive and expansionHasNoPlayers:
self._removeExpansion(expansionID)
activeChanged = True
elif (not expansionIsActive) and (not expansionHasNoPlayers) and expansionDefined:
self._createExpansion(expansionID)
creation_out = self._createExpansion(expansionID)
if isinstance(creation_out, expansionsLib.Expansion):
self._activeExpansions[expansionID] = creation_out
activeChanged = True
else:
raise creation_out
# Update the inverse lookup
if not activeChanged:
removedPlayers = set(previousPlayers).difference(newPlayers)
addedPlayers = set(newPlayers).difference(previousPlayers)
for playerName in removedPlayers:
self._playersLookUp[playerName].pop(expansionID)
for playerName in addedPlayers:
self._playersLookUp[playerName].append(expansionID)
def lookupPlayer(self, playerName):
"""
Get a tuple of all expansions available to a player.
Arguments:
playerName (str): Name of the player
Returns:
expansionsID (tuple of str): ID of the expansions available to the
player
"""
return tuple(self._playersLookUp.get(playerName, []))
if __name__ == "__main__":
# Test run to make sure nothing is flagrantly flawed
configPath = Path(__file__).parent / "players.json"
pm = PlayersManager(playersPath=configPath, gameID="gameID0")
configPath = Path(__file__).parent.parent.parent / "players.json"
pm = PlayersManager(gameID="gameID0", activePlayers=["Brosef"], playersPath=configPath)
# Iteration
for name in pm:
print(name)
# Modification of a players data
brosef = pm["Brosef"]
brosef.gameSave = [1]
print(pm["Brosef"].gameSave)
brosef.state = ["alive"]
# TODO Verify that changing the gameID works as intended
# TODO Test out the expansion manager
# Implement a way to search within expansions
# Test run for the expansionsManager
# Create the managers
configPath = Path(__file__).parent.parent.parent / "players.json"
pm = PlayersManager(gameID="gameID0", activePlayers=["Brosef"], playersPath=configPath)
em = ExpansionsManager(pm, includeExpansions=["Simple", "SourCandy"])
# Use the expansion manager to interact with a player using the expansion "Simple"
brosefAvailableExpansionsID = em.lookupPlayer("Brosef")
if "Simple" in brosefAvailableExpansionsID:
# Define some random action
vibrateInstead, duration, intensity = False, 1.0, 100
action = vibrateInstead, duration, intensity
# Perform the action
expansionObject = em["Simple"]
return_infos = expansionObject(action)
assert return_infos["done"], "The step was not successfully completed"