flaskapp.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from flask import (
  2. Flask,
  3. abort,
  4. flash,
  5. redirect,
  6. render_template,
  7. request,
  8. session,
  9. url_for,
  10. )
  11. import logging
  12. from game import Game, randomword
  13. app = Flask(__name__)
  14. app.secret_key = "somebullshit"
  15. app.games = []
  16. logging.basicConfig(
  17. level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s"
  18. )
  19. @app.route("/")
  20. def home():
  21. return render_template("home.html")
  22. @app.route("/newgame")
  23. def new_game():
  24. try:
  25. app.logger.info("Creating game...")
  26. name = request.args["playerName"]
  27. hand_size = int(request.args["handSize"])
  28. match_count = int(request.args["matchCount"])
  29. turn_count = int(request.args["turnCount"])
  30. if not name or not hand_size or not match_count or not turn_count:
  31. raise KeyError
  32. except KeyError as e:
  33. app.logger.error(e)
  34. app.logger.error("Failed, missing args")
  35. flash("Failed to create game, bad arguments")
  36. return redirect(url_for("home"))
  37. except TypeError as e:
  38. app.logger.error(e)
  39. app.logger.error("Failed, bad args")
  40. return abort(400)
  41. game_id = None
  42. while game_id := randomword(4):
  43. if game_id not in [game.id for game in app.games]:
  44. break
  45. app.logger.info(
  46. f"Game created: {game_id} {name} {hand_size} {match_count} {turn_count}"
  47. )
  48. game = Game(name, hand_size, match_count, turn_count, game_id)
  49. app.games.append(game)
  50. session["game_id"] = game.id
  51. session["player_id"] = game.player1.id
  52. return redirect(url_for("game", game_id=game.id))
  53. @app.route("/game/<game_id>")
  54. def game(game_id):
  55. return render_template("game.html", game_id=game_id)
  56. if __name__ == "__main__":
  57. app.run(debug=True)