Пример #1
0
    def test_end_game_function(self, mock_stdout):
        """ Test that the end of game function displays the proper text. """

        game.end_game(self.player1, self.player2)

        function_text = ("\tThe final score is:\n\t" + self.player1.name +
                         ":" + str(self.player1.hand.points) + "\n\t" +
                         self.player2.name + ":" +
                         str(self.player2.hand.points) + "\n\n" +
                         "The winner is " + self.player2.name + " With " +
                         str(self.player2.hand.points) + " points!\n\n")

        self.assertEqual(mock_stdout.getvalue(), function_text)
Пример #2
0
def _set_friendship(user_id, friend_id, relation):
    try:
        User.objects.get(obfuscated_id=user_id)
        User.objects.get(obfuscated_id=friend_id)
    except User.DoesNotExist:
        raise RemoteException('Invalid user id.')

    if user_id == friend_id:
        raise RemoteException(
            'Cannot set friendship between two identical users')

    # If friend_id has blocked user_id, return invalid user id
    friendship, _ = Friend.objects.get_or_create(user_id1=friend_id,
                                                 user_id2=user_id)
    if friendship.relation == config.FRIEND_STATUS_BLOCKED:
        raise RemoteException('Invalid user id.')

    # If too many friends deny request
    if relation == config.FRIEND_STATUS_FRIEND:
        if _get_num_friends(
                user_id=user_id) >= config.FRIEND_LIMIT or _get_num_friends(
                    user_id=friend_id) >= config.FRIEND_LIMIT:
            raise RemoteException('Too many friends')

    # Otherwise, do as normal for the reverse relation
    if relation == config.FRIEND_STATUS_BLOCKED:
        friendship.relation = config.FRIEND_STATUS_REMOVED
    else:
        friendship.relation = relation
    friendship.save()

    # If removing or blocking friend and there is an active game, end the game
    if relation == config.FRIEND_STATUS_BLOCKED or relation == config.FRIEND_STATUS_REMOVED:
        existing_game = None
        try:
            existing_game = game.get_game_status(user_id=user_id,
                                                 friend_id=friend_id)
        except RemoteException:
            pass
        if existing_game is not None and existing_game.active:
            game.end_game(user_id=user_id,
                          game_id=existing_game.game_id,
                          award_stars=False)

    # This relation is a straightforward assignment
    friendship, _ = Friend.objects.get_or_create(user_id1=user_id,
                                                 user_id2=friend_id)
    friendship.relation = relation
    friendship.save()

    return SuccessPacket()
Пример #3
0
    def testEndGame(self):
        user1_id = User.objects.get(name='user1').obfuscated_id
        user2_id = User.objects.get(name='user2').obfuscated_id
        game.start_new_game(user_id=user1_id, friend_id=user2_id)
        game_id = Game.objects.get(user_id1=user1_id, user_id2=user2_id).id

        game_remote = game.end_game(user_id=user1_id, game_id=game_id)
        self.assertFalse(game_remote.active)
        self.assertFalse(Game.objects.get(id=game_id).active)
Пример #4
0
def end_game():
    playermgmt.ensure_session_vars(auth)
    response.generic_patterns = ['json']
    wininfo = gluon.contrib.simplejson.loads(request.body.read())

    try:
        saveid = game.end_game(request.vars.game_id, wininfo)
        websocket_send("http://" + config.websocket_server, 
                       gluon.contrib.simplejson.dumps(
                            {"gameFinished": True}),
                            config.websocket_key,
                            str(request.vars.game_id))
        return {"saveid": saveid}  
    #except game.storeGameException as e:
    except e:
        pass
Пример #5
0
def query(request):
        context = RequestContext(request, {})
        gid = ''
        data = {}
        if request.COOKIES.has_key('gid'):
            gid = request.COOKIES['gid']
        game = retrieve_game(gid)
        if game:
            game.issue_query()
            store_game(gid, game)
            data = game.get_game_state()

        new_high = False
        if game.is_game_over():
            # check if this is a high score
            # update userprofile stats
            new_high = end_game(request.user, game)

        return render_to_response('asg/game.html', {'sid':gid, 'data': data, 'new_high':new_high}, context)
Пример #6
0
    def testGetUserGames(self):
        user1_id = User.objects.get(name='user1').obfuscated_id
        user2_id = User.objects.get(name='user2').obfuscated_id
        user3_id = User.objects.get(name='user3').obfuscated_id
        user4_id = User.objects.get(name='user4').obfuscated_id
        user0_id = User.objects.get(name='user0').obfuscated_id

        game1 = game.start_new_game(user_id=user1_id, friend_id=user2_id)
        game2 = game.start_new_game(user_id=user1_id, friend_id=user3_id)
        game3 = game.start_new_game(user_id=user4_id, friend_id=user1_id)

        user1_games = game.get_user_games(user_id=user1_id)
        user0_games = game.get_user_games(user_id=user0_id)

        self.assertEqual(len(user1_games.games), 3)
        self.assertEqual(len(user0_games.games), 0)

        game.end_game(user_id=user1_id, game_id=game1.game_id)
        game.end_game(user_id=user1_id, game_id=game2.game_id)
        game.end_game(user_id=user1_id, game_id=game3.game_id)

        user1_games = game.get_user_games(user_id=user1_id)
        self.assertEqual(len(user1_games.games), 0)
Пример #7
0
async def on_message(message):
    message_delete = message
    message_author = message.author
    message_author_id = message.author.id
    message_channel = message.channel
    message_content = message.content.lower()

    if message_content.startswith(bot_trigger + 'join'):
        game.join_player(message_author_id)
        await bot.send_message(
            message.channel, "<@%s> has joined the game." % message_author_id)

        print(message_author)

        print(game.players)
    if message_content.startswith(bot_trigger + 'leave'):
        game.leave_player(message_author_id)
        await bot.send_message(message.channel,
                               "<@%s> has left the game." % message_author_id)

        print(game.players)
    if message_content.startswith(bot_trigger + 'purge'):
        game.purge()
        await bot.send_message(message.channel, "All users purged!")

        print(game.players)

    if message_content.startswith(bot_trigger + 'startgame'):
        if game.is_live:
            await bot.send_message(message.channel, 'Game is still ongoing.')
        else:
            game.start_game()

            for player in game.players:
                await bot.send_message(discord.User(id=player.name),
                                       embed=embeded_message(
                                           player.role,
                                           game._game_data['locations'][
                                               game.location]['Location']))

            await bot.send_message(message.channel, "The game has started!")

            location_title = "Spyfall - Locations List"
            location_content = ''
            for i in game.loc_list:
                location_content += "**%s**\n" % i

            loc_embed = discord.Embed(title=location_title,
                                      description=location_content)

            locs = await bot.send_message(message.channel, embed=loc_embed)

            # Create a simple timer to time the game.
            time = await bot.send_message(message.channel,
                                          game.get_formatted_time())

            while game.is_live and game.tick():
                await bot.edit_message(time, game.get_formatted_time())
                await asyncio.sleep(1)

            # Loop exited, game has ended or has run out of time. End it and clear messages.
            await bot.delete_message(locs)
            await bot.delete_message(time)

            # If game is still live, it means the spy has not been revealed yet even though the time is up.
            # Players still have a last chance to vote who the spy is before ending the game.
            if game.is_live:
                await bot.send_message(
                    message.channel,
                    "Time's up! Vote who you think the spy is now.")

    if message_content.startswith(bot_trigger + 'players'):
        playing = 'Current Players:\n'
        for player in game.players:
            playing += "<@%s>" % player.name
            playing += ' '

        await bot.send_message(message.channel, playing)

    if message_content.startswith(bot_trigger + 'reveal'):
        reveal_title = 'Spyfall - Reveal'
        reveal_location = 'The Location Was --> %s\n' % (
            game._game_data['locations'][game.location]['Location'])

        reveal_players = ''
        for player in game.players:
            reveal_players += '<@%s> --> %s\n' % (player.name, player.role)

        reveal_content = reveal_location + reveal_players

        reveal_embed = discord.Embed(title=reveal_title,
                                     description=reveal_content)

        await bot.send_message(message.channel, embed=reveal_embed)
        game.end_game()

    if message_content.startswith(bot_trigger + 'settings'):
        command = message_content.split()
        setting = command[1]
        value = command[2]

        if setting == 'time':
            try:
                game.set_time(int(value))
                await bot.send_message(
                    message.channel,
                    'Game time set to {} seconds.'.format(game.round_time))
            except ValueError:
                # Show error message if an invalid integer was entered for time.
                await bot.send_message(
                    message.channel,
                    'Invalid value specified for "{}".'.format(setting))
        else:
            await bot.send_message(message.channel,
                                   'Invalid settings command.')
Пример #8
0
def endGame(request):
    context = RequestContext(request, {})
    gid = ''
    star_info = [0, 0, 0]
    star_thisGame = 0
    data = {}
    global access_limit
    access_limit = 10

    nextTreasureNo = 10 - access_limit

    if request.COOKIES.has_key('gid'):
        gid = request.COOKIES['gid']
    game = retrieve_game(gid)
    if game:

        # # check if query success or not
        # if query_msg == True:
        #     log_move_event(request.user.id, game, False, False)

        # gems coating here
        gain_list = []
        round = game.current_round
        for i in range(len(round)):
            r = round[i]
            gain_list.append(str(r['gain']))

        global treasure_display_list
        treasure_display_list = []

        # global current_display_list
        # current_display_list = gems_coating(gameId, gain_list)

        log_move_event(request.user.id, game, current_display_list, False,
                       True)
        store_game(gid, game)
        data = game.get_game_state()
        data['gameover'] = True

        rounds_list = data['round']
        zipped_data = zip(current_display_list, rounds_list)

    if game.id != 6:
        star_info = star_game(game.id)
        star_thisGame = star_calculate(data['points'], unlockScore[game.id])
        new_high = False

    # check if this is a high score
    # update userprofile stats
    log_move_event(request.user.id, game, current_display_list, False, True)
    new_high = end_game(request.user, game)

    global noise
    noise = 4

    if game.id == 6:
        return render_to_response(
            'asg/game.html', {
                'sid': gid,
                'data': data,
                'zipped_data': zipped_data,
                'new_high': new_high,
                'gameId': gameId,
                'next': nextTreasureNo,
                'noise': noise
            }, context)

    return render_to_response(
        'asg/game.html', {
            'sid': gid,
            'data': data,
            'zipped_data': zipped_data,
            'new_high': new_high,
            'gameId': gameId,
            'starInfo': star_info,
            'star': star_thisGame,
            'next': nextTreasureNo,
            'noise': noise
        }, context)
Пример #9
0
def assess(request):
    context = RequestContext(request, {})
    gid = ''
    star_info = [0, 0, 0]
    star_thisGame = 0
    if request.COOKIES.has_key('gid'):
        gid = request.COOKIES['gid']

    data = {}
    access_msg = True

    game = retrieve_game(gid)
    if game:
        global access_limit
        if access_limit > 0:
            game.examine_document()
            access_limit -= 1
        else:
            access_msg = False

        nextTreasureNo = 10 - access_limit

        store_game(gid, game)
        data = game.get_game_state()

        rounds_list = data['round']
        zipped_data = zip(access_display_list, rounds_list)
        # -----------------------------------------
    if game.id != 6:
        star_info = star_game(game.id)
        star_thisGame = star_calculate(data['points'], unlockScore[game.id])

    global noise
    noise = 1

    new_high = False
    if game.is_game_over():
        # check if this is a high score
        # update userprofile stats
        log_move_event(request.user.id, game, current_display_list, False,
                       True)
        new_high = end_game(request.user, game)
        global noise
        noise = 4

        if game.id == 6:
            return render_to_response(
                'asg/game.html', {
                    'sid': gid,
                    'data': data,
                    'zipped_data': zipped_data,
                    'gameId': gameId,
                    'new_high': new_high,
                    'access_msg': access_msg,
                    'gameId': gameId,
                    'next': nextTreasureNo,
                    'noise': noise
                }, context)

    if data['tokens'] == 1 and access_msg == False:
        special_msg = True
        return render_to_response(
            'asg/game.html', {
                'sid': gid,
                'data': data,
                'zipped_data': zipped_data,
                'gameId': gameId,
                'new_high': new_high,
                'special_msg': special_msg,
                'gameId': gameId,
                'next': nextTreasureNo,
                'noise': noise
            }, context)

    return render_to_response(
        'asg/game.html', {
            'sid': gid,
            'data': data,
            'zipped_data': zipped_data,
            'new_high': new_high,
            'access_msg': access_msg,
            'gameId': gameId,
            'starInfo': star_info,
            'star': star_thisGame,
            'next': nextTreasureNo,
            'noise': noise
        }, context)
Пример #10
0
def endGame(request):
    context = RequestContext(request, {})
    gid = ''
    star_info = [0, 0, 0]
    star_thisGame = 0
    data = {}
    global access_limit
    access_limit = 10

    nextTreasureNo = 10 - access_limit

    if request.COOKIES.has_key('gid'):
        gid = request.COOKIES['gid']
    game = retrieve_game(gid)
    if game:

        # # check if query success or not
        # if query_msg == True:
        #     log_move_event(request.user.id, game, False, False)

        # gems coating here
        gain_list = []
        round = game.current_round
        for i in range(len(round)):
            r = round[i]
            gain_list.append(str(r['gain']))

        global treasure_display_list
        treasure_display_list = []

        # global current_display_list
        # current_display_list = gems_coating(gameId, gain_list)

        log_move_event(request.user.id, game, current_display_list, False, True)
        store_game(gid, game)
        data = game.get_game_state()
        data['gameover'] = True

        rounds_list = data['round']
        zipped_data = zip(current_display_list, rounds_list)

    if game.id != 6:
        star_info = star_game(game.id)
        star_thisGame = star_calculate(data['points'], unlockScore[game.id])
        new_high = False

    # check if this is a high score
    # update userprofile stats
    log_move_event(request.user.id, game, current_display_list, False, True)
    new_high = end_game(request.user, game)

    global noise
    noise = 4

    if game.id == 6:
        return render_to_response('asg/game.html',
                                  {'sid': gid, 'data': data, 'zipped_data': zipped_data, 'new_high': new_high,
                                   'gameId': gameId,
                                   'next': nextTreasureNo, 'noise': noise},
                                  context)

    return render_to_response('asg/game.html',
                              {'sid': gid, 'data': data, 'zipped_data': zipped_data, 'new_high': new_high,
                               'gameId': gameId,
                               'starInfo': star_info, 'star': star_thisGame,
                               'next': nextTreasureNo, 'noise': noise},
                              context)
Пример #11
0
def assess(request):
    context = RequestContext(request, {})
    gid = ''
    star_info = [0, 0, 0]
    star_thisGame = 0
    if request.COOKIES.has_key('gid'):
        gid = request.COOKIES['gid']

    data = {}
    access_msg = True

    game = retrieve_game(gid)
    if game:
        global access_limit
        if access_limit > 0:
            game.examine_document()
            access_limit -= 1
        else:
            access_msg = False

        nextTreasureNo = 10 - access_limit

        store_game(gid, game)
        data = game.get_game_state()

        rounds_list = data['round']
        zipped_data = zip(access_display_list, rounds_list)
        # -----------------------------------------
    if game.id != 6:
        star_info = star_game(game.id)
        star_thisGame = star_calculate(data['points'], unlockScore[game.id])

    global noise
    noise = 1

    new_high = False
    if game.is_game_over():
        # check if this is a high score
        # update userprofile stats
        log_move_event(request.user.id, game, current_display_list, False, True)
        new_high = end_game(request.user, game)
        global noise
        noise = 4

        if game.id == 6:
            return render_to_response('asg/game.html',
                                      {'sid': gid, 'data': data, 'zipped_data': zipped_data, 'gameId': gameId,
                                       'new_high': new_high, 'access_msg': access_msg,
                                       'gameId': gameId, 'next': nextTreasureNo, 'noise': noise},
                                      context)

    if data['tokens'] == 1 and access_msg == False:
        special_msg = True
        return render_to_response('asg/game.html',
                                  {'sid': gid, 'data': data, 'zipped_data': zipped_data, 'gameId': gameId,
                                   'new_high': new_high, 'special_msg': special_msg,
                                   'gameId': gameId, 'next': nextTreasureNo, 'noise': noise},
                                  context)

    return render_to_response('asg/game.html',
                              {'sid': gid, 'data': data, 'zipped_data': zipped_data, 'new_high': new_high,
                               'access_msg': access_msg,
                               'gameId': gameId, 'starInfo': star_info, 'star': star_thisGame, 'next': nextTreasureNo,
                               'noise': noise},
                              context)