game_api.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. from flask import Blueprint, abort, request, jsonify
  2. import db
  3. import lib
  4. game = Blueprint("game", __name__)
  5. rsv_gen = lib.random_street_view_generator(only_america=False)
  6. rsv_gen_usa = lib.random_street_view_generator(only_america=True)
  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. coords = []
  42. if gen_method == "MAPCRUNCH":
  43. for _ in range(rounds):
  44. maybe_coord = lib.generate_coord(only_america=only_america)
  45. while maybe_coord is None:
  46. maybe_coord = lib.generate_coord(only_america=only_america)
  47. coords.append(maybe_coord)
  48. elif gen_method == "RANDOMSTREETVIEW":
  49. gen = rsv_gen_usa if only_america else rsv_gen
  50. for _ in range(rounds):
  51. coords.append(next(gen))
  52. else:
  53. abort(400)
  54. new_game = db.Game.create(timer, rounds, only_america, gen_method, coords)
  55. return jsonify({"gameId": new_game.game_id})
  56. @game.route("/<game_id>/config")
  57. def game_config(game_id):
  58. g = require_game(game_id)
  59. return jsonify({
  60. "timer": g.timer,
  61. "rounds": g.rounds,
  62. "onlyAmerica": g.only_america,
  63. "generationMethod": g.gen_method,
  64. })
  65. @game.route("/<game_id>/coords")
  66. def coords(game_id):
  67. g = require_game(game_id)
  68. return jsonify({
  69. str(c.round_number): {
  70. "lat": c.latitude,
  71. "lng": c.longitude,
  72. } for c in g.coordinates
  73. })
  74. @game.route("/<game_id>/players")
  75. def players(game_id):
  76. g = require_game(game_id)
  77. return jsonify({
  78. "players": [{
  79. "name": p.player_name,
  80. "currentRound": p.get_current_round(),
  81. "totalScore": p.get_total_score(),
  82. "guesses": {
  83. str(g.round_number): {
  84. "lat": g.latitude,
  85. "lng": g.longitude,
  86. "score": g.round_score,
  87. "timeRemaining": g.time_remaining,
  88. } for g in p.guesses
  89. },
  90. } for p in g.players]
  91. })
  92. @game.route("/<game_id>/linked", methods=["GET", "POST"])
  93. def link_game(game_id):
  94. g = require_game(game_id)
  95. if request.method == "GET":
  96. return jsonify({"linkedGame": g.linked_game})
  97. js = request.get_json()
  98. if js is None:
  99. abort(400)
  100. link_id = js.get("linkedGame", None)
  101. if link_id is None or db.Game.query.get(link_id) is None:
  102. abort(401)
  103. g.link(link_id)
  104. return "", 201
  105. @game.route("/<game_id>/join", methods=["POST"])
  106. def join(game_id):
  107. js = request.get_json()
  108. if js is None:
  109. abort(400)
  110. name = js.get("playerName", None)
  111. if name is None:
  112. abort(400)
  113. g = require_game(game_id)
  114. if db.Player.query.filter(db.Player.game_id == game_id, db.Player.player_name == name).first() is not None:
  115. abort(409)
  116. p = g.join(name)
  117. return jsonify({
  118. "playerId": str(p.player_id)
  119. }), 201
  120. @game.route("/<game_id>/current")
  121. def current_round(game_id):
  122. g = require_game(game_id)
  123. player = require_player(game_id)
  124. cur_rnd = player.get_current_round()
  125. if cur_rnd is None:
  126. coord = None
  127. else:
  128. lookup = db.Coordinate.query.get((game_id, cur_rnd))
  129. cur_rnd = str(cur_rnd)
  130. if lookup is None:
  131. coord = None
  132. else:
  133. coord = {
  134. "lat": lookup.latitude,
  135. "lng": lookup.longitude,
  136. }
  137. return jsonify({
  138. "currentRound": cur_rnd,
  139. "coord": coord,
  140. "timer": g.timer,
  141. })
  142. @game.route("/<game_id>/guesses/<int:round_num>", methods=["POST"])
  143. def make_guess(game_id, round_num):
  144. player = require_player(game_id)
  145. if round_num != player.get_current_round():
  146. abort(409)
  147. js = request.get_json()
  148. if js is None:
  149. abort(400)
  150. timed_out = js.get("timeout", False)
  151. if timed_out:
  152. player.add_timeout(round_num)
  153. db.session.commit()
  154. return jsonify({
  155. "score": 0,
  156. "totalScore": player.get_total_score(),
  157. "distance": None,
  158. }), 201
  159. try:
  160. lat = float(js.get("lat", None))
  161. lng = float(js.get("lng", None))
  162. remaining = int(js.get("timeRemaining", None))
  163. except ValueError:
  164. abort(400)
  165. target = db.Coordinate.query.get((game_id, round_num))
  166. if target is None:
  167. abort(400)
  168. guess_score, distance = lib.score((target.latitude, target.longitude), (lat, lng))
  169. player.add_guess(round_num, lat, lng, guess_score, remaining)
  170. return jsonify({
  171. "score": guess_score,
  172. "totalScore": player.get_total_score(),
  173. "distance": distance,
  174. }), 201