Ejemplo n.º 1
0
def load_puzzles():
    """Loads in the JSON files listed in the global PUZZLE_PATHS variable to Puzzle models
    :return: A list of Puzzle objects
    """
    puzzles = []
    for path in PUZZLE_PATHS:
        with open(path, 'r') as f:
            puzzle_dict = json.load(f)
            new_puzzle = Puzzle()
            new_puzzle.input_anagrams = puzzle_dict['input_anagrams']
            new_puzzle.sentence_indices = puzzle_dict['sentence_indices']
            new_puzzle.sentence_word_lengths = puzzle_dict[
                'sentence_word_lengths']
            puzzles.append(new_puzzle)
    return puzzles
Ejemplo n.º 2
0
 def get(self):
     puzzles = Puzzle.gql("ORDER BY name ASC")
     pieces = self.get_pieces()
     locations = Location.gql("ORDER BY x ASC")
     svg_path = os.path.join(os.path.dirname(__file__), 'templates/puzzle.svg')
     svg_values = {
         "pieces": pieces,
         "locations": locations,
         "width": 641,
         "height": 481
     }
     svg_text = template.render(svg_path, svg_values)
     try:
         first_puzzle = puzzles[0]
     except IndexError:
         first_puzzle = "None"
     template_values = {
         "title": "HTML5 Hacks: SVG",
         "puzzles": puzzles,
         "first_puzzle": first_puzzle,
         "host": os.environ["HTTP_HOST"],
         "config": config,
         "svg_text": svg_text,
         "is_dev": IS_DEV,
         "rows": ["A", "B", "C", "D", "E", "F", "G", "H"],
         "cols": ["1", "2", "3", "4", "5", "6", "7", "8"],
     }
     path = os.path.join(os.path.dirname(__file__), 'templates/svg.html')
     self.response.out.write(template.render(path, template_values))
Ejemplo n.º 3
0
def set_answer(puzzle_name, player_id, question, content_type, content):
    player = Player.get(Player.id == player_id)
    puzzle, _ = Puzzle.get_or_create(name=puzzle_name)
    try:
        answer = Answer.get(
            (Answer.puzzle == puzzle) & (Answer.player == player))
    except Answer.DoesNotExist:
        answer = Answer(puzzle=puzzle, player=player)

    answer.question = question

    if content_type == 'text':
        answer.value = content
    elif content_type == 'image':
        filename = '%s_%s.jpg' %  (puzzle.id, player.id)
        path = '%s/images/%s' % (STATIC_DIR, filename)
        with open(path, 'wb') as fp:
            fp.write(content)
        answer.value = 'image:' + filename
    elif content_type == 'video':
        filename = '%s_%s.mp4' %  (puzzle.id, player.id)
        path = '%s/videos/%s' % (STATIC_DIR, filename)
        with open(path, 'wb') as fp:
            fp.write(content)
        answer.value = 'video:' + filename

    answer.save()
Ejemplo n.º 4
0
def set_answer(puzzle_name, player_id, question, content_type, content):
    player = Player.get(Player.id == player_id)
    puzzle, _ = Puzzle.get_or_create(name=puzzle_name)
    try:
        answer = Answer.get((Answer.puzzle == puzzle)
                            & (Answer.player == player))
    except Answer.DoesNotExist:
        answer = Answer(puzzle=puzzle, player=player)

    answer.question = question

    if content_type == 'text':
        answer.value = content
    elif content_type == 'image':
        filename = '%s_%s.jpg' % (puzzle.id, player.id)
        path = '%s/images/%s' % (STATIC_DIR, filename)
        with open(path, 'wb') as fp:
            fp.write(content)
        answer.value = 'image:' + filename
    elif content_type == 'video':
        filename = '%s_%s.mp4' % (puzzle.id, player.id)
        path = '%s/videos/%s' % (STATIC_DIR, filename)
        with open(path, 'wb') as fp:
            fp.write(content)
        answer.value = 'video:' + filename

    answer.save()
Ejemplo n.º 5
0
 def post(self):
     url = self.request.get("img_url")
     if url:
         inputimage = urlfetch.fetch(url)
         if inputimage.status_code == 200:
             image = Image()
             image.source_url = url
             image.full_size = inputimage.content
             image.title = "Test image"
             # TODO move to task queue
             image.thumb_nail = images.resize(image.full_size, 64, 64)
             image.put()
             puzzle = Puzzle()
             puzzle.name = "Test puzzle"
             puzzle.image = image
             puzzle.put()
             self.redirect("/svg")
Ejemplo n.º 6
0
    def _new_puzzle(self, skin):
        if not skin:
            ErrorPopup("No skin is loaded.")
            return

        puzzle = Puzzle.new(self.module, self.view.module())
        editor = EditorVC(puzzle, skin, self.view)

        # The connection seems to prevent garbage collection also.
        editor.view.winclose.connect(self.view._updatePuzzleSelector)
Ejemplo n.º 7
0
 def get(self):
     puzzle = Puzzle.get(self.request.get("img_id"))
     thumb = self.request.get("thumb")
     if puzzle.image:
         self.response.headers['Content-Type'] = "image/png"
         if thumb and thumb == "1":
             self.response.out.write(puzzle.image.thumb_nail)
         else:
             self.response.out.write(puzzle.image.full_size)
     else:
         self.error(404)
Ejemplo n.º 8
0
async def crawl_all():
    fts = [asyncio.ensure_future(crawl()) for _ in range(0, 50)]

    for f in asyncio.as_completed(fts):
        try:
            puzzle = await f
            puzzle = Puzzle(**puzzle)
            session.add(puzzle)
            session.commit()
        except Exception as e:
            pass
Ejemplo n.º 9
0
def group(group_name):
    group_answers = []
    for puzzle in Puzzle.select().order_by(Puzzle.name):
        puzzle_answers = (
            puzzle.answers.select().join(Player).join(Group).where(
                Group.name == group_name))
        group_answers.append((puzzle.name, puzzle_answers))

    return render_template('group.html',
                           group=Group.get(Group.name == group_name),
                           group_answers=group_answers)
Ejemplo n.º 10
0
 def buildup_teardown_wrapper(*args, **kwargs):
     name = "unittest"
     module = PuzzleModule.new(
         modulename=name,
         board_shape=(12, 6),
         board_nhide=1,
         move_shape=(2, 1),
         color_limit=4,
         pop_limit=4,
         modulereadme="",
     )
     puzzle = Puzzle.new(module, "unittest")
     func(*args, module, puzzle, **kwargs)
     shutil.rmtree("./modules/" + name + "/")
Ejemplo n.º 11
0
def group(group_name):
    group_answers = []
    for puzzle in Puzzle.select().order_by(Puzzle.name):
        puzzle_answers = (
            puzzle.answers.select()
            .join(Player).join(Group)
            .where(Group.name == group_name)
        )
        group_answers.append((puzzle.name, puzzle_answers))

    return render_template(
        'group.html',
        group=Group.get(Group.name == group_name),
        group_answers=group_answers)
Ejemplo n.º 12
0
def build_puzzle(question, answer, difficulty):
    question = question.upper()
    answer = answer.upper()
    difficulty = int(difficulty)
    print('Cleaning up', file=sys.stderr)
    regex = re.compile('[^a-zA-Z]')
    answer_root = regex.sub('', answer).upper()
    answer_letter_count = len(answer_root)

    print('Preparing', file=sys.stderr)
    min_key_count = 1
    max_key_count = 3

    min_word_length = ceil(4 * (1 + difficulty * 5 / 10))
    max_word_length = min_word_length + ceil(2 * (1 + difficulty * 5 / 10))

    puzzle_words = {'Word': [], 'Keys': [], 'Length': []}
    keys_list = list(answer_root.upper())
    print('making wordlist', file=sys.stderr)
    while keys_list:
        print(len(keys_list), 'remaining:', keys_list)
        key_length = randint(min_key_count, min(len(keys_list), max_key_count))
        word_keys, keys_list = get_random_keys(keys_list, key_length)
        word_length = randint(min_word_length, max_word_length)
        print(word_keys, word_length, keys_list, file=sys.stderr)
        possible_word = get_word_suggestion(word_keys, word_length)
        print(possible_word, file=sys.stderr)
        if not possible_word or possible_word.name in puzzle_words['Word']:
            print('redoing', file=sys.stderr)
            keys_list = word_keys + keys_list
        else:
            puzzle_words['Word'].append(possible_word.name)
            puzzle_words['Keys'].append(word_keys)
            puzzle_words['Length'].append(possible_word.length)
    pw = ','.join(puzzle_words['Word'])
    kw = ';'.join([','.join(k) for k in puzzle_words['Keys']])
    new_puzzle = Puzzle(question=question, answer=answer, words=pw, letter_keys=kw)
    db.session.add(new_puzzle)
    db.session.commit()
    return 'Created Puzzle', new_puzzle.id
Ejemplo n.º 13
0
def create_puzzle():
    # Get fields from Form Data
    name_of_puzzle = request.form["name_of_puzzle"]
    picture_of_puzzle = request.files["picture_of_puzzle"]
    picture_of_box = request.files["picture_of_box"]
    number_of_pieces = request.form["number_of_pieces"]
    age_range = request.form["age_range"]
    category = request.form["category"]
    owner_id = request.form["owner_id"]

    if picture_of_box is not None:
        # upload box to cloudinary
        box_upload_result = cloudinary.uploader.upload(picture_of_box)
    else:
        return jsonify("Failed to upload picture of box"), 500

    if picture_of_puzzle is not None:
        # upload puzzle to cloudinary
        puzzle_upload_result = cloudinary.uploader.upload(picture_of_puzzle)
    else:
        return jsonify("Failed to upload picture of puzzle"), 500

    # add to db

    request_body_puzzle = request.get_json()

    newpuzzle = Puzzle(name_of_puzzle=name_of_puzzle,
                       picture_of_puzzle=puzzle_upload_result['secure_url'],
                       picture_of_box=box_upload_result['secure_url'],
                       number_of_pieces=number_of_pieces,
                       age_range=age_range,
                       category=category,
                       owner_id=owner_id,
                       is_available=True)
    db.session.add(newpuzzle)
    db.session.commit()

    return jsonify("successfully added puzzle"), 200