From 664c374fbf89c85032dc1ec2002e9e8193e0bfe2 Mon Sep 17 00:00:00 2001 From: Daniel Dolezal Date: Fri, 12 Apr 2024 11:16:49 +0200 Subject: [PATCH] make better save and load function of files and add snake config into a json file --- main.py | 24 +++++++++++++----------- server/Files.py | 16 ++++++++++++++++ 2 files changed, 29 insertions(+), 11 deletions(-) create mode 100644 server/Files.py diff --git a/main.py b/main.py index 8d91fd9..5db1cc7 100644 --- a/main.py +++ b/main.py @@ -10,6 +10,7 @@ # To get you started we've included code to prevent your Battlesnake from moving backwards. # For more info see docs.battlesnake.com +from server.Files import read_file, save_file from config import SNAKE import typing import json, os @@ -18,15 +19,16 @@ import json, os # and controls your Battlesnake's appearance # TIP: If you open your Battlesnake URL in a browser you should see this data def info() -> typing.Dict: - print("INFO") + CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'snake-config.json') + snake = read_file(CONFIG_PATH, json.load) + if not snake: + snake = {"apiversion":"1","author":"","color":"#888888","head":"default","tail":"default"} + save_file(CONFIG_PATH, snake, callback=json.dump, indent=2, ensure_ascii=False) + print("INFO", snake) + return snake - return { - "apiversion": "1", - "author": "daniel156161", # TODO: Your Battlesnake Username - "color": "#00ff00", # TODO: Choose color - "head": "default", # TODO: Choose head - "tail": "default", # TODO: Choose tail - } + print("INFO Snake: ", snake) + return snake # start is called when your Battlesnake begins a game def start(game_state: typing.Dict): @@ -35,9 +37,9 @@ def start(game_state: typing.Dict): # end is called when your Battlesnake finishes a game def end(game_state: typing.Dict): - os.makedirs(f"{os.path.dirname(__file__)}/history", exist_ok=True) - with open(f"{os.path.dirname(__file__)}/history/{SNAKE.__class__.__name__}-{game_state['game']['id']}", "w") as f: - json.dump(SNAKE.get_history(), f, ensure_ascii=False) + HISTORY_PATH = os.path.join(os.path.dirname(__file__), 'history') + + save_file(os.path.join(HISTORY_PATH, f"{SNAKE.__class__.__name__}-{game_state['game']['id']}.json"), SNAKE.get_history(), callback=json.dump, ensure_ascii=False) print("GAME OVER\n") diff --git a/server/Files.py b/server/Files.py new file mode 100644 index 0000000..22d9c2f --- /dev/null +++ b/server/Files.py @@ -0,0 +1,16 @@ +import os + +def read_file(path, callback=None): + if os.path.exists(path): + with open(path, 'r') as f: + data = callback(f) + return data + else: + return None + +def save_file(path, data, callback=None, *args, **kwargs): + if not os.path.exists(path): + os.makedirs(os.path.dirname(path), exist_ok=True) + + with open(path, 'w') as f: + callback(data, f, *args, **kwargs)