game_api.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. from flask import Blueprint, abort, request, jsonify
  2. import db
  3. import lib
  4. from sources import sources, restock_all
  5. restock_all()
  6. game = Blueprint("game", __name__)
  7. def require_game(game_id):
  8. g = db.Game.query.get(game_id)
  9. if g is None:
  10. abort(404)
  11. return g
  12. def require_player(game_id):
  13. auth = request.headers.get("Authorization", type=str)
  14. if auth is None:
  15. abort(401)
  16. try:
  17. pid = int(auth.split(maxsplit=1)[-1])
  18. except ValueError:
  19. abort(401)
  20. player = db.Player.query.get(pid)
  21. if player is None:
  22. abort(404)
  23. return player
  24. @game.route("", methods=["PUT"])
  25. def create_game():
  26. js = request.get_json()
  27. if js is None:
  28. abort(400)
  29. timer = js.get("timer", None)
  30. if not isinstance(timer, int) or timer <= 0:
  31. abort(400)
  32. rounds = js.get("rounds", None)
  33. if not isinstance(rounds, int) or rounds <= 0:
  34. abort(400)
  35. only_america = js.get("onlyAmerica", False)
  36. if not isinstance(only_america, bool):
  37. abort(400)
  38. gen_method = js.get("generationMethod", "MAPCRUNCH")
  39. if not isinstance(gen_method, str):
  40. abort(400)
  41. src = sources.get((gen_method, only_america), None)
  42. if src is None:
  43. abort(400)
  44. coords = src.get_points(n=rounds)
  45. new_game = db.Game.create(timer, rounds, only_america, gen_method, coords)
  46. return jsonify({"gameId": new_game.game_id})
  47. @game.route("/<game_id>/config")
  48. def game_config(game_id):
  49. g = require_game(game_id)
  50. return jsonify({
  51. "timer": g.timer,
  52. "rounds": g.rounds,
  53. "onlyAmerica": g.only_america,
  54. "generationMethod": g.gen_method,
  55. })
  56. @game.route("/<game_id>/coords")
  57. def coords(game_id):
  58. g = require_game(game_id)
  59. return jsonify({
  60. str(c.round_number): {
  61. "lat": c.latitude,
  62. "lng": c.longitude,
  63. } for c in g.coordinates
  64. })
  65. @game.route("/<game_id>/players")
  66. def players(game_id):
  67. g = require_game(game_id)
  68. return jsonify({
  69. "players": [{
  70. "name": p.player_name,
  71. "currentRound": p.get_current_round(),
  72. "totalScore": p.get_total_score(),
  73. "guesses": {
  74. str(g.round_number): {
  75. "lat": g.latitude,
  76. "lng": g.longitude,
  77. "score": g.round_score,
  78. "timeRemaining": g.time_remaining,
  79. } for g in p.guesses
  80. },
  81. } for p in g.players]
  82. })
  83. @game.route("/<game_id>/linked", methods=["GET", "POST"])
  84. def link_game(game_id):
  85. g = require_game(game_id)
  86. if request.method == "GET":
  87. return jsonify({"linkedGame": g.linked_game})
  88. js = request.get_json()
  89. if js is None:
  90. abort(400)
  91. link_id = js.get("linkedGame", None)
  92. if link_id is None or db.Game.query.get(link_id) is None:
  93. abort(401)
  94. g.link(link_id)
  95. return "", 201
  96. @game.route("/<game_id>/join", methods=["POST"])
  97. def join(game_id):
  98. js = request.get_json()
  99. if js is None:
  100. abort(400)
  101. name = js.get("playerName", None)
  102. if name is None:
  103. abort(400)
  104. g = require_game(game_id)
  105. if db.Player.query.filter(db.Player.game_id == game_id, db.Player.player_name == name).first() is not None:
  106. abort(409)
  107. p = g.join(name)
  108. return jsonify({
  109. "playerId": str(p.player_id)
  110. }), 201
  111. @game.route("/<game_id>/current")
  112. def current_round(game_id):
  113. g = require_game(game_id)
  114. player = require_player(game_id)
  115. cur_rnd = player.get_current_round()
  116. if cur_rnd is None:
  117. coord = None
  118. else:
  119. lookup = db.Coordinate.query.get((game_id, cur_rnd))
  120. cur_rnd = str(cur_rnd)
  121. if lookup is None:
  122. coord = None
  123. else:
  124. coord = {
  125. "lat": lookup.latitude,
  126. "lng": lookup.longitude,
  127. }
  128. return jsonify({
  129. "currentRound": cur_rnd,
  130. "coord": coord,
  131. "timer": g.timer,
  132. })
  133. @game.route("/<game_id>/guesses/<int:round_num>", methods=["POST"])
  134. def make_guess(game_id, round_num):
  135. player = require_player(game_id)
  136. if round_num != player.get_current_round():
  137. abort(409)
  138. js = request.get_json()
  139. if js is None:
  140. abort(400)
  141. timed_out = js.get("timeout", False)
  142. if timed_out:
  143. player.add_timeout(round_num)
  144. db.session.commit()
  145. return jsonify({
  146. "score": 0,
  147. "totalScore": player.get_total_score(),
  148. "distance": None,
  149. }), 201
  150. try:
  151. lat = float(js.get("lat", None))
  152. lng = float(js.get("lng", None))
  153. remaining = int(js.get("timeRemaining", None))
  154. except ValueError:
  155. abort(400)
  156. target = db.Coordinate.query.get((game_id, round_num))
  157. if target is None:
  158. abort(400)
  159. guess_score, distance = lib.score((target.latitude, target.longitude), (lat, lng))
  160. player.add_guess(round_num, lat, lng, guess_score, remaining)
  161. return jsonify({
  162. "score": guess_score,
  163. "totalScore": player.get_total_score(),
  164. "distance": distance,
  165. }), 201