add methode to create more snake and use them when more games are running

This commit is contained in:
2024-04-13 10:48:08 +02:00
parent 22b8746972
commit cf5b70953c
2 changed files with 14 additions and 10 deletions
+1 -2
View File
@@ -12,7 +12,6 @@
# 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.SnakeBuilder import SnakeBuilder
from server.Server import Server from server.Server import Server
from dotenv import load_dotenv, find_dotenv from dotenv import load_dotenv, find_dotenv
@@ -24,7 +23,7 @@ if __name__ == "__main__":
server = Server( server = Server(
data_path=os.path.dirname(__file__), data_path=os.path.dirname(__file__),
snake=SnakeBuilder.build(os.environ.get("SNAKE", "DummSnake")), snake_type=os.environ.get("SNAKE", "DummSnake"),
) )
if os.environ.get("STORE_GAME_HISTORY", None): if os.environ.get("STORE_GAME_HISTORY", None):
+13 -8
View File
@@ -1,6 +1,7 @@
from server.Files import read_file, save_file from server.Files import read_file, save_file
from server.GameStorage import GameStorage from server.GameStorage import GameStorage
from snakes.TemplateSnake import TemplateSnake from snakes.TemplateSnake import TemplateSnake
from server.SnakeBuilder import SnakeBuilder
from datetime import datetime from datetime import datetime
from flask import Flask from flask import Flask
@@ -10,15 +11,16 @@ import logging, json, os
class Server: class Server:
default_snake_config = {"apiversion":"1","author":"","color":"#888888","head":"default","tail":"default"} default_snake_config = {"apiversion":"1","author":"","color":"#888888","head":"default","tail":"default"}
def __init__(self, data_path:str, snake:TemplateSnake, debug:bool=False): def __init__(self, data_path:str, snake_type:str, debug:bool=False):
self.debug = debug self.debug = debug
self.snake = snake self.snake_type = snake_type
self.config_file = os.path.join(data_path, 'data', 'snake-config.json') self.config_file = os.path.join(data_path, 'data', 'snake-config.json')
self.data_path = data_path self.data_path = data_path
self.store_game_state = False self.store_game_state = False
self.running_games:dict[str, TemplateSnake] = {} self.running_games:dict[str, GameStorage] = {}
self.running_snake:dict[str, TemplateSnake] = {}
self.app = Flask("Battlesnake") self.app = Flask("Battlesnake")
@@ -53,7 +55,7 @@ class Server:
def run(self, host:str="0.0.0.0", port:str="8000", debug:bool=False): def run(self, host:str="0.0.0.0", port:str="8000", debug:bool=False):
logging.getLogger("werkzeug").setLevel(logging.ERROR) logging.getLogger("werkzeug").setLevel(logging.ERROR)
print(f"\nRunning Battlesnake at http://{host}:{port} with the {self.snake.__class__.__name__.replace('Snake', '')} Snake") print(f"\nRunning Battlesnake at http://{host}:{port} with the {self.snake_type.replace('Snake', '')} Snake")
self.app.run(host=host, port=port, debug=debug) self.app.run(host=host, port=port, debug=debug)
def _read_json_config_or_create(self): def _read_json_config_or_create(self):
@@ -80,12 +82,12 @@ class Server:
self.running_games[game_state["game"]["id"]] = GameStorage(self.snake.__class__.__name__, path=os.path.join(self.data_path, 'data', 'history')) self.running_games[game_state["game"]["id"]] = GameStorage(self.snake.__class__.__name__, path=os.path.join(self.data_path, 'data', 'history'))
self.running_games[game_state["game"]["id"]].start_new_game(game_state["game"], game_state["board"], game_state["you"]) self.running_games[game_state["game"]["id"]].start_new_game(game_state["game"], game_state["board"], game_state["you"])
self.snake.clear_history() self.running_snake[game_state["game"]["id"]] = SnakeBuilder.build(self.snake_type)
print("GAME START:", game_state["game"]) print("GAME START:", game_state["game"])
# move is called when your Battlesnake game is running game # move is called when your Battlesnake game is running game
def _move(self, game_state:dict) -> dict: def _move(self, game_state:dict) -> dict:
next_move = self.snake.choose_move(game_state) next_move = self.running_snake[game_state["game"]["id"]].choose_move(game_state)
if self.store_game_state: if self.store_game_state:
self.running_games[game_state["game"]["id"]].add_moves(game_state["board"], next_move) self.running_games[game_state["game"]["id"]].add_moves(game_state["board"], next_move)
@@ -98,11 +100,14 @@ class Server:
# end is called when your Battlesnake finishes a game # end is called when your Battlesnake finishes a game
def _end(self, game_state:dict): def _end(self, game_state:dict):
if self.store_game_state: if self.store_game_state:
self.running_games[game_state["game"]["id"]].add_end_state(game_state["board"], self.snake.get_history(), game_state["turn"]) snake = self.running_snake[game_state["game"]["id"]]
self.running_games[game_state["game"]["id"]].add_end_state(game_state["board"], snake.get_history(), game_state["turn"])
self.running_games[game_state["game"]["id"]].save( self.running_games[game_state["game"]["id"]].save(
f"{self.snake.__class__.__name__}_{datetime.now().strftime('%d.%m.%Y_%H%M%S')}_{game_state['game']['id']}.json", f"{snake.__class__.__name__}_{datetime.now().strftime('%d.%m.%Y_%H%M%S')}_{game_state['game']['id']}.json",
callback=json.dump, indent=2, ensure_ascii=False callback=json.dump, indent=2, ensure_ascii=False
) )
del self.running_games[game_state["game"]["id"]] del self.running_games[game_state["game"]["id"]]
print("GAME OVER:\n- Winner is", [ x["name"] for x in game_state["board"]['snakes']]) print("GAME OVER:\n- Winner is", [ x["name"] for x in game_state["board"]['snakes']])
del self.running_snake[game_state["game"]["id"]]