コード例 #1
0
    def test_guess_same_word(self):
        table_id, user = self.setup_quiz(p_min=5, p_max=15, length=8)
        wwg = WordwallsGame()
        with transaction.atomic():
            wwg.start_quiz(table_id, user)

        def guess_fn(w, user):
            with closing(connection):
                with transaction.atomic():
                    wwg.guess(w, table_id, user, sleep=1)

        user_1 = User.objects.get(username='******')
        user_2 = User.objects.get(username='******')
        threads = []
        word = 'ELATIONS'
        threads.append(threading.Thread(target=guess_fn, args=(word, user)))
        threads.append(threading.Thread(target=guess_fn, args=(word, user_1)))
        threads.append(threading.Thread(target=guess_fn, args=(word, user_2)))
        for t in threads:
            t.start()
        for t in threads:
            t.join()

        st = wwg.state(table_id)
        self.assertFalse(word in st['answerHash'])
        self.assertTrue(word in st['originalAnswerHash'])
        self.assertTrue(word in st['solvers'])
        self.assertTrue(
            st['solvers'][word] in ['cesar', 'user_4738', 'user_131'])
コード例 #2
0
def challenge_submit(user, post):
    """
        Called when a challenge is submitted.
    """
    lexForm = LexiconForm(post)
    dcForm = DailyChallengesForm(post)
    if not(lexForm.is_valid() and dcForm.is_valid()):
        return response({'success': False,
                         'error': _('No challenge was selected.')})
    lex = Lexicon.objects.get(
        lexiconName=lexForm.cleaned_data['lexicon'])
    wwg = WordwallsGame()
    challengeName = DailyChallengeName.objects.get(
        name=dcForm.cleaned_data['challenge'])
    chDate = dcForm.cleaned_data['challengeDate']
    logger.debug('Selected in form: %s, %s, %s',
                 dcForm.cleaned_data['challenge'],
                 dcForm.cleaned_data['challengeDate'],
                 lexForm.cleaned_data['lexicon'])
    if not chDate or chDate > date.today():
        chDate = date.today()

    tablenum = wwg.initialize_daily_challenge(user, lex, challengeName, chDate)
    if tablenum == 0:
        return response({'success': False,
                         'error': _('Challenge does not exist.')})

    return response(
        {'url': reverse('wordwalls_table',
                        args=(tablenum,)),
         'success': True})
コード例 #3
0
 def test_continue_unfinished_list(self):
     LIST_NAME = "i live in a giant bucket"
     word_list = WordList.objects.get(name=LIST_NAME)
     # Continue the list.
     table_id = self.wwg.initialize_by_saved_list(
         self.lex, self.user, word_list, SavedListForm.CONTINUE_LIST_CHOICE,
         240)
     word_list = WordList.objects.get(name=LIST_NAME)
     self.assert_wl(word_list, {
         'numAlphagrams': 11, 'numCurAlphagrams': 11,
         'numFirstMissed': 0, 'numMissed': 3, 'goneThruOnce': False,
         'questionIndex': 10, 'is_temporary': False, 'name': LIST_NAME
     })
     # Start the quiz; we should only get one question.
     wwg = WordwallsGame()
     params = wwg.start_quiz(table_id, self.user)
     self.assertEqual(len(params['questions']), 1)
     self.assertEqual(params['questions'][0]['a'], 'AEIORSTU')
     # Miss it.
     gave_up = wwg.give_up(self.user, table_id)
     self.assertTrue(gave_up)
     word_list = WordList.objects.get(name=LIST_NAME)
     self.assert_wl(word_list, {
         'numAlphagrams': 11, 'numCurAlphagrams': 11,
         'numFirstMissed': 4, 'numMissed': 4, 'goneThruOnce': True,
         'questionIndex': 15, 'is_temporary': False, 'name': LIST_NAME,
     })
     self.assertEqual(set([0, 2, 3, 10]),
                      set(json.loads(word_list.firstMissed)))
コード例 #4
0
 def test_continue_unfinished_list(self):
     LIST_NAME = "i live in a giant bucket"
     word_list = WordList.objects.get(name=LIST_NAME)
     # Continue the list.
     table_id = self.wwg.initialize_by_saved_list(
         self.lex, self.user, word_list, SavedListForm.CONTINUE_LIST_CHOICE,
         240)
     word_list = WordList.objects.get(name=LIST_NAME)
     self.assert_wl(word_list, {
         'numAlphagrams': 11, 'numCurAlphagrams': 11,
         'numFirstMissed': 0, 'numMissed': 3, 'goneThruOnce': False,
         'questionIndex': 10, 'is_temporary': False, 'name': LIST_NAME
     })
     # Start the quiz; we should only get one question.
     wwg = WordwallsGame()
     params = wwg.start_quiz(table_id, self.user)
     self.assertEqual(len(params['questions']), 1)
     self.assertEqual(params['questions'][0]['a'], 'AEIORSTU')
     # Miss it.
     gave_up = wwg.give_up(self.user, table_id)
     self.assertTrue(gave_up)
     word_list = WordList.objects.get(name=LIST_NAME)
     self.assert_wl(word_list, {
         'numAlphagrams': 11, 'numCurAlphagrams': 11,
         'numFirstMissed': 4, 'numMissed': 4, 'goneThruOnce': True,
         'questionIndex': 15, 'is_temporary': False, 'name': LIST_NAME,
     })
     self.assertEqual(set([0, 2, 3, 10]),
                      set(json.loads(word_list.firstMissed)))
コード例 #5
0
 def test_cant_overwrite_list(self):
     table_id, user = self.setup_quiz(p_min=5, p_max=15, length=8)
     wwg = WordwallsGame()
     # Try saving the word list.
     LIST_NAME = 'This is my NWL list.'
     resp = wwg.save(user, table_id, LIST_NAME)
     self.assertFalse(resp['success'])
コード例 #6
0
def search_params_submit(user, post):
    """
        Called when user submits a search params query.
    """
    lexForm = LexiconForm(post)
    timeForm = TimeForm(post)
    fwForm = FindWordsForm(post)
    num_q_form = NumQuestionsForm(post)

    # form bound to the POST data
    if not (lexForm.is_valid() and timeForm.is_valid() and fwForm.is_valid()
            and num_q_form.is_valid()):
        return response({'success': False,
                         'error': _('There was something wrong with your '
                                    'search parameters or time selection.')})
    lex = Lexicon.objects.get(
        lexiconName=lexForm.cleaned_data['lexicon'])
    quiz_time = int(round(timeForm.cleaned_data['quizTime'] * 60))
    questions_per_round = num_q_form.cleaned_data['num_questions']
    search = searchForAlphagrams(fwForm.cleaned_data, lex)
    wwg = WordwallsGame()
    tablenum = wwg.initialize_by_search_params(user, search, quiz_time,
                                               questions_per_round)

    return response({'url': reverse('wordwalls_table', args=(tablenum,)),
                     'success': True})
コード例 #7
0
def named_lists_submit(user, post):
    lexForm = LexiconForm(post)
    timeForm = TimeForm(post)
    nlForm = NamedListForm(post)
    if not (lexForm.is_valid() and timeForm.is_valid() and nlForm.is_valid()):
        return response({
            'success':
            False,
            'error':
            'Please check that you have selected a '
            'list and that your quiz time is greater '
            'than 1 minute.'
        })

    lex = Lexicon.objects.get(lexiconName=lexForm.cleaned_data['lexicon'])
    quizTime = int(round(timeForm.cleaned_data['quizTime'] * 60))
    wwg = WordwallsGame()
    tablenum = wwg.initializeByNamedList(lex, user,
                                         nlForm.cleaned_data['namedList'],
                                         quizTime)
    if tablenum == 0:
        raise Http404
    return response({
        'url': reverse('wordwalls_table', args=(tablenum, )),
        'success': True
    })
コード例 #8
0
def named_lists_submit(user, post):
    lexForm = LexiconForm(post)
    timeForm = TimeForm(post)
    nlForm = NamedListForm(post)
    num_q_form = NumQuestionsForm(post)
    if not (lexForm.is_valid() and timeForm.is_valid() and nlForm.is_valid()
            and num_q_form.is_valid()):
        return response({'success': False,
                         'error': _('Please check that you have selected a '
                                    'list and that your quiz time is greater '
                                    'than 1 minute.')})

    lex = Lexicon.objects.get(
        lexiconName=lexForm.cleaned_data['lexicon'])
    quizTime = int(
        round(timeForm.cleaned_data['quizTime'] * 60))
    wwg = WordwallsGame()
    questions_per_round = num_q_form.cleaned_data['num_questions']
    tablenum = wwg.initialize_by_named_list(
        lex, user, nlForm.cleaned_data['namedList'],
        quizTime, questions_per_round)
    if tablenum == 0:
        raise Http404
    return response({'url': reverse('wordwalls_table',
                                    args=(tablenum,)),
                    'success': True})
コード例 #9
0
 def test_cant_overwrite_list(self):
     table_id, user = self.setup_quiz(p_min=5, p_max=15, length=8)
     wwg = WordwallsGame()
     # Try saving the word list.
     LIST_NAME = u'This is my list.'
     resp = wwg.save(user, table_id, LIST_NAME)
     self.assertFalse(resp['success'])
コード例 #10
0
ファイル: rpc.py プロジェクト: adrianiainlam/Webolith
def table_rpc(request, tableid):
    body = json.loads(request.body)
    req_id = body.get('id', 0)

    if body.get('jsonrpc') != '2.0':
        return bad_rpc_response(req_id, 'Wrong RPC version')
    method = body.get('method')
    params = body.get('params')
    if not method:
        return bad_rpc_response(req_id, 'Bad RPC method')

    wwg = WordwallsGame()
    permitted = wwg.allow_access(request.user, tableid)
    if not permitted:
        return bad_rpc_response(req_id,
                                'No access to table {}'.format(tableid))

    handler = method_lookup(method)
    if not handler:
        return bad_rpc_response(req_id,
                                'RPC method {} does not exist.'.format(method))
    try:
        ret = handler(request.user, tableid, params)
    except RPCError as e:
        return bad_rpc_response(req_id, str(e))

    return rpc_response(req_id, ret)
コード例 #11
0
def challenge_submit(user, post):
    """
        Called when a challenge is submitted.
    """
    lexForm = LexiconForm(post)
    dcForm = DailyChallengesForm(post)
    if not (lexForm.is_valid() and dcForm.is_valid()):
        return response({
            'success': False,
            'error': 'No challenge was selected.'
        })
    lex = Lexicon.objects.get(lexiconName=lexForm.cleaned_data['lexicon'])
    wwg = WordwallsGame()
    challengeName = DailyChallengeName.objects.get(
        name=dcForm.cleaned_data['challenge'])
    chDate = dcForm.cleaned_data['challengeDate']
    if not chDate or chDate > date.today():
        chDate = date.today()

    tablenum = wwg.initializeByDailyChallenge(user, lex, challengeName, chDate)
    if tablenum == 0:
        return response({
            'success': False,
            'error': 'Challenge does not exist.'
        })

    return response({
        'url': reverse('wordwalls_table', args=(tablenum, )),
        'success': True
    })
コード例 #12
0
def search_params_submit(user, post):
    """
        Called when user submits a search params query.
    """
    lexForm = LexiconForm(post)
    timeForm = TimeForm(post)
    fwForm = FindWordsForm(post)
    # form bound to the POST data
    if not (lexForm.is_valid() and timeForm.is_valid() and fwForm.is_valid()):
        return response({
            'success':
            False,
            'error':
            'There was something wrong with your '
            'search parameters or time selection.'
        })
    lex = Lexicon.objects.get(lexiconName=lexForm.cleaned_data['lexicon'])
    quizTime = int(round(timeForm.cleaned_data['quizTime'] * 60))
    alphasSearchDescription = searchForAlphagrams(fwForm.cleaned_data, lex)
    wwg = WordwallsGame()
    tablenum = wwg.initializeBySearchParams(user, alphasSearchDescription,
                                            quizTime)

    return response({
        'url': reverse('wordwalls_table', args=(tablenum, )),
        'success': True
    })
コード例 #13
0
def table(request, tableid=None):
    if request.method == 'POST':
        return handle_table_post(request, tableid)
    # Otherwise, it's a GET
    wwg = WordwallsGame()
    if tableid:
        # Check if the user is allowed to enter this table.
        permitted = wwg.allow_access(request.user, tableid)
        if gargoyle.is_active('disable_games', request):
            permitted = False
        if not permitted:
            return render(request, 'wordwalls/notPermitted.html',
                          {'tablenum': tableid})
    params = wwg.get_add_params(tableid)
    # Add styling params from user's profile (for styling table
    # tiles, backgrounds, etc)
    profile = request.user.aerolithprofile
    style = profile.customWordwallsStyle
    if style != "":
        params['style'] = style

    meta_info = get_create_meta_info()
    usermeta = get_user_meta_info(request.user)
    wgm = None
    if tableid:
        wgm = wwg.get_wgm(tableid, False)

    return render(
        request,
        'wordwalls/table.html',
        {
            'tablenum':
            tableid if tableid else 0,
            'current_host':
            wgm.host.username if wgm else '',
            'multiplayer': (json.dumps(wgm.playerType == WordwallsGameModel.
                                       MULTIPLAYER_GAME if wgm else False)),
            'user':
            json.dumps(usermeta),
            'addParams':
            json.dumps(params),
            'avatarUrl':
            profile.avatarUrl,
            'lexicon':
            wgm.lexicon.lexiconName if wgm else None,
            'default_lexicon':
            profile.defaultLexicon.pk,
            'challenge_info':
            json.dumps(meta_info['challenge_info']),
            'available_lexica':
            json.dumps(meta_info['lexica']),
            'intercom_app_id':
            settings.INTERCOM_APP_ID,
            # Use the webpack server if DEBUG is on. XXX This might not actually
            # be a good test; consider using an IS_PRODUCTION flag.
            'STATIC_SRV':
            (settings.WEBPACK_DEV_SERVER_URL if
             (settings.USE_WEBPACK_DEV_SERVER and settings.DEBUG) else '')
        })
コード例 #14
0
ファイル: rpc.py プロジェクト: adrianiainlam/Webolith
def start(user, tableid, params):
    wwg = WordwallsGame()
    quiz_params = wwg.start_quiz(tableid, user)
    if 'error' in quiz_params:
        raise RPCError(quiz_params['error'])
    # If this is a multiplayer game, should broadcast to group.
    # if wwg.is_multiplayer(tableid):
    #     broadcast_to_table(tableid, BroadcastTypes.GAME_PAYLOAD, quiz_params)
    return quiz_params
コード例 #15
0
 def setup_quiz(self, p_min=10, p_max=90, length=8):
     """
     A helper function to start a quiz.
     """
     wwg = WordwallsGame()
     user = User.objects.get(username='******')
     lex = Lexicon.objects.get(lexiconName='America')
     search = SearchDescription.probability_range(p_min, p_max, length, lex)
     table_id = wwg.initialize_by_search_params(user, search, 240)
     return table_id, user
コード例 #16
0
ファイル: api.py プロジェクト: adrianiainlam/Webolith
def api_answers(request):
    if request.method != "GET":
        return bad_request("Must use GET.")
    tablenum = request.GET.get("tablenum")
    wwg = WordwallsGame()
    answer_list = wwg.answer_list(tablenum)
    if answer_list:
        return response(answer_list)

    return bad_request("Could not fetch answer list")
コード例 #17
0
ファイル: api.py プロジェクト: adrianiainlam/Webolith
def access_to_table(tablenum, user):
    """Return whether user has access to table. For now we just use
    the wordwalls game model. We should fix the logic for multiplayer
    afterwards."""
    if tablenum == 0:
        # A table num of 0 implies that the user is not currently in a
        # table. Return true to allow the logic to proceed.
        return True
    game = WordwallsGame()
    return game.allow_access(user, tablenum)
コード例 #18
0
def start_game(request, id):
    if gargoyle.is_active('disable_games', request):
        return response(
            {'serverMsg': _(
                'The Aerolith server is currently undergoing '
                'maintenance. Please try again in a few minutes.')})
    wwg = WordwallsGame()
    quiz_params = wwg.start_quiz(id, request.user)
    if 'error' in quiz_params:
        return response(quiz_params, StatusCode.BAD_REQUEST)
    return response(quiz_params)
コード例 #19
0
 def test_continue_finished_list(self):
     """ Continue a list that is tested through all the way."""
     LIST_NAME = u'This is my list.'
     word_list = WordList.objects.get(name=LIST_NAME)
     table_id = self.wwg.initialize_by_saved_list(
         self.lex, self.user, word_list, SavedListForm.CONTINUE_LIST_CHOICE,
         240)
     self.assertNotEqual(table_id, 0)
     wwg = WordwallsGame()
     params = wwg.start_quiz(table_id, self.user)
     self.assertTrue('quiz is done' in params['error'])
コード例 #20
0
 def test_continue_finished_list(self):
     """ Continue a list that is tested through all the way."""
     LIST_NAME = 'This is my list.'
     word_list = WordList.objects.get(name=LIST_NAME)
     table_id = self.wwg.initialize_by_saved_list(
         self.lex, self.user, word_list, SavedListForm.CONTINUE_LIST_CHOICE,
         240)
     self.assertNotEqual(table_id, 0)
     wwg = WordwallsGame()
     params = wwg.start_quiz(table_id, self.user)
     self.assertTrue('quiz is done' in params['error'])
コード例 #21
0
 def test_quiz_params_correct(self):
     table_id, user = self.setup_quiz()
     wwg = WordwallsGame()
     params = wwg.start_quiz(table_id, user)
     self.assertEqual(len(params['questions']), 50)
     self.assertEqual(params['time'], 240)
     self.assertEqual(params['gameType'], 'regular')
     self.assertEqual(params['serverMsg'],
                      'These are questions 1 through 50 of 81.')
     guess_state = wwg.guess('CATS', table_id, user)
     self.assertTrue(guess_state['going'])
     self.assertEqual(guess_state['alphagram'], '')
コード例 #22
0
ファイル: views.py プロジェクト: atomiccupcake/Webolith
def start_game(request, id):
    if gargoyle.is_active('disable_games', request):
        return response(
            {'serverMsg': 'Unable to start game as this is temporarily '
                          'disabled. Please try again in a few minutes.'})
    wwg = WordwallsGame()
    gameReady = wwg.startRequest(request.user, id)
    if not gameReady:
        return response({"serverMsg": request.user.username})
    else:
        quizParams = wwg.startQuiz(id, request.user)
        return response(quizParams)
コード例 #23
0
ファイル: api.py プロジェクト: adrianiainlam/Webolith
def api_challengers_by_tablenum(request):
    if request.method != "GET":
        return bad_request("Must use GET.")
    tablenum = request.GET.get("tablenum")
    tiebreaker = request.GET.get("tiebreaker", "errors")
    wwg = WordwallsGame()
    dc_id = wwg.get_dc_id(tablenum)
    if dc_id > 0:
        dc = DailyChallenge.objects.get(pk=dc_id)
        leaderboard_data = get_leaderboard_data_for_dc_instance(dc, tiebreaker)
        return response(leaderboard_data)
    return bad_request("No such daily challenge.")
コード例 #24
0
    def test_missed_behavior(self):
        wwg = WordwallsGame()
        table_id, user = self.round_1()
        wgm = wwg.get_wgm(table_id)
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 11, 'numCurAlphagrams': 11,
            'numFirstMissed': 6, 'numMissed': 6, 'goneThruOnce': True,
            'questionIndex': 15, 'is_temporary': True
        })
        qs = json.loads(word_list.origQuestions)
        self.assertEqual(len(qs), 11)
        # Now start the quiz again. Should get missed words.
        self.round_2(table_id, user)
        wgm = wwg.get_wgm(table_id)
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 11, 'numCurAlphagrams': 6,
            'numFirstMissed': 6, 'numMissed': 2, 'goneThruOnce': True,
            'questionIndex': 10, 'is_temporary': True
        })

        qs = json.loads(word_list.origQuestions)
        self.assertEqual(len(qs), 11)

        # Finally, let's solve the final two alphagrams.
        self.round_3(table_id, user)
        wgm = wwg.get_wgm(table_id)
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 11, 'numCurAlphagrams': 2,
            'numFirstMissed': 6, 'numMissed': 0, 'goneThruOnce': True,
            'questionIndex': 5, 'is_temporary': True
        })

        # And try to start the quiz again.
        params = wwg.start_quiz(table_id, user)
        self.assertTrue('quiz is done' in params['error'])
        wgm = wwg.get_wgm(table_id)
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 11, 'numCurAlphagrams': 0,
            'numFirstMissed': 6, 'numMissed': 0, 'goneThruOnce': True,
            'questionIndex': 0, 'is_temporary': True
        })

        # Try saving the word list.
        LIST_NAME = 'my cool lišt'
        resp = wwg.save(user, table_id, LIST_NAME)
        self.assertTrue(resp['success'])
        self.assertEqual(resp['listname'], LIST_NAME)
        wgm = wwg.get_wgm(table_id)
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 11, 'numCurAlphagrams': 0,
            'numFirstMissed': 6, 'numMissed': 0, 'goneThruOnce': True,
            'questionIndex': 0, 'is_temporary': False, 'name': LIST_NAME
        })
コード例 #25
0
 def test_quiz_ends_after_time(self, timer_ran_out):
     # Mock timer running out by the time the guess comes in.
     timer_ran_out.return_value = True
     table_id, user = self.setup_quiz()
     wwg = WordwallsGame()
     wwg.start_quiz(table_id, user)
     guess_state = wwg.guess('CATS', table_id, user)
     self.assertFalse(guess_state['going'])
     self.assertEqual(guess_state['alphagram'], '')
     wgm = wwg.get_wgm(table_id)
     state = json.loads(wgm.currentGameState)
     self.assertFalse(state['quizGoing'])
コード例 #26
0
 def test_quiz_params_correct(self):
     table_id, user = self.setup_quiz()
     wwg = WordwallsGame()
     params = wwg.start_quiz(table_id, user)
     self.assertEqual(len(params['questions']), 50)
     self.assertEqual(params['time'], 240)
     self.assertEqual(params['gameType'], 'regular')
     self.assertEqual(params['serverMsg'],
                      'These are questions 1 through 50 of 81.')
     guess_state = wwg.guess('CATS', table_id, user)
     self.assertTrue(guess_state['going'])
     self.assertEqual(guess_state['alphagram'], '')
コード例 #27
0
 def test_firstmissed_allowed(self):
     LIST_NAME = u'list the sécond'
     word_list = WordList.objects.get(name=LIST_NAME)
     table_id = self.wwg.initialize_by_saved_list(
         self.lex, self.user, word_list, SavedListForm.FIRST_MISSED_CHOICE,
         240)
     self.assertNotEqual(table_id, 0)
     wwg = WordwallsGame()
     params = wwg.start_quiz(table_id, self.user)
     self.assertEqual(len(params['questions']), 6)
     self.assertEqual(
         set([q['a'] for q in params['questions']]),
         set(['AEEILORT', 'AEEILNRT', 'ADEINOST', 'ADEINORS', 'AEILNOST',
             'ADEILORT']))
コード例 #28
0
def start_game(request, id):
    if gargoyle.is_active('disable_games', request):
        return response({
            'serverMsg':
            'Unable to start game as this is temporarily '
            'disabled. Please try again in a few minutes.'
        })
    wwg = WordwallsGame()
    gameReady = wwg.startRequest(request.user, id)
    if not gameReady:
        return response({"serverMsg": request.user.username})
    else:
        quizParams = wwg.startQuiz(id, request.user)
        return response(quizParams)
コード例 #29
0
 def test_firstmissed_allowed(self):
     LIST_NAME = 'list the sécond'
     word_list = WordList.objects.get(name=LIST_NAME)
     table_id = self.wwg.initialize_by_saved_list(
         self.lex, self.user, word_list, SavedListForm.FIRST_MISSED_CHOICE,
         240)
     self.assertNotEqual(table_id, 0)
     wwg = WordwallsGame()
     params = wwg.start_quiz(table_id, self.user)
     self.assertEqual(len(params['questions']), 6)
     self.assertEqual(
         set([q['a'] for q in params['questions']]),
         set(['AEEILORT', 'AEEILNRT', 'ADEINOST', 'ADEINORS', 'AEILNOST',
             'ADEILORT']))
コード例 #30
0
 def setup_quiz(self, p_min=10, p_max=90, length=8):
     """
     A helper function to start a quiz.
     """
     wwg = WordwallsGame()
     user = User.objects.get(username='******')
     lex = Lexicon.objects.get(lexiconName='NWL18')
     search = [
         SearchDescription.lexicon(lex),
         SearchDescription.length(length, length),
         SearchDescription.probability_range(p_min, p_max)
     ]
     logger.debug('In setup_quiz, word lists: %s', WordList.objects.all())
     table_id = wwg.initialize_by_search_params(user, search, 240)
     return table_id, user
コード例 #31
0
 def test_can_save_loaded_list(self):
     """ Can we save a list we just loaded? """
     LIST_NAME = u'list the sécond'
     num_lists_before = WordList.objects.filter(user=self.user).count()
     word_list = WordList.objects.get(name=LIST_NAME)
     table_id = self.wwg.initialize_by_saved_list(
         self.lex, self.user, word_list, SavedListForm.CONTINUE_LIST_CHOICE,
         240)
     self.assertNotEqual(table_id, 0)
     wwg = WordwallsGame()
     resp = wwg.save(self.user, table_id, LIST_NAME)
     self.assertTrue(resp['success'])
     self.assertEqual(resp['listname'], LIST_NAME)
     self.assertEqual(num_lists_before,
                      WordList.objects.filter(user=self.user).count())
コード例 #32
0
 def test_can_save_loaded_list(self):
     """ Can we save a list we just loaded? """
     LIST_NAME = 'list the sécond'
     num_lists_before = WordList.objects.filter(user=self.user).count()
     word_list = WordList.objects.get(name=LIST_NAME)
     table_id = self.wwg.initialize_by_saved_list(
         self.lex, self.user, word_list, SavedListForm.CONTINUE_LIST_CHOICE,
         240)
     self.assertNotEqual(table_id, 0)
     wwg = WordwallsGame()
     resp = wwg.save(self.user, table_id, LIST_NAME)
     self.assertTrue(resp['success'])
     self.assertEqual(resp['listname'], LIST_NAME)
     self.assertEqual(num_lists_before,
                      WordList.objects.filter(user=self.user).count())
コード例 #33
0
    def test_missed_behavior(self):
        wwg = WordwallsGame()
        table_id, user = self.round_1()
        wgm = wwg.get_wgm(table_id)
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 11, 'numCurAlphagrams': 11,
            'numFirstMissed': 6, 'numMissed': 6, 'goneThruOnce': True,
            'questionIndex': 15, 'is_temporary': True
        })
        qs = json.loads(word_list.origQuestions)
        self.assertEqual(len(qs), 11)
        # Now start the quiz again. Should get missed words.
        self.round_2(table_id, user)
        wgm = wwg.get_wgm(table_id)
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 11, 'numCurAlphagrams': 6,
            'numFirstMissed': 6, 'numMissed': 2, 'goneThruOnce': True,
            'questionIndex': 10, 'is_temporary': True
        })

        qs = json.loads(word_list.origQuestions)
        self.assertEqual(len(qs), 11)

        # Finally, let's solve the final two alphagrams.
        self.round_3(table_id, user)
        wgm = wwg.get_wgm(table_id)
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 11, 'numCurAlphagrams': 2,
            'numFirstMissed': 6, 'numMissed': 0, 'goneThruOnce': True,
            'questionIndex': 5, 'is_temporary': True
        })

        # And try to start the quiz again.
        params = wwg.start_quiz(table_id, user)
        self.assertTrue('quiz is done' in params['error'])
        wgm = wwg.get_wgm(table_id)
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 11, 'numCurAlphagrams': 0,
            'numFirstMissed': 6, 'numMissed': 0, 'goneThruOnce': True,
            'questionIndex': 0, 'is_temporary': True
        })

        # Try saving the word list.
        LIST_NAME = u'my cool lišt'
        resp = wwg.save(user, table_id, LIST_NAME)
        self.assertTrue(resp['success'])
        self.assertEqual(resp['listname'], LIST_NAME)
        wgm = wwg.get_wgm(table_id)
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 11, 'numCurAlphagrams': 0,
            'numFirstMissed': 6, 'numMissed': 0, 'goneThruOnce': True,
            'questionIndex': 0, 'is_temporary': False, 'name': LIST_NAME
        })
コード例 #34
0
 def round_1(self):
     table_id, user = self.setup_quiz(p_min=5, p_max=15, length=8)
     wwg = WordwallsGame()
     # Let's guess some of the words from the 5-15 range
     words_to_guess = [
         'ABCDEFGH',     # miss AEROLITE
         'IDOLATER',     # miss TAILORED
         'OUTRAISE', 'SAUTOIRE',
         'ALIENORS', 'AILERONS',
         '',  # miss ANEROIDS/ANODISER
         'SEDATION',     # miss ASTONIED
         'DELATION',
         '',  # miss all of the AEILNOST words.
         'ASTEROID',
         'ELATERIN',  # miss ENTAILER and TREENAIL
         'DETAINER', 'RETAINED'
     ]
     # Guess all the words 3 times. (5, 5 and 1)
     for i in range(3):
         params = wwg.start_quiz(table_id, user)
         if i != 2:
             self.assertEqual(len(params['questions']), 5)
         else:
             self.assertEqual(len(params['questions']), 1)
         for w in words_to_guess:
             wwg.guess(w, table_id, user)
         wwg.give_up(user, table_id)
     return table_id, user
コード例 #35
0
 def test_range_list_long(self):
     table_id = self.wwg.initialize_by_named_list(
         self.lex, self.user, NamedList.objects.get(pk=3099), 240)
     self.assertNotEqual(table_id, 0)
     wgm = self.wwg.get_wgm(table_id)
     word_list = wgm.word_list
     self.assert_wl(word_list, {
         'numAlphagrams': 21063, 'numCurAlphagrams': 21063,
         'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
         'questionIndex': 0, 'is_temporary': True
     })
     orig_questions = set(json.dumps(q)
                          for q in json.loads(word_list.origQuestions))
     self.assertEqual(len(orig_questions), 21063)
     # Start the quiz.
     wwg = WordwallsGame()
     params = wwg.start_quiz(table_id, self.user)
     self.assertEqual(len(params['questions']), 50)
コード例 #36
0
 def test_range_list_long(self):
     table_id = self.wwg.initialize_by_named_list(
         self.lex, self.user, NamedList.objects.get(pk=3099), 240)
     self.assertNotEqual(table_id, 0)
     wgm = self.wwg.get_wgm(table_id)
     word_list = wgm.word_list
     self.assert_wl(word_list, {
         'numAlphagrams': 21063, 'numCurAlphagrams': 21063,
         'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
         'questionIndex': 0, 'is_temporary': True
     })
     orig_questions = set(json.dumps(q)
                          for q in json.loads(word_list.origQuestions))
     self.assertEqual(len(orig_questions), 21063)
     # Start the quiz.
     wwg = WordwallsGame()
     params = wwg.start_quiz(table_id, self.user)
     self.assertEqual(len(params['questions']), 50)
コード例 #37
0
 def test_word_list_created(self):
     table_id, user = self.setup_quiz()
     wwg = WordwallsGame()
     wgm = wwg.get_wgm(table_id)
     word_list = wgm.word_list
     self.assert_wl(word_list, {
         'version': 2,
         'lexicon': Lexicon.objects.get(lexiconName='America'),
         'user': user, 'numAlphagrams': 81, 'numCurAlphagrams': 81,
         'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
         'questionIndex': 0, 'is_temporary': True
     })
     # The name should be a random uuid.
     self.assertEqual(len(word_list.name), 32)
     qs = json.loads(word_list.origQuestions)
     self.assertEqual(len(qs), 81)
     # Search for one in particular
     self.assertTrue({'q': 'AEEINRSU', 'a': ['UNEASIER']} in qs)
コード例 #38
0
ファイル: rpc.py プロジェクト: adrianiainlam/Webolith
def guess(user, tableid, params):
    g = params['guess']
    wrong_answers = params.get('wrongAnswers', 0)
    wwg = WordwallsGame()
    state = wwg.guess(g.strip(), tableid, user, wrong_answers=wrong_answers)
    if state is None:
        raise RPCError('Quiz is already over.')

    game_packet = {
        'g': state['going'],
        'C': state['alphagram'],
        'w': state['word'],
        'a': state['already_solved'],
        's': state['solver']
    }
    # If this is a multiplayer game, should broadcast to group.
    # if wwg.is_multiplayer(tableid):
    #     broadcast_to_table(tableid, BroadcastTypes.GUESS_RESPONSE, game_packet)
    return game_packet
コード例 #39
0
def log(request):
    body = json.loads(request.body)
    if body['type'] == 'nothost':
        tablenum = body['tablenum']
        current_host = body['currentHost']
        username = body['username']
        multiplayer = body['tableIsMultiplayer']
        wgm = None
        if tablenum:
            wwg = WordwallsGame()
            wgm = wwg.get_wgm(tablenum, False)
            actual_host = wgm.host.username if wgm.host else None
            players_in = ', '.join([u.username for u in wgm.inTable.all()])
            logger.info(
                '[event=nothost] tablenum=%s current_host=%s username=%s '
                'multiplayer=%s actual_host=%s players_in="%s"', tablenum,
                current_host, username, multiplayer, actual_host, players_in)

    return response('OK')
コード例 #40
0
 def test_word_list_created(self):
     logger.debug('In test_word_list_created')
     table_id, user = self.setup_quiz()
     wwg = WordwallsGame()
     wgm = wwg.get_wgm(table_id)
     word_list = wgm.word_list
     self.assert_wl(word_list, {
         'version': 2,
         'lexicon': Lexicon.objects.get(lexiconName='NWL18'),
         'user': user, 'numAlphagrams': 81, 'numCurAlphagrams': 81,
         'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
         'questionIndex': 0, 'is_temporary': True
     })
     # The name should be a random uuid.
     self.assertEqual(len(word_list.name), 32)
     qs = json.loads(word_list.origQuestions)
     self.assertEqual(len(qs), 81)
     # Search for one in particular
     self.assertTrue({'q': 'AEEINRSU', 'a': ['UNEASIER']} in qs)
コード例 #41
0
 def test_continue_gonethru_list(self):
     LIST_NAME = u'list the sécond'
     word_list = WordList.objects.get(name=LIST_NAME)
     table_id = self.wwg.initialize_by_saved_list(
         self.lex, self.user, word_list, SavedListForm.CONTINUE_LIST_CHOICE,
         240)
     self.assertNotEqual(table_id, 0)
     wwg = WordwallsGame()
     params = wwg.start_quiz(table_id, self.user)
     self.assertEqual(len(params['questions']), 1)
     self.assertEqual(params['questions'][0]['a'], 'ADEILORT')
     # Miss it.
     gave_up = wwg.give_up(self.user, table_id)
     self.assertTrue(gave_up)
     word_list = WordList.objects.get(name=LIST_NAME)
     self.assert_wl(word_list, {
         'numAlphagrams': 11, 'numCurAlphagrams': 6,
         'numFirstMissed': 6, 'numMissed': 1, 'goneThruOnce': True,
         'questionIndex': 10, 'is_temporary': False, 'name': LIST_NAME
     })
コード例 #42
0
 def test_continue_gonethru_list(self):
     LIST_NAME = 'list the sécond'
     word_list = WordList.objects.get(name=LIST_NAME)
     table_id = self.wwg.initialize_by_saved_list(
         self.lex, self.user, word_list, SavedListForm.CONTINUE_LIST_CHOICE,
         240)
     self.assertNotEqual(table_id, 0)
     wwg = WordwallsGame()
     params = wwg.start_quiz(table_id, self.user)
     self.assertEqual(len(params['questions']), 1)
     self.assertEqual(params['questions'][0]['a'], 'ADEILORT')
     # Miss it.
     gave_up = wwg.give_up(self.user, table_id)
     self.assertTrue(gave_up)
     word_list = WordList.objects.get(name=LIST_NAME)
     self.assert_wl(word_list, {
         'numAlphagrams': 11, 'numCurAlphagrams': 6,
         'numFirstMissed': 6, 'numMissed': 1, 'goneThruOnce': True,
         'questionIndex': 10, 'is_temporary': False, 'name': LIST_NAME
     })
コード例 #43
0
 def test_individual_alphas(self):
     table_id = self.wwg.initialize_by_named_list(
         self.lex, self.user, NamedList.objects.get(pk=3092), 240)
     self.assertNotEqual(table_id, 0)
     wgm = self.wwg.get_wgm(table_id)
     word_list = wgm.word_list
     self.assert_wl(word_list, {
         'numAlphagrams': 691, 'numCurAlphagrams': 691,
         'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
         'questionIndex': 0, 'is_temporary': True
     })
     orig_questions = set(json.dumps(q)
                          for q in json.loads(word_list.origQuestions))
     self.assertEqual(len(orig_questions), 691)
     # Start the quiz.
     wwg = WordwallsGame()
     params = wwg.start_quiz(table_id, self.user)
     self.assertEqual(len(params['questions']), 50)
     logger.debug(params['questions'])
     self.assertNotEqual(re.search(r'[JQXZ]', params['questions'][0]['a']),
                         None)
コード例 #44
0
 def test_individual_alphas(self):
     table_id = self.wwg.initialize_by_named_list(
         self.lex, self.user, NamedList.objects.get(pk=3092), 240)
     self.assertNotEqual(table_id, 0)
     wgm = self.wwg.get_wgm(table_id)
     word_list = wgm.word_list
     self.assert_wl(word_list, {
         'numAlphagrams': 691, 'numCurAlphagrams': 691,
         'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
         'questionIndex': 0, 'is_temporary': True
     })
     orig_questions = set(json.dumps(q)
                          for q in json.loads(word_list.origQuestions))
     self.assertEqual(len(orig_questions), 691)
     # Start the quiz.
     wwg = WordwallsGame()
     params = wwg.start_quiz(table_id, self.user)
     self.assertEqual(len(params['questions']), 50)
     logger.debug(params['questions'])
     self.assertNotEqual(re.search(r'[JQXZ]', params['questions'][0]['a']),
                         None)
コード例 #45
0
 def round_1(self):
     table_id, user = self.setup_quiz(p_min=5, p_max=15, length=8)
     wwg = WordwallsGame()
     # Let's guess some of the words from the 5-15 range
     words_to_guess = [
         'ABCDEFGH',     # miss AEROLITE
         'IDOLATER',     # miss TAILORED
         'OUTRAISE', 'SAUTOIRE',
         'ALIENORS', 'AILERONS',
         '',  # miss ANEROIDS/ANODISER
         'SEDATION',     # miss ASTONIED
         'DELATION',
         '',  # miss all of the AEILNOST words.
         'ASTEROID',
         'ELATERIN',  # miss ENTAILER and TREENAIL
         'DETAINER', 'RETAINED'
     ]
     # Guess all the words 3 times. (5, 5 and 1)
     for i in range(3):
         params = wwg.start_quiz(table_id, user)
         if i != 2:
             self.assertEqual(len(params['questions']), 5)
         else:
             self.assertEqual(len(params['questions']), 1)
         for w in words_to_guess:
             wwg.guess(w, table_id, user)
         wwg.give_up(user, table_id)
     return table_id, user
コード例 #46
0
ファイル: api.py プロジェクト: adrianiainlam/Webolith
def table_response(tablenum):
    game = WordwallsGame()
    addl_params = game.get_add_params(tablenum)
    wgm = game.get_wgm(tablenum, lock=False)

    # Sometimes, 'tempListName' will not be in addl_params, when this
    # is loading an already existing saved list. Instead, get from saveName.
    if addl_params.get("saveName"):
        autosave = True
        list_name = addl_params["saveName"]
    else:
        autosave = False
        list_name = addl_params["tempListName"]
    return response(
        {
            "tablenum": tablenum,
            "list_name": list_name,
            "lexicon": wgm.lexicon.lexiconName,
            "autosave": autosave,
            "multiplayer": addl_params.get("multiplayer", False),
        }
    )
コード例 #47
0
 def test_restart_unfinished_list(self):
     LIST_NAME = "i live in a giant bucket"
     word_list = WordList.objects.get(name=LIST_NAME)
     questions = set(json.dumps(q)
                     for q in json.loads(word_list.origQuestions))
     # Try restarting the list.
     table_id = self.wwg.initialize_by_saved_list(
         self.lex, self.user, word_list, SavedListForm.RESTART_LIST_CHOICE,
         240)
     word_list = WordList.objects.get(name=LIST_NAME)
     self.assert_wl(word_list, {
         'numAlphagrams': 11, 'numCurAlphagrams': 11,
         'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
         'questionIndex': 0, 'is_temporary': False, 'name': LIST_NAME
     })
     orig_questions = set(json.dumps(q)
                          for q in json.loads(word_list.origQuestions))
     # Make sure old questions == new questions
     self.assertEqual(orig_questions, questions)
     # Start the quiz and make sure we got all 11 questions
     wwg = WordwallsGame()
     params = wwg.start_quiz(table_id, self.user)
     self.assertEqual(len(params['questions']), 11)
コード例 #48
0
 def test_restart_unfinished_list(self):
     LIST_NAME = "i live in a giant bucket"
     word_list = WordList.objects.get(name=LIST_NAME)
     questions = set(json.dumps(q)
                     for q in json.loads(word_list.origQuestions))
     # Try restarting the list.
     table_id = self.wwg.initialize_by_saved_list(
         self.lex, self.user, word_list, SavedListForm.RESTART_LIST_CHOICE,
         240)
     word_list = WordList.objects.get(name=LIST_NAME)
     self.assert_wl(word_list, {
         'numAlphagrams': 11, 'numCurAlphagrams': 11,
         'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
         'questionIndex': 0, 'is_temporary': False, 'name': LIST_NAME
     })
     orig_questions = set(json.dumps(q)
                          for q in json.loads(word_list.origQuestions))
     # Make sure old questions == new questions
     self.assertEqual(orig_questions, questions)
     # Start the quiz and make sure we got all 11 questions
     wwg = WordwallsGame()
     params = wwg.start_quiz(table_id, self.user)
     self.assertEqual(len(params['questions']), 11)
コード例 #49
0
ファイル: api.py プロジェクト: adrianiainlam/Webolith
def load_raw_questions(request, parsed_req_body):
    try:
        tablenum = WordwallsGame().initialize_by_raw_questions(
            parsed_req_body["lexicon"],
            request.user,
            parsed_req_body["raw_questions"],
            parsed_req_body["quiz_time_secs"],
            parsed_req_body["questions_per_round"],
            use_table=parsed_req_body["tablenum"],
            multiplayer=parsed_req_body["multiplayer"],
        )
    except GameInitException as e:
        return bad_request(str(e))
    return table_response(tablenum)
コード例 #50
0
ファイル: views.py プロジェクト: atomiccupcake/Webolith
def saved_lists_submit(user, post):
    lexForm = LexiconForm(post)
    timeForm = TimeForm(post)
    slForm = SavedListForm(post)
    if not (lexForm.is_valid() and timeForm.is_valid() and slForm.is_valid()):
        return response({'success': False,
                         'error': 'Please check that you have selected '
                                  'a word list and a time greater than '
                                  '1 minute.'})


    lex = Lexicon.objects.get(
        lexiconName=lexForm.cleaned_data['lexicon'])
    quizTime = int(
        round(timeForm.cleaned_data['quizTime'] * 60))
    wwg = WordwallsGame()
    tablenum = wwg.initializeBySavedList(
        lex, user, slForm.cleaned_data['wordList'],
        slForm.cleaned_data['listOption'], quizTime)
    if tablenum == 0:
        raise Http404
    return response({'url': reverse('wordwalls_table',
                                    args=(tablenum,)),
                     'success': True})
コード例 #51
0
ファイル: test_api.py プロジェクト: adrianiainlam/Webolith
 def test_continue_list_multiplayer(self):
     # Fist load a new challenge, to create a table.
     result = self.client.post('/wordwalls/api/new_challenge/',
                               data=json.dumps({
                                   'lexicon': 7,
                                   'challenge': 14,
                                   'tablenum': 0,
                                   'date': '2013-11-29'
                               }),
                               content_type='application/json')
     self.assertEqual(result.status_code, 200)
     content = json.loads(result.content)
     tablenum = content['tablenum']
     # Now try to continue a saved list in multiplayer mode.
     result = self.client.post('/wordwalls/api/load_saved_list/',
                               data=json.dumps({
                                   'lexicon': 7,
                                   'desiredTime': 5,
                                   'questionsPerRound': 50,
                                   'selectedList': 2,
                                   'tablenum': tablenum,
                                   'listOption': 'continue',
                                   'multiplayer': True
                               }),
                               content_type='application/json')
     logger.debug(result.content)
     self.assertEqual(result.status_code, 200)
     # We should make a new copy of the word list, instead of use
     # the existing one.
     game = WordwallsGame()
     new_word_list = game.get_wgm(tablenum, lock=False).word_list
     old_word_list = WordList.objects.get(pk=2)
     self.assertEqual(new_word_list.origQuestions,
                      old_word_list.origQuestions)
     self.assertTrue(new_word_list.is_temporary)
     self.assertFalse(old_word_list.is_temporary)
コード例 #52
0
 def round_2(self, table_id, user):
     wwg = WordwallsGame()
     words_to_guess = [
         'AEROLITE',
         'IDOLATER', 'TAILORED',
         '',  # miss ANEROIDS again
         'ASTONIED', 'SEDATION',
         'ELATIONS', 'INSOLATE', 'TOENAILS',
         'ELATERIN', 'ENTAILER'  # miss TREENAIL
     ]
     # Guess all the words 2 times. (5, 5 and 1)
     for i in range(2):
         params = wwg.start_quiz(table_id, user)
         logger.debug('params %s', params)
         if i == 0:
             self.assertEqual(len(params['questions']), 5)
         else:
             self.assertEqual(len(params['questions']), 1)
         for w in words_to_guess:
             wwg.guess(w, table_id, user)
         wwg.give_up(user, table_id)
コード例 #53
0
class WordwallsNamedListTest(TestCase, WordListAssertMixin):
    """ "Named" lists. """
    fixtures = ['test/lexica.json',
                'test/users.json',
                'test/profiles.json',
                'test/word_lists.json',
                'test/named_lists.json']

    def setUp(self):
        self.user = User.objects.get(username='******')
        self.lex = Lexicon.objects.get(lexiconName='America')
        self.wwg = WordwallsGame()

    def test_range_list_short(self):
        table_id = self.wwg.initialize_by_named_list(
            self.lex, self.user, NamedList.objects.get(pk=3143), 240)
        self.assertNotEqual(table_id, 0)
        wgm = self.wwg.get_wgm(table_id)
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 1000, 'numCurAlphagrams': 1000,
            'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
            'questionIndex': 0, 'is_temporary': True
        })
        orig_questions = set(json.dumps(q)
                             for q in json.loads(word_list.origQuestions))
        self.assertEqual(len(orig_questions), 1000)
        # Start the quiz.
        wwg = WordwallsGame()
        params = wwg.start_quiz(table_id, self.user)
        self.assertEqual(len(params['questions']), 50)

    def test_range_list_long(self):
        table_id = self.wwg.initialize_by_named_list(
            self.lex, self.user, NamedList.objects.get(pk=3099), 240)
        self.assertNotEqual(table_id, 0)
        wgm = self.wwg.get_wgm(table_id)
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 21063, 'numCurAlphagrams': 21063,
            'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
            'questionIndex': 0, 'is_temporary': True
        })
        orig_questions = set(json.dumps(q)
                             for q in json.loads(word_list.origQuestions))
        self.assertEqual(len(orig_questions), 21063)
        # Start the quiz.
        wwg = WordwallsGame()
        params = wwg.start_quiz(table_id, self.user)
        self.assertEqual(len(params['questions']), 50)

    def test_individual_alphas(self):
        table_id = self.wwg.initialize_by_named_list(
            self.lex, self.user, NamedList.objects.get(pk=3092), 240)
        self.assertNotEqual(table_id, 0)
        wgm = self.wwg.get_wgm(table_id)
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 691, 'numCurAlphagrams': 691,
            'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
            'questionIndex': 0, 'is_temporary': True
        })
        orig_questions = set(json.dumps(q)
                             for q in json.loads(word_list.origQuestions))
        self.assertEqual(len(orig_questions), 691)
        # Start the quiz.
        wwg = WordwallsGame()
        params = wwg.start_quiz(table_id, self.user)
        self.assertEqual(len(params['questions']), 50)
        logger.debug(params['questions'])
        self.assertNotEqual(re.search(r'[JQXZ]', params['questions'][0]['a']),
                            None)
コード例 #54
0
 def setUp(self):
     self.user = User.objects.get(username='******')
     self.lex = Lexicon.objects.get(lexiconName='America')
     self.wwg = WordwallsGame()
コード例 #55
0
def mark_missed(request, id):
    wwg = WordwallsGame()
    marked = wwg.mark_missed(request.POST['idx'], id, request.user)
    return response({'success': marked})
コード例 #56
0
def table(request, id):
    if request.method == 'POST':
        action = request.POST['action']
        logger.debug(u'user=%s, action=%s, table=%s', request.user, action, id)
        if action == "start":
            return start_game(request, id)
        elif action == "guess":
            logger.debug(u'guess=%s', request.POST['guess'])
            wwg = WordwallsGame()
            state = wwg.guess(request.POST['guess'].strip(), id, request.user)
            if state is None:
                return response(_('Quiz is already over.'),
                                status=StatusCode.BAD_REQUEST)
            logger.debug(u'table=%s Returning %s', id, state)
            return response({'g': state['going'], 'C': state['alphagram'],
                             'w': state['word'],
                             'a': state['already_solved']})
        elif action == "gameEnded":
            wwg = WordwallsGame()
            ret = wwg.check_game_ended(id)
            # 'going' is the opposite of 'game ended'
            return response({'g': not ret})
        elif action == "giveUp":
            wwg = WordwallsGame()
            ret = wwg.give_up(request.user, id)
            return response({'g': not ret})
        elif action == "save":
            wwg = WordwallsGame()
            ret = wwg.save(request.user, id, request.POST['listname'])
            return response(ret)
        elif action == "giveUpAndSave":
            wwg = WordwallsGame()
            ret = wwg.give_up_and_save(request.user, id,
                                       request.POST['listname'])
            # this shouldn't return a response, because it's not going to be
            # caught by the javascript
            logger.debug("Give up and saving returned: %s" % ret)
            return response(ret)
        elif action == "savePrefs":
            profile = request.user.aerolithprofile
            profile.customWordwallsStyle = request.POST['prefs']
            profile.save()
            return response({'success': True})
        elif action == "getDcData":
            wwg = WordwallsGame()
            dcId = wwg.get_dc_id(id)
            if dcId > 0:
                leaderboardData = getLeaderboardDataDcInstance(
                    DailyChallenge.objects.get(pk=dcId))
                return response(leaderboardData)
        else:
            return response({'success': False},
                            status=StatusCode.BAD_REQUEST)

    else:   # it's a GET
        wwg = WordwallsGame()
        permitted = wwg.permit(request.user, id)
        if gargoyle.is_active('disable_games', request):
            permitted = False
        if not permitted:
            return render(request, 'wordwalls/notPermitted.html',
                          {'tablenum': id})
        params = wwg.get_add_params(id)
        # Add styling params from user's profile (for styling table
        # tiles, backgrounds, etc)
        profile = request.user.aerolithprofile
        style = profile.customWordwallsStyle
        if style != "":
            params['style'] = style

        return render(request, 'wordwalls/table.html',
                      {'tablenum': id,
                       'username': request.user.username,
                       'addParams': json.dumps(params),
                       'avatarUrl': profile.avatarUrl,
                       'CURRENT_VERSION': CURRENT_VERSION,
                       'lexicon': wwg.get_wgm(id).lexicon
                       })
コード例 #57
0
class WordwallsSavedListModesTest(WordwallsBasicLogicTest):
    """
    Test modes of saved list such as missed, first missed, continue,
    restart.

    """

    def setUp(self):
        self.user = User.objects.get(username='******')
        self.lex = Lexicon.objects.get(lexiconName='America')
        self.wwg = WordwallsGame()

    def test_firstmissed_not_allowed(self):
        LIST_NAME = "i live in a giant bucket"
        word_list = WordList.objects.get(name=LIST_NAME)
        table_id = self.wwg.initialize_by_saved_list(
            self.lex, self.user, word_list, SavedListForm.FIRST_MISSED_CHOICE,
            240)
        self.assertEqual(table_id, 0)

    def test_restart_unfinished_list(self):
        LIST_NAME = "i live in a giant bucket"
        word_list = WordList.objects.get(name=LIST_NAME)
        questions = set(json.dumps(q)
                        for q in json.loads(word_list.origQuestions))
        # Try restarting the list.
        table_id = self.wwg.initialize_by_saved_list(
            self.lex, self.user, word_list, SavedListForm.RESTART_LIST_CHOICE,
            240)
        word_list = WordList.objects.get(name=LIST_NAME)
        self.assert_wl(word_list, {
            'numAlphagrams': 11, 'numCurAlphagrams': 11,
            'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
            'questionIndex': 0, 'is_temporary': False, 'name': LIST_NAME
        })
        orig_questions = set(json.dumps(q)
                             for q in json.loads(word_list.origQuestions))
        # Make sure old questions == new questions
        self.assertEqual(orig_questions, questions)
        # Start the quiz and make sure we got all 11 questions
        wwg = WordwallsGame()
        params = wwg.start_quiz(table_id, self.user)
        self.assertEqual(len(params['questions']), 11)

    @override_settings(WORDWALLS_QUESTIONS_PER_ROUND=5)
    def test_continue_unfinished_list(self):
        LIST_NAME = "i live in a giant bucket"
        word_list = WordList.objects.get(name=LIST_NAME)
        # Continue the list.
        table_id = self.wwg.initialize_by_saved_list(
            self.lex, self.user, word_list, SavedListForm.CONTINUE_LIST_CHOICE,
            240)
        word_list = WordList.objects.get(name=LIST_NAME)
        self.assert_wl(word_list, {
            'numAlphagrams': 11, 'numCurAlphagrams': 11,
            'numFirstMissed': 0, 'numMissed': 3, 'goneThruOnce': False,
            'questionIndex': 10, 'is_temporary': False, 'name': LIST_NAME
        })
        # Start the quiz; we should only get one question.
        wwg = WordwallsGame()
        params = wwg.start_quiz(table_id, self.user)
        self.assertEqual(len(params['questions']), 1)
        self.assertEqual(params['questions'][0]['a'], 'AEIORSTU')
        # Miss it.
        gave_up = wwg.give_up(self.user, table_id)
        self.assertTrue(gave_up)
        word_list = WordList.objects.get(name=LIST_NAME)
        self.assert_wl(word_list, {
            'numAlphagrams': 11, 'numCurAlphagrams': 11,
            'numFirstMissed': 4, 'numMissed': 4, 'goneThruOnce': True,
            'questionIndex': 15, 'is_temporary': False, 'name': LIST_NAME,
        })
        self.assertEqual(set([0, 2, 3, 10]),
                         set(json.loads(word_list.firstMissed)))

    def test_firstmissed_allowed(self):
        LIST_NAME = u'list the sécond'
        word_list = WordList.objects.get(name=LIST_NAME)
        table_id = self.wwg.initialize_by_saved_list(
            self.lex, self.user, word_list, SavedListForm.FIRST_MISSED_CHOICE,
            240)
        self.assertNotEqual(table_id, 0)
        wwg = WordwallsGame()
        params = wwg.start_quiz(table_id, self.user)
        self.assertEqual(len(params['questions']), 6)
        self.assertEqual(
            set([q['a'] for q in params['questions']]),
            set(['AEEILORT', 'AEEILNRT', 'ADEINOST', 'ADEINORS', 'AEILNOST',
                'ADEILORT']))

    @override_settings(WORDWALLS_QUESTIONS_PER_ROUND=5)
    def test_continue_gonethru_list(self):
        LIST_NAME = u'list the sécond'
        word_list = WordList.objects.get(name=LIST_NAME)
        table_id = self.wwg.initialize_by_saved_list(
            self.lex, self.user, word_list, SavedListForm.CONTINUE_LIST_CHOICE,
            240)
        self.assertNotEqual(table_id, 0)
        wwg = WordwallsGame()
        params = wwg.start_quiz(table_id, self.user)
        self.assertEqual(len(params['questions']), 1)
        self.assertEqual(params['questions'][0]['a'], 'ADEILORT')
        # Miss it.
        gave_up = wwg.give_up(self.user, table_id)
        self.assertTrue(gave_up)
        word_list = WordList.objects.get(name=LIST_NAME)
        self.assert_wl(word_list, {
            'numAlphagrams': 11, 'numCurAlphagrams': 6,
            'numFirstMissed': 6, 'numMissed': 1, 'goneThruOnce': True,
            'questionIndex': 10, 'is_temporary': False, 'name': LIST_NAME
        })

    def test_continue_finished_list(self):
        """ Continue a list that is tested through all the way."""
        LIST_NAME = u'This is my list.'
        word_list = WordList.objects.get(name=LIST_NAME)
        table_id = self.wwg.initialize_by_saved_list(
            self.lex, self.user, word_list, SavedListForm.CONTINUE_LIST_CHOICE,
            240)
        self.assertNotEqual(table_id, 0)
        wwg = WordwallsGame()
        params = wwg.start_quiz(table_id, self.user)
        self.assertTrue('quiz is done' in params['error'])

    def test_can_save_loaded_list(self):
        """ Can we save a list we just loaded? """
        LIST_NAME = u'list the sécond'
        num_lists_before = WordList.objects.filter(user=self.user).count()
        word_list = WordList.objects.get(name=LIST_NAME)
        table_id = self.wwg.initialize_by_saved_list(
            self.lex, self.user, word_list, SavedListForm.CONTINUE_LIST_CHOICE,
            240)
        self.assertNotEqual(table_id, 0)
        wwg = WordwallsGame()
        resp = wwg.save(self.user, table_id, LIST_NAME)
        self.assertTrue(resp['success'])
        self.assertEqual(resp['listname'], LIST_NAME)
        self.assertEqual(num_lists_before,
                         WordList.objects.filter(user=self.user).count())
コード例 #58
0
class WordwallsMissedBingosTest(WordwallsBasicLogicTest):
    """
    Missed bingos.

    We have one basic case here. It is easiest to test given a good text
    editor; we can search for "board": {some integer} in the leaderboard
    entry json, for example, to quickly find the total number of people
    who did that challenge, etc.

    The answers below are a little bit off from the count, because
    we throw away leaderboard entries where "qualifyForAward" is false.

    For this case, we got Monday, Tuesday, Wednesday, Thursday. We throw
    away the first two (Monday 7s and 8s) since the "missed bingo"
    challenge week starts on Tuesday.

    challenge 40256, leaderboard 40079, answers: 54   Tues  7s
    challenge 40260, leaderboard 40082, answers: 34   Tues  8s
    challenge 40279, leaderboard 40106, answers: 47   Wed   7s
    challenge 40287, leaderboard 40108, answers: 34   Wed   8s
    challenge 40307, leaderboard 40128, answers: 58   Thurs 7s
    challenge 40313, leaderboard 40134, answers: 33   Thurs 8s

    """
    fixtures = ['test/lexica.json',
                # Eventually get rid of these two, because they are
                # replaced by sqlite, but for now we test for backwards
                # compatibility, since we are doing an in-place
                # migration.
                'test/users.json',
                'test/profiles.json',
                'dcNames.json',
                'test/daily_challenge.json',
                'test/daily_challenge_leaderboard.json',
                'test/daily_challenge_leaderboard_entry.json',
                'test/daily_challenge_missed_bingos.json']

    expected_missed_bingos = set([
        'ADEEIKKS', 'DEIILMMS', 'ACIORRTT', 'ACELOPRT', 'AFIIMNPR',
        'ALMOOPRS', 'AACEOSST', 'BDEEILNR', 'HIMORSST', 'EHOORSST',
        'AGHNORST', 'ACCILRSY', 'ACCDEILY', 'ACIIRSTT', 'DEHKLNOU',
        'AADGMNOP', 'AEORRRST', 'CIILNOPS', 'AAGIMNOS', 'ADILMOSY',
        'ADEIMSTY', 'DEELLORW', 'EGIILNRS', 'AACEEHRT', 'EEILNOSV',

        'AABLLOR', 'FIOPRST', 'AEHIMSS', 'ACCDHIL', 'ACEHRRX',
        'CEHNOSU', 'ACHHIRS', 'AEGILNR', 'EIMORST', 'EGMORSU',
        'ACCEIST', 'AELMMSY', 'EEINSTV', 'LLOSTUY', 'ACEIRTT',
        'AAAKLMY', 'BIMNOSU', 'AALOPRS', 'CIKNPSY', 'BDNOORU',
        'AEHMPTY', 'ACCILST', 'AEGIKPR', 'ENNORSU', 'ACIRTUY'
    ])

    def setUp(self):
        self.user = User.objects.get(username='******')
        self.lex = Lexicon.objects.get(lexiconName='America')
        self.wwg = WordwallsGame()

    def test_load_missed_bingos(self):
        challenge = DailyChallengeName.objects.get(
            name="Week's Bingo Toughies")
        table_id = self.wwg.initialize_daily_challenge(
            self.user, self.lex, challenge, date(2015, 10, 20))
        wgm = self.wwg.get_wgm(table_id)
        state = json.loads(wgm.currentGameState)
        # This test is run more than a week afterwards, for all time,
        # so it does not qualify for an award anymore. We should maybe
        # mock time to make it clear it's at least a week after 2015/10/19
        self.assertFalse(state['qualifyForAward'])
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 50, 'numCurAlphagrams': 50,
            'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
            'questionIndex': 0, 'is_temporary': True
        })
        questions = json.loads(word_list.origQuestions)
        # logger.debug('Questions: %s', questions)
        self.assertEqual(set([q['q'] for q in questions]),
                         self.expected_missed_bingos)
コード例 #59
0
ファイル: views.py プロジェクト: atomiccupcake/Webolith
def table(request, id):
    logger.info("request: %s", request.method)

    if request.method == 'POST':
        action = request.POST['action']
        logger.info('action %s', action)
        if action == "start":
            return start_game(request, id)
        elif action == "guess":
            logger.info('%s: guess %s, table %s', request.user.username,
                        request.POST['guess'], id)

            wwg = WordwallsGame()

            state = wwg.guess(request.POST['guess'].strip(), id, request.user)

            return response({'g': state[0], 'C': state[1]})
        elif action == "gameEnded":
            wwg = WordwallsGame()
            ret = wwg.checkGameEnded(id)
            # 'going' is the opposite of 'game ended'
            return response({'g': not ret})
        elif action == "giveUp":
            wwg = WordwallsGame()
            ret = wwg.giveUp(request.user, id)
            return response({'g': not ret})
        elif action == "save":
            wwg = WordwallsGame()
            ret = wwg.save(request.user, id, request.POST['listname'])
            return response(ret)
        elif action == "giveUpAndSave":
            wwg = WordwallsGame()
            ret = wwg.giveUpAndSave(request.user, id, request.POST['listname'])
            # this shouldn't return a response, because it's not going to be
            # caught by the javascript
            logger.debug("Give up and saving returned: %s" % ret)
            return response(ret)
        elif action == "savePrefs":
            profile = request.user.get_profile()
            profile.customWordwallsStyle = request.POST['prefs']
            profile.save()
            return response({'success': True})
        elif action == "getDcData":
            wwg = WordwallsGame()
            dcId = wwg.getDcId(id)
            if dcId > 0:
                leaderboardData = getLeaderboardDataDcInstance(
                    DailyChallenge.objects.get(pk=dcId))
                return response(leaderboardData)

    else:   # it's a GET
        wwg = WordwallsGame()
        permitted = wwg.permit(request.user, id)
        if gargoyle.is_active('disable_games', request):
            permitted = False
        if permitted:
            params = wwg.getAddParams(id)
            # Add styling params from user's profile (for styling table
            # tiles, backgrounds, etc)
            try:
                profile = request.user.get_profile()
                style = profile.customWordwallsStyle
                if style != "":
                    params['style'] = style
            except:
                pass

            return render_to_response('wordwalls/table.html',
                                      {'tablenum': id,
                                       'username': request.user.username,
                                       'addParams': json.dumps(params),
                                       'avatarUrl': profile.avatarUrl,
                                       'CURRENT_VERSION': CURRENT_VERSION
                                       },
                                      context_instance=RequestContext(request))
        else:
            return render_to_response('wordwalls/notPermitted.html',
                                      {'tablenum': id},
                                      context_instance=RequestContext(request))
コード例 #60
0
class WordwallsChallengeBehaviorTest(WordwallsBasicLogicTest):
    """
    Test challenge behavior. Create challenges, quiz on them, leaderboards,
    etc.

    """
    fixtures = ['test/lexica.json',
                'test/users.json',
                'test/profiles.json',
                'dcNames.json',
                'test/daily_challenge.json']

    def setUp(self):
        self.user = User.objects.get(username='******')
        self.lex = Lexicon.objects.get(lexiconName='America')
        self.wwg = WordwallsGame()

    def test_length_challenge(self):
        """ Test a regular challenge by word length (Today's 6s). """
        num_challenges = DailyChallenge.objects.count()
        challenge = DailyChallengeName.objects.get(name="Today's 6s")
        table_id = self.wwg.initialize_daily_challenge(
            self.user, self.lex, challenge, date.today())
        # Assert that it created a challenge.
        self.assertEqual(num_challenges + 1, DailyChallenge.objects.count())
        wgm = self.wwg.get_wgm(table_id)
        state = json.loads(wgm.currentGameState)
        self.assertTrue(state['qualifyForAward'])
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 50, 'numCurAlphagrams': 50,
            'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
            'questionIndex': 0, 'is_temporary': True
        })
        questions = json.loads(word_list.origQuestions)
        for q in questions:
            self.assertEqual(len(q['q']), 6, msg=q)
        self.assertEqual(
            len(set([q['q'] for q in questions])), 50)

    def test_bingo_marathon_challenge(self):
        """ Test bingo marathon challenge. """
        challenge = DailyChallengeName.objects.get(name='Bingo Marathon')
        table_id = self.wwg.initialize_daily_challenge(
            self.user, self.lex, challenge, date.today())
        wgm = self.wwg.get_wgm(table_id)
        state = json.loads(wgm.currentGameState)
        self.assertTrue(state['qualifyForAward'])
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 100, 'numCurAlphagrams': 100,
            'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
            'questionIndex': 0, 'is_temporary': True
        })
        questions = json.loads(word_list.origQuestions)
        # Check there are 50 7s and 50 8s
        num_7s = 0
        num_8s = 0
        for q in questions:
            if len(q['q']) == 7:
                num_7s += 1
            elif len(q['q']) == 8:
                num_8s += 1
        self.assertEqual(num_7s, 50)
        self.assertEqual(num_8s, 50)
        self.assertEqual(
            len(set([q['q'] for q in questions])), 100)
        params = self.wwg.start_quiz(table_id, self.user)
        self.assertEqual(len(params['questions']), 100)
        probability = params['questions'][0]['p']
        self.assertTrue(probability > 0)

    @mock.patch('wordwalls.challenges.gen_blank_challenges',
                side_effect=blank_bingo_generator)
    def test_blank_bingos(self, mock_content):
        """ Test blank bingos. (This comment is unnecessary, right?)"""
        challenge = DailyChallengeName.objects.get(name='Blank Bingos')
        table_id = self.wwg.initialize_daily_challenge(
            self.user, self.lex, challenge, date.today())
        wgm = self.wwg.get_wgm(table_id)
        state = json.loads(wgm.currentGameState)
        self.assertTrue(state['qualifyForAward'])
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 50, 'numCurAlphagrams': 50,
            'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
            'questionIndex': 0, 'is_temporary': True
        })
        questions = json.loads(word_list.origQuestions)
        self.assertEqual(
            len(set([q['q'] for q in questions])), 50)
        params = self.wwg.start_quiz(table_id, self.user)
        self.assertEqual(len(params['questions']), 50)
        # Blank bingos have no probability for their alphagram.
        self.assertTrue(params['questions'][0]['p'] is None)

    def test_play_old_challenge(self):
        """ Play an old challenge instead of creating a new one. """
        num_challenges = DailyChallenge.objects.count()
        challenge = DailyChallengeName.objects.get(name="Bingo Marathon")
        table_id = self.wwg.initialize_daily_challenge(
            self.user, Lexicon.objects.get(lexiconName='CSW15'),
            challenge, date(2015, 12, 8))
        # Assert that it did not create an additional challenge.
        self.assertEqual(num_challenges, DailyChallenge.objects.count())
        wgm = self.wwg.get_wgm(table_id)
        state = json.loads(wgm.currentGameState)
        self.assertFalse(state['qualifyForAward'])
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 100, 'numCurAlphagrams': 100,
            'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
            'questionIndex': 0, 'is_temporary': True
        })
        questions = json.loads(word_list.origQuestions)
        for q in questions:
            self.assertTrue(len(q['q']) in (7, 8), msg=q)
        self.assertEqual(
            len(set([q['q'] for q in questions])), 100)
        params = self.wwg.start_quiz(table_id, self.user)
        self.assertEqual(len(params['questions']), 100)

    def test_play_old_blank_bingos(self):
        """
        Play an old blank bingos challenge instead of creating a new one.

        """
        num_challenges = DailyChallenge.objects.count()
        challenge = DailyChallengeName.objects.get(name="Blank Bingos")
        table_id = self.wwg.initialize_daily_challenge(
            self.user, Lexicon.objects.get(lexiconName='America'),
            challenge, date(2016, 1, 1))
        # Assert that it did not create an additional challenge.
        self.assertEqual(num_challenges, DailyChallenge.objects.count())
        wgm = self.wwg.get_wgm(table_id)
        state = json.loads(wgm.currentGameState)
        self.assertFalse(state['qualifyForAward'])
        word_list = wgm.word_list
        self.assert_wl(word_list, {
            'numAlphagrams': 50, 'numCurAlphagrams': 50,
            'numFirstMissed': 0, 'numMissed': 0, 'goneThruOnce': False,
            'questionIndex': 0, 'is_temporary': True
        })
        questions = json.loads(word_list.origQuestions)
        for q in questions:
            self.assertTrue(len(q['q']) in (7, 8), msg=q)
        self.assertEqual(
            len(set([q['q'] for q in questions])), 50)
        params = self.wwg.start_quiz(table_id, self.user)
        self.assertEqual(len(params['questions']), 50)