make better save and load function of files and add snake config into a json file

This commit is contained in:
2024-04-12 11:16:49 +02:00
parent 33bcb09556
commit 664c374fbf
2 changed files with 29 additions and 11 deletions
+13 -11
View File
@@ -10,6 +10,7 @@
# To get you started we've included code to prevent your Battlesnake from moving backwards. # To get you started we've included code to prevent your Battlesnake from moving backwards.
# For more info see docs.battlesnake.com # For more info see docs.battlesnake.com
from server.Files import read_file, save_file
from config import SNAKE from config import SNAKE
import typing import typing
import json, os import json, os
@@ -18,15 +19,16 @@ import json, os
# and controls your Battlesnake's appearance # and controls your Battlesnake's appearance
# TIP: If you open your Battlesnake URL in a browser you should see this data # TIP: If you open your Battlesnake URL in a browser you should see this data
def info() -> typing.Dict: 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 { print("INFO Snake: ", snake)
"apiversion": "1", return snake
"author": "daniel156161", # TODO: Your Battlesnake Username
"color": "#00ff00", # TODO: Choose color
"head": "default", # TODO: Choose head
"tail": "default", # TODO: Choose tail
}
# start is called when your Battlesnake begins a game # start is called when your Battlesnake begins a game
def start(game_state: typing.Dict): 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 # end is called when your Battlesnake finishes a game
def end(game_state: typing.Dict): def end(game_state: typing.Dict):
os.makedirs(f"{os.path.dirname(__file__)}/history", exist_ok=True) HISTORY_PATH = os.path.join(os.path.dirname(__file__), 'history')
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) 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") print("GAME OVER\n")
+16
View File
@@ -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)