Exemplo n.º 1
0
def save_comp():
    if g.user:

        datas = request.json
        data = datas[0]
        name = datas[1]
        print(len(data))
        print(data[0][0], data[0][1])
        i = 0
        pieces = []
        while i < len(data):
            piece = Piece(champion_id=data[i][1], position=data[i][0])
            pieces.append(piece)
            db.session.add(piece)
            db.session.commit()
            i = i + 1

        comp = Composition(name=name,
                           creator_id=g.user.id,
                           piece1_id=pieces[0].id,
                           piece2_id=pieces[2].id,
                           piece3_id=pieces[2].id,
                           piece4_id=pieces[3].id,
                           piece5_id=pieces[4].id,
                           piece6_id=pieces[5].id,
                           piece7_id=pieces[6].id,
                           piece8_id=pieces[7].id)

        db.session.add(comp)
        db.session.commit()
        return 'added comp'
Exemplo n.º 2
0
 def get_pieces(self):
     pieces = memcache.get("pieces")
     if pieces is not None:
         return pieces
     else:
         pieces = Piece.gql("ORDER BY address ASC")
         if not memcache.add("pieces", pieces, 10):
             logging.error("Memcache set failed.")
         return pieces
Exemplo n.º 3
0
    def create_pieces(self):
        piece_hashes = self.torrent_tracker['info']['pieces']
        piece_length = self.torrent_tracker['info']['piece length']

        if 'files' in self.torrent_tracker['info']:
            files = self.torrent_tracker['info']['files']
            total_length = sum([file['length'] for file in files])
            self.number_pieces = int(math.ceil(float(total_length) / piece_length))
        else:
            total_length = self.torrent_tracker['info']['length']
            self.number_pieces = int(math.ceil(float(total_length) / piece_length))

        counter = total_length
        self.total_length = total_length
        for index in range(self.number_pieces):
            if index == self.number_pieces - 1:
                self.pieces.append(Piece(index, counter, piece_hashes[0:20]))
            else:
                self.pieces.append(Piece(index, piece_length, piece_hashes[0:20]))
                counter -= piece_length
                piece_hashes = piece_hashes[20:]
        
        self.current_piece = self.pieces.popleft()
Exemplo n.º 4
0
    def selectPiece(self, match):
        available_pieces = match.board.unusedPieces()
        if len(available_pieces) < 1:
            # trick for tournament, when board is full
            return Piece({
                "color": "blue",
                "height": "small",
                "shape": "round",
                "state": "solid"
            })

        i = random.randint(0, len(available_pieces) - 1)

        ui.showPlayer(match.active_player)
        ui.showSelectedPiece(available_pieces[i])

        return available_pieces[i]
Exemplo n.º 5
0
    def selectPiece(self, match):
        available_pieces = match.board.unusedPieces()
        if len(available_pieces) < 1:
            # trick for tournament, when board is full
            return Piece({
                "color": "blue", "height": "small",
                "shape": "round", "state": "solid"
            })

        available_pos = match.board.unusedPositions()
        fallback_i = random.randint(0, len(available_pieces) - 1)
        chosen_piece = available_pieces[fallback_i]
        alpha, beta = 0, Minimax.EVAL_WIN

        if len(available_pieces) >= Minimax.MINIMAX_1_UNTIL and \
                self.max_depth > 1:
            return Minimax(1).selectPiece(match)
        if len(available_pieces) >= Minimax.MINIMAX_2_UNTIL and \
                self.max_depth > 2:
            return Minimax(2).selectPiece(match)
        if len(available_pieces) >= Minimax.MINIMAX_3_UNTIL and \
                self.max_depth > 3:
            return Minimax(3).selectPiece(match)

        for piece in available_pieces:
            alpha = 0

            for pos in available_pos:
                eval = self.min_evaluation(
                    match.board, piece, pos,
                    alpha, beta, 1
                )

                alpha = max(alpha, eval)

            if alpha < beta:
                beta = alpha
                chosen_piece = piece

        ui.showPlayer(match.active_player)
        ui.showSelectedPiece(chosen_piece)

        return chosen_piece
Exemplo n.º 6
0
def play(ip_address, web_browser, coor_x, coor_y, app_logger):
    """Update the information of the game of the player.
    :param ip_address: IP Adress of actual player
    :param web_browser: User-Agent Header of player request
    :param coor_x: X Coordinate of piece
    :param coor_y: Y Coordinate of piece
    :param app_logger: Flask app logger
    """
    player = find_player_by_ip(ip_address, web_browser)
    if player:
        client = MongoClient(CONNECTION_STRING)
        database = client.othello
        games = database.games
        game = games.find_one({'_id': player['game_id']})
        if game:
            game_id = game['_id']
            game['matrix'] = pickle.loads(game['matrix'])
            game = Game(game['white'], game['black'], game['matrix'],
                        game['turn'])

            result = game.play(Piece(coor_x, coor_y, player['_id']))

            copy_save = dict(game)
            copy_save['matrix'] = Binary(
                pickle.dumps(copy_save['matrix'], protocol=2))
            copy_save['possible_moves'] = numpy.array(
                copy_save['possible_moves']).tolist()
            games.update_one({'_id': game_id}, {'$set': copy_save})
            game.matrix = game.matrix.tolist()
            result['matrix'] = game.matrix
            client.close()
            return result
        client.close()
        app_logger.error(
            "/play: Game not found. game_id: {0} player_id: {1}".format(
                player['game_id'], player['_id']))
        return {'success': False, 'code': 500}
    app_logger.error(
        "/play: Player not found. ip_address: {0} \nweb_browser: {1}".format(
            ip_address, web_browser))
    return {'success': False, 'code': 500}
Exemplo n.º 7
0
def upload(request):
    res = Result()
    if request.FILES.has_key('file'):
        try:
            f = request.FILES['file']
            filename = f.name

            path = request.POST.get('path', None)
            if path:
                foreignPath = path.replace("'", "\"")
            else:
                foreignPath = filename

            galleries = request.POST.get('galleries', '1').split(',')
            tags = filter(None, request.POST.get('tags', '').split(','))

            username = request.POST.get('user', False)
            if username:
                user = User.objects.get(username=username)
            else:
                if request.user.is_anonymous():
                    username = '******'
                    user = User.objects.get(username=username)
                else:
                    user = request.user
            
            uniqueName = request.POST.get('uid', Piece.getUniqueID(foreignPath, user))
            
            if f.content_type.startswith('image'):
                if Path(filename).ext.lower() not in EXT['image']:
                    raise MediaTypeError
                model = Image
            else:
                if Path(filename).ext not in EXT['video']:
                    raise MediaTypeError
                model = Video

            obj, created = model.objects.get_or_create(unique_id=uniqueName, defaults={'author': user})
            guid = obj.getGuid()
            hashVal = getHashForFile(f)

            if hashVal == obj.hash:
                for gal in galleries:
                    g = Gallery.objects.get(pk=int(gal))
                    obj.gallery_set.add(g)
                res.isSuccess = True
                res.message = "Files were the same"

                return JsonResponse(res)

            objPath = ROOT
            if FROG_PATH:
                objPath = objPath / FROG_PATH
            objPath = objPath / guid.guid[-2:] / guid.guid / filename
            print objPath
            hashPath = objPath.parent / hashVal + objPath.ext
            
            if not objPath.parent.exists():
                objPath.parent.makedirs()

            handle_uploaded_file(hashPath, f)

            obj.hash = hashVal
            obj.foreign_path = foreignPath
            obj.title = objPath.namebase
            obj.export(hashVal, hashPath, tags=tags, galleries=galleries)

            res.append(obj.json())

            for key,f in request.FILES.iteritems():
                if key != 'file':
                    dest = objPath.parent / f.name
                    handle_uploaded_file(dest, f)

            res.isSuccess = True
        except MediaTypeError:
            res.isError = True
            res.message = 'Filetype not supported'
            
            return JsonResponse(res)

    else:
        res.isError = True
        res.message = "No file found"

    return JsonResponse(res)
Exemplo n.º 8
0
def upload(request):
    res = Result()
    if request.FILES.has_key('file'):
        try:
            f = request.FILES['file']
            filename = f.name

            path = request.POST.get('path', None)
            if path:
                foreignPath = path.replace("'", "\"")
            else:
                foreignPath = filename

            galleries = request.POST.get('galleries', '1').split(',')
            tags = filter(None, request.POST.get('tags', '').split(','))

            username = request.POST.get('user', False)
            if username:
                user = User.objects.get(username=username)
            else:
                if request.user.is_anonymous():
                    username = '******'
                    user = User.objects.get(username=username)
                else:
                    user = request.user

            uniqueName = request.POST.get('uid',
                                          Piece.getUniqueID(foreignPath, user))

            if f.content_type.startswith('image'):
                if Path(filename).ext.lower() not in EXT['image']:
                    raise MediaTypeError
                model = Image
            else:
                if Path(filename).ext not in EXT['video']:
                    raise MediaTypeError
                model = Video

            obj, created = model.objects.get_or_create(
                unique_id=uniqueName, defaults={'author': user})
            guid = obj.getGuid()
            hashVal = getHashForFile(f)

            if hashVal == obj.hash:
                for gal in galleries:
                    g = Gallery.objects.get(pk=int(gal))
                    obj.gallery_set.add(g)
                res.isSuccess = True
                res.message = "Files were the same"

                return JsonResponse(res)

            objPath = ROOT
            if FROG_PATH:
                objPath = objPath / FROG_PATH
            objPath = objPath / guid.guid[-2:] / guid.guid / filename
            print objPath
            hashPath = objPath.parent / hashVal + objPath.ext

            if not objPath.parent.exists():
                objPath.parent.makedirs()

            handle_uploaded_file(hashPath, f)

            obj.hash = hashVal
            obj.foreign_path = foreignPath
            obj.title = objPath.namebase
            obj.export(hashVal, hashPath, tags=tags, galleries=galleries)

            res.append(obj.json())

            for key, f in request.FILES.iteritems():
                if key != 'file':
                    dest = objPath.parent / f.name
                    handle_uploaded_file(dest, f)

            res.isSuccess = True
        except MediaTypeError:
            res.isError = True
            res.message = 'Filetype not supported'

            return JsonResponse(res)

    else:
        res.isError = True
        res.message = "No file found"

    return JsonResponse(res)