import string import pathlib import time from PIL import ImageFont, Image, ImageDraw from numpy import average BASE64_DIGITS = string.digits + string.ascii_letters + "+_" FONT_SIZE = 120 FONT_COLOR = (0,0,0) IMAGE_BACKGROUND = (255,255,255) IMAGE_SIZE = (1800, 1200) MARGINS = 60 MAKE_TESTS = False TEST_TEXT = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" def read_file(path: str) -> dict: with open(path, "r", encoding="utf-8") as file: game_dict = dict( [tuple(line.split(":")) for line in file.read().split('\n')] ) return game_dict def write_file(path: str, game: dict): game_string = "\n".join( [f"{key}:{value}" for key, value in game.items()] ) with open(path, "w", encoding="utf-8") as file: file.write(game_string) def base64(num: int) -> str: temp = "" for _ in range(10): temp = BASE64_DIGITS[num % 64] + temp num = num//64 if num > 0: raise Exception() return temp def gen_id() -> str: micro_seconds = int(time.time() * 1000000) return base64((micro_seconds * 9876534021204356789) % 0xfffffffffffffff) def make_test_pages(fonts: dict[str, ImageFont.FreeTypeFont]): image_width = FONT_SIZE*8 image_height = FONT_SIZE*8 image_margin = FONT_SIZE//3 writable_area = image_width - image_margin*2 for font_name, font in fonts.items(): final_text = [] current_text = "" for char in TEST_TEXT: if font.getbbox(current_text + char)[2] > (writable_area): final_text.append(current_text) current_text = char else: current_text += char final_text.append(current_text) im = Image.new("RGB", (image_width, image_height), (255, 255, 255)) drawer = ImageDraw.ImageDraw(im) drawer.text( (image_margin, image_margin), '\n'.join(final_text), (0, 0, 0), font ) im.save(f"fonts/test_pages/{font_name}.png") def make_fonts(): with open("font-list.txt", "r", encoding="utf-8") as file_pointer: fonts = file_pointer.read().split("\n") image_fonts = {} for font_name in fonts: if font_name == "" or font_name[0] == "#": continue font_name = font_name.replace(" ","-") if pathlib.Path(f"./fonts/{font_name}.TTF").is_file(): file_type = "TTF" elif pathlib.Path(f"./fonts/{font_name}.OTF").is_file(): file_type = "OTF" else: print(f"Could not locate font \033[0;31m{font_name}\033[0m") continue font_path = f"./fonts/{font_name}.{file_type}" tmp_font = ImageFont.truetype(font_path, FONT_SIZE) letter_height = int(average([ tmp_font.getbbox(i)[3] for i in TEST_TEXT ])) new_size = (FONT_SIZE**2)//letter_height new_font = ImageFont.truetype(font_path, new_size) image_fonts[font_name] = new_font print(f"Successfully loaded font \033[0;32m{font_name}\033[0m") if MAKE_TESTS: make_test_pages(image_fonts) print("Successfully created test pages") return image_fonts FONTS = make_fonts()