flaskapp.py 1.5 KB

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