flaskapp.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. @app.route("/game")
  55. def game(game_id=None):
  56. try:
  57. name = request.args["playerName"]
  58. if not name or not game_id:
  59. raise KeyError
  60. if game_id not in [game.id for game in app.games]:
  61. flash("Game not found")
  62. return redirect(url_for("home"))
  63. except KeyError as e:
  64. app.logger.error(e)
  65. app.logger.error("Failed, missing args")
  66. flash("Failed to join game, bad game code or player name")
  67. return redirect(url_for("home"))
  68. except Exception as e:
  69. app.logger.error(e)
  70. app.logger.error("Failed, bad args")
  71. return abort(400)
  72. return render_template("game.html", game_id=game_id)
  73. if __name__ == "__main__":
  74. app.run(debug=True)