예제 #1
0
def post_handler(request):
    '''
    '''
    conn = updateGame.get_db_connection(
    )  # connect to that database (will create if it doesn't already exist)
    c = conn.cursor()
    c.execute(
        '''CREATE TABLE IF NOT EXISTS Login (kerberos text, password text);''')
    kerberos = request['form']['kerberos']
    if request['form'].get('new') == 'True':
        pw1 = request['form']['password1']
        pw2 = request['form']['password2']
        if pw1 == pw2:
            c.execute('''INSERT into Login VALUES (?,?);''', (kerberos, pw1))
            conn.commit()
            conn.close()
            return REDIRECT.format(HOME + kerberos)
        return LOGIN_TEXT.format(
            "Sorry, passwords do not match! Please try again.")
    pw = c.execute('''SELECT password FROM Login WHERE kerberos=?;''',
                   (kerberos, )).fetchone()
    if not pw:
        conn.commit()
        conn.close()
        return LOGIN_TEXT.format(
            "Sorry, this user does not exist. Please make an account.")
    password = request['form']['password']
    if pw[0] == password:
        conn.commit()
        conn.close()
        return REDIRECT.format(HOME + kerberos)
    conn.commit()
    conn.close()
    return LOGIN_TEXT.FORMAT("Sorry,wrong password.")
예제 #2
0
파일: home.py 프로젝트: mad4math/mafia
def get_handler(request):
    '''
    '''
    conn = updateGame.get_db_connection(
    )  # connect to that database (will create if it doesn't already exist)
    c = conn.cursor()
    kerberos = request['values']['kerberos']
    #    use the name of the database that has been used in other places (might not end up in the folder with the current script)
    #    connect to the database

    c.execute(
        '''CREATE TABLE IF NOT EXISTS playersT (timing timestamp, kerberos text, gameID int, espID text);'''
    )
    c.execute(
        '''CREATE TABLE IF NOT EXISTS votesTiming (timing timestamp, gameID int);'''
    )
    c.execute(
        '''CREATE TABLE IF NOT EXISTS rolesTe (kerberos text, gameID int, role text, status text);'''
    )
    kerberos = request['values']['kerberos']
    games = c.execute('''SELECT gameID FROM playersT WHERE kerberos=?;''',
                      (kerberos, )).fetchall()
    games = [str(x[0]) for x in games]
    games = list(dict.fromkeys(games))

    out = HTMLHEAD
    out += HEAD.format(urls['home'] + '?kerberos=' + kerberos, "black",
                       "black", urls['home'] + '?kerberos=' + kerberos,
                       urls['vote'] + '?kerberos=' + kerberos + '&gameID=home',
                       urls['gamedb'] + '?kerberos=' + kerberos,
                       urls['newgame'] + '?kerberos=' + kerberos)
    out += """<p>
               Hi, {}! Here are the games you are currently a part of:
            </p>
            <ul>
            """.format(kerberos)
    c.execute('''CREATE TABLE IF NOT EXISTS finishedGames (gameID int);''')
    old_games = c.execute('''SELECT gameID FROM finishedGames;''').fetchall()
    old_games = [str(x[0]) for x in old_games]
    new_list = ''
    old_list = ''
    for game in games:
        if game not in old_games:
            new_list += '<li><a href="{}"> Game: {} </a> </li>'.format(
                urls['status'] + '?kerberos=' + kerberos + '&gameID=' + game,
                game)
        else:
            old_list += '<li><a href="{}"> Game: {} </a> </li>'.format(
                urls['status'] + '?kerberos=' + kerberos + '&gameID=' + game,
                game)
    out += new_list + '</ul> <br> <br> Old games: <ul>' + old_list
    out += "</ul> </body> </html>  "

    return out
예제 #3
0
def request_handler(request):
    '''request should be a get request with 'kerberos':kerberos in its values, also 'gameID':gameID
    '''
    if request['method'] == 'GET':
        kerberos = request['values']['kerberos']
        gameID = int(request['values']['gameID'])
        conn = updateGame.get_db_connection(
        )  # connect to that database (will create if it doesn't already exist)
        c = conn.cursor(
        )  # make cursor into database (allows us to execute commands)
        killid = c.execute(
            '''SELECT espID FROM playersT WHERE kerberos=? AND gameID=?''',
            (kerberos, gameID)).fetchone()
        killid = killid[0]
        return killid
    return "Sorry, you can only send a get request"
예제 #4
0
파일: admin.py 프로젝트: mad4math/mafia
def request_handler(r):
    conn = updateGame.get_db_connection()
    c = conn.cursor()
    if r['method'] == "GET":
        game_id = r['values']['id']
        x = c.execute("select command from log where game_id = ?",
                      (game_id, )).fetchall()
        return '\n'.join(a[0] for a in x)
    elif r['method'] == 'POST':
        game_id = r['form']['id']
        result = ""
        for line in r['form']['commands'].split('\n'):
            print(">{}".format(line))
            s = updateGame.execute_command(line, gameID=game_id)
            if s: print(s)
        conn.close()
        return result
예제 #5
0
def get_handler(request):
    '''
    '''
    conn = updateGame.get_db_connection(
    )  # connect to that database (will create if it doesn't already exist)
    c = conn.cursor()
    c.execute(
        '''CREATE TABLE IF NOT EXISTS playersT (timing timestamp, kerberos text, gameID int);'''
    )
    kerberos = request['values']['kerberos']
    gameID = getGameID(c)
    out = HTMLHEAD
    out += HEAD.format(urls['home'] + '?kerberos=' + kerberos, "black",
                       "black", urls['home'] + '?kerberos=' + kerberos,
                       urls['vote'] + '?kerberos=' + kerberos + '&gameID=home',
                       urls['gamedb'] + '?kerberos=' + kerberos,
                       urls['newgame'] + '?kerberos=' + kerberos)
    best = c.execute('''SELECT kerberos FROM playersT WHERE gameID=?;''',
                     (gameID, )).fetchall()
    users = []
    #        append the users to the list of users in a random order
    for tup in set(best):
        if tup[0] != "":
            users.append(tup[0])
    if kerberos not in users:
        out += "<p> Game {} currently has {} people waiting to start. Do you want to join game {}? </p>".format(
            gameID, len(users), gameID)
        out += '''<form method="POST">
                    <input type="submit" value="Join game" />
                    <input type="hidden" name="kerberos" value="{}">
                    <input type="hidden" name="start" value="False" />
                 </form>
                    '''.format(kerberos)
    else:
        out += "<p> You are waiting to join game {}, which currently has {} people waiting to start.".format(
            gameID, len(users), gameID)
    out += "<p> To start game {}, click the button below. </p>".format(gameID)
    out += '''<form method="POST" >
                <input type="submit" value="Start game" />
                <input type="hidden" name="kerberos" value="{}">
                <input type="hidden" name="start" value="True" />
             </form>
                '''.format(kerberos)
    out += "</body></html>"
    return out
예제 #6
0
def get_handler(request):
    kerberos = request['values']['kerberos']
    conn = updateGame.get_db_connection()
    c = conn.cursor()
    old_games = c.execute('''SELECT gameID FROM finishedGames;''').fetchall()
    old_games = [str(x[0]) for x in old_games]
    games = c.execute(
        '''SELECT gameID FROM rolesTe WHERE kerberos=? ORDER BY gameID DESC;''',
        (kerberos, )).fetchall()
    games = [str(x[0]) for x in games]
    games = list(dict.fromkeys(games))
    games.sort(reverse=True)

    for game in games:

        if game not in old_games:
            return game
    return 'You are not in a game.'
예제 #7
0
def handle_get(request):
    if 'kerberos' in request['args'] and 'gameID' in request['args']:
        gameID = request['values']['gameID']
        kerberos = request['values']['kerberos']
        conn = updateGame.get_db_connection()
        c = conn.cursor(
        )  # make cursor into database (allows us to execute commands)
        c.execute(
            '''CREATE TABLE IF NOT EXISTS rolesTe (kerberos text, gameID int, role text, status text);'''
        )  # run a CREATE TABLE command
        role = c.execute(
            '''SELECT role FROM rolesTe WHERE gameID=? and kerberos=?;''',
            (gameID, kerberos)).fetchone()
        if role is None:
            return "0 waiting for game to start ..."
        info = str(1) + " " + str(role[0]) + ': ' + roles_dict[role[0]]
        return info
    return "there was an issue with your request"
예제 #8
0
파일: gameDB.py 프로젝트: mad4math/mafia
def handle_get(request):

    conn = updateGame.get_db_connection()
    c = conn.cursor(
    )  # make cursor into database (allows us to execute commands)
    kerberos = request['values']['kerberos']
    gameID = c.execute(
        '''SELECT gameID from playersT WHERE kerberos=? ORDER BY gameID DESC;''',
        (kerberos, )).fetchone()
    if not gameID:
        gameID = 0
    else:
        gameID = gameID[0]
    out1 = HTMLHEAD
    out1 += HEAD.format(
        urls['home'] + '?kerberos=' + kerberos, "black", "black",
        urls['home'] + '?kerberos=' + kerberos,
        urls['vote'] + '?kerberos=' + kerberos + '&gameID=home',
        urls['gamedb'] + '?kerberos=' + kerberos,
        urls['newgame'] + '?kerberos=' + kerberos)

    c.execute(
        '''CREATE TABLE IF NOT EXISTS statsT (kerberos text, wins int, games int);'''
    )  # run a CREATE TABLE command
    try:
        wins, games = c.execute(
            '''SELECT wins,games FROM statsT WHERE kerberos=?;''',
            (kerberos, )).fetchone()
        out1 += '<body bgcolor = {}>Hi, {}! You have won {}/{} games.'.format(
            '#EBF5FB', kerberos, wins, games) + win_games

    except:
        out1 += '<body bgcolor = {}>Hi, {}! You have not played any games!'.format(
            '#EBF5FB', kerberos) + no_games
    conn.commit()
    conn.close()
    out1 += """</font></body> </html> """
    return out1
예제 #9
0
파일: gameDB.py 프로젝트: mad4math/mafia
def handle_post(request):
    print(request)
    if 'kerberos' in request['form'] and 'win' in request['form']:
        kerberos = request['form']['kerberos']
        add = 0
        if request['form']['win'] == 'True':
            add = 1
            conn = updateGame.get_db_connection()
            c = conn.cursor(
            )  # make cursor into database (allows us to execute commands)

            def add_stats(kerberos, add, c):
                c.execute(
                    '''CREATE TABLE IF NOT EXISTS statsT (kerberos text, wins int, games int);'''
                )  # run a CREATE TABLE command
                try:
                    wins, games = c.execute(
                        '''SELECT wins,games FROM statsT WHERE kerberos=?;''',
                        (kerberos, )).fetchone()
                    c.execute(
                        '''UPDATE statsT SET wins=?, games=? WHERE kerberos=?;''',
                        (wins + add, games + 1, kerberos))  #with time
                except:
                    wins = 0
                    games = 0
                    c.execute('''INSERT into statsT VALUES (?,?,?);''',
                              (kerberos, add, 1))  #with time

                return "Win Percentage: " + str(wins + add) + "/" + str(games +
                                                                        1)

            add_stats(kerberos, add, c)
            conn.commit()
            conn.close()
        else:
            return "invalid request"
예제 #10
0
def handle_get(request):
    example_db = "__HOME__/playersT.db"  # just come up with name of database
    conn = updateGame.get_db_connection()
    c = conn.cursor(
    )  # make cursor into database (allows us to execute commands)
    out = ""

    if 'kerberos' in request['values']:
        status = ''

        kerberos = request['values']['kerberos']
        c.execute(
            '''CREATE TABLE IF NOT EXISTS rolesTe (kerberos text, gameID int, role text, status text);'''
        )  # run a CREATE TABLE command
        c.execute(
            '''CREATE TABLE IF NOT EXISTS playersT (timing timestamp, kerberos text, gameID int);'''
        )

        try:
            gameID = c.execute(
                '''SELECT gameID FROM playersT ORDER BY timing DESC;'''
            ).fetchone()
            gameID = int(gameID[0]) - 1
        except:
            gameID = 0

        roles = c.execute(
            '''SELECT status,role,kerberos FROM rolesTe WHERE gameID=?;''',
            (gameID, )).fetchall()

        other_roles = []
        role = None

        for rol in roles:
            if rol[2] == kerberos:
                status = rol[0]
                role = rol[1]
            else:
                other_roles.append((rol[0], rol[2]))

        if not role:
            conn.commit()
            conn.close()
            return 'Sorry, {} is not in the current game.'.format(kerberos)

        #        add on the heading which should be large and say welcome to the game
        out += """ Welcome to live action mafia! """

        #        check if the person is alive, because then the result will depend on the role
        if status == 'alive':
            out += 'Hi, {}! You are currently alive and your role is {}.'.format(
                kerberos, role)
        else:
            out += 'Hi, {}! Unfortunately, you have died in the game. ' \
                   'Your role was {}. Come back and play the next game!'.format(kerberos, role)

        if role == 'detective':
            a = c.execute(
                "select (suspect1, suspect2, victim, result) from inv where user=?",
                (kerberos, )).fetchall()

        out += '\nThe other players are: '

        other_roles.sort(key=lambda a: a[1])
        other_roles.sort(key=lambda a: a[0])

        for rol in other_roles:
            out += """\n {}, who is {} """.format(rol[1], rol[0])

        conn.commit()
        conn.close()
        return out

    conn.commit()
    conn.close()
    return "You must include your kerberos in your request."
예제 #11
0
def handle_post(request):
    conn = updateGame.get_db_connection()
    c = conn.cursor(
    )  # make cursor into database (allows us to execute commands)
    c.execute(
        '''CREATE TABLE IF NOT EXISTS playersT (timing timestamp, kerberos text, gameID int, espID text);'''
    )  # run a CREATE TABLE command

    gameID = request['form'].get('gameID')

    roles = 0
    start = False
    if 'kerberos' in request['form'] and 'start' in request['form']:

        kerberos = request['form']['kerberos']
        start = True if request['form']['start'] == 'True' else False
        try:
            gameID = c.execute(
                '''SELECT gameID FROM playersT ORDER BY timing DESC;'''
            ).fetchone()
            gameID = int(gameID[0])
#            print(gameID)
        except:
            gameID = 0
        add_player(datetime.datetime.now(), kerberos, gameID, c)
        #        if start:
        #        I edited this part so that it finds the current number of users with each post request and only creates a new game at start
        minutes5_ago = datetime.datetime.now() - datetime.timedelta(
            minutes=COLLECT_PLAYER_TIME)
        best = c.execute(
            '''SELECT kerberos FROM playersT WHERE gameID=? AND timing>?;''',
            (gameID, minutes5_ago)).fetchall()
        #        print(best)
        users = []
        #        append the users to the list of users in a random order

        for tup in set(best):
            if tup[0] != "":
                users.append(tup[0])

        extra = "Push start when ready."
        if start:

            #            c.execute('''INSERT into playersT VALUES (?,?,?,?);''',(datetime.datetime.now(), "", gameID+1,"")) #with time

            c.execute(
                '''CREATE TABLE IF NOT EXISTS votesTiming (timing timestamp, gameID int);'''
            )

            c.execute('''INSERT into votesTiming VALUES (?,?);''',
                      (datetime.datetime.now(), gameID + 1))  #with time

            extra = "Game is started!"
            #            conn.commit() # commit commands
            #            conn.close()
            #            print('creating game')

            create_game(users, gameID, c)
            c.execute('''INSERT into playersT VALUES (?,?,?,?);''',
                      (datetime.datetime.now(), "", gameID + 1, 0))  #with time

#        if not start:
#        return request
        conn.commit()

        conn.close()

        return 'Game ID is {}. There are currently {} people in the game. {}'.format(
            gameID, len(users), extra)
    return 'You must specify a user and whether or not to start the game.'
예제 #12
0
def handle_get(request):
    kerberos = request['values']['kerberos']
    gameID = request['values']['gameID']

    out = HTMLHEAD
    out += HEAD.format(urls['home'] + '?kerberos=' + kerberos, "black",
                       "black", urls['home'] + '?kerberos=' + kerberos,
                       urls['vote'] + '?kerberos=' + kerberos + '&gameID=home',
                       urls['gamedb'] + '?kerberos=' + kerberos,
                       urls['newgame'] + '?kerberos=' + kerberos)
    out += """<iframe src="https://giphy.com/embed/l2SpWPGLYJK94yY00" width="480" height="270" frameBorder="0" class="giphy-embed" allowFullScreen></iframe><br><br>"""
    out += '<body bgcolor = {}>Hi, {}! Here are the current votes for today.'.format(
        'white', kerberos)

    try:
        gameID = int(gameID)
    except:
        gameID = None

    out += '<br>'

    conn = updateGame.get_db_connection()
    c = conn.cursor(
    )  # make cursor into database (allows us to execute commands)
    c.execute(
        '''CREATE TABLE IF NOT EXISTS votes (timing timestamp, kerberos text, gameID int, vote text);'''
    )
    if type(gameID) == int:
        #        send_updates(str(gameID), c)
        last_time = c.execute(
            '''SELECT timing FROM votes WHERE gameID=? AND kerberos=? ORDER BY timing DESC;''',
            (gameID, 'last voting period')).fetchone()
        best = c.execute(
            '''SELECT kerberos FROM rolesTe WHERE gameID=? AND status=?;''',
            (gameID, 'alive')).fetchall()
        users = []
        for tup in set(best):
            if tup[0] != "":
                users.append(tup[0])

        if last_time:
            start = last_time[0]
        else:
            start = 0

        end = datetime.datetime.now()
        for voter in users:
            d = eval(
                c.execute(
                    "select artifact_data from inventory where game_id = ? and owner = ? and artifact = 'vote'",
                    (gameID, voter)).fetchone()[0])
            vote = (d['vote'], ) if 'vote' in d else None
            #vote = c.execute('''SELECT vote FROM votes WHERE gameID=? AND timing>? AND timing<? AND kerberos=? ORDER BY timing DESC;''',(gameID, start, end, voter)).fetchone()
            if vote is not None:
                vote = vote[0]
                out += voter + " voted for " + vote + "<br>"
    else:
        out += '<p> Please select a game to see current votes. </p>'
        out += '<ul>'
        games = c.execute('''SELECT gameID FROM playersT WHERE kerberos=?;''',
                          (kerberos, )).fetchall()
        games = [str(x[0]) for x in games]
        games = list(dict.fromkeys(games))
        c.execute('''CREATE TABLE IF NOT EXISTS finishedGames (gameID int);''')
        old_games = c.execute(
            '''SELECT gameID FROM finishedGames;''').fetchall()
        old_games = [str(x[0]) for x in old_games]
        for game in games:
            if game not in old_games:
                out += '<li><a href="{}"> Game: {} </a> </li>'.format(
                    urls['vote'] + '?kerberos=' + kerberos + '&gameID=' + game,
                    game)
        out += "</ul> </body> </html> "
    out += """</font></body> </html> """
    return out
예제 #13
0
def handle_post(request):
    to_return = "no dead"
    conn = updateGame.get_db_connection()
    c = conn.cursor(
    )  # make cursor into database (allows us to execute commands)
    c.execute('''CREATE TABLE IF NOT EXISTS finishedGames (gameID int);'''
              )  # run a CREATE TABLE command
    finished_games = c.execute(
        '''SELECT gameID from finishedGames''').fetchall()
    finished_games = [x[0] for x in finished_games]
    #    print(finished_games)
    if 'kerberos' in request['form'] and 'vote' in request[
            'form'] and 'gameID' in request['form']:
        c.execute(
            '''CREATE TABLE IF NOT EXISTS votes (timing timestamp, kerberos text, gameID int, vote text);'''
        )  # run a CREATE TABLE command
        kerberos = request['form']['kerberos']
        vote = request['form']['vote']
        gameID = request['form']['gameID']
        dead = c.execute(
            '''SELECT kerberos FROM rolesTe WHERE status!="alive";'''
        ).fetchall()
        dead = [x[0] for x in dead]
        #        send_updates(gameID, c)
        if vote == kerberos:
            return "You cannot vote for yourself."
        elif vote in dead:
            return "You cannot vote for dead people."
        if int(gameID) in finished_games:
            return 'This game has terminated.'
        alive = c.execute(
            '''SELECT kerberos FROM rolesTe WHERE gameID=? AND status="alive";''',
            (gameID, )).fetchall()
        alive = [x[0] for x in alive]
        if kerberos not in alive:
            return "Sorry, you must be a current, living member of the game to vote."
        c.execute(
            '''INSERT into votes VALUES (?,?,?,?);''',
            (datetime.datetime.now(), kerberos, gameID, vote))  #with time
        conn.commit()
        to_return = "You successfully voted for {}.".format(vote, )
    if 'end_voting' in request['form'] and 'gameID' in request['form']:

        c.execute(
            '''CREATE TABLE IF NOT EXISTS executions (timing timestamp, kerberos text, gameID int);'''
        )
        if request['form']['end_voting'] == 'True':
            gameID = int(request['form']['gameID'])
            if gameID in finished_games:
                return 'This game has terminated.'
            store = end_voting(gameID, c)
            #            return store
            c.execute('''INSERT into votes VALUES (?,?,?,?);''',
                      (datetime.datetime.now(), "last voting period", gameID,
                       ""))  #with time
            if store != None:
                c.execute(
                    '''UPDATE rolesTe SET status = "executed" WHERE kerberos = ? AND gameID = ?''',
                    (store, gameID))
                c.execute('''INSERT into executions VALUES (?,?,?);''',
                          (datetime.datetime.now(), store, gameID))
                return None
                conn.commit()
                all_players = c.execute(
                    '''SELECT role,kerberos,status FROM rolesTe WHERE gameID=? ;''',
                    (gameID, )).fetchall()
                alive_roles = []
                dead = []
                #        append the users to the list of users in a random order
                for tup in set(all_players):
                    if tup[0] != "":
                        if tup[2] != "dead" and tup[2] != "executed":
                            alive_roles.append(tup[0])
                        else:
                            dead.append(tup[0])
                others_alive = [x for x in alive_roles if x != 'mafia']
                if 'mafia' not in alive_roles:

                    print('citizens win')
                    for player in all_players:
                        role = player[0]
                        kerb = player[1]
                        win = 'True'
                        if role == 'mafia':
                            win = 'False'
#                        return kerberos
                        gameDB_post(
                            {
                                'method': 'POST',
                                'args': ['kerberos', 'start'],
                                'form': {
                                    'kerberos': kerb,
                                    'win': win
                                }
                            }, c)
#                        requests.post(urls['gamedb'],data={'kerberos':kerb,'win':win})
#                        return gameID
#                        print(test.text)
                    c.execute('''INSERT into finishedGames VALUES (?);''',
                              (gameID, ))
                    conn.commit()
                elif not others_alive:
                    print('mafia win')
                    for player in all_players:
                        role = player[0]
                        kerb = player[1]
                        win = 'True'
                        if role != 'mafia':
                            win = 'False'
                        gameDB_post(
                            {
                                'method': 'POST',
                                'args': ['kerberos', 'start'],
                                'form': {
                                    'kerberos': kerb,
                                    'win': win
                                }
                            }, c)
#                        test = requests.post(urls['gamedb'],data={'kerberos':kerb,'win':win})
#                        print(test.text)
#                    return all_players
                    c.execute('''INSERT into finishedGames VALUES (?);''',
                              (gameID, ))
                    conn.commit()


#                        return kerb,win
#                now need to mark the game as done so people don't try to post a bunch of times after the game is done
                to_return = store + " died"

    conn.commit()
    conn.close()
    return to_return
예제 #14
0
def handle_post(request):
    '''post requests sent by clicking buttons on this page come back to this page
    this function reformats them to send to updateGame and update the game appropriately
    lets people know their requests went through
    '''
    #    start the html output
    out = HTMLHEAD

    conn = updateGame.get_db_connection()
    c = conn.cursor(
    )  # make cursor into database (allows us to execute commands)
    #    for now no login required
    #    check if they submitted a kerb to check on
    if 'kerberos' in request['values']:
        kerberos = request['values']['kerberos']
        #        make sure the tables you need exist so you don't get errors later
        c.execute(
            '''CREATE TABLE IF NOT EXISTS rolesTe (kerberos text, gameID int, role text, status text);'''
        )  # run a CREATE TABLE command
        c.execute(
            '''CREATE TABLE IF NOT EXISTS playersT (timing timestamp, kerberos text, gameID int, espID text);'''
        )
        #        got the current game ID using Elizabeth's method from newGame
        try:
            gameID = c.execute(
                '''SELECT gameID FROM playersT ORDER BY timing DESC;'''
            ).fetchone()
            gameID = int(gameID[0]) - 1
        except:
            gameID = 0
        if request['form'].get('gameID'):
            gameID = request['form']['gameID']
#        assumes they only have one entry with this kerberos
#        get the roles of all the people in the current game
        newgame = None
        if request['form'].get('startgame'):
            #            return 'testing'
            start = 'True'
            conn.commit()
            conn.close()
            response = requests.post(urls['new'],
                                     data={
                                         'kerberos': kerberos,
                                         'start': start,
                                         'gameID': gameID
                                     })
            out = HTMLHEAD
            out += HEAD.format(
                urls['home'] + '?kerberos=' + kerberos, "black", "black",
                urls['home'] + '?kerberos=' + kerberos,
                urls['vote'] + '?kerberos=' + kerberos + '&gameID=home',
                urls['gamedb'] + '?kerberos=' + kerberos,
                urls['newgame'] + '?kerberos=' + kerberos)
            #        append the users to the list of users in a random order
            out += response.text
            #
            out += '<p><a href="{}"> Click to see game: {} </a> </p>'.format(
                urls['status'] + '?kerberos=' + kerberos + '&gameID=' + gameID,
                gameID)
            out += """ </body> </html>"""
            return out

        c = conn.cursor()
        roles = c.execute(
            '''SELECT status,role,kerberos FROM rolesTe WHERE gameID=?;''',
            (gameID, )).fetchall()

        #        keep track of the people you're not looking for
        other_roles = []
        role = None
        #        check if this kerb is in the current game; also keep track of the other players
        for rol in roles:
            if rol[2] == kerberos:
                status = rol[0]
                role = rol[1]
            else:
                other_roles.append((rol[0], rol[2], rol[1]))

#        if the person isn't playing, let them know
        if not role and not newgame:

            conn.commit()
            conn.close()
            return 'Sorry, {} is not in game {}.'.format(kerberos, gameID)
#        secret admirer comes out weird (as just secret), prob because it's two words
        if role == 'secret' or role == 'sa':
            role = 'secret admirer'
#        font color will be white only if the background is black, which is for mafia only
        if status == 'dead' or status == 'executed' or role != 'mafia':
            fontcolor = 'black'
        else:
            fontcolor = "white"

#        add on the heading which should be large and say welcome to the game

        out += HEAD.format(
            urls['home'] + '?kerberos=' + kerberos, fontcolor, fontcolor,
            urls['home'] + '?kerberos=' + kerberos,
            urls['vote'] + '?kerberos=' + kerberos + '&gameID=' + str(gameID),
            urls['gamedb'] + '?kerberos=' + kerberos,
            urls['newgame'] + '?kerberos=' + kerberos)

        #        check if the person is alive, because then the result will depend on the role

        if status == 'alive' and not newgame:
            color = colors.get(role)
            if not color:
                color = 'white'
            out += INTRO.format(color, gameID, kerberos, role)
            #            if role in gifs:
            #                message  = updateGame.execute_command("show_log {}".format(kerberos),gameID=gameID)
            #
            #                if message:
            #                    message_list = message.split('\n')
            #                    out += '<ul>'
            #                    for message in message_list:
            #                        out += '<li>' + message + '</li>'
            #                    out += '</ul>'
            #                out += str(message)
            out += '<br><br>'
            #            if they're voting, send a voting request
            if 'vote' in request['form']:
                vote = request['form']['vote']
                #                out += requests.post(VOTE_URL, data = {'vote':vote,'kerberos':kerberos, 'gameID':str(gameID)}).text
                out += updateGame.execute_command("{} vote {}".format(
                    kerberos, vote),
                                                  gameID=gameID)
                out += "<br>"
#
            elif role == 'mafia':
                out += str(request)
                lat, lon = request['form']['place'].split("|")
                out += updateGame.execute_command(
                    "{} mafia_kill \"['{}', {}, {}]\"".format(
                        kerberos, request['form']['victim'], lat, lon),
                    gameID=gameID)
                out += '<br>'
            elif role == 'detective':
                suspect1 = request['form']['suspect1']
                suspect2 = request['form']['suspect2']
                victim = request['form']['victim']
                out += updateGame.execute_command(
                    "{} pair_investigation \"['{}','{}','{}']\"".format(
                        kerberos, suspect1, suspect2, victim),
                    gameID=gameID)
                out += '<br>'
            elif role == 'doctor':
                place = request['form']['place']
                victim = request['form']['victim']
                lat, lon = place.split("|")
                out += updateGame.execute_command(
                    "{} doctor_role \"['{}',{},{}]\"".format(
                        kerberos, victim, lat, lon),
                    gameID=gameID)
                out += '<br> <br>'
            elif role == 'priest':
                sinners = []
                saints = []
                for entry in request['form']:
                    if 'saint' in entry:
                        saints.append(request['form'][entry])
                    if 'sinner' in entry:
                        sinners.append(request['form'][entry])
#                print('sending command',sinners,saints)
                response = updateGame.execute_command(
                    kerberos + ''' priest_role "{'sinners':''' + str(sinners) +
                    ''', 'saints':''' + str(saints) + '''}"''',
                    gameID=gameID)
                if response:
                    out += response
                else:
                    out += 'Response recorded!'
                print('command sent')
                #                out += '<p> Recorded! </p>'
                out += '<br><br>'
            elif role == 'secret admirer' and 'admired' in request['form']:
                admired = request['form']['admired']
                out += "<p> Admiration recorded! </p>"
                updateGame.execute_command(kerberos + ' sa_role ' + admired,
                                           gameID=gameID)
            elif 'ability' in request['form']:
                ability = request['form']['ability']
                if ability == "sa_set_investigation":
                    targets = '"[{}]"'.format(",".join(
                        "'{}'".format(x)
                        for x in request['form']['set'].split(",")))
                    s = updateGame.execute_command(kerberos + ' ' + ability +
                                                   ' ' + targets,
                                                   gameID=gameID)
                elif ability == "sa_kill_investigation":
                    s = updateGame.execute_command(kerberos + ' ' + ability +
                                                   ' ' +
                                                   request['form']['suspect'],
                                                   gameID=gameID)
                if s: out += s + "<br>"
#        attach the dead background color and gif if you are dead
        else:
            out += '''<body bgcolor = {}>
                    Currently viewing gameID: {} <br>
                    Hi, {}! Unfortunately, you {} in the game. Your role was {}. Come back and play the next game!

            '''.format(colors['dead'], gameID, kerberos, message_dict[status],
                       role) + gifs['status']
#        start a list of the other players in the game
        out += '<br> The other players are: <br>'
        #        alphabetize the list by name and then by status so all the dead and all the alive are grouped together
        other_roles.sort(key=lambda a: a[1])
        other_roles.sort(key=lambda a: a[0])
        #        add the other statuses to the list of other players

        out += """<ul class="others-alive"> """

        for rol in other_roles:
            out += """<li> {}, who is {} </li> """.format(rol[1], rol[0])
        out += """</ul> """

        if role == 'mafia':
            out += '<br><br> <p> The other mafia members are: <ul class="others-alive">'
            for rol in other_roles:
                if rol[2] == 'mafia':
                    out += '<li> {}, who is </li>'.format(rol[0])
            out += '</ul> </p>'

#        end the text
        if role in gifs:

            out += gifs[role]
        out += """</div></div></font></body> </html> """
        #        close and commit the changes
        conn.commit()
        conn.close()
        #        return the text you generated
        return out
#    close the connection and let them know they need a kerb
    conn.commit()
    conn.close()
    return "You must include your kerberos in your request."
예제 #15
0
def handle_get(request):
    '''figures out if the player submitted is in the current game
    if they are playing, displays information about their role and who else is still in the game
    also adds buttons for sending requests
    '''

    #    connect to the database
    conn = updateGame.get_db_connection()
    c = conn.cursor(
    )  # make cursor into database (allows us to execute commands)
    #        got the current game ID using Elizabeth's method from newGame
    try:
        gameID = c.execute(
            '''SELECT gameID FROM playersT ORDER BY timing DESC;''').fetchone(
            )
        gameID = int(gameID[0]) - 1
    except:
        gameID = 0
    if request['values'].get('gameID'):
        gameID = request['values']['gameID']
    c.execute(
        '''CREATE TABLE IF NOT EXISTS rolesTe (kerberos text, gameID int, role text, status text);'''
    )
    all_players = c.execute(
        '''SELECT role,kerberos,status FROM rolesTe WHERE gameID=? ;''',
        (gameID, )).fetchall()
    alive_roles = []
    for tup in set(all_players):
        if tup[0] != "":
            if tup[2] == "alive":
                alive_roles.append(tup[0])
#    start the html output
    out = HTMLHEAD
    #    use the name of the database that has been used in other places (might not end up in the folder with the current script)

    c.execute('''CREATE TABLE IF NOT EXISTS finishedGames (gameID int);''')
    finished_games = c.execute(
        '''SELECT gameID from finishedGames''').fetchall()
    finished_games = [x[0] for x in finished_games]
    #    for now no login required
    #    check if they submitted a kerb to check on
    if 'kerberos' in request['values']:
        kerberos = request['values']['kerberos']
        #        make sure the tables you need exist so you don't get errors later
        #        c.execute('''CREATE TABLE IF NOT EXISTS rolesTe (kerberos text, gameID int, role text, status text);''') # run a CREATE TABLE command
        c.execute(
            '''CREATE TABLE IF NOT EXISTS playersT (timing timestamp, kerberos text, gameID int, espID text);'''
        )

        #        assumes they only have one entry with this kerberos
        #        get the roles of all the people in the current game
        roles = c.execute(
            '''SELECT status,role,kerberos FROM rolesTe WHERE gameID=?;''',
            (gameID, )).fetchall()

        #        keep track of the people you're not looking for
        other_roles = []
        role = None
        #        check if this kerb is in the current game; also keep track of the other players
        for rol in roles:
            if rol[2] == kerberos:
                status = rol[0]
                role = rol[1]
            else:
                other_roles.append((rol[0], rol[2], rol[1]))
#        if the person isn't playing, let them know
        if not role:
            games = c.execute(
                '''SELECT gameID FROM playersT WHERE kerberos=?;''',
                (kerberos, )).fetchall()
            games = [x[0] for x in games]
            if int(gameID) not in games:
                conn.commit()
                conn.close()
                return 'Sorry, {} is not in game {}.'.format(kerberos, gameID)
        if role == 'secret' or role == 'sa':
            role = 'secret admirer'

#        font color will be white only if the background is black, which is for mafia only
        if not role or status == 'dead' or status == 'executed' or role != 'mafia':
            fontcolor = 'black'
        else:
            fontcolor = "white"

#        add on the heading which should be large and say welcome to the game

        out += HEAD.format(
            urls['home'] + '?kerberos=' + kerberos, fontcolor, fontcolor,
            HOME_URL + '?kerberos=' + kerberos,
            VOTE_URL + '?kerberos=' + kerberos + '&gameID=' + str(gameID),
            GAMEDB + '?kerberos=' + kerberos,
            NEWGAME_URL + '?kerberos=' + kerberos)
        best = c.execute('''SELECT kerberos FROM playersT WHERE gameID=?;''',
                         (gameID, )).fetchall()
        users = []
        #        append the users to the list of users in a random order
        for tup in set(best):
            if tup[0] != "":
                users.append(tup[0])
        if not role:
            out += NOTSTARTED.format(gameID, len(users), kerberos, gameID)
            out += """</font></body> </html> """
            conn.commit()
            conn.close
            return out

        out += '<div class="row"> <div class="column">'
        #        check if the person is alive, because then the result will depend on the role
        if status == 'alive':
            color = colors.get(role)
            if not color:
                color = 'white'
            out += INTRO.format(color, gameID, kerberos, role)
            if role in gifs:
                message = updateGame.execute_command(
                    "show_log {}".format(kerberos), gameID=gameID)

                if message:
                    message_list = message.split('\n')
                    out += '<ul>'
                    for message in message_list:
                        out += '<li>' + message + '</li>'
                    out += '</ul>'
#                out += str(message)

            if int(gameID) not in finished_games:
                #                out += str(finished_games)
                if role == 'mafia':
                    #                give them a kill option if they're a mafia member
                    out += MAFIA_ACT + MAFIA_ACT2.format(gameID)
    #            give them an investigate option if they're a detective
                elif role == 'detective':
                    out += DETECTIVE_ACT.format(gameID)

    #            give them a save ability if they're a doctor and someone has been killed recently
                elif role == 'doctor':
                    c.execute(
                        '''CREATE TABLE IF NOT EXISTS killsRecord (killer text, victim text, gameID int, time timestamp,date text,lat float, lon float);'''
                    )
                    c.execute(
                        '''SELECT * FROM killsRecord ORDER BY time DESC;'''
                    ).fetchone()
                    #                check for the most recent kill
                    kill_info = c.execute(
                        '''SELECT * FROM killsRecord ORDER BY time DESC;'''
                    ).fetchone()
                    #                check if there even was a kill
                    if kill_info != None:
                        dead_status = c.execute(
                            '''SELECT status FROM rolesTe WHERE kerberos=?;''',
                            (kill_info[1], )).fetchone()[0]
                        #                        print(dead_status)
                        #                    check the time of the most recent kill
                        kill_time = datetime.datetime.strptime(
                            kill_info[3], '%Y-%m-%d %H:%M:%S.%f')
                        minutes_since_kill = (datetime.datetime.now() -
                                              kill_time).total_seconds() / 60
                        #                    if the kill has happened recently enough, give a save option
                        if minutes_since_kill < SAVE_TIME and dead_status != 'alive':
                            #                            out += DOCTOR_ACT.format(kill_info[1],round(kill_info[5],4),round(kill_info[6],4),kill_info[1],kerberos,gameID)
                            out += '''<p>{} has been murdered at {},{}.'''.format(
                                kill_info[1], round(kill_info[5], 4),
                                round(kill_info[6], 4)) + '''
                                        Go save them!! </p>
                                        <form method="POST" id="mafia">
                                        <input type="hidden" name="victim" value="{}"/>'''.format(
                                    kill_info[1]) + '''
                                        <input type="hidden" name="kerberos" value="{}"/>'''.format(
                                        kerberos) + '''
                                        <input type = "hidden" name = "gameID" value ="{}"/>'''.format(
                                            gameID) + '''
                                    <input type="hidden" name="place" id="placeField" value = ""/>
                                    ''' + location_script + '''
                                    </form> <button onclick="getLocation()">Save them!</button>  <br>  <br>  <br> '''

                elif role == 'priest':
                    num_per_list = int(np.ceil(len(alive_roles) * .1))
                    out += PRIEST_ACT.format(gameID)

                    for i in range(num_per_list):
                        out += '''<input type="text" name="saint{}" /> <br>'''.format(
                            i)
                    out += '''<br> Who are the sinners? <br> '''
                    for i in range(num_per_list):
                        out += '''<input type="text" name="sinner{}" /><br>'''.format(
                            i)
                    out += '''<input type="hidden" name="kerberos" value="{}"/> 
                            <input type="submit" value="submit"/>
                            </form> '''.format(kerberos)

                elif role == 'secret admirer':
                    abilities = updateGame.get_abilities(kerberos, gameID)
                    abilities = [x[1] for x in abilities]
                    #                    out += str(abilities)
                    if "sa_role" in abilities:
                        out += '''<form method="POST"> Who would you like to admire today?
                                    <input type="text" name="admired" />
                                    <input type="hidden" name="gameID" value="{}" />
                                    <input type="submit" value="submit"/></form>
                        '''.format(gameID)
                    if "sa_set_investigation" in abilities:
                        out += '''<form method="POST"> Someone killed your admiree. Who do you think did it? 
                        Enter a comma separated list and you will be told if the killer is in that set.
                        <input type="text" name="set" />
                        <input type="hidden" name="gameID" value="{}" /><input type="hidden" name="ability" value="{}" />
                        <input type="submit" value="investigate!"/></form>'''.format(
                            gameID, "sa_set_investigation")
                    if "sa_kill_investigation" in abilities:
                        out += '''<form method="POST"> Someone killed your admiree. Who do you think did it? Enter a single name and you will be told if they did it.
                        <input type="text" name="suspect" />
                        <input type="hidden" name="gameID" value="{}" /><input type="hidden" name="ability" value="{}" />
                        <input type="submit" value="investigate!"/></form>'''.format(
                            gameID, "sa_kill_investigation")
    #            let people vote to execute if they are alive

                out += VOTINGFORM.format(gameID)
            else:
                all_players = c.execute(
                    '''SELECT role,kerberos,status FROM rolesTe WHERE gameID=? ;''',
                    (gameID, )).fetchall()
                alive_roles = []
                for tup in set(all_players):
                    if tup[0] != "":
                        if tup[2] != "dead" and tup[2] != "executed":
                            alive_roles.append(tup[0])
                if 'mafia' in alive_roles:
                    won = 'mafia'
                else:
                    won = 'citizens'
                out += """<p> This game is over.The {} won. </p>""".format(won)
#                out += flaskrequest.environ.get('HTTP_X_REAL_IP', flaskrequest.remote_addr) + '<br>'
#        attach the dead background color and gif if you are dead
        else:

            out += '''<body bgcolor = {}>
                    Currently viewing gameID: {} <br>
                    Hi, {}! Unfortunately, you {} in the game. Your role was {}. Come back and play the next game!

            '''.format(colors['dead'], gameID, kerberos, message_dict[status],
                       role) + gifs[status]
            out += '</div> <div class="column">'
            if int(gameID) in finished_games:
                all_players = c.execute(
                    '''SELECT role,kerberos,status FROM rolesTe WHERE gameID=? ;''',
                    (gameID, )).fetchall()
                alive_roles = []
                for tup in set(all_players):
                    if tup[0] != "":
                        if tup[2] != "dead" and tup[2] != "executed":
                            alive_roles.append(tup[0])
                if 'mafia' in alive_roles:
                    won = 'mafia'
                else:
                    won = 'citizens'
                out += """<p> This game is over.The {} won. </p>""".format(won)
#        start a list of the other players in the game
        out += '</div> <div class="column" >'
        out += '<br> The other players are: <br>'
        #        alphabetize the list by name and then by status so all the dead and all the alive are groped together
        other_roles.sort(key=lambda a: a[1])
        other_roles.sort(key=lambda a: a[0])
        #        add the other statuses to the list of other players
        out += """<ul class="others-alive"> """

        for rol in other_roles:
            out += """<li> {}, who is {} </li> """.format(rol[1], rol[0])
        out += """</ul> """

        if role == 'mafia':
            out += '<br><p>The other mafia members are: <ul class="others-alive">'
            for rol in other_roles:
                if rol[2] == 'mafia':
                    out += '<li> {}, who is {} </li>'.format(rol[1], rol[0])
            out += '</ul></p>'

        if role in gifs:
            out += gifs[role]

#        end the text
        out += """</div></div></font></body> </html> """
        #        close and commit the changes
        conn.commit()
        conn.close()
        #        return the text you generated
        return out


#    close the connection and let them know they need a kerb
    conn.commit()
    conn.close()
    return "You must include your kerberos in your request."