Exemplo n.º 1
0
def jumbled( word_list, n ):
    """
    Create an anagram of n strings randomly chosen
    from word_list.  The jumble is enough to create
    any one of the selected words, but duplicates between
    words are merged (see letterbag). 
    Args:
       word_list:  non-empty list of strings
       n: 1 <= n <= len(word_list), number of words
          to jumble together.
    Returns:
       A jumbled string with the property that any of the
       selected strings from word_list can be formed.  The 
       result should be the smallest jumble with this property
       (i.e., duplicates between words have been removed).
    """
    selected = random.sample(word_list, n)
    bag = LetterBag("")
    for word in selected:
        bag.merge( LetterBag(word) )
    letters = list(bag.as_string())
    print("Letters: {}".format(letters))
    random.shuffle(letters)
    result = "".join(letters)
    return result
Exemplo n.º 2
0
def check():
  """
  The user has pressed a key. We respond by sending back 2 
  booleans and 1 list. The first boolean we send back is whether 
  all the characters in the text that the user has typed in so far
  are in the jumble/anagram word. The second boolean we send back
  is whether the text the user has typed in so far is a word that is 
  in the list of vocabulary words. Lastly, we send back a list of all 
  the words in the vocabulary list that contain all the letters that 
  have been typed so far by the user. 
  """
  app.logger.debug("Entering check")
  
  text = request.args.get("text", type=str)
  jumble = request.args.get("jumble", type=str)
  
  ## Is it good? 
  in_jumble = LetterBag(jumble).contains(text) #all letters are in the jumble/anagram word
  matched = WORDS.has(text) #the text is a word that is in the list of vocab words
  
  highlight_list = []
  for word in WORDS.as_list():
    if (LetterBag(word).contains(text)):
        highlight_list.append(word)
  
  rslt = { "in_jumble": in_jumble, "matched": matched, "highlight_list": highlight_list } 
  return jsonify(result=rslt)
def check():
    app.logger.debug("Entering AJAX check")
    text = flask.request.args.get(
        "text", type=str
    )  # Get the text provided from vocab.html where check was called
    jumble = flask.session[
        "jumble"]  # Set jumble equal to the anagram from the session value jumble
    matches = flask.session.get(
        "matches", [])  # Set matches to the empty session value for matches
    flask.session[
        "input_letters"] = text  # Update the session variable input_letters with the local one
    next_url = 0  # Default case where the user still needs to get more matches and the current word is not a match
    # Check if input letter is valid
    input_key = text[(len(text) - 1)]  # Most recent letter pressed
    valid_key = LetterBag(jumble).contains(
        input_key
    )  # valid_key is a bool that tells us if the key the user just pressed is in the anagram
    if not valid_key:  # If the key the user input isn't in the anagram
        next_url = 1  # Code for html to "undo" that keystroke
    # Check if the input was already used
    txt_instances = jumble_instances = 0
    # Number of times the new key is present in txt and in jumble
    for letter in text:
        if letter == input_key:
            txt_instances += 1  # Should be >0
    for letter in jumble:
        if letter == input_key:
            jumble_instances += 1  # Should be >0
    if txt_instances > jumble_instances:  # The letter has been used more times than it exists in jumble
        if next_url == 0:  # The letter was in the jumble
            next_url = 1
    # Is it good?
    in_jumble = LetterBag(jumble).contains(
        text
    )  # in_jumble is a bool that tells us if the text the user entered is in the anagram
    matched = WORDS.has(
        text)  # matched is a bool that tells us if text is in the words list
    # Respond appropriately
    if matched and in_jumble and not (
            text in matches):  # Cool, they found a new word
        matches.append(text)  # Add text to the local matches variable
        flask.session[
            "matches"] = matches  # Update the session variable matches with the local one
        next_url = flask.url_for("keep_going")  # Set next
    # Choose page:  Solved enough, or keep going?
    if len(matches) >= flask.session[
            "target_count"]:  # If you have as many matches as defined by your target_count
        next_url = flask.url_for("success")  # Define the target url as success
    rslt = {"new_url": next_url}  # Define a list to for the return data
    return flask.jsonify(result=rslt)  # Send the data back to vocab.html
Exemplo n.º 4
0
def check():
    """
  User has submitted the form with a word ('attempt')
  that should be formed from the jumble and on the
  vocabulary list.  We respond depending on whether
  the word is on the vocab list (therefore correctly spelled),
  made only from the jumble letters, and not a word they
  already found.
  """
    app.logger.debug("Entering check")  #grab arguments from flask
    text = request.args.get("text", type=str)
    jumble = flask.session["jumble"]
    matches = flask.session.get("matches", [])  # Default to empty list

    ## Is it good?
    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)

    rez = {"key": ''}  #result dict, is what's sent to the html
    ## Respond appropriately
    if matched and in_jumble and not (text in matches):
        ## Cool, they found a new word
        matches.append(text)
        flask.session["matches"] = matches
        if len(matches) >= flask.session["target_count"]:
            rez['key'] = 'STOP'  #once we complete the 3 words, stop asking for more
        else:
            rez['key'] = text + ' '  #keep going otherwise

    return jsonify(result=rez)  #pop result to json regardless of user success
Exemplo n.º 5
0
def check():
    """
  User has submitted the form with a word ('attempt')
  that should be formed from the jumble and on the
  vocabulary list.  We respond depending on whether
  the word is on the vocab list (therefore correctly spelled),
  made only from the jumble letters, and not a word they
  already found.
  """
    app.logger.debug("Entering check")

    ## The data we need, from form and from cookie
    text = request.args.get("text", type=str)
    jumble = flask.session["jumble"]
    matches = flask.session.get("matches", [])  # Default to empty list

    ## Is it good?
    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)

    rslt = {"key": "incomplete"}

    ## Respond appropriately
    if matched and in_jumble and not (text in matches):
        matches.append(text)
        flask.session["matches"] = matches
        if len(matches) >= flask.session["target_count"]:
            rslt['key'] = 'TARGET_MET'
        else:
            rslt['key'] = text

    return jsonify(result=rslt)
Exemplo n.º 6
0
def myCheck():
    flask.jsonify()
    app.logger.debug("Entering check")
    # The data we need, from form and from cookie
    text = flask.request.args.get("text", type=str)
    jumble = flask.session["jumble"]
    # Make a list of the words the client has found
    matches = flask.session.get("matches", [])  # Default to empty list
    # Is it good?
    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)
    # Respond appropriately
    if matched and in_jumble and not (text in matches):
        # Cool, they found a new word
        app.logger.debug("Found Match")
        matches.append(text)
        ie = False
        flask.session["matches"] = matches
        # If the correct amount of matches are found
        if len(matches) >= CONFIG.SUCCESS_AT_COUNT:
            ie = True
        # Create a dict containing the completed word and a boolean on whether enough
        # words have been found to redirect the client to the success page.
        word_in_list = {"complete_word": True, "is_enough": ie}
        # Send the dict to vocab.html
        return flask.jsonify(result=word_in_list)
    else:
        # Case for if the entry isn't a correct word.
        app.logger.debug("Incorrect word has been entered")
        assert False  # Raises AssertionError
Exemplo n.º 7
0
def check():
    """
    """
    app.logger.debug("Entering check")

    flask.g.vocab = WORDS.as_list()
    text = flask.request.args.get("text", type=str)
    matches = flask.session.get("matches", [])
    jumble = flask.session["jumble"]
    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)

    # dictionary to set booleans for various cases
    rslt = {
        "valid_word": matched and in_jumble and not (text in matches),
        "duplicate_words": text in matches,
        "invalid_letters": text in flask.g.vocab and not in_jumble
    }

    # add matched word to list
    if matched and in_jumble and not (text in matches):
        app.logger.debug("about to add match to list")
        matches.append(text)
        flask.session["matches"] = matches

    # dictionary to set boolean for enough matches
    engh = {"enough_words": len(matches) >= flask.session["target_count"]}

    return flask.jsonify(result=rslt, enough=engh)
def check():
    """
    User has submitted the form with a word ('attempt')
    that should be formed from the jumble and on the
    vocabulary list.  We respond depending on whether
    the word is on the vocab list (therefore correctly spelled),
    made only from the jumble letters, and not a word they
    already found.
    """

    app.logger.debug("Entering check")
    text = flask.request.args.get("text", type=str)
    jumble = flask.session["jumble"]
    matches = flask.session.get("matches", [])  # Default to empty list
    # Is it good?
    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)
    rslt = {
        "Already_found": text in matches,
        "Not_in_list": not matched,
        "Letter_not_in_jumble": not in_jumble,
        "Word_found": matched and in_jumble and not (text in matches),
        "Game_over": len(matches) >= flask.session["target_count"],
        "currentword": text
    }
    # Respond appropriately
    if rslt["Word_found"]:
        # Cool, they found a new word
        matches.append(text)
        flask.session["matches"] = matches
        # Choose page:  Solved enough, or keep going?

    return flask.jsonify(result=rslt)
Exemplo n.º 9
0
def checkmatch():
    """
    Example ajax request handler
    """
    app.logger.debug("Got a JSON request")

    text = flask.request.args.get("text", type=str)
    jumble = flask.session["jumble"]
    matches = flask.session.get("matches", [])

    #test for match
    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)
    print(text)
    print(matches)
    if matched and in_jumble and not (text in matches):  #success case
        matches.append(text)
        flask.session["matches"] = matches
        rslt = {"gotmatch": True}
    elif text in matches:
        rslt = {"alreadyfound": True}
    elif not matched:
        rslt = {"notinlist": True}
    elif not in_jumble:
        rslt = {"cantmake": True}
    else:
        app.logger.debug("this case shouldn't happen!")
        assert False  #raises asserterror

    if len(matches) >= flask.session["target_count"]:
        rslt = {"success": True}

    return flask.jsonify(result=rslt)
Exemplo n.º 10
0
def solved():
    """
    updates page when a new word is found. most of this code is copy/pasted
    from the "check" function or the minijax .py script. the bottom bit is 
    basically the bottom of the original if conditional from "check" as well.
    """

    ## The data we need, from form and from cookie
    text = request.args.get("text", type=str)
    jumble = flask.session["jumble"]
    matches = flask.session.get("matches", [])  # Default to empty list

    ## Is it good?
    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)

    if matched and in_jumble and not (text in matches):
        matches.append(text)
        flask.session["matches"] = matches
    if len(matches) >= flask.session["target_count"]:
        #matched 3 words
        rslt = {"function": "/success"}
        return jsonify(result=rslt)
    else:
        #yet to match 3 words
        rslt = {"function": "/keep_going"}
        return jsonify(result=rslt)
Exemplo n.º 11
0
	def check():
	"""
	User has submitted the form with a word ('attempt')
	that should be formed from the jumble and on the
	vocabulary list.  We respond depending on whether
	the word is on the vocab list (therefore correctly spelled),
	made only from the jumble letters, and not a word they
	already found.
	"""
	app.logger.debug("Entering check")
	
# The data we need, from form and from cookie
	text = flask.request.form["attempt"]
	jumble = flask.session["jumble"]
	matches = flask.session.get("matches", [])  # Default to empty list
	
	success = false		#flag
	
	
# Is it good?
	in_jumble = LetterBag(jumble).contains(text)
	matched = WORDS.has(text)
	
# Respond appropriately
	if matched and in_jumble and not (text in matches):
# Cool, they found a new word
	matches.append(text)
		flask.session["matches"] = matches	
        message = “Hey, you  found {}!".format(text)
            return flask.jsonify(message = message, target=flask.session["target_count"])                                                               
		elif text in matches:
			message = “You already found {}".format(text)
Exemplo n.º 12
0
def compute():
    """
    Computes the input string. To see if the string
    is made from the scramble and if words can be made
    from the bank.
    """
    app.logger.debug("Got a JSON request")

    text = flask.request.args.get("text", type=str)
    jumble = flask.session["jumble"]
    matches = flask.session.get("matches", [])
    app.logger.debug(matches)

    # Text made from jumbled letters
    in_jumble = LetterBag(jumble).contains(text)
    # Text is in words list
    matched = WORDS.has(text)

    if matched and in_jumble and not (text in matches):
        # Cool, they found a new word
        matches.append(text)
        flask.session["matches"] = matches

    result = {
        "matches": " ".join(matches),
        "found": len(matches) >= flask.session["target_count"]
    }
    return flask.jsonify(result=result)
Exemplo n.º 13
0
def check():
    """
    User has submitted the form with a word ('attempt')
    that should be formed from the jumble and on the
    vocabulary list.  We respond depending on whether
    the word is on the vocab list (therefore correctly spelled),
    made only from the jumble letters, and not a word they
    already found.
    """
    app.logger.debug("Entering check")

    # The data we need, from form and from cookie
    text = flask.request.args.get(
        "text", type=str)  #change to raw text as in flask_minijax.py
    jumble = flask.session["jumble"]
    matches = flask.session.get("matches", [])  # Default to empty list

    # Is it good?
    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)
    flashMessage = ""

    #AJAX will not reload the page, so we need to get rid of the flash feature
    #(which requires reload) and turn what flash is suppose to return
    #to return with JSON inputs, done via flashMessage collecting and reporting
    #the messages that come based off words entered
    # Respond appropriately
    if matched and in_jumble and not (text in matches):
        # Cool, they found a new word
        matches.append(text)
        flask.session["matches"] = matches
    elif text in matches:
        flashMessage = "You already found {}".format(text)
    elif not matched:
        flashMessage = "{} isn't in the list of words".format(text)
    elif not in_jumble:
        flashMessage = '"{}" can\'t be made from the letters {}'.format(
            text, jumble)
    else:
        app.logger.debug("This case shouldn't happen!")
        assert False  # Raises AssertionError

    # Choose page:  Solved enough, or keep going?
    if len(matches) >= flask.session["target_count"]:
        solved = True  #this boolean will trigger success page to show on vocab.html
    else:
        solved = False

    #put our result (rslt) into a dictionary and send a JSON response via flask.jsonify()
    #matchesMade = matches that have already been made so they can't duplicate, and also to store
    #matchMade = current match
    rslt = {
        "flashMessage": flashMessage,
        "solved": solved,
        "matchesMade": matches,
        "matchMade": matched
    }
    return flask.jsonify(result=rslt)
    '''
Exemplo n.º 14
0
def test_contains_basic_examples():
    """
    Examples from the docstring of LetterBag.contains,
    with and without auto-conversion to LetterBag
    """
    # Passing other as LetterBag
    assert LetterBag("abbc").contains(LetterBag("abc"))
    assert LetterBag("abbc").contains(LetterBag("abbc"))
    assert not LetterBag("abc").contains(LetterBag("abbc"))
    # Passing other as string
    assert LetterBag("abbc").contains("abc")
    assert LetterBag("abbc").contains("abbc")
    assert not LetterBag("abc").contains("abbc")
Exemplo n.º 15
0
def test_advanced_merge():
    """
    Examples using more advanced cases from class.
    """
    capital_bag = LetterBag("A")
    lc_bag = LetterBag("a")
    empty_bag1 = LetterBag("")
    empty_bag2 = LetterBag("")
    assert capital_bag.merge(lc_bag).as_string() == "Aa"
    assert empty_bag1.merge(empty_bag2).as_string() == ""
Exemplo n.º 16
0
def check():
    """
    User has submitted the form with a word ('attempt')
    that should be formed from the jumble and on the
    vocabulary list.  We respond depending on whether
    the word is on the vocab list (therefore correctly spelled),
    made only from the jumble letters, and not a word they
    already found.
    """
    app.logger.debug("Entering check")

    # The data we need, from form and from cookie
    text = flask.request.args.get("text",
                                  type=str)  #Taken from flask_minijax.py
    jumble = flask.session["jumble"]
    matches = flask.session.get("matches", [])  # Default to empty list

    # Is it good?
    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)
    msg = text

    # Respond appropriately
    if matched and in_jumble and not (text in matches):
        # Cool, they found a new word
        matches.append(text)
        flask.session["matches"] = matches
    elif text in matches:
        msg = "You already found {}".format(text)
    elif not matched:
        msg = "{} isn't in the list of words".format(text)
    elif not in_jumble:
        msg = '"{}" can\'t be made from the letters {}'.format(text, jumble)
    else:
        app.logger.debug("This case shouldn't happen!")
        assert False  # Raises AssertionError

    #print("Matches = ")
    #print(' '.join(matches))

    # Choose page:  Solved enough, or keep going?
    if len(matches) >= flask.session["target_count"]:
        rslt = {
            "matches": matched,
            "message": msg,
            "matching": "You have word 3 or more words in the Anagram!",
            "anagramFinished": True
        }  #Taken from example()
        return flask.jsonify(result=rslt)
    else:
        rslt = {
            "matches": matched,
            "message": msg,
            "matching": matches,
            "anagramFinished": False
        }  #Taken from example()
        return flask.jsonify(result=rslt)
Exemplo n.º 17
0
def check():
    """
    User has submitted the form with a word ('attempt')
    that should be formed from the jumble and on the
    vocabulary list.  We respond depending on whether
    the word is on the vocab list (therefore correctly spelled),
    made only from the jumble letters, and not a word they
    already found.
    """
    # 3 things to check: 1, in_jumble: letter from anagram? 2, mached: input word in WORDS?
    # 3, matches: input already been tested before?
    app.logger.debug("Entering check")

    # The data we need, from form and from cookie
    text = flask.request.args.get("text", type=str) # get the user input
    ## text = flask.request.form["attempt"]
    jumble = flask.session["jumble"]
    matches = flask.session.get("matches", [])  # Default to empty list
    
    
    # Is it good?
    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)
    # matched should be call from Vocab
    #matched = Vocab

    # Respond appropriately
    if matched and in_jumble and not (text in matches):
        # Cool, they found a new word
        matches.append(text)
        flask.session["matches"] = matches
        #JSON Code:
        # count the number of success, if the lenght is >= 2(target_count), pass to the html.
        # join_matches: if not in matches: true; else: false; in_WORDS(mached):in:True, not in False;
        # in_jumble: in: True, not in False;
        # variable here: join_matches is equal to False
        if len(matches) >= flask.session["target_count"]:
            rslt = {"join_matches": False, "in_WORDS":True, "in_jumble":True}
        else:
            rslt = {"join_matches": True, "in_WORDS":True, "in_jumble":True}
        
    elif text in matches:
        flask.flash("You already found {}".format(text))  #Words in matches
        rslt = {"joinin_matches": False, "in_WORDS": True, "in_jumble": True} 
    elif not matched:
        flask.flash("{} isn't in the list of words".format(text))   #Words in WORDS?
        rslt = {"join_matches": True, "in_WORDS": False, "in_jumble": True}
    elif not in_jumble:
        flask.flash(
            '"{}" can\'t be made from the letters {}'.format(text, jumble))
        rslt = {"join_matches":True, "in_WORDS": True, "in_jumble": False}
    else:
        app.logger.debug("This case shouldn't happen!")
        assert False  # Raises AssertionError
        rslt = {"join_matches":False, "in_WORDS": False, "in_jumble": False}
    rslt["input"] = text
    return flask.jsonify(result=rslt)
Exemplo n.º 18
0
def check():
    """
    User has submitted the form with a word ('attempt')
    that should be formed from the jumble and on the
    vocabulary list.  We respond depending on whether
    the word is on the vocab list (therefore correctly spelled),
    made only from the jumble letters, and not a word they
    already found.
    """
    app.logger.debug("Entering check")

    # The data we need, from form and from cookie
    text = flask.request.args.get(
        "text", type=str)  # current text in #attempt input field
    letter = flask.request.args.get("letr",
                                    type=str)  # most recently pressed key
    jumble = flask.session["jumble"].upper(
    )  # use .upper() to prevent case sensitive issues
    matches = flask.request.args.get("spelt", type=str).split(
        "\n")  # list of spelled words for current game

    # Is it good?
    in_jumble = LetterBag(jumble).contains(letter)
    matched = WORDS.has(text)

    rslt = {
        "have_letter": in_jumble,
        "valid_word": matched and in_jumble and not (text in matches),
        "is_playing": len(matches) - 1 < CONFIG.SUCCESS_AT_COUNT,
        "msg": ""
    }

    # Respond appropriately
    if rslt["valid_word"]:
        # Cool, they found a new word
        matches.append(text)
        flask.session["matches"] = matches
        if (len(matches) - 1 == CONFIG.SUCCESS_AT_COUNT):
            # Game Over
            rslt["is_playing"] = False
        else:
            rslt["is_playing"] = True
            rslt["msg"] = "Only {} words remaining".format(
                CONFIG.SUCCESS_AT_COUNT - len(matches) + 1)
    elif text in matches:
        # they've already found this word
        rslt["msg"] = "You already found {}".format(text)
    elif not matched:
        # the word they've entered doesn't exist
        rslt["msg"] = "{} isn't in the list of words".format(text)
    elif not in_jumble:
        # The word they've spelled cannot be made
        rslt["msg"] = '"{}"can\'t be made from the letters {}'.format(
            text, jumble)

    return flask.jsonify(result=rslt)
Exemplo n.º 19
0
def check():
    """
    User has submitted the form with a word ('attempt')
    that should be formed from the jumble and on the
    vocabulary list.  We respond depending on whether
    the word is on the vocab list (therefore correctly spelled),
    made only from the jumble letters, and not a word they
    already found.
    """
    app.logger.debug("Entering check")

    # The data we need, from form and from cookie
    
    #1. text = flask.request.form["attempt"]
    text = flask.request.args.get("attempt", type = str)
    
    jumble = flask.session["jumble"]
    matches = flask.session.get("matches", [])  # Default to empty list

    # Is it good?

    #2. add something
    send_message = {}
    
    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)

    # Respond appropriately
    if matched and in_jumble and not (text in matches):
        # Cool, they found a new word
        matches.append(text)
        #3.
        send_message["message"] = "find {}".format(text)
        flask.session["matches"] = matches
    elif text in matches:
        #4.
        matched = False
        send_message["message"] = "You already found {}".format(text)
    elif not matched:
        #5.
        matched = False
        send_message["message"] = "{} isn't in the list of words".format(text)
    elif not in_jumble:
        #6.
        send_message["message"] =  '"{}" can\'t be made from the letters {}'.format(text, jumble)
    else:
        app.logger.debug("This case shouldn't happen!")
        assert False  # Raises AssertionError

    # Choose page:  Solved enough, or keep going?
    if len(matches) >= flask.session["target_count"]:
        #7.
        send_message["message"] = True
       return flask.redirect(flask.url_for("success"))
    else:
Exemplo n.º 20
0
def ajax_check():
    """
    User has submitted the form with a word ('attempt')
    that should be formed from the jumble and on the
    vocabulary list.  We respond depending on whether
    the word is on the vocab list (therefore correctly spelled),
    made only from the jumble letters, and not a word they
    already found.
    """

    # The data we need, from form and from cookie
    text = flask.request.args.get("attempt", type=str)
    app.logger.debug("Got json request with string {}".format(text))

    jumble = flask.session["jumble"]
    matches = flask.session.get("matches", [])  # Default to empty list

    # early exit if length is not long enough
    #if(len(text) != len(jumble)):
    #    return flask.jsonify(result = {"msg" : "wrong_len"})

    # Is it good?
    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)

    msg_code = ""
    res = {}

    # Respond appropriately
    if matched and in_jumble and not (text in matches):
        # Cool, they found a new word
        matches.append(text)
        flask.session["matches"] = matches
        res["msg"] = "Nice job!"
        res["code"] = "new"
    elif text in matches:
        res["msg"] = "You already found {}".format(text)
        res["code"] = "not_new"
    elif not matched:
        res["msg"] = "{} isn't in the list of words".format(text)
        res["code"] = "not_found"
    elif not in_jumble:
        res["msg"] = '"{}" can\'t be made from the letters {}'.format(
            text, jumble)
        res["code"] = "not_jumble"
    else:
        res["msg"] = "lol who it"
        app.logger.debug("This case shouldn't happen!")
        assert False  # Raises AssertionError
        res["code"] = "err"

    res["words"] = matches
    return flask.jsonify(result=res)
Exemplo n.º 21
0
def check():
    """
    User has submitted the form with a word ('attempt')
    that should be formed from the jumble and on the
    vocabulary list.  We respond depending on whether
    the word is on the vocab list (therefore correctly spelled),
    made only from the jumble letters, and not a word they
    already found.
    """
    app.logger.debug("Entering check")

    # The data we need, from form and from cookie
    # text = flask.request.form["attempt"]
    jumble = flask.session["jumble"]
    matches = flask.session.get("matches", [])
    text = flask.request.args.get("text", type=str)  # Default to empty list
    gameover = False
    # Is it good?
    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)
    res = {}
    error = ""

    # Respond appropriately
    if matched and in_jumble and not (text in matches):
        # Cool, they found a new word
        matches.append(text)
        flask.session["matches"] = matches

        res = {"word_exist": True}
    elif text in matches:
        res = {"error": ("You already found {}".format(text))}

    elif not matched:
        res = {"error": ("{} isn't in the list of words".format(text))}

    elif not in_jumble:
        res = {
            "error":
            ('"{}" can\'t be made from the letters {}'.format(text, jumble))
        }
    # flask.flash(
    #     '"{}" can\'t be made from the letters {}'.format(text, jumble))
    else:
        app.logger.debug("This case shouldn't happen!")
        assert Falses  # Raises AssertionError

    # Choose page:  Solved enough, or keep going?
    if len(matches) >= flask.session["target_count"]:
        gameover = True
        res = {"done": gameover, "error": error}

    return flask.jsonify(result=res)
Exemplo n.º 22
0
def jumbled(word_list, n):
    """
    Create an anagram of n strings randomly chosen
    from word_list.  The jumble is enough to create
    any one of the selected words, but duplicates between
    words are merged (see letterbag).
    Args:
       word_list:  non-empty list of strings
       n: 1 <= n <= len(word_list), number of words
          to jumble together.
    Returns:
       A jumbled string with the property that any of the
       selected strings from word_list can be formed.  The
       result should be the smallest jumble with this property
       (i.e., duplicates between words have been removed).
    """
    # Create the anagram
    selected = random.sample(word_list, n)
    bag = LetterBag("")
    for word in selected:
        bag.merge(LetterBag(word))
    letters = list(bag.as_string())
    print("Letters: {}".format(letters))
    random.shuffle(letters)
    result = "".join(letters)
    return result
Exemplo n.º 23
0
def check():
    """
  User has submitted the form with a word ('attempt')
  that should be formed from the jumble and on the
  vocabulary list.  We respond depending on whether
  the word is on the vocab list (therefore correctly spelled),
  made only from the jumble letters, and not a word they
  already found.
  """
    app.logger.debug("Entering check")

    ## The data we need, from form and from cookie
    text = request.args.get("text", type=str)
    jumble = flask.session["jumble"]
    matches = flask.session.get("matches", [])  # Default to empty list

    ## Is it good?
    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)
    # Boolean for checking if the user reached the target count
    solved = len(matches) >= flask.session["target_count"]

    # Empty dictionary that is sent over to html file
    is_match = {}

    ## Respond appropriately
    if matched and in_jumble and not (text in matches):
        ## Cool, they found a new word
        matches.append(text)
        flask.session["matches"] = matches
        # Send message to html file that a word is found
        is_match = {"word": "found"}
        return jsonify(result=is_match)
    elif text in matches:
        # Send message that user already found a word
        is_match = {"word": "already found"}
        return jsonify(result=is_match)
    elif not matched:
        # Send message if word is not in the list of words
        is_match = {"word": "not found"}
        return jsonify(result=is_match)
    elif not in_jumble:
        # Send message if word is not available in the list of letters
        is_match = {"word": "unavailable"}
        return jsonify(result=is_match)
    elif solved:
        # Send message if user reaches the target count
        is_match = {"word": "success"}
        return jsonify(result=rslt)
    else:
        app.logger.debug("This case shouldn't happen!")
        assert False  # Raises AssertionError
Exemplo n.º 24
0
def test_merge_unchaged():
    """
    Calling merge on a bag with a bag whose characters
    are already contained in the calling bag
    should not change its contents
    """
    bag_a = LetterBag("abcde")
    bag_b = LetterBag("ae")
    bag_a_str = bag_a.as_string()
    bag_a.merge(bag_b)
    assert bag_a.as_string() == bag_a_str
Exemplo n.º 25
0
def test_identical():
    """
    Two Letterbags with letters in different order should still be identical
    """
    bag_1 = LetterBag("edccba")
    bag_2 = LetterBag("abccde")
    assert bag_1.contains(bag_2)
    assert bag_2.contains(bag_1)
Exemplo n.º 26
0
def check():
    """
    User has submitted the form with a word ('attempt')
    that should be formed from the jumble and on the
    vocabulary list.  We respond depending on whether
    the word is on the vocab list (therefore correctly spelled),
    made only from the jumble letters, and not a word they
    already found.
    """
    app.logger.debug("Entering check")

    # The data we need, from form and from cookie
    text = flask.request.args.get("text", type=str)
    letter = flask.request.args.get("lett", type=str)
    jumble = flask.session["jumble"].upper()
    target_count = flask.session["target_count"]
    matches = flask.request.args.get("matches", type=str).split("\n")

    # Is it good?
    in_jumble = LetterBag(jumble).contains(letter)
    matched = WORDS.has(text)

    # If letter is valid
    # If word is valid
    # If word has been found already

    rslt = {
        "letter_valid": in_jumble,
        "word_valid": (matched and in_jumble and not (text in matches)),
        "repeat_word": text in matches,
        "game_over": False
    }

    if rslt["word_valid"]:
        matches.append(text)
        flask.session["matches"] = matches
        if (target_count - len(matches)) + 1 > 0:
            rslt[
                "message"] = "You found a new word! Only {} more to go".format(
                    target_count - len(matches) + 1)
        else:
            rslt["game_over"] = True
    elif rslt["repeat_word"]:
        rslt["message"] = "You already found {}".format(text)
    elif not in_jumble:
        rslt["message"] = "{} is not in the jumbled letters".format(
            letter.lower())
    elif not matched:
        rslt["message"] = "{} isn't in the list of words".format(text)

    return flask.jsonify(result=rslt)
Exemplo n.º 27
0
def check():
    """
    User has submitted the form with a word ('attempt')
    that should be formed from the jumble and on the
    vocabulary list.  We respond depending on whether
    the word is on the vocab list (therefore correctly spelled),
    made only from the jumble letters, and not a word they
    already found.
    """
    app.logger.debug("Got a JSON request")

    text = flask.request.args.get("text", type=str)
    jumble = flask.session["jumble"]
    matchList = flask.session.get("matches", [])

    isJumble = LetterBag(jumble).contains(text)
    isMatch = WORDS.has(text)
    wdList = WORDS.as_list()

    if isMatch and isJumble and not (text in matchList):
        matchList.append(text)
        flask.session["matches"] = matchList
        rslt = {"matL": matchList, "wL": wdList}

    elif text in matchList:
        rslt = {
            "msg": "You already found {}".format(text),
            "flag": True,
            "wL": wdList
        }
    elif not isJumble:
        rslt = {
            "noJm": True,
            "msg":
            '"{}" can\'t be made from the letters {}'.format(text, jumble),
            "wL": wdList
        }
    elif not isMatch:
        rslt = {
            "msg": "{} isn't in the list of words".format(text),
            "wL": wdList
        }
    else:
        app.logger.debug("This case shouldn't happen!")
        assert False

    if len(matchList) >= flask.session["target_count"]:
        rslt = {"url": flask.url_for("success")}
    return flask.jsonify(result=rslt)
Exemplo n.º 28
0
def check():
    """
    User has submitted the form with a word ('attempt')
    that should be formed from the jumble and on the
    vocabulary list.  We respond depending on whether
    the word is on the vocab list (therefore correctly spelled),
    made only from the jumble letters, and not a word they
    already found.
    """
    app.logger.debug("Entering check")

    # The data we need, from form and from cookie
    text = flask.request.form["attempt"]
    jumble = flask.session["jumble"]
    matches = flask.session.get("matches", [])  # Default to empty list

    # Is it good?
    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)

    # Choose page:  Solved enough, or keep going?
    # Logic redone partially
    message = ""
    if matched and in_jumble and not (text in matches):
        # New word found
        matches.append(text)
        flask.session["matches"] = matches

        if len(matches) >= flask.session["target_count"]:
            # Enough matches redirect to success
            return flask.jsonify(complete=True, response="/success")
        else:
            # Not enough matches redirect to keep_going
            return flask.jsonify(complete=True, response="/keep_going")

    # Show error message, don't redirect
    elif text in matches:
        message = "You already found {}".format(text)
    elif not matched:
        message = "{} isn't in the list of words".format(text)
    elif not in_jumble:
        message = '"{}" can\'t be made from the letters {}'.format(
            text, jumble)
    else:
        app.logger.debug("This case shouldn't happen!")
        assert False  # Raises AssertionErrorflash

    # JSON showing that redirect should not be made, error message should be shown
    return flask.jsonify(complete=False, response=message)
Exemplo n.º 29
0
def checkem():
    """
  User has entered a letter into the form with a word ('attempt')
  that should be from the jumble and on the
  vocabulary list.  We respond depending on whether
  the word is on the vocab list (therefore correctly spelled),
  made only from the jumble letters, and not a word they
  already found.
  tests logic if it is a good word and puts it in the matched list
  
  gets args from the url after the "?"
  
  returns jsonify results as {"key":"value","key":"value",...}
  """

    text = request.args.get("text", type=str)
    jumble = flask.session[
        "jumble"]  #jumble of letters that appear in html for user to use to make the words on the page
    matches = flask.session.get("matches", [])  # Default to empty list
    ## Is it good?
    in_jumble = LetterBag(jumble).contains(
        text)  #bool true if letters in text are letters in jumble
    matched = WORDS.has(text)  #bool true if text is in the words to be matched
    count = len(matches)  #how many matches

    if (matched and in_jumble and not (text in matches)):
        matches.append(text)
        flask.session["matches"] = matches
        rslt = {"matched": True}
        if count == (flask.session["target_count"] -
                     1):  #if there is enough matches to be success
            rslt = {
                "success": True,
                "matched": True,
                "url": url_for("success")
            }
            return jsonify(result=rslt)
        else:
            return jsonify(result=rslt)
    elif not in_jumble:
        rslt = {"not_jumble": True}
        return jsonify(result=rslt)
    elif (text in matches):
        rslt = {"duplicate": True}
        return jsonify(result=rslt)
    else:
        rslt = {"this_shouldn't_happen": True}
        return jsonify(result=rslt)
Exemplo n.º 30
0
def check():
    """
    User has submitted the form with a word ('attempt')
    that should be formed from the jumble and on the
    vocabulary list.  We respond depending on whether
    the word is on the vocab list (therefore correctly spelled),
    made only from the jumble letters, and not a word they
    already found.
    """
    app.logger.debug("Entering check")

    # get data from args
    text = flask.request.args.get("text", type=str)
    jumble = flask.session["jumble"]
    matches = flask.session.get("matches", [])  # Default to empty list
    rslt = { "was_match": False }
    is_long = "false"

    # Is it good?
    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)
    #in_anagram = check_input(text, jumble)

    # Respond appropriately
    if matched and in_jumble and not (text in matches):
        # Cool, they found a new word
        matches.append(text + " ")
        flask.session["matches"] = matches
        current_status = "matched"
        if len(matches) >= flask.session["target_count"]:
            is_long = "true"
    elif text in matches:
        current_status = "exists"
    elif not matched:
        current_status = "unmatched"
    elif not in_jumble:
        current_status = "impossible"
    else:
        app.logger.debug("This case shouldn't happen!")
        assert False  # Raises AssertionError

    rslt = {"enough_length": is_long,
            "current_status": current_status,
            "matched_list": matches,
            "jumble": jumble,
            "word": text}
    return flask.jsonify(result=rslt)
Exemplo n.º 31
0
def check():
    """
    User has typed text into the attempt input field
    which sends the text as an AJAX Request
    We evaluate if the text is a word that can be
    formed from the jumble and is on the vocabulary list,
    and if so respond with a flag indicating the new entry
    If we have enough matches to win, we skip to
    sending a flag to redirect to the success page
    """

    app.logger.debug("Received Entry")

    # Receive input to test via AJAX Request
    text = flask.request.args.get("text", type=str)
    jumble = flask.session["jumble"]
    matches = flask.session.get("matches", [])  # Default to empty list
    is_new_match = False  # Assume it's not new

    in_jumble = LetterBag(jumble).contains(text)
    matched = WORDS.has(text)

    # Respond appropriately
    if matched and in_jumble and not (text in matches):
        # Cool, they found a new word
        matches.append(text)
        flask.session["matches"] = matches
        is_new_match = True

    # Other Cases
    # elif text in matches:
    #   already found this word
    # elif not matched:
    #   word not in our list
    # elif not in_jumble:
    #     has letters not in the letterbag
    # else:
    #     app.logger.debug("This case shouldn't happen!")
    #     assert False  # Raises AssertionError

    # Flag for redirect if complete, return matched text otherwise
    if len(matches) >= flask.session["target_count"]:
        return flask.jsonify(success=True)
    else:
        return flask.jsonify(match=text,
                             is_new_match=is_new_match,
                             success=False)
Exemplo n.º 32
0
def test_simple_merge():
    bag_abbc = LetterBag("abbc")
    bag_abccd = LetterBag("abccd")
    bag_abbc.merge(bag_abccd)
    assert bag_abbc.as_string() == "abbccd"