components.py 1.91 KB
Newer Older
Sorrel Harriet's avatar
Sorrel Harriet committed
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
#!/usr/bin/env python3

""" 
	This module provides a set of reuseable functions
	which provide the main app functionality.
	We could even go a stage further and separate
	database interactions from logic...
"""

from config import config
import utils

def home():
    """ The homepage functionality
    """
    print( utils.render_template( config['TEMPLATE_DIR'] + 'home.html') )
    return

def play_game(cursor, player_id):
    """ The game interface
        Initiates a new hangman game
        for the current user
    """
    # define query to fetch a random row from the Word table
    query = ("SELECT letters, hint FROM Word ORDER BY RAND() LIMIT 1")

    # execute the query
    cursor.execute(query)
    # if a word came back, output the game board
    for (letters, hint) in cursor:
        print( utils.render_template( config['TEMPLATE_DIR']+'hangman.html', data=[player_id, letters, hint, player_id] ) )

def record_game(cursor, form_data):
    """ Check for form submission
        and record game in database
    """
    # make a string based on won status
    if int(form_data['won'].value) == 0:
        game_status = 'loss'
    else:
        game_status = 'win'

    # define a query to insert a new row in Game table
    query = ("INSERT INTO Game (player_id, won, guessed_word) VALUES (%s, %s, %s)")
    
    # define data as tuple to replace tokens in query
    data = ( int(form_data['player_id'].value), int(form_data['won'].value), form_data['guessed_word'].value)

    # execute the query
    cursor.execute(query, data)

    # check if rows were produced
    if cursor.lastrowid:
        # output message
        print( utils.render_template( config['TEMPLATE_DIR']+'record-game.html', data=[game_status] ) )
    else:
        # the game was not recorded
        return False

def leaderboard():
    """ The leaderboard component
    """
    print( utils.render_template( config['TEMPLATE_DIR'] + 'leaderboard.html') )
    return