aboutsummaryrefslogtreecommitdiff
path: root/api/game/random.py
blob: 54ab2a857467a36898635410f6210f4dfc6f14a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from flask import Blueprint, request, make_response
from db import cursor, connection
from randid import new_uuid
import time
import json
import random
from game.socket import io, game, games
from auth.login_token import token_login

random_game = Blueprint('random', __name__)

@random_game.route('/random', methods = ['POST'])
def index():
    data = request.get_json()

    token = request.cookies.get("token") or ""
    user_id = data.get("user_id") or ""
    if not user_id and not token:
        print("a temporary user should be set up here")

    if not user_id and token:
        user_id = token_login(token)

    public_games = cursor.execute("select game_id from games where private = FALSE and status = \"wait_for_opponent\"").fetchall()

    timestamp = int( time.time() * 1000 )

    game_started = False

    if len(public_games) == 0:
        game_id = new_uuid("games")

        cursor.execute("insert into games values (?, NULL, \"\", ?, NULL, NULL, ?, NULL, ?, NULL, NULL, NULL, \"wait_for_opponent\", \"default\", FALSE, FALSE) ", (game_id, user_id, timestamp, timestamp))
        connection.commit()
        player_1 = True
    else:
        game_id = random.choice(public_games)[0]
        cursor.execute("update games set player_2_id = ?, status = \"in_progress\", started = ?, last_activity = ? where game_id = ?", (user_id, timestamp, timestamp, game_id))
        connection.commit()

        players = cursor.execute("select player_1_id, player_2_id from games where game_id = ?", [game_id]).fetchone()
        games[game_id] = game(game_id, io, players[0], players[1])

        io.emit("gameStart", room=games[game_id].room)

        player_1 = False
        game_started = True

    return { "id": game_id, "player_1": player_1, "game_started": game_started }, 200

dynamic_route = ["/game", random_game]