import os import json from flask import Blueprint, redirect, render_template, request from . import cluster bp = Blueprint("puzzle", __name__, url_prefix="/") root = "chaospuzzles" def list_folders(path): """Return all the folders in a folder""" names = [] for entry in os.scandir(path): # add to the list only proper files if not entry.name.startswith(".") and entry.is_dir(): # remove the extension from the filename names.append(entry.name) return names @bp.route("/") def home(): puzzles = list_folders(f"{root}/puzzles") return render_template("home.html", puzzles=puzzles) @bp.route("/", methods=("GET", "POST")) def puzzle(puzzle=None): with open(f"{root}/puzzles/{puzzle}/info.json") as data: info = json.load(data) if request.method == "POST": fragments = request.form.getlist("pieces") with open(f"{root}/puzzles/{puzzle}/adjacents.json") as adj_data: adjacents = json.load(adj_data) valid = cluster.is_valid(adjacents, fragments) if valid: with open(f"{root}/puzzles/{puzzle}/pieces.json") as pieces_data: pieces = json.load(pieces_data) c = cluster.create( pieces, fragments, puzzle, int(info["width"] / info["rows"]) ) with open(f"{root}/puzzles/{puzzle}/info.json", "w") as data: info["clusters"].append(c) data.write(json.dumps(info)) redirect(f"/{puzzle}") # cringe sorry if info["width"] >= info["height"]: info["ratio"] = info["width"] / info["height"] else: info["ratio"] = info["height"] / info["width"] return render_template("puzzle.html", puzzle=puzzle, **info)