import random import os import pathlib from font_game.images import gen_image from font_game import gen_id, FONTS, read_file, write_file def purge_games(): for root, _, files in os.walk("current_games"): for file in files: os.remove(os.path.join(root, file)) def pick_fonts(game_length: int): weights = {key: 100 for key in FONTS} font_list = [] for _ in range(game_length): picked = random.choice([k for k in weights for _ in range(weights[k])]) font_list.append(picked) weights[picked] = weights[picked] // 2 return [(i, FONTS[i]) for i in font_list] def start_game(game_length: int = 10, hard_mode: bool = False) -> str: picked_fonts = pick_fonts(game_length) images = [] for font in picked_fonts: images.append(gen_image(font[1])) game_id = gen_id() game_dict = { "points": "0", "i": "0", "game_length": str(game_length), "images": ','.join(images), "fonts": ','.join(i[0] for i in picked_fonts), "hard_mode": str(hard_mode) } game = "\n".join([f"{key}:{value}" for key, value in game_dict.items()]) with open(f"current_games/{game_id}", "w", encoding="utf-8") as file: file.write(game) return game_id def test_game(game_id: str): return pathlib.Path(f"current_games/{game_id}").is_file() def guess_font(game_id: str, font_guess: str): game_dict = read_file(f"current_games/{game_id}") i = int(game_dict['i']) font_guess = font_guess.lower().replace(" ","-") font = game_dict['fonts'].split(',')[i].lower().replace(" ","-") if font_guess == font: game_dict['points'] = str(int(game_dict['points']) + 1) game_dict['i'] = str(i+1) write_file(f"current_games/{game_id}", game_dict)