Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue/#858 validity in game info #900

Draft
wants to merge 7 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ aio_pika = "~=8.2"
aiocron = "*"
aiohttp = "*"
aiomysql = {git = "https://github.com/aio-libs/aiomysql"}
cachetools = "*"
docopt = "*"
humanize = ">=2.6.0"
maxminddb = "*"
Expand Down
11 changes: 10 additions & 1 deletion Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

34 changes: 32 additions & 2 deletions server/game_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from typing import Optional, Union, ValuesView

import aiocron
from cachetools import LRUCache
from sqlalchemy import select

from server.config import config
Expand All @@ -30,6 +31,7 @@
from .message_queue_service import MessageQueueService
from .players import Player
from .rating_service import RatingService
from .types import MapInfo


@with_logger
Expand Down Expand Up @@ -57,12 +59,15 @@ def __init__(
self._allow_new_games = False
self._drain_event = None

# Populated below in really_update_static_ish_data.
# Populated below in update_data.
self.featured_mods = dict()

# A set of mod ids that are allowed in ranked games
self.ranked_mods: set[str] = set()

# A cache of map_version info needed by Game
self.map_info_cache = LRUCache(maxsize=128)

# The set of active games
self._games: dict[int, Game] = dict()

Expand Down Expand Up @@ -120,6 +125,30 @@ async def update_data(self):
# Turn resultset into a list of uids
self.ranked_mods = {row.uid for row in result}

async def get_map_info(self, filename: str) -> Optional[MapInfo]:
filename = filename.lower()
map_info = self.map_info_cache.get(filename)
if map_info is not None:
return map_info

async with self._db.acquire() as conn:
result = await conn.execute(
"SELECT id, filename, ranked FROM map_version "
"WHERE lower(filename) = lower(:filename)",
filename=filename
)
row = result.fetchone()
if not row:
return None

map_info = MapInfo(
id=row.id,
filename=row.filename,
ranked=row.ranked
)
self.map_info_cache[filename] = map_info
return map_info

def mark_dirty(self, obj: Union[Game, MatchmakerQueue]):
if isinstance(obj, Game):
self._dirty_games.add(obj)
Expand All @@ -143,7 +172,7 @@ def create_uid(self) -> int:

return self.game_id_counter

def create_game(
async def create_game(
self,
game_mode: str,
game_class: type[Game] = CustomGame,
Expand Down Expand Up @@ -175,6 +204,7 @@ def create_game(
}
game_args.update(kwargs)
game = game_class(**game_args)
await game.initialize()

self._games[game_id] = game

Expand Down
39 changes: 19 additions & 20 deletions server/gameconnection.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,9 @@
GameConnectionState,
GameError,
GameState,
ValidityState,
Victory
ValidityState
)
from .games.typedefs import FA
from .games.typedefs import FA, Victory
from .player_service import PlayerService
from .players import Player, PlayerState
from .protocol import DisconnectedError, GpgNetServerProtocol, Protocol
Expand Down Expand Up @@ -228,22 +227,24 @@ async def handle_game_option(self, key: str, value: Any):
if not self.is_host():
return

# Type transformations
if key == "Victory":
self.game.gameOptions["Victory"] = Victory.__members__.get(
value.upper(), None
)
else:
self.game.gameOptions[key] = value
value = Victory.__members__.get(value.upper())
elif key == "Slots":
value = int(value)

if key == "Slots":
self.game.max_players = int(value)
elif key == "ScenarioFile":
self.game.game_options[key] = value

# Additional attributes
if key == "ScenarioFile":
# TODO: What is the point of this transformation?
raw = repr(value)
self.game.map_scenario_path = \
scenario_path = \
raw.replace("\\", "/").replace("//", "/").replace("'", "")
self.game.map_file_path = "maps/{}.zip".format(
self.game.map_scenario_path.split("/")[2].lower()
)
with contextlib.suppress(IndexError):
map_name = scenario_path.split("/")[2].lower()
self.game.map_file_path = f"maps/{map_name}.zip"
await self.game.update_map_info()
elif key == "Title":
with contextlib.suppress(ValueError):
self.game.name = value
Expand Down Expand Up @@ -332,7 +333,9 @@ async def handle_operation_complete(
)
return

if self.game.validity != ValidityState.COOP_NOT_RANKED:
validity = self.game.get_validity()
if validity is not ValidityState.COOP_NOT_RANKED:
self._logger.info("Game was not valid: %s", validity)
return

secondary, delta = secondary, str(delta)
Expand Down Expand Up @@ -471,10 +474,6 @@ async def handle_game_state(self, state: str):
return

elif state == "Lobby":
# TODO: Do we still need to schedule with `ensure_future`?
#
# We do not yield from the task, since we
# need to keep processing other commands while it runs
await self._handle_lobby_state()

elif state == "Launching":
Expand Down
29 changes: 13 additions & 16 deletions server/games/coop.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from server.games.validator import COMMON_RULES, GameOptionRule, Validator

from .game import Game
from .typedefs import FA, GameType, InitMode, ValidityState, Victory

Expand All @@ -6,13 +8,22 @@ class CoopGame(Game):
"""Class for coop game"""
init_mode = InitMode.NORMAL_LOBBY
game_type = GameType.COOP
default_validity = ValidityState.COOP_NOT_RANKED
validator = Validator([
*COMMON_RULES,
GameOptionRule("Victory", Victory.SANDBOX, ValidityState.WRONG_VICTORY_CONDITION),
GameOptionRule("TeamSpawn", "fixed", ValidityState.SPAWN_NOT_FIXED),
GameOptionRule("RevealedCivilians", FA.DISABLED, ValidityState.CIVILIANS_REVEALED),
GameOptionRule("Difficulty", 3, ValidityState.WRONG_DIFFICULTY),
GameOptionRule("Expansion", FA.ENABLED, ValidityState.EXPANSION_DISABLED),
])

def __init__(self, *args, **kwargs):
kwargs["game_mode"] = "coop"
super().__init__(*args, **kwargs)

self.validity = ValidityState.COOP_NOT_RANKED
self.gameOptions.update({
self.is_coop = True
self.game_options.update({
"Victory": Victory.SANDBOX,
"TeamSpawn": "fixed",
"RevealedCivilians": "No",
Expand All @@ -21,20 +32,6 @@ def __init__(self, *args, **kwargs):
})
self.leaderboard_saved = False

async def validate_game_mode_settings(self):
"""
Checks which only apply to the coop mode
"""

valid_options = {
"Victory": (Victory.SANDBOX, ValidityState.WRONG_VICTORY_CONDITION),
"TeamSpawn": ("fixed", ValidityState.SPAWN_NOT_FIXED),
"RevealedCivilians": (FA.DISABLED, ValidityState.CIVILIANS_REVEALED),
"Difficulty": (3, ValidityState.WRONG_DIFFICULTY),
"Expansion": (FA.ENABLED, ValidityState.EXPANSION_DISABLED),
}
await self._validate_game_options(valid_options)

async def process_game_results(self):
"""
When a coop game ends, we don't expect there to be any game results.
Expand Down
25 changes: 18 additions & 7 deletions server/games/custom_game.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,37 @@
import time
from typing import Optional

from server.decorators import with_logger
from server.games.validator import COMMON_RULES, NON_COOP_RULES, Validator
from server.rating import RatingType

from .game import Game
from .typedefs import GameType, InitMode, ValidityState


def minimum_length_rule(game: Game) -> Optional[ValidityState]:
if game.launched_at is None:
return

limit = len(game.players) * 60
if not game.enforce_rating and time.time() - game.launched_at < limit:
return ValidityState.TOO_SHORT


@with_logger
class CustomGame(Game):
init_mode = InitMode.NORMAL_LOBBY
game_type = GameType.CUSTOM
validator = Validator([
*COMMON_RULES,
*NON_COOP_RULES,
minimum_length_rule
])

def __init__(self, id_, *args, **kwargs):
def __init__(self, *args, **kwargs):
new_kwargs = {
"rating_type": RatingType.GLOBAL,
"setup_timeout": 30
}
new_kwargs.update(kwargs)
super().__init__(id_, *args, **new_kwargs)

async def _run_pre_rate_validity_checks(self):
limit = len(self.players) * 60
if not self.enforce_rating and time.time() - self.launched_at < limit:
await self.mark_invalid(ValidityState.TOO_SHORT)
super().__init__(*args, **new_kwargs)
Loading
Loading