Default game save file is game.save

This commit is contained in:
Yohann D'ANELLO 2021-11-12 14:32:02 +01:00
parent 94d8173f06
commit 8890d88ab8
Signed by: ynerant
GPG Key ID: 3A75C55819C8CF85
3 changed files with 24 additions and 20 deletions

View File

@ -1,4 +1,3 @@
import os
from functools import partial from functools import partial
import disnake import disnake
@ -90,23 +89,23 @@ async def on_ready():
role, overwrite=PermissionOverwrite(read_message_history=True, read_messages=True) role, overwrite=PermissionOverwrite(read_message_history=True, read_messages=True)
) )
game = Game.load('game.save') game = Game.load()
if not game: if not game:
game = Game() game = Game()
for player in config.PLAYERS: for player in config.PLAYERS:
game.register_player(player, config.vote_channels[player.lower()]) game.register_player(player, config.vote_channels[player.lower()])
game.save('game.save') game.save()
# Update private channel id if necessary # Update private channel id if necessary
for player in list(game.players.values()): for player in list(game.players.values()):
if player.private_channel_id != config.vote_channels[player.name.lower()]: if player.private_channel_id != config.vote_channels[player.name.lower()]:
game.register_player(player.name, config.vote_channels[player.name.lower()]) game.register_player(player.name, config.vote_channels[player.name.lower()])
game.save('game.save') game.save()
# Setup first round if not exists # Setup first round if not exists
if not game.rounds: if not game.rounds:
game.rounds.append(game.default_first_round()) game.rounds.append(game.default_first_round())
game.save('game.save') game.save()
if not config.telepathy_channel: if not config.telepathy_channel:
channel: TextChannel = await secret_category.create_text_channel("bigbrain") channel: TextChannel = await secret_category.create_text_channel("bigbrain")
@ -187,14 +186,14 @@ async def on_ready():
@bot.command(help="Sauvegarde la partie") @bot.command(help="Sauvegarde la partie")
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
async def save(ctx: commands.Context, filename: str = 'game.save'): async def save(ctx: commands.Context, filename: str | None = None):
Game.INSTANCE.save(filename) Game.INSTANCE.save(filename)
await ctx.reply("La partie a été sauvegardée.") await ctx.reply("La partie a été sauvegardée.")
@bot.command(help="Recharger la partie") @bot.command(help="Recharger la partie")
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
async def load(ctx: commands.Context, filename: str = 'game.save'): async def load(ctx: commands.Context, filename: str | None = None):
game = Game.load(filename) game = Game.load(filename)
if not game: if not game:
return await ctx.reply("Une erreur est survenue : le fichier n'existe pas ?") return await ctx.reply("Une erreur est survenue : le fichier n'existe pas ?")
@ -306,7 +305,7 @@ async def close(ctx: commands.Context):
"Mais ... Attendrez-vous vos camarades ?") "Mais ... Attendrez-vous vos camarades ?")
await ctx.reply("Les votes ont bien été fermés.") await ctx.reply("Les votes ont bien été fermés.")
game.save('game.save') game.save()
@bot.command(help="Préparation du tour suivant") @bot.command(help="Préparation du tour suivant")
@ -336,7 +335,7 @@ async def prepare(ctx: commands.Context):
vote2=RoundVote(), vote2=RoundVote(),
), ),
)) ))
game.save('game.save') game.save()
await ctx.reply("Le tour suivant est en préparation. Utilisez `!setup A|B|C` pour paramétrer les salles A, B ou C. " await ctx.reply("Le tour suivant est en préparation. Utilisez `!setup A|B|C` pour paramétrer les salles A, B ou C. "
"Dan peut faire la même chose.") "Dan peut faire la même chose.")
@ -399,7 +398,7 @@ async def vote(ctx: commands.Context, player_name: str, vote: Vote | None):
if current_player in v.players: if current_player in v.players:
v.vote = vote v.vote = vote
game.save('game.save') game.save()
await ctx.reply(f"Le vote de **{current_player.name}** a bien été falsifié (nouveau vote : *{vote}**).") await ctx.reply(f"Le vote de **{current_player.name}** a bien été falsifié (nouveau vote : *{vote}**).")
@ -427,7 +426,7 @@ async def swap(ctx: commands.Context, player_name: str):
if current_player in v.players: if current_player in v.players:
v.swapped ^= True v.swapped ^= True
game.save('game.save') game.save()
await ctx.reply(f"Le vote de **{current_player.name}** a bien été inversé. S'il était déjà inversé, " await ctx.reply(f"Le vote de **{current_player.name}** a bien été inversé. S'il était déjà inversé, "
"alors il est de retour à la normale.") "alors il est de retour à la normale.")
@ -449,7 +448,7 @@ async def override(ctx: commands.Context, player_name: str, target_score: int):
game.score_overrides[current_player] = target_score game.score_overrides[current_player] = target_score
game.save('game.save') game.save()
await ctx.reply(f"Le score de **{current_player.name}** a bien été modifié. " await ctx.reply(f"Le score de **{current_player.name}** a bien été modifié. "
f"Il sera maintenant de **{target_score}**.") f"Il sera maintenant de **{target_score}**.")
@ -462,13 +461,13 @@ async def reboot(ctx: commands.Context):
channel = bot.get_channel(player.private_channel_id) channel = bot.get_channel(player.private_channel_id)
await channel.send("REB0OT.") await channel.send("REB0OT.")
os.rename('game.save', 'game-prereboot.save') game.save('game-prereboot.save')
game = Game() game = Game()
for player in bot.config.PLAYERS: for player in bot.config.PLAYERS:
game.register_player(player, bot.config.vote_channels[player.lower()]) game.register_player(player, bot.config.vote_channels[player.lower()])
game.rounds.append(game.default_first_round()) game.rounds.append(game.default_first_round())
game.save('game.save') game.save()
await ctx.reply("REB0OT.") await ctx.reply("REB0OT.")
@ -516,7 +515,7 @@ class VoteView(disnake.ui.View):
if current_vote.vote is None: if current_vote.vote is None:
current_vote.vote = vote current_vote.vote = vote
game.save('game.save') game.save()
class PrepareRoomView(disnake.ui.View): class PrepareRoomView(disnake.ui.View):
@ -592,7 +591,7 @@ class PrepareRoomView(disnake.ui.View):
"Vous pouvez redéfinir la salle tant que le tour n'est pas lancé. " "Vous pouvez redéfinir la salle tant que le tour n'est pas lancé. "
"Utilisez !preview pour un récapitulatif des tours.") "Utilisez !preview pour un récapitulatif des tours.")
game.save('game.save') game.save()
game: Game = Game.INSTANCE game: Game = Game.INSTANCE
current_round = game.rounds[-1] current_round = game.rounds[-1]

View File

@ -30,14 +30,14 @@ class Config:
player_roles: dict[str, int] = field(default_factory=dict) player_roles: dict[str, int] = field(default_factory=dict)
@classmethod @classmethod
def load(cls, filename=None) -> "Config": def load(cls, filename: str | None = None) -> "Config":
if filename is None: if filename is None:
filename = Path(__file__).parent.parent / 'config.yml' filename = Path(__file__).parent.parent / 'config.yml'
with open(filename) as config_file: with open(filename) as config_file:
return Config(**(yaml.safe_load(config_file) or {})) return Config(**(yaml.safe_load(config_file) or {}))
def save(self, filename=None) -> None: def save(self, filename: str | None = None) -> None:
if filename is None: if filename is None:
filename = Path(__file__).parent.parent / 'config.yml' filename = Path(__file__).parent.parent / 'config.yml'

View File

@ -1,6 +1,7 @@
import pickle import pickle
from dataclasses import dataclass, field from dataclasses import dataclass, field
from enum import Enum from enum import Enum
from pathlib import Path
from typing import ClassVar, Iterable, Generator from typing import ClassVar, Iterable, Generator
@ -160,18 +161,22 @@ class Game:
player2=self.players['Oji'])), player2=self.players['Oji'])),
) )
def save(self, filename: str) -> None: def save(self, filename: str | None = None) -> None:
""" """
Uses pickle to save the current state of the game. Uses pickle to save the current state of the game.
""" """
if filename is None:
filename = Path(__file__).parent.parent / 'game.save'
with open(filename, 'wb') as f: with open(filename, 'wb') as f:
pickle.dump(self, f) pickle.dump(self, f)
@classmethod @classmethod
def load(cls, filename: str) -> "Game | None": def load(cls, filename: str | None = None) -> "Game | None":
""" """
Reload the game from a saved file. Reload the game from a saved file.
""" """
if filename is None:
filename = Path(__file__).parent.parent / 'game.save'
try: try:
with open(filename, 'rb') as f: with open(filename, 'rb') as f:
game = pickle.load(f) game = pickle.load(f)