Esempio n. 1
0
def main():
    parser = ArgumentParser(description="Solve a given boggle board")
    parser.add_argument("--board", dest="board", help="a list of 16 characters making up \
            the board - if not provided, this is generated randomly")
    args = parser.parse_args()

    if (args.board):
        board = Boggle(args.board)
    else:
        board = random_board()

    trie = build_english_language_trie()
    solutions = board.solve(trie)
    num_words = len(solutions)
    points = count_points(solutions)
    sorted_words = sorted(solutions.keys())

    # render report to HTML
    env = Environment(loader=PackageLoader('boggle', 'templates'))
    template = env.get_template('report.html')

    # setup solutions for render:
    formatted_solutions = {}
    for word in solutions:
        formatted_pos = ['%d-%d' % pos for pos in solutions[word]]
        formatted_solutions[word] = formatted_pos

    output = template.render(grid=board.grid, solutions=formatted_solutions, num_words=num_words, points=points, sorted_words=sorted_words, size=Boggle.size)
    print output
Esempio n. 2
0
def index(board=None):
    board = Board().create()
    session['board'] = board
    boggle = Boggle(board, dictionary)
    session['comp_words'] = boggle.find_words()
    session['user_words'] = []
    return render_template('index.html', board=session['board'])
Esempio n. 3
0
 def test_check_points(self):
     with app.test_client() as client:
         with client.session_transaction() as change_session:
             change_session['answered'] = ['word']
             change_session['point_total'] = 0
         resp = client.get("/")
         self.assertEqual(resp.status_code, 200)
         self.assertEqual(Boggle.check_points(Boggle(),'word', 'ok'), 4)
Esempio n. 4
0
def test_boggle_2():
    board = [['f', 'y', 'c', 'l'], ['i', 'o', 'm', 'g'], ['o', 'r', 'i', 'l'],
             ['h', 'j', 'h', 'u']]
    dictionary = [
        'coif', 'coil', 'coir', 'corm', 'firm', 'giro', 'glim', 'hoof', 'iglu',
        'limo', 'limy', 'miri', 'moil', 'moor', 'rimy', 'roil', 'hello',
        'goodbye'
    ]
    boggle = Boggle(board, dictionary)
    assert len(boggle.find_words()) == 16
Esempio n. 5
0
 def test_check_repeat_guess(self):
     with app.test_client() as client:
         with client.session_transaction() as session:
             session['answered'] = ['word','banana','ice', 'of', 'baby']
         resp = client.get("/")
         self.assertEqual(resp.status_code, 200)
         self.assertIn('word',session['answered'])
         assert Boggle.check_repeat_guess(Boggle, "word", session['answered']) == True
         self.assertTrue(Boggle.check_repeat_guess(Boggle,'ice', session['answered'])) 
         self.assertFalse(Boggle.check_repeat_guess(Boggle, 'nottheword',session['answered']))
Esempio n. 6
0
def test_false_word():
    board = [['x', 'q', 'a', 'e'], ['z', 'o', 't', 's'], ['i', 'n', 'd', 'l'],
             ['y', 'r', 'u', 'k']]

    def word_lower(word):
        return word.lower()

    dictionary = map(word_lower, ['SETS'])
    boggle = Boggle(board, dictionary)
    assert len(boggle.find_words()) == 0
Esempio n. 7
0
 def test_check(self):
     with app.test_client() as client:
         boggle_game_test  = Boggle()
         with client.session_transaction() as session:
             session['answered'] = ['word']
             session['game_board'] = boggle_game_test.make_board()
         resp = client.get('/check?Guess=word')
         jason = resp.get_data(as_text=True)
         self.assertEqual(resp.status_code, 200)
         self.assertIn('msg', jason)
Esempio n. 8
0
 def test_check_guess(self):
     with app.test_client() as client:
         with client.session_transaction() as session:
             session['answered'] = ['word']
             session['game_board'] = Boggle().make_board()
             theboard  = session['game_board']
         resp = client.get("/")
         self.assertEqual(resp.status_code, 200)
         # self.assertEqual(Boggle.check_guess(Boggle(),'of'), 'not-on-board') cant know in any instance what the board actually is
         self.assertEqual(Boggle.check_guess(Boggle(), 'asfgh', theboard), 'not-word')
Esempio n. 9
0
    def test_check_word(self):

        boggle_game = Boggle()

        with app.test_client() as client:
            with client.session_transaction() as change_session:
                change_session['board'] = boggle_game.make_board()
                change_session['score'] = 7
            res = client.get('/check-word?word=mario')

            self.assertEqual(res.status_code, 200)
Esempio n. 10
0
def check_valid():
    """Check if a word is valid on the board"""
    word = request.args['word']
    board = session['board']
    size = session.get('size')

    if not size:
        result = Boggle().check_valid_word(board, word)
    else:
        result = Boggle(size).check_valid_word(board, word)
    return jsonify({'result': result})
    def test_boggle_get_route(self):
        with app.test_client() as client:
            with client.session_transaction() as session:
                boggle_game = Boggle()
                session['board'] = boggle_game.make_board()

            resp = client.get('/boggle')
            html = resp.get_data(as_text=True)

            self.assertEqual(resp.status_code, 200)
            self.assertIn('<td>', html)
            self.assertIn(
                '<form id="guess-form" action="/boggle" method="POST">', html)
Esempio n. 12
0
def test_boggle():
    board = [['x', 'q', 'a', 'e'], ['z', 'o', 't', 's'], ['i', 'n', 'd', 'l'],
             ['y', 'r', 'u', 'k']]

    def word_lower(word):
        return word.lower()

    dictionary = map(word_lower, [
        'XQAESLKURYIZ', 'DNOT', 'NIZOTS', 'KUDL', 'STONI', 'SEAT', 'ONIYR',
        'ZONIY', 'MY', 'SEAN', 'SETS', 'TOO', 'DOT'
    ])
    boggle = Boggle(board, dictionary)
    assert len(boggle.find_words()) == 8
Esempio n. 13
0
    def test_find_word_simple(self):
        size = 4
        b = Boggle(size)
        board = b.create_empty_board(size)
        for row in range(size):
            for col in range(size):
                board[row][col] = 'A'.encode()

        result = b.find_word('AAA')
        print("Result is: {}".format(result))

        result = b.find_word('XYZ')
        print("Result is: {}".format(result))
Esempio n. 14
0
    def test_find_word(self):
        """Testing the findword page"""
        with app.test_client() as client:
            boggle_game = Boggle()
            board = boggle_game.make_board()
            with client.session_transaction() as change_session:
                change_session['board'] = board

            res = client.get("/find?word=word")
            html = res.get_data(as_text=True)

            self.assertEqual(res.status_code , 200)
            self.assertEqual(res.content_type , "application/json")
            self.assertIn(boggle_game.check_valid_word(board , "word") , html)
Esempio n. 15
0
def boggle_play():
    global boggle_game
    """Makes and inits the board to begin game play"""
    time = int(request.args['length'])
    width = int(request.args['width'])
    height = int(request.args['height'])
    boggle_game = Boggle(width, height)
    boggle_board = boggle_game.make_board()
    
    session['board'] = boggle_board
    games = session.get('game_nums', 0)
    high_score = session.get('game_nums', 0)
    print(session)
    return render_template('play.html', boggle_board=boggle_board, games=games, high_score=high_score, time=time)
Esempio n. 16
0
    def test_end_game(self):
        """Testing the endgame page"""
        with app.test_client() as client:
            boggle_game = Boggle()
            board = boggle_game.make_board()
            with client.session_transaction() as change_session:
                change_session['board'] = board

            res = client.post("/end" ,  data=json.dumps({"score" : 10}), content_type='application/json')
            html = res.get_data(as_text=True)

            self.assertEqual(res.status_code , 200)
            self.assertEqual(res.content_type , "application/json")
            scores = session["scores"]
            self.assertEqual(scores[0]["score"] , 10)
            self.assertIn("10" , html)
Esempio n. 17
0
def homepage():
    """Homepage Route: sets up the board and saves it in session"""

    session['board'] = Boggle.make_board(boggle_game)
    board = session.get('board')

    return render_template('homepage.html', board=board)
Esempio n. 18
0
 def setUp(self):
     self.boggle_game = Boggle()
     self.board = [['L','A','T','E', 'R'],
                   ['F','Z','N','O','K'],
                   ['L','R','T','E', 'P'],
                   ['L','A','T','E','R'],
                   ['L','A','T','E','V']]
Esempio n. 19
0
    def test_check_not_word(self):
        """Tests that response for none word value equal to 'not-word'"""
        with app.test_client() as client:
            client.get('/')
            res = Boggle.check_valid_word(self.game, session['board'], 'nklfvdsahjkpvdas')

            self.assertEqual(res, 'not-word')
Esempio n. 20
0
 def test_check_valid_word(self):
     """Test invalid word on the board"""
     with app.test_client() as client:
         resp = client.get("/4")
         word = "ant"
         board = session["board"]
         self.assertEqual(resp.status_code, 200)
         self.assertEqual(Boggle().check_valid_word(board, word, 4), "not-on-board")
Esempio n. 21
0
def reset_game():
    """Clear Session | Reset Game"""

    global boggle_game
    session.clear()
    boggle_game = Boggle()

    return redirect("/")
Esempio n. 22
0
    def test_handle_stats(self):
        with app.test_client() as client:
            with client.session_transaction() as change_session:
                change_session['game_board'] = Boggle().make_board()
            resp = client.post('/statistics', json={'score': 5})
            data = resp.get_data(as_text=True)

            self.assertEqual(resp.status_code, 200)
            self.assertTrue(data == 'Thanks for the statistics')
Esempio n. 23
0
def display_board():
    """Show board"""
    size = session.get('size')
    print(f'size is {size}')
    # check the value of the size
    if size:
        boggle_game = Boggle(size)
    else:
        boggle_game = Boggle(5)
    print(f'boggle game current size is {boggle_game.size}')

    board = boggle_game.make_board()

    # add board into session
    session['board'] = board

    size = session.get('size')
    if not size:
        size = 5

    return render_template('home.html', board=board, size=size)
Esempio n. 24
0
def check_word():
    """POST request Route for AJAX axios call for board and word"""

    board = session.get('board')
    res = request.get_json()
    print(res)
    word = res['word']
    print(word)
    board = session.get('board')
    msg = Boggle.check_valid_word(boggle_game, board, word)

    return jsonify({"result": msg})
Esempio n. 25
0
    def test_find_word_complex(self):
        size = 6
        b = Boggle(size)
        board = b.create_empty_board(size)
        for row in range(size):
            for col in range(size):
                board[row][col] = 'X'.encode()
        board[0][0] = 'X'.encode()
        board[0][1] = 'B'.encode()
        board[0][2] = 'E'.encode()
        board[0][3] = 'D'.encode()

        board[1][0] = 'E'.encode()
        board[1][1] = 'O'.encode()
        board[1][2] = 'R'.encode()
        board[1][3] = 'C'.encode()

        board[2][0] = 'M'.encode()
        board[2][1] = 'W'.encode()
        board[2][2] = 'R'.encode()
        board[2][3] = 'E'.encode()

        board[3][0] = 'S'.encode()
        board[3][1] = 'C'.encode()
        board[3][2] = 'A'.encode()
        board[3][3] = 'Q'.encode()

        b.print_board()
        result = b.find_word('SCARECROW')
        print("Result is: {}".format(result))
Esempio n. 26
0
    def test_find_word_slightly_complex(self):
        size = 4
        b = Boggle(size)
        board = b.create_empty_board(size)
        for row in range(size):
            for col in range(size):
                board[row][col] = 'A'.encode()
        board[1][0] = 'B'.encode()
        board[1][1] = 'M'.encode()
        board[1][2] = 'C'.encode()
        board[1][3] = 'K'.encode()

        b.print_board()
        result = b.find_word('BMCK')
        print("Result is: {}".format(result))

        result = b.find_word('KCMB')
        print("Result is: {}".format(result))

        result = b.find_word('KBCM')
        print("Result is: {}".format(result))
Esempio n. 27
0
    def test_handle_guess(self):
        # May fail sometimes due to the letters on the board being random
        with app.test_client() as client:
            with client.session_transaction() as change_session:
                change_session['game_board'] = Boggle().make_board()
            resp = client.post('/submit-guess', json = {'guess': 'butter'})
            data = resp.get_json()
            self.assertEqual(data['result'], 'not-on-board')
            self.assertEqual(resp.status_code, 200)

            resp = client.post('/submit-guess', json = {'guess': 'a3424njndsjf323'})
            data = resp.get_json()
            self.assertEqual(data['result'], 'not-a-word')
            self.assertEqual(resp.status_code, 200)


            resp = client.post('/submit-guess', json = {'guess': 'b'})
            data = resp.get_json()
            self.assertEqual(data['result'], 'ok')
            self.assertEqual(resp.status_code, 200)
Esempio n. 28
0
def main():
    welcome = """
    #############################################
    ### WELCOME TO THE SUPER BYTE BOGGLE GAME ###
    #############################################
    
    """
    print(welcome)
    try:
        npt_dice_type = int(input("Would you like to play with the classic or new dice's type? (type '1' for Classic or '2' for New): "))
        if npt_dice_type not in [1, 2]:
            raise Exception()
    except:
        print("Invalid dice type.")
        return
    
    boggle = Boggle()
    boggle.start(npt_dice_type)
    print(boggle)
    
    boggle.user_words = get_user_answers(60*3)
    
    print('Wait, as soon the intern come back with my coffe he might start checking your answers...')
    boggle.get_all_words() #save all possible words based on dictionary on boggle.word_list
    points = 0
    valid_on_board = []
    for word in boggle.user_words:
        if boggle.has_word(word):
            valid_on_board.append(word)
    valid_on_dict = set(valid_on_board).intersection(boggle.word_list)
    for word in valid_on_dict:
        point = boggle.calculate_points(word)
        points += point
        print("{} = {} points".format(word, point))
    
    print("You total score is {} points!".format(points))
    print("Those were all possible words: ")
    print(boggle.word_list)
    print("Better lucky next time :)")
Esempio n. 29
0
class TestBoggle(unittest.TestCase):
    def setUp(self):
        self.board = Boggle('./4x4_board.txt')

    def tearDown(self):
        self.board = None

    def test_board_size(self):
        self.assertEqual(len(self.board.letters), 16)

    def test_word_in_board(self):
        self.assertTrue(self.board.find_word('alien'))
        self.assertTrue(self.board.find_word('tane'))
        self.assertTrue(self.board.find_word('genitals'))

    def test_word_not_in_board(self):
        self.assertFalse(self.board.find_word('zambapollos'))
        self.assertFalse(self.board.find_word('caradura'))
        self.assertFalse(self.board.find_word('fuoiuas'))
Esempio n. 30
0
class TestBoggle(unittest.TestCase):
    
    def setUp(self):
        self.board = Boggle('./4x4_board.txt')

    def tearDown(self):
        self.board = None

    def test_board_size(self):
        self.assertEqual(len(self.board.letters), 16)

    def test_word_in_board(self):
        self.assertTrue(self.board.find_word('alien'))
        self.assertTrue(self.board.find_word('tane'))
        self.assertTrue(self.board.find_word('genitals'))

    def test_word_not_in_board(self):
        self.assertFalse(self.board.find_word('zambapollos'))
        self.assertFalse(self.board.find_word('caradura'))
        self.assertFalse(self.board.find_word('fuoiuas'))
Esempio n. 31
0
from flask import Flask, request, session, render_template, jsonify
from flask_debugtoolbar import DebugToolbarExtension

from boggle import Boggle

app = Flask(__name__)
app.config['SECRET_KEY'] = "oh-so-secret"

debug = DebugToolbarExtension(app)

boggle_game = Boggle()


@app.route('/')
def load_game():
    board = boggle_game.make_board()
    session['game'] = board

    return render_template('index.html', board=board)


# route to check guess
@app.route('/check-word')
def check_word_guess():
    word = request.args.get('word')

    result = boggle_game.check_valid_word(session['game'], word)
    return jsonify(result=result)


# route to update stats: highscore and total number of games played
Esempio n. 32
0
"""Main entry point of boggle-bot."""
import getpass
import os
import sys
import time

from boggle import Boggle
from wordplays import Wordplays

MAX_CONSECUTIVE_ERRORS = 3

module_dir = os.path.dirname(__file__)
Boggle.load_dictionary(module_dir + '/dict.list')

username = input('Enter username: '******'Enter password: '******'Login unsuccessful.', file=sys.stderr)
            print('Exiting.', file=sys.stderr)
            sys.exit(1)
    except RuntimeError as e:
        print('Error:', e, file=sys.stderr)
        print('Exiting.', file=sys.stderr)
        sys.exit(1)

    print('Login successful.\n')

    # Continuously solve puzzles until too many consecutive errors are
Esempio n. 33
0
from boggle import Boggle
from flask import Flask, request, render_template, jsonify
from flask_debugtoolbar import DebugToolbarExtension
from flask import session

boggle_game = Boggle()

app = Flask(__name__)
app.config["SECRET_KEY"] = "oh-so-secret"
# app.config("DEBUG_TB_INTERCEPT_REDIRECTS") = False
debug = DebugToolbarExtension

board = boggle_game.make_board()


@app.route("/")
def show_landing_page():
    session['board'] = board
    highscore = session.get("highscore", 0)
    nplayed = session.get("nplayed", 0)
    return render_template("index.html", board=board, boggle=boggle_game, highscore=highscore, nplayed=nplayed)


@app.route("/guess", methods=["POST"])
def say_hi():
    guessed_word = request.json["guess"]     #allows access to the data posted from axios, guess is key, guessed_word is value
    guessed_response = boggle_game.check_valid_word(board, guessed_word) #method of boggle class returns the validity of the guessed word
    return jsonify(guessed_response) #by returning guessed response, it shows up as value of 'data' key in the var we stored our axios post

@app.route("/final-score", methods=["POST"])
def save_current_score():
Esempio n. 34
0
 def setUp(self):
     self.board = Boggle('./4x4_board.txt')
Esempio n. 35
0
board.clear()
assert len(board.board) == 0, "Board should be empty after calling clean()."

board.start()
assert type(board.get_item(1,2)) == Dice, "Should return the the 3rd item from the second row, an Dice object"

assert len(board.get_surrounds(3,3)) == 3, "Should return a list with 3 Dices, the surrounds of the dice on 4th row and 4th column."
assert len(board.get_surrounds(1,1)) == 8, "Should return a list with 8 Dices, the surrounds of the dice on 2nd row and 2nd column."
assert len(board.get_surrounds(0,2)) == 5, "Should return a list with 5 Dices, the surrounds of the dice on 1st row and 3rd column."


### Boggle tests ###
from boggle import Boggle

boggle = Boggle()
boggle.start()
assert type(boggle) == Boggle, "Should be an instance of boggle"

word = ''
word += str(boggle.get_item(0,0))
word += str(boggle.get_item(0,1))
word += str(boggle.get_item(0,2))
print(boggle)
print(word)
assert boggle.has_word(word) == True, "Should be True as the 'word' is the first 3 letters from 1st row"

word = ''
word += str(boggle.get_item(1,1))
word += str(boggle.get_item(2,2))
word += str(boggle.get_item(3,3))
Esempio n. 36
0
 def setUp(self):
     self.board = Boggle('./4x4_board.txt')