aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/server/server.py
blob: 71b6f0f52758755c4485e9afc65474d0d5b1d10b (plain) (blame)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import json
import toggle_game as tg


def recieve_game(game_fp) -> dict:
    """
    Load game in from json string, returning game dict
    Raises exception on invalid game
    """
    game = json.load(game_fp)
    if game['size'] < 0 or game['size'] > 100:
        raise Exception("Invalid Board size")
    if game['size'] != len(game['board']):
        raise Exception("Game size and Board size do not match")
    if game['finished']:
        raise Exception("The game is finished")
    if game['human_turn']:
        raise Exception("Not the computer's turn")
    if game['version'] != "0.0.0":
        raise Exception("Invalid version")
    return game


def create_game(length: int) -> None:
    return {
            'size': length,
            'finished': False,
            'board': [True] * length,
            'turn': 0,
            'version': '0.0.0',
            'human_turn': False,
            'winner': ''
            }

def send_game(game: dict) -> str:
    game_json = json.dumps(game)
    return game_json.encode('utf-8')


def play_game(game: dict) -> None:
    if game['turn'] == 0:
        game['human_turn'] = not tg.P(game['size']) > 0
        game['turn'] += 1

    if game['human_turn']:
        return

    game['turn'] += 1
    i = tg.find_move(game)
    game['board'] = tg.make_move(game, i)
    game['human_turn'] = True
    game['finished'] = tg.i_have_won(game)
    if game['finished']:
        game['winner'] = 'Computer'


def parse_query_params(query_string) -> dict:
    queries = {}
    for entry in query_string.split('&'):
        key, val = entry.split('=', 2)
        queries[key] = val

    return queries


def application(env, start_response):
    headers = [('Content-Type', 'application/json')]

    path_info = env['PATH_INFO']
    status = '200 OK'
    response = []

    match env['REQUEST_METHOD'], env['PATH_INFO']:
        case ('GET', '/toggle/game/new'):
            queries = parse_query_params(env['QUERY_STRING'])
            game = create_game(queries['size'])
            response.append(send_game(game))

        case ('POST', '/toggle/game/play'):
            try:
                game = recieve_game(env['wsgi.input'])

            except json.JSONDecodeError:
                status = '500 Internal Server Error'
                decode_error = {
                        'Error': 'json parsing error, is your request formatter correctly'
                        }
                response.append(json.dumps(decode_error).encode('utf-8'))

            play_game(game)
            response.append(send_game(game))

        case ('DELETE', _):
            status = '405 Method Not Allowed'
            headers.remove(('Content-Type', 'application/json'))

        case _:
            status = '404 Not Found'
            headers.remove(('Content-Type', 'application/json'))

    start_response(status, headers)
    return response


def main():
    pass