Exemplo n.º 1
0
 def add_background_to_image(self, ):
     assert self.image_bank is not None, "Images need to be loaded before calling this method (try load_images_json_file)"
     if "Background to" in self.image_bank:
         background_to_pixmap = QPixmap(self.image_bank["Background to"]["path"])
         self.background_to_image = QGraphicsPixmapItem(background_to_pixmap)
         self.scene.addItem(self.background_to_image)
         self.background_to_image.setZValue(2)
Exemplo n.º 2
0
    def make_move(self):
        if not self.game.is_my_turn:
            x = randint(0, 9)
            y = randint(0, 8)
            if self.game.my_board[x][y] not in range(2,4):
                if self.game.my_board[x][y] == 1:
                    self.game.my_board[x][y] = 2
                    picture = 'res/cancel.png'
                else:
                    self.game.my_board[x][y] = 3
                    picture = 'res/ok.png'

                if x % 2 != 0:
                    self.item = QGraphicsPixmapItem(QPixmap(picture))
                    self.item.setOffset(16+y*61, 17+(x*52))
                    self.game.scene.addItem(self.item)

                elif x % 2 == 0:
                    self.item = QGraphicsPixmapItem(QPixmap(picture))
                    self.item.setOffset(47+y*61, 16+x*53)
                    self.game.scene.addItem(self.item)

            print(self.game.enemies_board)
            print(self.game.my_board)
            self.game.is_my_turn = True
Exemplo n.º 3
0
    def get_shot(self, x, y):
        '''
        Shot handler.
        :param x: x coord of shot
        :param y: y coord of shot
        '''
        is_Hit = False

        if self.my_board[x][y] == 1:
            self.my_board[x][y] = 2
            is_hit = True
            picture = 'res/ok.png'
        else:
            self.my_board[x][y] = -1
            is_hit = False
            picture = 'res/cancel.png'

        if x % 2 != 0:
            self.item = QGraphicsPixmapItem(QPixmap(picture))
            self.item.setOffset(16+y*61, 17+(x*52))
            self.scene.addItem(self.item)

        elif x % 2 == 0:
            self.item = QGraphicsPixmapItem(QPixmap(picture))
            self.item.setOffset(47+y*61, 16+x*53)
            self.scene.addItem(self.item)
Exemplo n.º 4
0
class StartSelectView(QGraphicsView):

    def __init__(self, *args):
        QGraphicsView.__init__(self, *args)
        self.move(2, 250)
        self.btnSize = 28
        self.setMaximumHeight(self.btnSize * 2)
        self.setMaximumWidth(334)
        self.setMinimumHeight(self.btnSize * 2)
        self.setMinimumWidth(334)
        self.adjustSize()
        self.scene = QGraphicsScene(self)
        self.setStyleSheet('background-color:transparent; border-width: 0px; border: 0px;')
        self.psButtons = QPixmap(os.getcwd() + '/../icons/controller-sprite.png')
        self.select = self.psButtons.copy(696, 120, 45, 30)
        self.select = self.select.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.selectItem = QGraphicsPixmapItem(self.select)
        self.selectItem.setOffset(QPointF(0, 0))
        self.scene.addItem(self.selectItem)
        self.start = self.psButtons.copy(754, 120, 45, 30)
        self.start = self.start.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.startItem = QGraphicsPixmapItem(self.start)
        self.startItem.setOffset(QPointF(86, 0))
        self.scene.addItem(self.startItem)
        self.setScene(self.scene)
Exemplo n.º 5
0
 def __init__(self, *args):
       self.seleccionado = False
       self.velocity = random.randint(1,10)
       QGraphicsPixmapItem.__init__(self, *args)
       self.setPixmap(QPixmap("sprites/"+str(random.randint(1,45))+".png"))
       self.setTransformOriginPoint(self.boundingRect().width()/2.0,self.boundingRect().height()/2.0)
       self.setZValue(10)
       ##menu contextual
       self.menu = QMenu()
       self.Actions =[] #arreglo de acciones 
       self.Actions.append( self.menu.addAction("Seguir") )
       self.Actions.append( self.menu.addAction("Editar") )
       self.Actions.append( self.menu.addAction("girar clockwise") )
       self.Actions.append( self.menu.addAction("girar anti-clockwise") )
       self.Actions.append( self.menu.addAction("Colisiones") )
       self.Actions.append( self.menu.addAction("Duplicar") )
       self.Actions.append( self.menu.addAction("Eliminar") )
       self.menu.triggered[QAction].connect(self.test)
       ##offset para el arrastre
       self.offset= QPointF(0,0)
       ##poligono de vision
       poligono = QPolygonF()
       poligono.append(QPointF(-1,10))
       poligono.append(QPointF(-1,20))
       poligono.append(QPointF(-30,40))
       poligono.append(QPointF(-40,15))
       poligono.append(QPointF(-30,-10))
       self.vision = QGraphicsPolygonItem(poligono,self,self.scene())
       self.vision.setBrush(QColor(255, 255, 0,100))
       self.vision.setPen(QColor(255, 255, 0))
Exemplo n.º 6
0
 def __init__(self, *args):
     self.seleccionado = False
     self.velocity = random.randint(1, 10)
     QGraphicsPixmapItem.__init__(self, *args)
     self.setPixmap(
         QPixmap("sprites/" + str(random.randint(1, 45)) + ".png"))
     self.setTransformOriginPoint(self.boundingRect().width() / 2.0,
                                  self.boundingRect().height() / 2.0)
     self.setZValue(10)
     ##menu contextual
     self.menu = QMenu()
     self.Actions = []  #arreglo de acciones
     self.Actions.append(self.menu.addAction("Seguir"))
     self.Actions.append(self.menu.addAction("Editar"))
     self.Actions.append(self.menu.addAction("girar clockwise"))
     self.Actions.append(self.menu.addAction("girar anti-clockwise"))
     self.Actions.append(self.menu.addAction("Colisiones"))
     self.Actions.append(self.menu.addAction("Duplicar"))
     self.Actions.append(self.menu.addAction("Eliminar"))
     self.menu.triggered[QAction].connect(self.test)
     ##offset para el arrastre
     self.offset = QPointF(0, 0)
     ##poligono de vision
     poligono = QPolygonF()
     poligono.append(QPointF(-1, 10))
     poligono.append(QPointF(-1, 20))
     poligono.append(QPointF(-30, 40))
     poligono.append(QPointF(-40, 15))
     poligono.append(QPointF(-30, -10))
     self.vision = QGraphicsPolygonItem(poligono, self, self.scene())
     self.vision.setBrush(QColor(255, 255, 0, 100))
     self.vision.setPen(QColor(255, 255, 0))
Exemplo n.º 7
0
class FaceButtonsView(QGraphicsView):

    def __init__(self, *args):
        QGraphicsView.__init__(self, *args)
        self.move(170, 90)
        self.btnSize = 40
        self.padding = 5
        self.setMaximumHeight(self.btnSize * 4)
        self.setMaximumWidth(self.btnSize * 4)
        self.setMinimumHeight(self.btnSize * 4)
        self.setMinimumWidth(self.btnSize * 4)
        self.adjustSize()
        self.setStyleSheet('background-color:transparent; border-width: 0px; border: 0px;')
        self.scene = QGraphicsScene(self)
        self.psButtons = QPixmap(os.getcwd() + '/../icons/PS3_Buttons.png')
        self.triangle = self.psButtons.copy(0, 0, 220, 225)
        self.triangle = self.triangle.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.square = self.psButtons.copy(220, 0, 220, 225)
        self.square = self.square.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.circle = self.psButtons.copy(440, 0, 220, 225)
        self.circle = self.circle.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.cross = self.psButtons.copy(660, 0, 220, 225)
        self.cross = self.cross.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.triangleItem = QGraphicsPixmapItem(self.triangle)
        self.triangleItem.setOffset(QPointF(self.btnSize + self.padding, 0))
        self.scene.addItem(self.triangleItem)
        self.squareItem = QGraphicsPixmapItem(self.square)
        self.squareItem.setOffset(QPointF(0, self.btnSize + self.padding))
        self.scene.addItem(self.squareItem)
        self.circleItem = QGraphicsPixmapItem(self.circle)
        self.circleItem.setOffset(QPointF(self.btnSize * 2 + self.padding * 2, self.btnSize + self.padding))
        self.scene.addItem(self.circleItem)
        self.crossItem = QGraphicsPixmapItem(self.cross)
        self.crossItem.setOffset(QPointF(self.btnSize + self.padding, self.btnSize * 2 + self.padding * 2))
        self.scene.addItem(self.crossItem)
        self.effect = QGraphicsDropShadowEffect()
        self.effect.setOffset(0, 0)
        self.effect.setBlurRadius(20)
        self.effect.setColor(Qt.green)
        self.triangleItem.setGraphicsEffect(self.effect)
        self.setScene(self.scene)
        self.tl2 = QTimeLine(10000)
        self.tl2.setFrameRange(0, 10000)
        self.t = QGraphicsItemAnimation()
        self.t.setItem(self.triangleItem)
        self.t.setTimeLine(self.tl2)
        self.tl2.connect(self.tl2, SIGNAL('frameChanged(int)'), self.updateEffect)
        self.effectd = 3
        self.tl2.start()

    def updateEffect(self):
        if self.effect.blurRadius() > 50:
            self.effectd = -3
        elif self.effect.blurRadius() < 5:
            self.effectd = 3
        self.effect.setBlurRadius(self.effect.blurRadius() + self.effectd)
Exemplo n.º 8
0
 def __init__(self, classifier, granularity, scale, spacing, rect=None):
     orangeqt.PlotItem.__init__(self)
     self.classifier = classifier
     self.rect = rect
     self.granularity = granularity
     self.scale = scale
     self.spacing = spacing
     self.pixmap_item = QGraphicsPixmapItem(self)
     self.set_in_background(True)
     self.setZValue(ProbabilitiesZValue)
Exemplo n.º 9
0
class DpadView(QGraphicsView):

    def __init__(self, *args):
        QGraphicsView.__init__(self, *args)
        self.move(2, 90)
        self.btnSize = 75
        self.padding = -35
        self.setMaximumHeight(self.btnSize * 2 + 20)
        self.setMaximumWidth(self.btnSize * 2 + 20)
        self.setMinimumHeight(self.btnSize * 2 + 20)
        self.setMinimumWidth(self.btnSize * 2 + 20)
        self.adjustSize()
        self.setStyleSheet('background-color:transparent; border-width: 0px; border: 0px;')
        self.scene = QGraphicsScene(self)
        self.left = QPixmap(os.getcwd() + '/../icons/left.png')
        self.left = self.left.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.right = QPixmap(os.getcwd() + '/../icons/right.png')
        self.right = self.right.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.up = QPixmap(os.getcwd() + '/../icons/up.png')
        self.up = self.up.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.down = QPixmap(os.getcwd() + '/../icons/down.png')
        self.down = self.down.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.leftItem = QGraphicsPixmapItem(self.left)
        self.leftItem.setOffset(QPointF(0, self.btnSize + self.padding))
        self.scene.addItem(self.leftItem)
        self.rightItem = QGraphicsPixmapItem(self.right)
        self.rightItem.setOffset(QPointF(self.btnSize * 2 + self.padding * 2, self.btnSize + self.padding))
        self.scene.addItem(self.rightItem)
        self.upItem = QGraphicsPixmapItem(self.up)
        self.upItem.setOffset(QPointF(self.btnSize + self.padding, 0))
        self.scene.addItem(self.upItem)
        self.downItem = QGraphicsPixmapItem(self.down)
        self.downItem.setOffset(QPointF(self.btnSize + self.padding, self.btnSize * 2 + self.padding * 2))
        self.scene.addItem(self.downItem)
        self.effect = QGraphicsDropShadowEffect()
        self.effect.setOffset(0, 0)
        self.effect.setBlurRadius(20)
        self.effect.setColor(Qt.green)
        self.downItem.setGraphicsEffect(self.effect)
        self.setScene(self.scene)
        self.tl2 = QTimeLine(10000)
        self.tl2.setFrameRange(0, 10000)
        self.t = QGraphicsItemAnimation()
        self.t.setItem(self.downItem)
        self.t.setTimeLine(self.tl2)
        self.tl2.connect(self.tl2, SIGNAL('frameChanged(int)'), self.updateEffect)
        self.effectd = 3
        self.tl2.start()

    def updateEffect(self):
        if self.effect.blurRadius() > 50:
            self.effectd = -3
        elif self.effect.blurRadius() < 5:
            self.effectd = 3
        self.effect.setBlurRadius(self.effect.blurRadius() + self.effectd)
Exemplo n.º 10
0
 def __init__(self, data, encoding, x0, y0, x1, y1, xsize, ysize):
     p = QPixmap()
     p.loadFromData(data, encoding, Qt.AutoColor)
     w, h = p.width(), p.height()
     p = p.copy(x0, y0, min(w, x1-x0), min(h, y1-y0))
     if p.width() != xsize or p.height() != ysize:
         p = p.scaled(xsize, ysize, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
     QGraphicsPixmapItem.__init__(self, p)
     self.height, self.width = ysize, xsize
     self.setTransformationMode(Qt.SmoothTransformation)
     self.setShapeMode(QGraphicsPixmapItem.BoundingRectShape)
Exemplo n.º 11
0
 def __init__(self, data, encoding, x0, y0, x1, y1, xsize, ysize):
     p = QPixmap()
     p.loadFromData(data, encoding, Qt.AutoColor)
     w, h = p.width(), p.height()
     p = p.copy(x0, y0, min(w, x1 - x0), min(h, y1 - y0))
     if p.width() != xsize or p.height() != ysize:
         p = p.scaled(xsize, ysize, Qt.IgnoreAspectRatio,
                      Qt.SmoothTransformation)
     QGraphicsPixmapItem.__init__(self, p)
     self.height, self.width = ysize, xsize
     self.setTransformationMode(Qt.SmoothTransformation)
     self.setShapeMode(QGraphicsPixmapItem.BoundingRectShape)
Exemplo n.º 12
0
    def resizeEvent(self, event):
        view_size = self.view.size()
        new_background_height = (1.5 / 4.) * view_size.height()
        background_to_pixmap = QPixmap(self.image_bank["Background to"]["path"])
        background_to_pixmap = background_to_pixmap.scaled(new_background_height, new_background_height,
                                                           Qt.KeepAspectRatio)
        if not self.background_to_image:
            self.background_to_image = QGraphicsPixmapItem(background_to_pixmap)
        else:
            self.background_to_image.setPixmap(background_to_pixmap)
        sugested_x_position = int(2 * (view_size.width() / 3.))
        if sugested_x_position < 0:
            sugested_x_position = 0
        sugested_y_position = int(view_size.height() / 2. - background_to_pixmap.size().height() / 2)
        if sugested_y_position < 0:
            sugested_y_position = 0
        self.background_to_image.setPos(sugested_x_position, sugested_y_position)

        #####################
        new_background_height = (2.2 / 4.) * view_size.height()
        background_from_pixmap = QPixmap(self.image_bank["Background from"]["path"])
        background_from_pixmap = background_from_pixmap.scaled(new_background_height, new_background_height,
                                                               Qt.KeepAspectRatio)
        if not self.background_to_image:
            self.background_from_image = QGraphicsPixmapItem(background_from_pixmap)
        else:
            self.background_from_image.setPixmap(background_from_pixmap)

        sugested_x_position = int(view_size.width() / 5. - background_from_pixmap.size().height() / 2)
        if sugested_x_position < 0:
            sugested_x_position = 0
        sugested_y_position = int(view_size.height() / 2. - background_from_pixmap.size().height() / 2)
        if sugested_y_position < 0:
            sugested_y_position = 0
        self.background_from_image.setPos(sugested_x_position, sugested_y_position)

        ####
        new_widget_height = (1 / 4.) * view_size.height()
        if self.image_bank is not None:
            for image_id in self.image_bank.keys():
                if "clothes" in self.image_bank[image_id]["categories"]:
                    widget = self.image_bank[image_id]["widget"]
                    pixmap = widget.pixmap
                    pixmap = pixmap.scaled(new_widget_height, new_widget_height,
                                           Qt.KeepAspectRatio)
                    widget.setPixmap(pixmap)
                    print widget.moved_flag
                    if not widget.moved_flag:
                        newpos_x = self.background_from_image.boundingRect().width() / 2 - widget.boundingRect().width() / 2
                        newpos_y = self.background_from_image.boundingRect().height() / 2 - widget.boundingRect().height() / 2
                        widget.setPos(newpos_x, newpos_y)

        super(TakeDragGame, self).resizeEvent(event)
Exemplo n.º 13
0
 def __init__(o, parent, pieceid, w, h, dominant_colors):
     QGraphicsPixmapItem.__init__(o, parent=parent)
     o.id = pieceid
     o.dominant_colors = dominant_colors
     o.angle_deg = 0
     o.img = None
     o._got_image = False
     # create dummy pixmap, transparent
     pxm = QPixmap(w, h)
     pxm.fill(QColor(0, 0, 0, 0))
     o.setPixmap(pxm)
     o.setTransformationMode(Qt.SmoothTransformation)
Exemplo n.º 14
0
 def createPixmapItem(self, pixmap, position, matrix=QMatrix()):
     item = QGraphicsPixmapItem(pixmap)
     item.setFlags(QGraphicsItem.ItemIsSelectable|
                   QGraphicsItem.ItemIsMovable)
     item.setPos(position)
     item.setMatrix(matrix)
     self.scene.clearSelection()
     self.scene.addItem(item)
     item.setSelected(True)
Exemplo n.º 15
0
 def __init__(self, *args):
       QGraphicsPixmapItem.__init__(self, *args)
       self.setPixmap(QPixmap("sprites/calle/centro.png"))
       self.setTransformOriginPoint(self.boundingRect().width()/2.0,self.boundingRect().height()/2.0)
       self.setZValue(1)
       self.menu = QMenu()
       self.Actions =[] #arreglo de acciones 
       self.Actions.append( self.menu.addAction("girar clockwise") )
       self.Actions.append( self.menu.addAction("girar anti-clockwise") )
       self.Actions.append( self.menu.addAction("Duplicar") )
       self.Actions.append( self.menu.addAction("Eliminar") )
       self.menu.triggered[QAction].connect(self.test)
       self.offset=QPointF(0,0)
Exemplo n.º 16
0
    def build_ships_from_matrix(self):
        for x in range(10):
            for y in range(9):
                if self.my_board[x][y] == 1:

                    if x % 2 != 0:
                        self.item = QGraphicsPixmapItem(QPixmap(self.STATEK))
                        self.item.setOffset(18+y*61, 21+(x*52))
                        self.scene.addItem(self.item)

                    elif x % 2 == 0:
                        self.item = QGraphicsPixmapItem(QPixmap(self.STATEK))
                        self.item.setOffset(49+y*61, 21+x*53)
                        self.scene.addItem(self.item)
Exemplo n.º 17
0
    def __mouseReleaseEvent(self,event):
        global PIX
        self.drag_stop = event.pos()
        im = PIX.pixmap().toImage()
        
        start, stop = self.mapToScene(self.drag_start),self.mapToScene(self.drag_stop)
        logging.debug((start,stop))

        augmented = QGraphicsPixmapItem(QPixmap(tempfile))
        
        augmented.setOffset(rect.topLeft())
        augmented.setMatrix(QMatrix())
        if None != self.selectbox: self.scene().removeItem(self.selectbox)
        self.selectbox = augmented
        self.scene().addItem(self.selectbox)
Exemplo n.º 18
0
    def search(self):
        # first set/change the  font of the serach box
        font = self.dlg.search_lineEdit.font()
        font.setItalic(False)
        self.dlg.search_lineEdit.setFont(font)

        # clear description and quicklook
        self.dlg.textEdit.clear()
        
        # make a new emptey scene to show
        if not self.dlg.graphicsView is None:
            scene = QGraphicsScene()
            pic = QPixmap()
            scene.addItem(QGraphicsPixmapItem(pic))
            self.dlg.graphicsView.setScene(scene)        
            self.dlg.graphicsView.show()  
        
        # function the searches for a string in the datasets name, service type and otganization
        text = self.dlg.search_lineEdit.text()        
        # convert to lower case and remove greek accents in case of Greek
        text = text.lower()
        text = self.removeGreekAccents(text)  
        foundDatasets = []
        for dataset in self.datasets:
            # use lowercase characters and remove greek accents , to make the comparison
            name = self.removeGreekAccents(dataset.getName(self.language).lower())
            source = self.removeGreekAccents(dataset.getSource(self.language).lower())
            serviceType = self.removeGreekAccents(dataset.serviceType.lower())
            
            if text in name or text in source or text in serviceType:            
            #QMessageBox.information(None, "DEBUG:", str(type(dataset.getName(self.language))))                           
                foundDatasets.append(dataset)
        #fill the table with the found datasets
        self.fill_table(foundDatasets)     
Exemplo n.º 19
0
 def __init__(self, *args):
     QGraphicsView.__init__(self, *args)
     self.move(20, 240)
     self.outerD = 125
     self.innerD = 35
     self.innerRange = 48
     self.inputRange = 256
     self.thresh = 3
     self.padding = 40
     self.marginTop = 10
     self.worker = QSixAxisThread()
     self.worker.valueUpdated.connect(self.moveJoysticks)
     self.worker.start()
     self.setContentsMargins(0, 0, 0, 0)
     self.setMaximumHeight(180)
     self.setMaximumWidth(420)
     self.setMinimumHeight(240)
     self.setMinimumWidth(300)
     self.adjustSize()
     self.scene = QGraphicsScene(self)
     self.outerCircle1 = QGraphicsEllipseItem(0, self.marginTop, self.outerD, self.outerD)
     self.outerCircle1.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
     self.outerCircle1.setBrush(Qt.gray)
     self.innerCircle1 = QGraphicsEllipseItem(self.outerD / 2 - self.innerD / 2, self.outerD / 2 - self.innerD / 2 + self.marginTop, self.innerD, self.innerD)
     self.innerCircle1.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
     self.innerCircle1.setBrush(Qt.lightGray)
     self.scene.addItem(self.outerCircle1)
     self.scene.addItem(self.innerCircle1)
     self.outerCircle2 = QGraphicsEllipseItem(self.outerD + self.padding, self.marginTop, self.outerD, self.outerD)
     self.outerCircle2.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
     self.outerCircle2.setBrush(Qt.gray)
     self.innerCircle2 = QGraphicsEllipseItem(self.outerD + self.padding + self.outerD / 2 - self.innerD / 2, self.outerD / 2 - self.innerD / 2 + self.marginTop, self.innerD, self.innerD)
     self.innerCircle2.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
     self.innerCircle2.setBrush(Qt.lightGray)
     self.scene.addItem(self.outerCircle2)
     self.scene.addItem(self.innerCircle2)
     self.setScene(self.scene)
     self.setStyleSheet('background-color:transparent; border-width: 0px; border: 0px;')
     self.currentX = 0
     self.currentY = 0
     self.currentA = 0
     self.currentZ = 0
     self.psBtn = QPixmap(os.getcwd() + '/../icons/bt_PS.png')
     self.psBtn = self.psBtn.scaled(50, 50, Qt.KeepAspectRatio)
     self.psItem = QGraphicsPixmapItem(self.psBtn)
     self.psItem.setOffset(QPointF(self.outerD - 4, 0))
     self.effect = QGraphicsDropShadowEffect()
     self.effect.setOffset(0, 0)
     self.effect.setBlurRadius(20)
     self.effect.setColor(Qt.green)
     self.psItem.setGraphicsEffect(self.effect)
     self.scene.addItem(self.psItem)
     self.tl2 = QTimeLine(10000)
     self.tl2.setFrameRange(0, 10000)
     self.c = QGraphicsItemAnimation()
     self.c.setItem(self.psItem)
     self.c.setTimeLine(self.tl2)
     self.tl2.connect(self.tl2, SIGNAL('frameChanged(int)'), self.updateEffect)
     self.effectd = 3
     self.tl2.start()
Exemplo n.º 20
0
 def __init__(self, filename=None, width=None, height=None, x=0, y=0, pixmap=None, group=None, pos=None, size=None, padding=None):
     self.effects = {}
     self.animations = {}
     self.filename = filename if isinstance(filename, str) else None
     if pixmap :
         self.pixmap = pixmap
     elif isinstance(filename, QPixmap) :
         self.pixmap = filename
     elif isinstance(filename, str) :
         self.pixmap = QPixmap(os.path.dirname(__file__) + '/../buttons/' + filename)
     else :
         self.pixmap = None
     if (width != None or height != None) and self.pixmap != None :
         self.pixmap = self.pixmap.scaled(width if width != None else height,
                                  height if height != None else width, Qt.KeepAspectRatio)
     self.group = group
     self.pos = pos
     self.size = size
     self.padding = padding
     self.x = x
     self.y = y
     
     if isinstance(self.pixmap, QPixmap) :
         self.item = QGraphicsPixmapItem(self.pixmap)
         self.item.setOffset(QPointF(self.getX(), self.getY()))
         self.effect = QGraphicsDropShadowEffect()
         self.effect.setOffset(0, 0)
         self.effect.setBlurRadius(0)
         self.effect.setColor(Qt.green)
         self.addEffect('shadow', self.effect, True)
         self.addAnimation('glow', Glow(15, 300, self, maxRadius=80, minRadius=5))
Exemplo n.º 21
0
    def __init__(self,
                 parent=None,
                 direction=Qt.LeftToRight,
                 node=None,
                 icon=None,
                 iconSize=None,
                 **args):
        QGraphicsWidget.__init__(self, parent, **args)
        self.setAcceptedMouseButtons(Qt.NoButton)
        self.__direction = direction

        self.setLayout(QGraphicsLinearLayout(Qt.Horizontal))

        # Set the maximum size, otherwise the layout can't grow beyond its
        # sizeHint (and we need it to grow so the widget can grow and keep the
        # contents centered vertically.
        self.layout().setMaximumSize(QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX))

        self.setSizePolicy(QSizePolicy.MinimumExpanding,
                           QSizePolicy.MinimumExpanding)

        self.__iconSize = iconSize or QSize(64, 64)
        self.__icon = icon

        self.__iconItem = QGraphicsPixmapItem(self)
        self.__iconLayoutItem = GraphicsItemLayoutItem(item=self.__iconItem)

        self.__channelLayout = QGraphicsGridLayout()
        self.__channelAnchors = []

        if self.__direction == Qt.LeftToRight:
            self.layout().addItem(self.__iconLayoutItem)
            self.layout().addItem(self.__channelLayout)
            channel_alignemnt = Qt.AlignRight

        else:
            self.layout().addItem(self.__channelLayout)
            self.layout().addItem(self.__iconLayoutItem)
            channel_alignemnt = Qt.AlignLeft

        self.layout().setAlignment(self.__iconLayoutItem, Qt.AlignCenter)
        self.layout().setAlignment(self.__channelLayout,
                                   Qt.AlignVCenter | channel_alignemnt)

        if node is not None:
            self.setSchemeNode(node)
Exemplo n.º 22
0
    def __init__(self, win, rect, filename, metadata):
        self.win = win
        self.rect = rect
        self.filename = filename
        self.metadata = metadata

        if self.metadata:
            self.line1 = self.metadata['Name']
            self.line2 = "%s Mission" % (self.metadata['Mission'])
            self.line3 = "%s" % (self.metadata['Time'])
        else:
            self.line1 = ""
            self.line2 = ""
            self.line3 = ""

        self.image = QGraphicsPixmapItem()
        self.win.scene.addItem(self.image)
        self.image.setTransformationMode(Qt.SmoothTransformation)

        self.use_two_lines = True

        self.fontsize1 = 32
        self.fontsize2 = 26
        self.fontsize3 = 24

        self.font1 = QFont('Times New Roman', self.fontsize1)
        self.font2 = QFont('Times New Roman', self.fontsize2)
        self.font3 = QFont('Times New Roman', self.fontsize3)

        self.title1 = self.win.scene.addText(self.line1, self.font1)
        self.title1.setDefaultTextColor(Qt.white)
        self.title1.setVisible(False)

        self.title2 = self.win.scene.addText(self.line2, self.font2)
        self.title2.setDefaultTextColor(Qt.white)
        self.title2.setVisible(False)

        self.title3 = self.win.scene.addText(self.line3, self.font3)
        self.title3.setDefaultTextColor(Qt.white)
        self.title3.setVisible(False)

        self.reservedHeight = 128
        self.padding = 20

        self.hide()
Exemplo n.º 23
0
    def build_shots_from_matrix(self):
        picture = 'res/cancel.png'
        for x in range(10):
            for y in range(9):

                if self.my_board[x][y] == 2 or self.my_board[x][y] == 3:

                    if x % 2 != 0:
                        self.item = QGraphicsPixmapItem(QPixmap(picture))
                        self.item.setOffset(16+y*61, 17+(x*52))
                        self.scene.addItem(self.item)

                    elif x % 2 == 0:
                        self.item = QGraphicsPixmapItem(QPixmap(picture))
                        self.item.setOffset(47+y*61, 16+x*53)
                        self.scene.addItem(self.item)

                self.build_ships_from_matrix()
Exemplo n.º 24
0
    def createPixmapItem(self, pixmap, matrix=QMatrix()):
        global PIX
        item = QGraphicsPixmapItem(pixmap)
        PIX = item
#        item.setFlags(QGraphicsItem.ItemIsSelectable|
#                      QGraphicsItem.ItemIsMovable)
        item.setMatrix(matrix)
        self.scene.clearSelection()
        
        for i in self.scene.items():
            self.scene.removeItem(i)
        
        self.scene.addItem(item)
        self.view.fitInView(item,Qt.KeepAspectRatio)
        
        
        global DIRTY
        DIRTY = True
Exemplo n.º 25
0
class AI(object):

    def __init__(self, QMainWindow):
        self.game = QMainWindow
        self.clear_unused_fields()
        ships = 0
        while ships < 10:
            x = randint(0, 9)
            y = randint(0, 8)
            if self.game.enemies_board[x][y] == 0:
                self.game.enemies_board[x][y] = 1
                ships += 1

    def clear_unused_fields(self):
        self.game.connect_btn.hide()
        self.game.ip_addr_field.hide()
        self.game.port_field.hide()

    def make_move(self):
        if not self.game.is_my_turn:
            x = randint(0, 9)
            y = randint(0, 8)
            if self.game.my_board[x][y] not in range(2,4):
                if self.game.my_board[x][y] == 1:
                    self.game.my_board[x][y] = 2
                    picture = 'res/cancel.png'
                else:
                    self.game.my_board[x][y] = 3
                    picture = 'res/ok.png'

                if x % 2 != 0:
                    self.item = QGraphicsPixmapItem(QPixmap(picture))
                    self.item.setOffset(16+y*61, 17+(x*52))
                    self.game.scene.addItem(self.item)

                elif x % 2 == 0:
                    self.item = QGraphicsPixmapItem(QPixmap(picture))
                    self.item.setOffset(47+y*61, 16+x*53)
                    self.game.scene.addItem(self.item)

            print(self.game.enemies_board)
            print(self.game.my_board)
            self.game.is_my_turn = True
 def btnLoadImageClicked(self):
     if self.dlgLoadImage.exec_():
         filename = self.dlgLoadImage.selectedFiles()[0]
         self._image = QImage(filename)
         self._imagePixmap = QGraphicsPixmapItem(QPixmap(self._image), None,
                                                 self._imageScene)
         self.grObjectImage.setScene(self._imageScene)
         self.grObjectImage.fitInView(self._imageScene.sceneRect(),
                                      Qt.KeepAspectRatio)
         self._imagePixmap.mousePressEvent = self.getRGBFromPixel
Exemplo n.º 27
0
 def __init__(self, classifier, granularity, scale, spacing, rect=None):
     orangeqt.PlotItem.__init__(self)
     self.classifier = classifier
     self.rect = rect
     self.granularity = granularity
     self.scale = scale
     self.spacing = spacing
     self.pixmap_item = QGraphicsPixmapItem(self)
     self.set_in_background(True)
     self.setZValue(ProbabilitiesZValue)
Exemplo n.º 28
0
    def inicializarUI(self):
        self.setWindowTitle("BlueKing::Reversa")
        self.setGeometry(0,0,320,240)
        self.setAutoFillBackground(True)

        #QGraphicsView/Scene
        self.view = QGraphicsView()
        self.view.setStyleSheet("border: 0px;margin: 0px;background-color: #000000;")

        self.scene = QGraphicsScene(0,0,320,240)
        self.view.setScene(self.scene)

        self.baseLayout = QVBoxLayout()
        self.baseLayout.setContentsMargins(0,0,0,0)
        self.baseLayout.addWidget(self.view)

        #Decoracion
        car_logo = QPixmap("imagenes/car_logo.png")
        car_logo_item = QGraphicsPixmapItem(car_logo)
        car_logo_item.setPos(5,5)
        self.scene.addItem(car_logo_item)

        self.distlabel = QLabel("-")
        self.distlabel.setGeometry(20, 20, 280, 200)
        self.distlabel.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
        self.distlabel.setStyleSheet("color: #00FFFF;font-size: 150px;background-color: transparent;")
        self.scene.addWidget(self.distlabel)

        self.measureLabel=QLabel("metros")
        self.measureLabel.setGeometry(10,190,300,30)
        self.measureLabel.setAlignment(QtCore.Qt.AlignRight |QtCore.Qt.AlignVCenter)
        self.measureLabel.setStyleSheet("color: #FFFF00;font-size: 30px; font-weight: bold; font-style: italic;background-color: transparent;")
        self.scene.addWidget(self.measureLabel)

        self.setLayout(self.baseLayout)

        transformacion = QTransform()
        transformacion.scale(1.0,-1.0)

        #self.view.setTransform(transformacion)

        self.show()
Exemplo n.º 29
0
 def __init__(self, power, color, bot):
     QGraphicsPixmapItem.__init__(self)
     #graphics
     self.maskColor = QtGui.QColor(255, 128, 0)
     self.pixmap = QtGui.QPixmap(os.getcwd() + "/robotImages/blast.png")
     self.setPixmap(self.pixmap)
     self.setColour(color)
     self.isfired = False
     #physics
     self.width = self.boundingRect().width()
     self.height = self.boundingRect().height()
     if power <= 0.5:
         power = 0.5
     elif power >= 10:
         power = 10
     self.power = power
     bsize = power
     if power < 3:
         bsize = 4
     self.pixmap = self.pixmap.scaled(bsize, bsize)
     self.setPixmap(self.pixmap)
     self.robot = bot
Exemplo n.º 30
0
 def __init__(self, *args):
     QGraphicsView.__init__(self, *args)
     self.move(2, 22)
     self.btnSize = 60
     self.setMaximumHeight(60)
     self.setMaximumWidth(332)
     self.setMinimumHeight(60)
     self.setMinimumWidth(332)
     self.adjustSize()
     self.scene = QGraphicsScene(self)
     self.setStyleSheet('background-color:transparent; border-width: 0px; border: 0px;')
     self.l1 = QPixmap(os.getcwd() + '/../icons/l1.png')
     self.l1 = self.l1.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
     self.l1Item = QGraphicsPixmapItem(self.l1)
     self.l1Item.setOffset(QPointF(30, 0))
     self.scene.addItem(self.l1Item)
     self.r1 = QPixmap(os.getcwd() + '/../icons/r1.png')
     self.r1 = self.l1.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
     self.r1Item = QGraphicsPixmapItem(self.r1)
     self.r1Item.setOffset(QPointF(200, 0))
     self.scene.addItem(self.r1Item)
     self.setScene(self.scene)
Exemplo n.º 31
0
    def set_ship(self):
        if not self.is_client_connected:
            x = self.set_X.text()
            y = self.set_Y.text()
            x, y = parser(x, y)

            if self.my_ships < 10:
                if x != -1 and y != -1:

                    # Dodanie statku do pola
                    self.my_board[x][y] = 1
                    self.my_ships += 1

                    self.enemies_board[x][y] = 1

                    QMessageBox.about(self, "Statek na polu", "({}, {})".format(x, y))
                    if x % 2 != 0:
                        self.item = QGraphicsPixmapItem(QPixmap(self.STATEK))
                        self.item.setOffset(18+y*61, 21+(x*52))
                        self.scene.addItem(self.item)

                    elif x % 2 == 0:
                        self.item = QGraphicsPixmapItem(QPixmap(self.STATEK))
                        self.item.setOffset(49+y*61, 21+x*53)
                        self.scene.addItem(self.item)

                else:
                    QMessageBox.about(self, "Blad", "Niepoprawne pola")
            else:
                    QMessageBox.about(self, "Blad", "Wykorzystales juz cala flote")
        else:
            QMessageBox.about(self, "Info", "Nie polaczyles sie z przeciwnikiem")

        if self.my_ships == 5:
            self.ready_to_play = True
            self.set_X.hide()
            self.set_Y.hide()
            self.set_ship_btn.hide()
            QMessageBox.about(self, "Info", "Jestes gotowy aby rozpoczac gre")
Exemplo n.º 32
0
 def draw_env(self, image):
     if self.scene_env == 0:    
         self.scene_env = QGraphicsPixmapItem()
     else:
         self.removeItem(self.scene_env)
     
     self.scene_env.setPixmap(QPixmap(image))
     
     if self.scene_env != 0:
         self.scene_env.setPos(0, -self.environment.im.shape[1])
     
     self.addItem(self.scene_env)
     self.scene_env.setZValue(-1)
         
     if not self.f_show_env:
         self.scene_env.hide()
     
     self.spinEnvX.setValue(self.environment.im.shape[0])
     self.spinEnvY.setValue(self.environment.im.shape[1])
         
     if self.f_auto_edge:
         self.delete_all_edges()
         self.net.recalculate_edges()
         self.draw_all_edges()
Exemplo n.º 33
0
    def __init__(self, master, *args):
        QGraphicsView.__init__(self, *args)
        self.master = master

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        self.setRenderHints(QPainter.Antialiasing)
        scene = QGraphicsScene(self)
        self.pixmapGraphicsItem = QGraphicsPixmapItem(None, scene)
        self.setScene(scene)

        self.setMouseTracking(True)
        self.viewport().setMouseTracking(True)

        self.setFocusPolicy(Qt.WheelFocus)
Exemplo n.º 34
0
 def close(self):
     #clear everything
     self.init_table()
     # clear description and quicklook
     self.dlg.textEdit.clear()
     # clear search box
     #text = self.dlg.search_lineEdit.setText("")
     self.init_searchBox()
     # make a new emptey scene to show
     if not self.dlg.graphicsView is None:
         scene = QGraphicsScene()
         pic = QPixmap()
         scene.addItem(QGraphicsPixmapItem(pic))
         self.dlg.graphicsView.setScene(scene)        
         self.dlg.graphicsView.show()
     """close the dialog"""
     self.dlg.close()
Exemplo n.º 35
0
    def updateDescAndQL(self):
        # get the name of the selected dataset
        dataset_name, dataset_serviceType = self.getSelectedNameAndType()

        #custom web service object
        dataset = self.selectdataSets(dataset_name, dataset_serviceType)

        quicklook = os.path.join(self.quicklooks_dir, dataset.QLname + ".jpg")
        desc = dataset.getDescription(self.language)
        name = dataset.getName(self.language)

        #update decription
        self.dlg.textEdit.clear()
        #creation and last update
        if self.language == "EN":
            crDate = "Creation date : " + dataset.creationDate
            update = "Last update : " + dataset.lastUpdate
        elif self.language == "GR":
            crDate = unicode(
                "Ημερομηνια δημιουργιας : " + dataset.creationDate, 'utf-8')
            update = unicode("Τελευταία ενημέρωση : " + dataset.lastUpdate,
                             'utf-8')

        cursor = QTextCursor(self.dlg.textEdit.document())
        cursor.insertHtml("<h3> " + name + " <br><br></h3>")
        cursor.insertHtml("<p> " + desc + " <br><br><br></p>")
        cursor.insertHtml("<p><i> " + crDate + " <br></i></p>")
        #cursor.insertHtml("<p><i> "+update+" <br></i></p>")

        self.dlg.textEdit.setReadOnly(True)
        #update quicklook

        #GET DIMENSIONS OF THE IMAGE
        img = Image.open(quicklook)
        w, h = img.size

        scene = QGraphicsScene()
        pic = QPixmap(quicklook)
        scene.addItem(QGraphicsPixmapItem(pic))

        self.dlg.graphicsView.setScene(scene)
        self.dlg.graphicsView.fitInView(QRectF(0, 0, w, h), Qt.KeepAspectRatio)
        self.dlg.graphicsView.show()
Exemplo n.º 36
0
    def __init__(self, parent=None, direction=Qt.LeftToRight,
                 node=None, icon=None, iconSize=None, **args):
        QGraphicsWidget.__init__(self, parent, **args)
        self.setAcceptedMouseButtons(Qt.NoButton)
        self.__direction = direction

        self.setLayout(QGraphicsLinearLayout(Qt.Horizontal))

        # Set the maximum size, otherwise the layout can't grow beyond its
        # sizeHint (and we need it to grow so the widget can grow and keep the
        # contents centered vertically.
        self.layout().setMaximumSize(QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX))

        self.setSizePolicy(QSizePolicy.MinimumExpanding,
                           QSizePolicy.MinimumExpanding)

        self.__iconSize = iconSize or QSize(64, 64)
        self.__icon = icon

        self.__iconItem = QGraphicsPixmapItem(self)
        self.__iconLayoutItem = GraphicsItemLayoutItem(item=self.__iconItem)

        self.__channelLayout = QGraphicsGridLayout()
        self.__channelAnchors = []

        if self.__direction == Qt.LeftToRight:
            self.layout().addItem(self.__iconLayoutItem)
            self.layout().addItem(self.__channelLayout)
            channel_alignemnt = Qt.AlignRight

        else:
            self.layout().addItem(self.__channelLayout)
            self.layout().addItem(self.__iconLayoutItem)
            channel_alignemnt = Qt.AlignLeft

        self.layout().setAlignment(self.__iconLayoutItem, Qt.AlignCenter)
        self.layout().setAlignment(self.__channelLayout,
                                   Qt.AlignVCenter | channel_alignemnt)

        if node is not None:
            self.setSchemeNode(node)
Exemplo n.º 37
0
    def updateLanguage(self):
        # get the new language
        language = str(self.dlg.language_comboBox.currentText())        
        # Change the self.language propertie and change the labe;s
        if language == "English":
            self.language = "EN"
            self.dlg.desc_lbl.setText("Description")
            self.dlg.preview_lbl.setText("Preview")
            self.dlg.load_btn.setText("Load")
            self.dlg.close_btn.setText("Close")
            self.dlg.search_lbl.setText("Search")
            self.dlg.info_btn.setText("Info")
        elif language == "Greek":
            self.language = "GR"
            self.dlg.desc_lbl.setText(unicode("Περιγραφή", 'utf-8'))
            self.dlg.preview_lbl.setText(unicode("Προεπισκόπηση",'utf-8'))
            self.dlg.load_btn.setText(unicode("Φόρτωση",'utf-8'))
            self.dlg.close_btn.setText(unicode("Κλείσιμο",'utf-8'))
            self.dlg.search_lbl.setText(unicode("Αναζήτηση",'utf-8'))
            self.dlg.info_btn.setText(unicode("Πληροφορίες", 'utf-8'))

        self.dlg.preview_lbl.setAlignment(Qt.AlignRight)
        #refill the table
        self.init_table()
        # clear description and quicklook
        self.dlg.textEdit.clear()
        # clear search box
        #text = self.dlg.search_lineEdit.setText("")
        self.init_searchBox()
        # make a new emptey scene to show
        if not self.dlg.graphicsView is None:
            scene = QGraphicsScene()
            pic = QPixmap()
            scene.addItem(QGraphicsPixmapItem(pic))
            self.dlg.graphicsView.setScene(scene)        
            self.dlg.graphicsView.show()          
Exemplo n.º 38
0
 def __init__(self, pathway, objects, *args, **kwargs):
     QGraphicsPixmapItem.__init__(self, *args)
     self.setTransformationMode(Qt.SmoothTransformation)
     self.setPathway(pathway)
     self.setMarkedObjects(objects,
                           name_mapper=kwargs.get("name_mapper", {}))
Exemplo n.º 39
0
 def __init__(self, face, pixmap):
     QGraphicsPixmapItem.__init__(self, pixmap)
Exemplo n.º 40
0
 def background_pixmap_item(self):
     return QGraphicsPixmapItem(self.background_pixmap)
Exemplo n.º 41
0
class SlideshowFrame(object):
    def __init__(self, win, rect, filename, metadata):
        self.win = win
        self.rect = rect
        self.filename = filename
        self.metadata = metadata

        if self.metadata:
            self.line1 = self.metadata['Name']
            self.line2 = "%s Mission" % (self.metadata['Mission'])
            self.line3 = "%s" % (self.metadata['Time'])
        else:
            self.line1 = ""
            self.line2 = ""
            self.line3 = ""

        self.image = QGraphicsPixmapItem()
        self.win.scene.addItem(self.image)
        self.image.setTransformationMode(Qt.SmoothTransformation)

        self.use_two_lines = True

        self.fontsize1 = 32
        self.fontsize2 = 26
        self.fontsize3 = 24

        self.font1 = QFont('Times New Roman', self.fontsize1)
        self.font2 = QFont('Times New Roman', self.fontsize2)
        self.font3 = QFont('Times New Roman', self.fontsize3)

        self.title1 = self.win.scene.addText(self.line1, self.font1)
        self.title1.setDefaultTextColor(Qt.white)
        self.title1.setVisible(False)

        self.title2 = self.win.scene.addText(self.line2, self.font2)
        self.title2.setDefaultTextColor(Qt.white)
        self.title2.setVisible(False)

        self.title3 = self.win.scene.addText(self.line3, self.font3)
        self.title3.setDefaultTextColor(Qt.white)
        self.title3.setVisible(False)

        self.reservedHeight = 128
        self.padding = 20

        self.hide()

    def move(self, x, y):
        self.rect = QRectF(x, y, self.rect.width(), self.rect.height())

    def __rotate(self, metadata, origImgSize):
        # Qt only handles orientation properly from v5.5
        try:
            # try directly to get the tag, because sometimes get_tags() returns
            # tags that don't actually are in the file
            rot = metadata['Exif.Image.Orientation']
        except KeyError:
            # guess :-/
            rot = '1'

        # see http://www.daveperrett.com/images/articles/2012-07-28-exif-orientation-handling-is-a-ghetto/EXIF_Orientations.jpg
        # we have to 'undo' the rotations, so the numbers are negative
        if rot == '1':
            rotate = 0
            imgSize = origImgSize
        if rot == '8':
            rotate = -90
            imgSize = QSize(origImgSize.height(), origImgSize.width())
        if rot == '3':
            rotate = -180
            imgSize = origImgSize
        if rot == '6':
            rotate = -270
            imgSize = QSize(origImgSize.height(), origImgSize.width())

        # undo the last rotation and apply the new one
        self.image.setRotation(rotate)

        return imgSize

    def __zoomFit(self, imgSize):

        reservedHeight = self.reservedHeight + self.padding * 2

        hZoom = self.rect.width() / imgSize.width()
        vZoom = (self.rect.height() - reservedHeight) / imgSize.height()
        scale = min(hZoom, vZoom)

        self.image.setScale(scale)

        width = imgSize.width() * scale
        height = imgSize.height() * scale
        self.image.setPos(
            (self.rect.width() - width) / 2 + self.rect.x(),
            (self.rect.height() - reservedHeight - height) / 2 + self.rect.y())

    def layoutText(self):
        reservedHeight = self.reservedHeight + self.padding
        vertical_spacing = (self.reservedHeight -
                            self.title1.boundingRect().height() -
                            self.title2.boundingRect().height() -
                            self.title3.boundingRect().height()) / 3

        x = (self.rect.width() - self.title1.boundingRect().width()) / 2
        y = self.rect.height() - reservedHeight + vertical_spacing
        self.title1.setPos(x + self.rect.x(), y + self.rect.y())

        x = (self.rect.width() - self.title2.boundingRect().width()) / 2
        y = self.rect.height(
        ) - reservedHeight + vertical_spacing * 2 + self.title1.boundingRect(
        ).height()
        self.title2.setPos(x + self.rect.x(), y + self.rect.y())

        x = (self.rect.width() - self.title3.boundingRect().width()) / 2
        y = self.rect.height(
        ) - reservedHeight + vertical_spacing * 3 + self.title1.boundingRect(
        ).height() + self.title2.boundingRect().height()
        self.title3.setPos(x + self.rect.x(), y + self.rect.y())

    def show(self):
        img = QPixmap(self.filename)

        try:
            metadata = GExiv2.Metadata(self.filename)
        except GLib.Error as e:
            print(repr(e))
            return

        self.image.setPixmap(img)
        self.image.setScale(1.0)
        self.image.setRotation(0)

        imgSize = self.__rotate(metadata, img.size())
        self.__zoomFit(imgSize)
        self.layoutText()

        self.title1.setVisible(True)
        self.title2.setVisible(True)
        self.title3.setVisible(True)
        self.image.setVisible(True)

    def hide(self):
        self.title1.setVisible(False)
        self.title2.setVisible(False)
        self.title3.setVisible(False)
        self.image.setVisible(False)
        self.image.setPixmap(QPixmap())

    def showImage(self, file, md):
        self.metadata = md

        try:
            metadata = GExiv2.Metadata(file)
        except GLib.Error as e:
            print(repr(e))
            return

        img = QPixmap(file)

        self.image.setPixmap(img)
        self.image.setScale(1.0)
        self.image.setRotation(0)

        imgSize = self.__rotate(metadata, img.size())

        self.__zoomFit(imgSize)
        self.layoutMetadata()
Exemplo n.º 42
0
 def __init__(self, face, node, pixmap):
     QGraphicsPixmapItem.__init__(self, pixmap)
     _ActionDelegator.__init__(self)
     self.node = node
Exemplo n.º 43
0
 def show_fullscreen_pixmap(self, pixmap):
     """:param pixmap: a QPixmap"""
     item = QGraphicsPixmapItem(pixmap)
     self.show_fullscreen_item(item)
Exemplo n.º 44
0
 def __init__(self, pathway, objects, *args, **kwargs):
     QGraphicsPixmapItem.__init__(self, *args)
     self.setTransformationMode(Qt.SmoothTransformation)
     self.setPathway(pathway)
     self.setMarkedObjects(objects,
                           name_mapper=kwargs.get("name_mapper", {}))
Exemplo n.º 45
0
 def head_pixmap_item(self):
     head_pixmap_item = QGraphicsPixmapItem(self.head_pixmap)
     head_pixmap_item.setZValue(1)
     return head_pixmap_item
Exemplo n.º 46
0
class ProbabilitiesItem(orangeqt.PlotItem):
    """
        Displays class probabilities in the background

        :param classifier: The classifier for which the probabilities are calculated
        :type classifier: orange.P2NN

        :param granularity: The size of individual cells
        :type granularity: int

        :param scale: The data scale factor
        :type scale: float

        :param spacing: The space between cells
        :param spacing: int

        :param rect: The rectangle into which to draw the probabilities. If unspecified, the entire plot is used.
        :type rect: QRectF
    """

    def __init__(self, classifier, granularity, scale, spacing, rect=None):
        orangeqt.PlotItem.__init__(self)
        self.classifier = classifier
        self.rect = rect
        self.granularity = granularity
        self.scale = scale
        self.spacing = spacing
        self.pixmap_item = QGraphicsPixmapItem(self)
        self.set_in_background(True)
        self.setZValue(ProbabilitiesZValue)

    def update_properties(self):
        ## Mostly copied from OWScatterPlotGraph
        if not self.plot():
            return

        if not self.rect:
            x, y = self.axes()
            self.rect = self.plot().data_rect_for_axes(x, y)
        s = self.graph_transform().mapRect(self.rect).size().toSize()
        if not s.isValid():
            return
        rx = s.width()
        ry = s.height()

        rx -= rx % self.granularity
        ry -= ry % self.granularity

        p = self.graph_transform().map(QPointF(0, 0)) - self.graph_transform().map(self.rect.topLeft())
        p = p.toPoint()

        ox = p.x()
        oy = -p.y()

        if isinstance(self.classifier.classVar, ContinuousVariable):
            imagebmp = orangeom.potentialsBitmap(self.classifier, rx, ry, ox, oy, self.granularity, self.scale)
            palette = [qRgb(255.0 * i / 255.0, 255.0 * i / 255.0, 255 - (255.0 * i / 255.0)) for i in range(255)] + [
                qRgb(255, 255, 255)
            ]
        else:
            imagebmp, nShades = orangeom.potentialsBitmap(
                self.classifier, rx, ry, ox, oy, self.granularity, self.scale, self.spacing
            )
            palette = []
            sortedClasses = get_variable_values_sorted(self.classifier.domain.classVar)
            for cls in self.classifier.classVar.values:
                color = self.plot().discPalette.getRGB(sortedClasses.index(cls))
                towhite = [255 - c for c in color]
                for s in range(nShades):
                    si = 1 - float(s) / nShades
                    palette.append(qRgb(*tuple([color[i] + towhite[i] * si for i in (0, 1, 2)])))
            palette.extend([qRgb(255, 255, 255) for i in range(256 - len(palette))])

        self.potentialsImage = QImage(imagebmp, rx, ry, QImage.Format_Indexed8)
        self.potentialsImage.setColorTable(ColorPaletteDlg.signedPalette(palette) if qVersion() < "4.5" else palette)
        self.potentialsImage.setNumColors(256)
        self.pixmap_item.setPixmap(QPixmap.fromImage(self.potentialsImage))
        self.pixmap_item.setPos(self.graph_transform().map(self.rect.bottomLeft()))

    def data_rect(self):
        return self.rect if self.rect else QRectF()
Exemplo n.º 47
0
def paintBoundaries(tgslicesFile, zSlice, d, boundaryData, mask, filename, swapCoordinates=False, colortable=None, penWidth=4.0):
    print "* making boundary img '%s'" % filename
    
    #b = BoundariesLayerPy(tgslicesFile=tgslicesFile, normalAxis=2, data2scene=QTransform(), swapCoordinates=True)
    b = BoundariesLayer(None, 2, QTransform(), True)
    
    n  = b.normalAxis()
    axis = None
    if swapCoordinates:
        if   n == 0: axis = "z"
        elif n == 1: axis = "y"
        else:        axis = "x"
    else:
        if   n == 0: axis = "x"
        elif n == 1: axis = "y"
        else:        axis = "z"
    
    f = h5py.File(tgslicesFile, 'r')
    group = "%s/%d" % (axis, zSlice)
    serializedBoundaries = f[group].value
    f.close()
    
    assert d.ndim == 2
    
    scene = QGraphicsScene()
    
    b.setSliceNumber( zSlice )
    b.setBoundaries(serializedBoundaries)
    b.setColormap("tyr")
    assert boundaryData.dtype == numpy.float32
    assert mask.dtype == numpy.float32
    b.setBoundaryData(boundaryData, boundaryData.size, boundaryData)
    b.setBoundaryMask(mask, mask.size)
    if colortable is not None:
        b.setColormap(colortable)
    print "setting pen width to be %f" % penWidth
    b.setPenWidth(float(penWidth))
    print "...done"
   
    mag = 4
    shape = d.shape
    
    dBig = vigra.sampling.resizeImageNoInterpolation(d.astype(numpy.float32), (mag*shape[0], mag*shape[1]))
    #dBig = dBig.swapaxes(0,1)
    qimg = qimage2ndarray.gray2qimage(dBig)
    #qimg = qimg.mirrored(True, False)
    imgItm = QGraphicsPixmapItem(QPixmap(qimg))
    imgItm.setScale(1.0/mag)
    scene.addItem(imgItm)
    
    sourceRect = QRectF(0,0,shape[1], shape[0])
    targetRect = QRectF(0,0,mag*shape[1], mag*shape[0])
    scene.setSceneRect(sourceRect)
    scene.addItem(b)
    
    img = QImage(targetRect.width(), targetRect.height(), QImage.Format_ARGB32);
    painter = QPainter(img);
    painter.setRenderHint(QPainter.Antialiasing);
    scene.render(painter, targetRect, sourceRect );
    img.save(filename)
    painter.end()
    #print "img has size ", img.width(), img.height()
    img = None
    painter = None
    scene = None
Exemplo n.º 48
0
 def head_pixmap_item(self):
     head_pixmap_item = QGraphicsPixmapItem(self.head_pixmap)
     head_pixmap_item.setZValue(1)
     return head_pixmap_item
Exemplo n.º 49
0
class TakeDragGame(QWidget):
    def __init__(self, parent=None):
        super(TakeDragGame, self).__init__(parent)

        # This is always the same
        self.dot2 = QGraphicsTextItem(':')
        self.dot1 = QGraphicsTextItem(':')
        self.animations = []
        self.digits = []
        self.main_layout = QHBoxLayout()
        self.setLayout(self.main_layout)
        self.scene = QGraphicsScene()
        self.scene.setSceneRect(0, 0, 600, 400)
        self.view = QGraphicsView()
        self.view.setScene(self.scene)
        # TODO: Check if its better with opengl or not
        # self.view.setViewport(QtOpenGL.QGLWidget())
        self.main_layout.addWidget(self.view)
        # self.setWindowState(Qt.WindowMaximized)
        self.view.setAlignment(Qt.AlignTop | Qt.AlignLeft)
        self.image_bank = None
        self.create_and_add_images()

        # self.scene.setBackgroundBrush(QBrush(Qt.red, Qt.SolidPattern))

        # self.populate()
        # self.animator = QTimer()
        # self.animator.timeout.connect(self.animate)
        # self.animate()

    def create_and_add_images(self):
        self.load_images_json_file()
        self.add_background_to_image()
        self.add_background_from_image()
        if self.image_bank is not None:
            for image_id in self.image_bank.keys():
                if "clothes" in self.image_bank[image_id]["categories"]:
                    image_path = self.image_bank[image_id]["path"]
                    new_image = DraggableItem(image_path, self.background_from_image)
                    new_image.moved_signal.moved.connect(self.item_moved)
                    self.image_bank[image_id]["widget"] = new_image
                    newpos_x = self.background_from_image.boundingRect().width() / 2 - new_image.boundingRect().width() / 2
                    newpos_y = self.background_from_image.boundingRect().height() / 2 - new_image.boundingRect().height() / 2
                    new_image.setPos(newpos_x, newpos_y)
                    # self.scene.addItem(new_image)
                    new_image.setZValue(30)

    def item_moved(self, pos):
        widget = self.sender().get_parent()
        print widget.zValue()
        print self.background_from_image.zValue()
        print self.background_to_image.zValue()
        item_br = widget.sceneBoundingRect()
        if self.background_from_image.sceneBoundingRect().contains(item_br):
            widget.setParentItem(self.background_from_image)
            newpos_x = self.background_from_image.boundingRect().width() / 2 - widget.boundingRect().width() / 2
            newpos_y = self.background_from_image.boundingRect().height() / 2 - widget.boundingRect().height() / 2
            # self.background_to_image.stackBefore(self.background_from_image)
            widget.setPos(newpos_x, newpos_y)
        elif self.background_to_image.sceneBoundingRect().contains(item_br):
            widget.setParentItem(self.background_to_image)
            newpos_x = self.background_to_image.boundingRect().width() / 2 - widget.boundingRect().width() / 2
            newpos_y = self.background_to_image.boundingRect().height() / 2 - widget.boundingRect().height() / 2
            # self.background_from_image.stackBefore(self.background_to_image)
            widget.setPos(newpos_x, newpos_y)



    def load_images_json_file(self):
        with open(os.path.join(CURRENT_PATH, './resources/images.json')) as f:
            self.image_bank = json.load(f)

    def add_background_from_image(self, ):
        assert self.image_bank is not None, "Images need to be loaded before calling this method (try load_images_json_file)"
        if "Background from" in self.image_bank:
            background_from_pixmap = QPixmap(self.image_bank["Background from"]["path"])
            self.background_from_image = QGraphicsPixmapItem(background_from_pixmap)
            self.scene.addItem(self.background_from_image)
            self.background_from_image.setZValue(2)

    def add_background_to_image(self, ):
        assert self.image_bank is not None, "Images need to be loaded before calling this method (try load_images_json_file)"
        if "Background to" in self.image_bank:
            background_to_pixmap = QPixmap(self.image_bank["Background to"]["path"])
            self.background_to_image = QGraphicsPixmapItem(background_to_pixmap)
            self.scene.addItem(self.background_to_image)
            self.background_to_image.setZValue(2)

    def resizeEvent(self, event):
        view_size = self.view.size()
        new_background_height = (1.5 / 4.) * view_size.height()
        background_to_pixmap = QPixmap(self.image_bank["Background to"]["path"])
        background_to_pixmap = background_to_pixmap.scaled(new_background_height, new_background_height,
                                                           Qt.KeepAspectRatio)
        if not self.background_to_image:
            self.background_to_image = QGraphicsPixmapItem(background_to_pixmap)
        else:
            self.background_to_image.setPixmap(background_to_pixmap)
        sugested_x_position = int(2 * (view_size.width() / 3.))
        if sugested_x_position < 0:
            sugested_x_position = 0
        sugested_y_position = int(view_size.height() / 2. - background_to_pixmap.size().height() / 2)
        if sugested_y_position < 0:
            sugested_y_position = 0
        self.background_to_image.setPos(sugested_x_position, sugested_y_position)

        #####################
        new_background_height = (2.2 / 4.) * view_size.height()
        background_from_pixmap = QPixmap(self.image_bank["Background from"]["path"])
        background_from_pixmap = background_from_pixmap.scaled(new_background_height, new_background_height,
                                                               Qt.KeepAspectRatio)
        if not self.background_to_image:
            self.background_from_image = QGraphicsPixmapItem(background_from_pixmap)
        else:
            self.background_from_image.setPixmap(background_from_pixmap)

        sugested_x_position = int(view_size.width() / 5. - background_from_pixmap.size().height() / 2)
        if sugested_x_position < 0:
            sugested_x_position = 0
        sugested_y_position = int(view_size.height() / 2. - background_from_pixmap.size().height() / 2)
        if sugested_y_position < 0:
            sugested_y_position = 0
        self.background_from_image.setPos(sugested_x_position, sugested_y_position)

        ####
        new_widget_height = (1 / 4.) * view_size.height()
        if self.image_bank is not None:
            for image_id in self.image_bank.keys():
                if "clothes" in self.image_bank[image_id]["categories"]:
                    widget = self.image_bank[image_id]["widget"]
                    pixmap = widget.pixmap
                    pixmap = pixmap.scaled(new_widget_height, new_widget_height,
                                           Qt.KeepAspectRatio)
                    widget.setPixmap(pixmap)
                    print widget.moved_flag
                    if not widget.moved_flag:
                        newpos_x = self.background_from_image.boundingRect().width() / 2 - widget.boundingRect().width() / 2
                        newpos_y = self.background_from_image.boundingRect().height() / 2 - widget.boundingRect().height() / 2
                        widget.setPos(newpos_x, newpos_y)

        super(TakeDragGame, self).resizeEvent(event)
Exemplo n.º 50
0
 def show_fullscreen_image(self, image):
     """:param image: a QImage"""
     pixmap = QPixmap.fromImage(image)
     item = QGraphicsPixmapItem(pixmap)
     self.show_fullscreen_item(item)
Exemplo n.º 51
0
class ProbabilitiesItem(orangeqt.PlotItem):
    """
        Displays class probabilities in the background

        :param classifier: The classifier for which the probabilities are calculated
        :type classifier: orange.P2NN

        :param granularity: The size of individual cells
        :type granularity: int

        :param scale: The data scale factor
        :type scale: float

        :param spacing: The space between cells
        :param spacing: int

        :param rect: The rectangle into which to draw the probabilities. If unspecified, the entire plot is used.
        :type rect: QRectF
    """
    def __init__(self, classifier, granularity, scale, spacing, rect=None):
        orangeqt.PlotItem.__init__(self)
        self.classifier = classifier
        self.rect = rect
        self.granularity = granularity
        self.scale = scale
        self.spacing = spacing
        self.pixmap_item = QGraphicsPixmapItem(self)
        self.set_in_background(True)
        self.setZValue(ProbabilitiesZValue)

    def update_properties(self):
        ## Mostly copied from OWScatterPlotGraph
        if not self.plot():
            return

        if not self.rect:
            x, y = self.axes()
            self.rect = self.plot().data_rect_for_axes(x, y)
        s = self.graph_transform().mapRect(self.rect).size().toSize()
        if not s.isValid():
            return
        rx = s.width()
        ry = s.height()

        rx -= rx % self.granularity
        ry -= ry % self.granularity

        p = self.graph_transform().map(QPointF(
            0, 0)) - self.graph_transform().map(self.rect.topLeft())
        p = p.toPoint()

        ox = p.x()
        oy = -p.y()

        if self.classifier.classVar.is_continuous:
            imagebmp = orangeom.potentialsBitmap(self.classifier, rx, ry, ox,
                                                 oy, self.granularity,
                                                 self.scale)
            palette = [
                qRgb(255. * i / 255., 255. * i / 255., 255 - (255. * i / 255.))
                for i in range(255)
            ] + [qRgb(255, 255, 255)]
        else:
            imagebmp, nShades = orangeom.potentialsBitmap(
                self.classifier, rx, ry, ox, oy, self.granularity, self.scale,
                self.spacing)
            palette = []
            sortedClasses = get_variable_values_sorted(
                self.classifier.domain.classVar)
            for cls in self.classifier.classVar.values:
                color = self.plot().discPalette.getRGB(
                    sortedClasses.index(cls))
                towhite = [255 - c for c in color]
                for s in range(nShades):
                    si = 1 - float(s) / nShades
                    palette.append(
                        qRgb(*tuple(
                            [color[i] + towhite[i] * si for i in (0, 1, 2)])))
            palette.extend(
                [qRgb(255, 255, 255) for i in range(256 - len(palette))])

        self.potentialsImage = QImage(imagebmp, rx, ry, QImage.Format_Indexed8)
        self.potentialsImage.setColorTable(
            ColorPaletteDlg.signedPalette(palette
                                          ) if qVersion() < "4.5" else palette)
        self.potentialsImage.setNumColors(256)
        self.pixmap_item.setPixmap(QPixmap.fromImage(self.potentialsImage))
        self.pixmap_item.setPos(self.graph_transform().map(
            self.rect.bottomLeft()))

    def data_rect(self):
        return self.rect if self.rect else QRectF()
Exemplo n.º 52
0
 def __init__(self, face, node, pixmap):
     QGraphicsPixmapItem.__init__(self, pixmap)
     _ActionDelegator.__init__(self)
     self.node = node
Exemplo n.º 53
0
class MyWin(QMainWindow):

    STATEK = 'res/ship1.png'

    def __init__(self, address='127.0.0.1', port=5007):
        QMainWindow.__init__(self)
        uic.loadUi('untitled.ui', self)

        self.step_nr = 0
        self.is_my_turn = True
        self.ai_mode = False

        #  List with game states
        self.state = []

        self.ready_to_play = False
        self.send = (-1, -1)

        # 1 - Ship
        # 2 - Hit
        # 3 - Missed 
        self.my_board = np.zeros((10, 9))
        self.enemies_board = np.zeros((10, 9))
        self.build_ships_from_matrix()
        self.tie = 0
        self.my_points = 0
        self.enemies_points = 0

        self.xml_init()
        self.state.append((self.my_board, self.enemies_board, self.my_points))

        self.my_ships = 0

        self.s = Server(self, address, port)
        self.s.start()

        self.is_client_connected = False

        WindowConfig.config(self)
        self.scene = QGraphicsScene()
        self.my_screen.setScene(self.scene)

        self.dm = DrawMap(self.scene)

        # self.my_screen.viewport().installEventFilter(self)

        # buttons

        self.ai_btn.clicked.connect(self.play_with_ai)
        self.move_btn.clicked.connect(self.move_ship)
        self.next_btn.clicked.connect(self.next_step)
        self.back_btn.clicked.connect(self.step_back)
        self.save_btn.clicked.connect(self.save_dialog)
        self.clear_btn.clicked.connect(self.clear_board)
        self.read_file_btn.clicked.connect(self.load_state)
        self.gen_rand_btn.clicked.connect(self.build_random_matrix)
        self.shot_btn.clicked.connect(self.execute_shot)
        self.set_ship_btn.clicked.connect(self.set_ship)
        self.connect_btn.clicked.connect(self.connect_with_enemy)
        self.exit_btn.clicked.connect(self.close_app)
        pass

    def xml_init(self):
        self.root = ET.Element("game")

        doc = ET.SubElement(self.root, "initialization")
        ET.SubElement(doc, "my_board", name="my board").text = str(self.my_board)
        ET.SubElement(doc, "enemies_board", name="enemies board").text = str(self.my_board)

    def play_with_ai(self):
        self.ai_mode = True
        self.ai = AI(self)
        pass

    def move_ship(self):
        x = self.x_field.text()
        y = self.y_field.text()
        x, y = parser(x, y)

        if (x != -1 and y != -1) and \
                (self.my_board[x][y] == 1):
            new_x = randint(0, 9)
            new_y = randint(0, 8)
            if self.my_board[new_x][new_y] not in range(1,4):
                self.my_board[x][y] = 0
                self.my_board[new_x][new_y] = 1
                self.clear_board()
                self.build_shots_from_matrix()
        else:
            QMessageBox.about(self, "Move", "Wybierz statek")
        pass

    def next_step(self):
        self.my_board = self.state[self.step_nr][0]
        self.enemies_board = self.state[self.step_nr][1]
        self.my_points = self.state[self.step_nr][2]

        self.clear_board()
        self.build_shots_from_matrix()
        self.step_nr += 1

    def step_back(self):
        self.step_nr -= 1

        self.my_board = self.state[self.step_nr][0]
        self.enemies_board = self.state[self.step_nr][1]
        self.my_points = self.state[self.step_nr][2]

        self.clear_board()
        self.build_shots_from_matrix()

    def save_dialog(self):

        fname = QFileDialog.getOpenFileName(self, 'Open file',
                '/home')

        pickle.dump( self.state, open( fname, "wb" ) )

        self.tree = ET.ElementTree(self.root)

        xmlstr = minidom.parseString(ET.tostring(self.root)).toprettyxml(indent="   ")
        with open("newState.xml", "w") as f:
            f.write(xmlstr)

        # self.tree.write("states.xml")

    def load_state(self):
        '''
        Reads game state from binary file.
        '''

        fname = QFileDialog.getOpenFileName(self, 'Open file', '/home')
        self.state = pickle.load(open(fname, "rb"))

        # TODO
        tree = ET.parse('New_Database.xml')
        root = tree.getroot()

    def eventFilter(self, source, event):
        if (event.type() == QEvent.MouseButtonPress and
                source is self.my_screen.viewport()):
                    QCursor.pos()
                    QMessageBox.about(self, "Debug", "debug {}".format(QCursor.pos()))

    def connect_with_enemy(self):
        '''
        Connects our game instance with our enemy
        '''
        ip_addr = self.ip_addr_field.text()
        port = self.port_field.text()
        port = int(port)

        pattern = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
        test = pattern.match(ip_addr)

        if test:
            QMessageBox.about(self, "Info", "{}".format(ip_addr, port))
            self.connect_btn.hide()
            self.ip_addr_field.hide()
            self.port_field.hide()
            self.client = jsonSocket.JsonClient(address=ip_addr, port=port)
            self.client.connect()
        else:
            QMessageBox.about(self, "Blad", "Bledny format adresu ip")

    def execute_shot(self):
        '''
        Shot execution.
        '''
        is_hit = False

        if not self.ai_mode:

            if not self.is_my_turn:
                QMessageBox.about(self, "Czekaj", "Czekaj na twoją turę!")
                return

            if not self.is_client_connected:
                x = self.x_field.text()
                y = self.y_field.text()
                x, y = parser(x, y)

                if x != -1 and y != -1:

                    if self.enemies_board[x][y] == 1:
                        self.enemies_board[x][y] = 2
                        is_hit = True
                        picture = 'res/ok.png'
                    else:
                        self.enemies_board[x][y] = 3
                        is_hit = False
                        picture = 'res/cancel.png'

                    # if x % 2 != 0:
                    #     self.item = QGraphicsPixmapItem(QPixmap(picture))
                    #     self.item.setOffset(16+y*61, 17+(x*52))
                    #     self.scene.addItem(self.item)
                    #
                    #
                    # elif x % 2 == 0:
                    #     self.item = QGraphicsPixmapItem(QPixmap(picture))
                    #     self.item.setOffset(47+y*61, 16+x*53)
                    #     self.scene.addItem(self.item)

                    # QMessageBox.about(self, "Strzal", "({}, {})".format(x, y))
                    self.send = (x, y)
                    self.client.sendObj({"x": x, "y": y})
                else:
                    QMessageBox.about(self, "Blad", "Niepoprawne pola")
            else:
                QMessageBox.about(self, "Info", "Nie polaczyles sie z przeciwnikiem")

            if is_hit:
                pass
            else:
                pass

        else:
            x = self.x_field.text()
            y = self.y_field.text()
            x, y = parser(x, y)

            if x != -1 and y != -1:

                if self.enemies_board[x][y] == 1:
                    self.enemies_board[x][y] = 2
                    is_hit = True
                    picture = 'res/ok.png'
                else:
                    self.enemies_board[x][y] = 3
                    is_hit = False
                    picture = 'res/cancel.png'

                self.is_my_turn = False
                self.ai.make_move()

    def get_shot(self, x, y):
        '''
        Shot handler.
        :param x: x coord of shot
        :param y: y coord of shot
        '''
        is_Hit = False

        if self.my_board[x][y] == 1:
            self.my_board[x][y] = 2
            is_hit = True
            picture = 'res/ok.png'
        else:
            self.my_board[x][y] = -1
            is_hit = False
            picture = 'res/cancel.png'

        if x % 2 != 0:
            self.item = QGraphicsPixmapItem(QPixmap(picture))
            self.item.setOffset(16+y*61, 17+(x*52))
            self.scene.addItem(self.item)

        elif x % 2 == 0:
            self.item = QGraphicsPixmapItem(QPixmap(picture))
            self.item.setOffset(47+y*61, 16+x*53)
            self.scene.addItem(self.item)

    def set_ship(self):
        if not self.is_client_connected:
            x = self.set_X.text()
            y = self.set_Y.text()
            x, y = parser(x, y)

            if self.my_ships < 10:
                if x != -1 and y != -1:

                    # Dodanie statku do pola
                    self.my_board[x][y] = 1
                    self.my_ships += 1

                    self.enemies_board[x][y] = 1

                    QMessageBox.about(self, "Statek na polu", "({}, {})".format(x, y))
                    if x % 2 != 0:
                        self.item = QGraphicsPixmapItem(QPixmap(self.STATEK))
                        self.item.setOffset(18+y*61, 21+(x*52))
                        self.scene.addItem(self.item)

                    elif x % 2 == 0:
                        self.item = QGraphicsPixmapItem(QPixmap(self.STATEK))
                        self.item.setOffset(49+y*61, 21+x*53)
                        self.scene.addItem(self.item)

                else:
                    QMessageBox.about(self, "Blad", "Niepoprawne pola")
            else:
                    QMessageBox.about(self, "Blad", "Wykorzystales juz cala flote")
        else:
            QMessageBox.about(self, "Info", "Nie polaczyles sie z przeciwnikiem")

        if self.my_ships == 5:
            self.ready_to_play = True
            self.set_X.hide()
            self.set_Y.hide()
            self.set_ship_btn.hide()
            QMessageBox.about(self, "Info", "Jestes gotowy aby rozpoczac gre")

    def build_ships_from_matrix(self):
        for x in range(10):
            for y in range(9):
                if self.my_board[x][y] == 1:

                    if x % 2 != 0:
                        self.item = QGraphicsPixmapItem(QPixmap(self.STATEK))
                        self.item.setOffset(18+y*61, 21+(x*52))
                        self.scene.addItem(self.item)

                    elif x % 2 == 0:
                        self.item = QGraphicsPixmapItem(QPixmap(self.STATEK))
                        self.item.setOffset(49+y*61, 21+x*53)
                        self.scene.addItem(self.item)

    def build_shots_from_matrix(self):
        picture = 'res/cancel.png'
        for x in range(10):
            for y in range(9):

                if self.my_board[x][y] == 2 or self.my_board[x][y] == 3:

                    if x % 2 != 0:
                        self.item = QGraphicsPixmapItem(QPixmap(picture))
                        self.item.setOffset(16+y*61, 17+(x*52))
                        self.scene.addItem(self.item)

                    elif x % 2 == 0:
                        self.item = QGraphicsPixmapItem(QPixmap(picture))
                        self.item.setOffset(47+y*61, 16+x*53)
                        self.scene.addItem(self.item)

                self.build_ships_from_matrix()

    def build_random_matrix(self):
        self.dm.clear()
        self.ready_to_play = True
        self.set_X.hide()
        self.set_Y.hide()
        self.set_ship_btn.hide()
        self.my_board = np.zeros((10, 9))
        ships = 0
        while ships < 10:
            x = randint(0, 9)
            y = randint(0, 8)
            if self.my_board[x][y] == 0:
                self.my_board[x][y] = 1
                ships += 1
        self.build_ships_from_matrix()
        # self.state.append((self.my_board, self.enemies_board, self.my_points))

    def clear_board(self):
        self.dm.clear()

    def close_app(self):
        if self.is_client_connected:
            self.client.close()
        self.s.stop()
        self.close()

    @staticmethod
    def _parser(x, y):
        try:
            x = int(x)
            y = int(y)
            if x not in range(11):
                x, y = 0, 0
            if y not in range(11):
                x, y = 0, 0
        except ValueError:
            x, y = 0, 0
        return x, y
Exemplo n.º 54
0
class EditLinksNode(QGraphicsWidget):
    """
    A Node representation with channel anchors.

    `direction` specifies the layout (default `Qt.LeftToRight` will
    have icon on the left and channels on the right).

    """

    def __init__(self, parent=None, direction=Qt.LeftToRight,
                 node=None, icon=None, iconSize=None, **args):
        QGraphicsWidget.__init__(self, parent, **args)
        self.setAcceptedMouseButtons(Qt.NoButton)
        self.__direction = direction

        self.setLayout(QGraphicsLinearLayout(Qt.Horizontal))

        # Set the maximum size, otherwise the layout can't grow beyond its
        # sizeHint (and we need it to grow so the widget can grow and keep the
        # contents centered vertically.
        self.layout().setMaximumSize(QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX))

        self.setSizePolicy(QSizePolicy.MinimumExpanding,
                           QSizePolicy.MinimumExpanding)

        self.__iconSize = iconSize or QSize(64, 64)
        self.__icon = icon

        self.__iconItem = QGraphicsPixmapItem(self)
        self.__iconLayoutItem = GraphicsItemLayoutItem(item=self.__iconItem)

        self.__channelLayout = QGraphicsGridLayout()
        self.__channelAnchors = []

        if self.__direction == Qt.LeftToRight:
            self.layout().addItem(self.__iconLayoutItem)
            self.layout().addItem(self.__channelLayout)
            channel_alignemnt = Qt.AlignRight

        else:
            self.layout().addItem(self.__channelLayout)
            self.layout().addItem(self.__iconLayoutItem)
            channel_alignemnt = Qt.AlignLeft

        self.layout().setAlignment(self.__iconLayoutItem, Qt.AlignCenter)
        self.layout().setAlignment(self.__channelLayout,
                                   Qt.AlignVCenter | channel_alignemnt)

        if node is not None:
            self.setSchemeNode(node)

    def setIconSize(self, size):
        """
        Set the icon size for the node.
        """
        if size != self.__iconSize:
            self.__iconSize = QSize(size)
            if self.__icon:
                self.__iconItem.setPixmap(self.__icon.pixmap(size))
                self.__iconLayoutItem.updateGeometry()

    def iconSize(self):
        """
        Return the icon size.
        """
        return QSize(self.__iconSize)

    def setIcon(self, icon):
        """
        Set the icon to display.
        """
        if icon != self.__icon:
            self.__icon = QIcon(icon)
            self.__iconItem.setPixmap(icon.pixmap(self.iconSize()))
            self.__iconLayoutItem.updateGeometry()

    def icon(self):
        """
        Return the icon.
        """
        return QIcon(self.__icon)

    def setSchemeNode(self, node):
        """
        Set an instance of `SchemeNode`. The widget will be initialized
        with its icon and channels.

        """
        self.node = node

        if self.__direction == Qt.LeftToRight:
            channels = node.output_channels()
        else:
            channels = node.input_channels()
        self.channels = channels

        loader = icon_loader.from_description(node.description)
        icon = loader.get(node.description.icon)

        self.setIcon(icon)

        label_template = ('<div align="{align}">'
                          '<b class="channelname">{name}</b><br/>'
                          '<span class="typename">{typename}</span>'
                          '</div>')

        if self.__direction == Qt.LeftToRight:
            align = "right"
            label_alignment = Qt.AlignVCenter | Qt.AlignRight
            anchor_alignment = Qt.AlignVCenter | Qt.AlignLeft
            label_row = 0
            anchor_row = 1
        else:
            align = "left"
            label_alignment = Qt.AlignVCenter | Qt.AlignLeft
            anchor_alignment = Qt.AlignVCenter | Qt.AlignLeft
            label_row = 1
            anchor_row = 0

        self.__channelAnchors = []
        grid = self.__channelLayout

        for i, channel in enumerate(channels):
            text = label_template.format(align=align,
                                         name=escape(channel.name),
                                         typename=escape(channel.type))

            text_item = GraphicsTextWidget(self)
            text_item.setHtml(text)
            text_item.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

            grid.addItem(text_item, i, label_row,
                         alignment=label_alignment)

            anchor = ChannelAnchor(self, channel=channel,
                                   rect=QRectF(0, 0, 20, 20))

            anchor.setBrush(self.palette().brush(QPalette.Mid))

            layout_item = GraphicsItemLayoutItem(grid, item=anchor)
            grid.addItem(layout_item, i, anchor_row,
                         alignment=anchor_alignment)

            if hasattr(channel, "description"):
                text_item.setToolTip((channel.description))

            self.__channelAnchors.append(anchor)

    def anchor(self, channel):
        """
        Return the anchor item for the `channel` name.
        """
        for anchor in self.__channelAnchors:
            if anchor.channel() == channel:
                return anchor

        raise ValueError(channel.name)

    def paint(self, painter, option, widget=None):
        painter.save()
        palette = self.palette()
        border = palette.brush(QPalette.Mid)
        pen = QPen(border, 1)
        pen.setCosmetic(True)
        painter.setPen(pen)
        painter.setBrush(palette.brush(QPalette.Window))
        brect = self.boundingRect()
        painter.drawRoundedRect(brect, 4, 4)
        painter.restore()
def img_received_triggered(gui, img):
    scene = QGraphicsScene()
    pixmap = QGraphicsPixmapItem(QPixmap(img), None, scene)
    gui.grOriginalImage.setScene(scene)
    gui.grOriginalImage.fitInView(scene.sceneRect(), Qt.KeepAspectRatio)
    def __init__(self):
        super(QTRehaZenterGUI, self).__init__()
        uic.loadUi(currentdir + '/ui_files/QTRehaZenterGUI.ui', self)
        
        # connect to DB and create cursor object to perform queries
        self._mysqldb_connection = MySQLdb.connect(host=self.mysql_hostname, user=self.mysql_user, passwd=self.mysql_password, db="iot")
        
        # initialize custom object loader widget
        self.defineNewColorWidget = DefineNewColor.UIDefineNewColorWidget(self)

        # disable camera feed tab on startup (enabled later)
        self.tabWidget.setTabEnabled(2, False)
        
        # load logo images
        uniLuLogoScene = QGraphicsScene()
        imagePixmap_unilu = QGraphicsPixmapItem(QPixmap(QImage(currentdir + "/imgs/university_of_luxembourg_logo.png")), None, uniLuLogoScene)
        self.grUniLuLogo.setScene(uniLuLogoScene)
        self.grUniLuLogo.fitInView(uniLuLogoScene.sceneRect(), Qt.KeepAspectRatio)
        luxAILogoScene = QGraphicsScene()
        imagePixmap_luxai = QGraphicsPixmapItem(QPixmap(QImage(currentdir + "/imgs/luxai_logo.png")), None, luxAILogoScene)
        self.grLuxAILogo.setScene(luxAILogoScene)
        self.grLuxAILogo.fitInView(luxAILogoScene.sceneRect(), Qt.KeepAspectRatio)
        
        # initialize calibration file selection dialog
        self.dlgLoadCalibFile = QFileDialog()
        self.dlgLoadCalibFile.setFileMode(QFileDialog.ExistingFile)
        self.dlgLoadCalibFile.setFilter("Calibration files (*.clb)")
        self.dlgLoadCalibFile.setAcceptMode(QFileDialog.AcceptOpen)
        
        # initialize color file selection dialog
        self.dlgLoadColorFile = QFileDialog()
        self.dlgLoadColorFile.setFileMode(QFileDialog.ExistingFile)
        self.dlgLoadColorFile.setFilter("Color files (*.clr)")
        self.dlgLoadColorFile.setAcceptMode(QFileDialog.AcceptOpen)
        
        # initialize calibration file save dialog
        self.dlgSaveCalibFile = QFileDialog()
        self.dlgSaveCalibFile.setFileMode(QFileDialog.AnyFile)
        self.dlgSaveCalibFile.setFilter("Calibration files (*.clb)")
        self.dlgSaveCalibFile.setAcceptMode(QFileDialog.AcceptSave)
        
        # initialize rotation exercises warning message box
        self.msgRotationExercises = QMessageBox()
        self.msgRotationExercises.setIcon(QMessageBox.Warning)
        self.msgRotationExercises.setText("Sorry, rotation exercises have not been implemented yet!")
        self.msgRotationExercises.setInformativeText("Please choose one of the motion exercises instead until rotation exercises become available.")
        self.msgRotationExercises.setWindowTitle("Rotation exercises warning")
        self.msgRotationExercises.setStandardButtons(QMessageBox.Ok)
        
        # initialize calibration fail message box
        self.msgErrorWarning = QMessageBox()
        self.msgErrorWarning.setIcon(QMessageBox.Warning)
        self.msgErrorWarning.setStandardButtons(QMessageBox.Ok)
        
        # initialize list of faces (in string form)
        self._faces_list = ["sad", "happy", "crying", "neutral", "showing_smile", "surprise", "breathing_exercise", "breathing_exercise_nose", "smile", "happy_blinking", "calming_down", "random emotion"]
        self.cmbFaces.addItems(self._faces_list)
        
        # disable various labels and widgets on startup
        self.lblPerRepetitions1.setEnabled(False)
        self.lblPerRepetitions2.setEnabled(False)
        self.spnQuantEncRep.setEnabled(False)
        self.cmbQualiEnc.setEnabled(False)
        self.btnDeleteLine.setEnabled(False)
        self.spnFixedReps.setEnabled(False)
        self.spnFrequencyReps.setEnabled(False)
        self.btnAddLine.setEnabled(False)
        self.lblAuth.setVisible(False)
        self.lblPINCode.setVisible(False)
        self.lnPINCode.setVisible(False)
        self.btnConfirm.setVisible(False)
        self.lblHelloMsg.setVisible(False)
        self.lblRemove.setVisible(False)
        self.grProfilePicture.setVisible(True)
        self.tabWidget.setTabEnabled(1, False)
        self.tabWidget.setTabEnabled(2, False)
        self.tabWidget.setTabEnabled(3, False)
        self.tabWidget.setTabEnabled(4, False)
        self.lblWrongPINCode.setVisible(False)
        self.grProfilePicture.setVisible(False)
        
        # resize table columns to match their text size
        header = self.tblEmotionalFeedback.horizontalHeader()
        header.setResizeMode(0, QHeaderView.Stretch)
        header.setResizeMode(1, QHeaderView.Stretch)
        header.setResizeMode(2, QHeaderView.Stretch)
        
        # initialize ROS publisher topics
        rospy.init_node("reha_interface", anonymous=True)
        self._exercise_request_pub = rospy.Publisher("exercise_request", ExerciseRequest, queue_size=1)
        self._exercise_stop_pub = rospy.Publisher("exercise_stop", Bool, queue_size=1)
        self._calibration_request_pub = rospy.Publisher("calibration_request", CalibrationRequest, queue_size=1)
        rospy.Subscriber("exercise_reply", ExerciseReply, self._server_reply_callback)
        rospy.Subscriber("calibration_reply", CalibrationReply, self._server_reply_callback)
        rospy.Subscriber("/plain/image_modified/compressed", CompressedImage, self._img_received_callback)
        rospy.Subscriber("/user_logging/initial_key", String, self._smartcard_detected_callback)
        #self._decryption_node = None

	# initialize some other necessary variables
        self._is_calibrating = False
        self._is_exercise_running = False
        self._bridge = CvBridge()
        
        # connect functions to widgets
        self.btnInternalRotationExercise.clicked.connect(self.btnInternalRotationExerciseClicked)
        self.btnExternalRotationExercise.clicked.connect(self.btnExternalRotationExerciseClicked)
        self.btnAbductionMotionExercise.clicked.connect(self.btnAbductionMotionExerciseClicked)
        self.btnFlexionMotionExercise.clicked.connect(self.btnFlexionMotionExerciseClicked)
        self.btnBegin.clicked.connect(self.btnBeginClicked)
        self.btnStop.clicked.connect(self.btnStopClicked)
        self.btnDefineNewColor.clicked.connect(self.openDefineNewColorWidget)
        self.slNbrBlocks.valueChanged.connect(self.slNbrBlocksValueChanged)
        self.rdFixed.clicked.connect(self.rdFixedClicked)
        self.rdFrequency.clicked.connect(self.rdFrequencyClicked)
        self.btnAddLine.clicked.connect(self.btnAddLineClicked)
        self.cmbFaces.currentIndexChanged.connect(self.cmbFacesCurrentIndexChanged)
        self.actionQuit.triggered.connect(self.closeEvent)
        self.btnDeleteLine.clicked.connect(self.btnDeleteLineClicked)
        self.tblEmotionalFeedback.itemClicked.connect(self.tblEmotionalFeedbackItemClicked)
        self.chkQualitative.clicked.connect(self.chkQualitativeClicked)
        self.chkQuantitative.clicked.connect(self.chkQuantitativeClicked)
        self.btnLoadColorFile.clicked.connect(self.btnLoadColorFileClicked)
        self.btnLoadCalibFile.clicked.connect(self.btnLoadCalibFileClicked)
        self.btnCalibrateNow.clicked.connect(self.btnCalibrateNowClicked)
        self.robot_finished.connect(robot_finished_triggered)
        self.img_received.connect(img_received_triggered)
        self.smartcard_rosmsg_received.connect(smartcard_rosmsg_received_triggered)
        self.logoff_signal_received.connect(logoff_signal_received_triggered)
        self.btnConfirm.clicked.connect(self.btnConfirmClicked)
        self.lnPINCode.textChanged.connect(self.disableErrorLabelOnEdit)
   def btnConfirmClicked(self):
       # check if PIN code corresponds to PIN code stored in database (use SHA-256 to hash passwords!)
       cursor = self._mysqldb_connection.cursor()
       query_str = "select * from tblUser where userID='" + self._rfid + "'"
       cursor.execute(query_str)
       if cursor.rowcount != 1:
           self.lblWrongPINCode.setVisible(True)
           cursor.close()
           return
       # fetch (only) matching row from DB
       tblUser_row = cursor.fetchone()
       # hash pin entered by user with salt string from DB
       pincode_hash = SHA256.new(str(self.lnPINCode.text()) + str(tblUser_row[4])).hexdigest().upper()
       #print pincode_hash
       if pincode_hash == tblUser_row[3]:
           # permit access to user and enable widgets accordingly
           self.lblWrongPINCode.setVisible(False)
           self.tabWidget.setTabEnabled(1, True)
           self.tabWidget.setTabEnabled(2, True)
           self.tabWidget.setTabEnabled(3, True)
           self.tabWidget.setTabEnabled(4, True)
           self.lblAuth.setEnabled(False)
           self.lblPINCode.setEnabled(False)
           self.lnPINCode.setEnabled(False)
           self.btnConfirm.setEnabled(False)
           self.lblHelloMsg.setVisible(True)
           self.lblHelloMsg.setText("Welcome back, " + tblUser_row[2] + "!")
           self.lblRemove.setVisible(True)
           self.grProfilePicture.setVisible(True)
           self.grProfilePicture.setEnabled(True)
           scene = QGraphicsScene()
           qimg = QtGui.QImage.fromData(tblUser_row[6])
           pixmap = QGraphicsPixmapItem(QPixmap.fromImage(qimg), None, scene)
           self.grProfilePicture.setScene(scene)
           self.grProfilePicture.fitInView(scene.sceneRect(), Qt.KeepAspectRatio)
           self.grProfilePicture.setVisible(True)
           self._encourager.say("Welcome back, " + tblUser_row[2] + "!")
           self._encourager.show_emotion("happy")
           ### HARDCODED: display different information depending on user connected ###
           if self._rfid == "3BEA00008131FE450031C573C0014000900077":
               self.slNbrBlocks.setValue(3)
               self.spnNbrRepetitions.setValue(25)
               self.chkQualitative.setChecked(False)
               self.chkQuantitative.setChecked(True)
               self.spnQuantEncRep.setEnabled(True)
               self.cmbQualiEnc.setEnabled(False)
               self.spnQuantEncRep.setValue(3)
           else:
               self.slNbrBlocks.setValue(2)
               self.spnNbrRepetitions.setValue(15)
               self.chkQualitative.setChecked(True)
               self.chkQuantitative.setChecked(True)
               self.spnQuantEncRep.setEnabled(True)
               self.spnQuantEncRep.setValue(2)
               self.cmbQualiEnc.setEnabled(True)
               self.cmbQualiEnc.setCurrentIndex(1)
 
           #launch_params = ['roslaunch', 'simple_image_cyphering', 'one_node_decryption.launch']
           #self._decryption_node = Popen(launch_params)
       else:
           self.lblWrongPINCode.setVisible(True)
       cursor.close()
Exemplo n.º 58
0
 def itemChange(self, change, variant):
     if change != QGraphicsItem.ItemSelectedChange:
         global Dirty; Dirty = True
     return QGraphicsPixmapItem.itemChange(self, change, variant)
Exemplo n.º 59
0
class Scene(QGraphicsScene):
    def __init__(self, lblXY, spinId, spinX, spinY, btnAddEdge, btnDeleteEdge, spinCommRange, spinEnvX, spinEnvY, comboChannelType):
        super(self.__class__, self).__init__()
        
        self.net = pymote.Network()
        self.net_dict = {} #for keeping pairs of net_node and scene_node
        
        self.comm_range = 200
        self.curr_id = 1
        self.node_size = 15
        self.node_color = QtCore.Qt.blue
        self.pressed_color = QtCore.Qt.red
        
        self.lblXY = lblXY #shows x,y position on scene
        self.spinId = spinId
        self.spinId.setEnabled(False)
        self.spinX = spinX
        self.spinY = spinY
        self.btnAddEdge = btnAddEdge
        self.btnDeleteEdge = btnDeleteEdge
        self.spinEnvX = spinEnvX
        self.spinEnvY = spinEnvY
        self.comboChannelType = comboChannelType
        self.hide_btn_edge() #on start: auto edge mode selected -> buttons add and delete edge not needed
        self.hide_pressed_item_data() #on start: no item is pressed -> hide item data
        
        self.spinCommRange = spinCommRange
        self.spinCommRange.setValue(self.comm_range)
        
        self.f_show_radius = False
        self.f_auto_edge = True
        self.f_move = False 
        self.f_moved = False
        self.f_show_env = True
        self.f_opening_net = False
        
        self.option = 0
        self.edge_option = 0
        self.last_pressed_node = 0
        self.radius = 0
        
        self.environment = pymote.Environment()
        self.scene_env = 0
        self.envX = 600
        self.envY = 600
        
        self.channel_type = self.comboChannelType.currentText()
        
        self.setSceneRect(QtCore.QRectF(0, -self.envY, self.envX, self.envY))
    
    def ini_scene(self):
        self.clear()
        
        new_net = pymote.Network()
        self.net = new_net
        self.net_dict.clear()
        
        self.curr_id = 1
        self.option = 0
        self.edge_option = 0
        self.last_pressed_node = 0
        self.radius = 0
        
        self.environment = pymote.Environment()
        self.scene_env = 0
    
    def get_net(self):
        return self.net
        
    def hide_pressed_item_data(self):
        #self.spinId.setEnable(False)
        self.spinId.setValue(0)
        self.spinX.setEnabled(False)
        self.spinX.setValue(0)
        self.spinY.setEnabled(False)
        self.spinY.setValue(0)
        
    def show_pressed_item_data(self):
        #self.spinId.setEnable(True)
        self.spinId.setValue(self.last_pressed_node.node_id)
        self.spinX.setEnabled(True)
        self.spinX.setValue(self.last_pressed_node.get_X())
        self.spinY.setEnabled(True)
        self.spinY.setValue(-self.last_pressed_node.get_Y())
    
    def hide_btn_edge(self):
        self.btnAddEdge.setEnabled(False)
        self.btnDeleteEdge.setEnabled(False)
    
    def show_btn_edge(self):
        self.btnAddEdge.setEnabled(True)
        self.btnDeleteEdge.setEnabled(True)
    
    def auto_add_edge(self, toggle):
        if toggle.isChecked() == True:
            self.f_auto_edge = True
            self.hide_btn_edge()
            
            self.delete_all_edges()            
            self.net.recalculate_edges()
            self.draw_all_edges()
        else:
            self.f_auto_edge = False
            self.show_btn_edge()
    
    def show_radius(self, toggle):
        if toggle.isChecked() == True:
            self.f_show_radius = True
            if self.last_pressed_node != 0 and self.option == 0:
                self.draw_radius(self.last_pressed_node.get_X() + self.node_size/2, self.last_pressed_node.get_Y() + self.node_size/2, self.comm_range)
        else:
            self.f_show_radius = False
            if self.radius != 0:
                self.delete_radius()
    
    def show_env(self, toggle):
        if toggle.isChecked() == True:
            self.f_show_env =True
            if self.scene_env != 0:
                self.scene_env.show()
        else:
            self.f_show_env = False
            if self.scene_env != 0:
                self.delete_env()
    
    def draw_radius(self, x, y, comm_range):
        self.radius = Radius(x, y, comm_range)
        self.addItem(self.radius)             
    
    def delete_radius(self):
        self.removeItem(self.radius)
        self.radius = 0

#    def search_node_by_id(self):
#        f_found = False
#        
#        if self.last_pressed_node != 0:
#            if self.last_pressed_node.node_id != self.spinId.value(): 
#                self.last_pressed_node.setBrush(self.node_color)
#                for n in self.items():
#                    if isinstance(n, Node):
#                        if n.node_id == self.spinId.value():
#                            if self.radius != 0 and self.f_show_radius:
#                                size = n.comm_range
#                                self.radius.setRect(n.get_X() - size, n.get_Y() - size, size * 2, size * 2)
#                            self.last_pressed_node = n
#                            n.setBrush(self.pressed_color)
#                            self.spinX.setValue(n.get_X())
#                            self.spinY.setValue(-n.get_Y())
#                            f_found = True
#            
#                if not f_found:
#                    self.last_pressed_node = 0
#                    self.spinX.setValue(0)
#                    self.spinY.setValue(0)
#                    if self.radius != 0:
#                        self.delete_radius()
        
    def change_node_x(self):
        if self.last_pressed_node != 0 and not self.f_move:
            if self.last_pressed_node.get_X() != self.spinX.value():
                self.spin_value_changed(True)
            
    def change_node_y(self):
        if self.last_pressed_node != 0 and not self.f_move:
            if -self.last_pressed_node.get_Y() != self.spinY.value():
                self.spin_value_changed(False)
    
    def spin_value_changed(self, f_isX):
        if not self.f_auto_edge:
            self.move_edges(self.last_pressed_node, self.spinX.value(), self.spinY.value())    
        if self.f_auto_edge and not self.f_moved: #delete edges before node is moved
            edges = list()
            for edge in self.last_pressed_node.edges:
                edges.append(edge)
            
            for edge in edges:
                self._delete_edge(edge, True)   
        
        if f_isX:        
            self.last_pressed_node.setX(self.spinX.value() - self.last_pressed_node.get_iniX())
            self.last_pressed_node.node_label.setX(self.spinX.value())
        else:
            self.last_pressed_node.setY(-self.spinY.value() - self.last_pressed_node.get_iniY())
            self.last_pressed_node.node_label.setY(-self.spinY.value())
            
        net_node, n = self.get_nodes_from_net(self.last_pressed_node, 0)
        self.net.pos[net_node] = [self.spinX.value(), self.spinY.value()]
        
        if self.f_auto_edge and not self.f_moved:
            self.net.recalculate_edges([self.last_pressed_node.net_node])
            self.draw_recalc_edges(self.last_pressed_node.net_node)
    
    def change_comm_range(self):
        self.comm_range = self.spinCommRange.value()
        if self.last_pressed_node != 0:            
            self.last_pressed_node.set_comm_range(self.comm_range)
            
            net_node, n = self.get_nodes_from_net(self.last_pressed_node, 0)
            net_node.commRange = self.comm_range
            
        if self.radius != 0:
            size = self.comm_range
            self.radius.setRect(self.radius.get_iniX() - size, self.radius.get_iniY() - size, size * 2, size * 2)
    
    def change_node_env_x(self):
        self.envX = self.spinEnvX.value()
        #TODO: dodati promjenu velicine env u net.env
        self.setSceneRect(QtCore.QRectF(0, -self.envY, self.envX, self.envY))
    
    def change_node_env_y(self):
        self.envY = self.spinEnvY.value()
        #TODO: dodati promjenu velicine env u net.env
        self.setSceneRect(QtCore.QRectF(0, -self.envY, self.envX, self.envY))
    
    def change_channel_type(self):
        if self.comboChannelType.currentIndex() == 0:
            self.net.channelType = pymote.channeltype.Udg(self.net.environment)            
        elif self.comboChannelType.currentIndex() == 1:
            self.net.channelType = pymote.channeltype.SquareDisc(self.net.environment)
        if not self.f_opening_net and self.f_auto_edge:
            self.delete_all_edges()
            self.net.recalculate_edges()
            self.draw_all_edges()
            
    def draw_net(self, net):
        self.ini_scene()
        self.net = net
        self.f_opening_net = True
        max_id = 0        
        
        for net_node in net:
            node = self.draw_node(net.pos[net_node][0], net.pos[net_node][1], net_node.id, net_node.commRange, net_node) 
            self.net_dict[net_node] = node
            if net_node.id > max_id:
                max_id = net_node.id
                
        self.curr_id = max_id + 1
        
        self.draw_all_edges()
        
        self.environment = net.environment
        img = Image.fromarray(net.environment.im[::-1, :], 'L')
        img.save('env.png')
        self.draw_env('env.png')
        
        combo_index = -1 
        if isinstance(net.channelType, pymote.channeltype.Udg):
            combo_index = 0
        elif isinstance(net.channelType, pymote.channeltype.SquareDisc):
            combo_index = 1
            
        self.comboChannelType.setCurrentIndex(combo_index)
        self.f_opening_net = False
                
    def draw_node(self, x, y, node_id, comm_range, net_node):
        node_label = Label(str(node_id), x, -y)
        self.addItem(node_label)
        
        node = Node(x - self.node_size/2, -y - self.node_size/2, self.node_size, node_id, node_label, comm_range, net_node)        
        node.setBrush(self.node_color)
        self.addItem(node)
        
        return node

    def draw_edge(self, node1, node2):
        edge = Edge(node1, node2)
        self.addItem(edge)
        
        node1.add_edge_to_list(edge)
        node2.add_edge_to_list(edge)
        
        return edge
    
    def draw_all_edges(self):
        net = self.net
        edges = list()
        for net_node in self.net:
            for n in net.adj[net_node].keys():
                f_draw_edge = True
                for e in edges: #check if edge already drawn
                    if (e[0] == net_node.id and e[1] == n.id) or (e[1] == net_node.id and e[0] == n.id):
                        f_draw_edge = False
                
                if f_draw_edge:
                    node = self.net_dict[net_node]
                    adj_node = self.net_dict[n]
                    self.draw_edge(node, adj_node)
                    edges.append((net_node.id, n.id))
                    
    def delete_all_edges(self):
        for item in self.items():
                if isinstance(item, Edge):
                    self._delete_edge(item, True)
                    
    def draw_recalc_edges(self, net_node):
        node = self.net_dict[net_node]
        
        for n in self.net.adj[net_node].keys():
            adj_node = self.net_dict[n]
            self.draw_edge(node, adj_node)
            
    def open_env(self):
        filters = ['Environment image (*.png)', 'All files (*)']
        selectedFilter = 'Environment image (*.png)'
        filters = ';;'.join(filters)

        fname = QFileDialog.getOpenFileName(
            self.parent(), "Choose a file to open", '', filters, selectedFilter)
        
        if fname:
            try:                
                self.environment.__init__(path = str(fname))
                self.net.environment = self.environment
                self.draw_env(fname)
            except Exception as e:
                print ("Error opening file %s" % str(e)),
                QMessageBox.critical(
                    self, "Error opening file", str(e),
                    QMessageBox.Ok, QMessageBox.NoButton)
    
    def draw_env(self, image):
        if self.scene_env == 0:    
            self.scene_env = QGraphicsPixmapItem()
        else:
            self.removeItem(self.scene_env)
        
        self.scene_env.setPixmap(QPixmap(image))
        
        if self.scene_env != 0:
            self.scene_env.setPos(0, -self.environment.im.shape[1])
        
        self.addItem(self.scene_env)
        self.scene_env.setZValue(-1)
            
        if not self.f_show_env:
            self.scene_env.hide()
        
        self.spinEnvX.setValue(self.environment.im.shape[0])
        self.spinEnvY.setValue(self.environment.im.shape[1])
            
        if self.f_auto_edge:
            self.delete_all_edges()
            self.net.recalculate_edges()
            self.draw_all_edges()
        
    def delete_env(self):
        if self.scene_env != 0:
            self.scene_env.hide()
    
    def option_change(self):
        if self.radius != 0:
            self.delete_radius()
        if self.edge_option != 0:
            self.edge_option = 0
            self.deselect_node()
        if self.last_pressed_node != 0:
            self.deselect_node()
    
    def move_node(self):
        self.option_change()
        self.option = 0    
    
    def add_node(self):
        self.option_change()
        self.option = 1
    
    def _add_node(self, x, y):        
        #add node to network
        net_node = pymote.Node()
        self.net.add_node(net_node, (x, y))
        net_node.id = self.curr_id
        net_node.commRange = self.comm_range
        
        #add node to scene
        node = self.draw_node(x, y, self.curr_id, self.comm_range, net_node)
        self.net_dict[net_node] = node
        
        self.curr_id = self.curr_id + 1
        
        '''when adding new node to network pymote calls recalculate_edges,
        if USE MODEL OF COMMUNICATON TO AUTO EDGES is not selected
        then we need to remove those edges'''
        if not self.f_auto_edge:
            self.net.adj[net_node].clear()
            for n in self.net:
                if self.net.adj[n].has_key(net_node):
                    del self.net.adj[n][net_node]
        else:
            self.draw_recalc_edges(net_node)
        
    def delete_node(self):
        self.option_change()
        self.option = 2
    
    def _delete_node(self, node):  
        #delete node edges from scene
        edges = list()
        for edge in node.edges:
            edges.append(edge)
            
        for edge in edges:
            self._delete_edge(edge, False)
            
        self.removeItem(node)
        self.removeItem(node.node_label)
        
        #delete node from network
        self.net.remove_node(node.net_node)
        del self.net_dict[node.net_node] 
        
    def add_edge(self):
        self.option_change()
        self.option = 3
            
    def _add_edge(self, pressed_node):
        if pressed_node != 0:
            if self.edge_option == 0:
                self.select_node(pressed_node)
                self.edge_option = 1
              
            if self.edge_option == 1 and self.last_pressed_node != pressed_node and self.last_pressed_node != 0:                   
                self.edge_option = 2
                edge_exists = self.find_edge(pressed_node, self.last_pressed_node)
                if edge_exists != 0: 
                    self.edge_option = 0 
                    self.deselect_node()
                        
            if self.edge_option == 2:
                self.draw_edge(self.last_pressed_node, pressed_node)
                self.edge_option = 0
                
                #add edge to net.adj            
                node1, node2 = self.get_nodes_from_net(self.last_pressed_node, pressed_node)
                if node1 != 0 and node2 != 0:            
                    self.net.adj[node1][node2] = []
                    self.net.adj[node2][node1] = []
                
                self.deselect_node()
                
        elif pressed_node == 0 and self.edge_option == 1:
            self.edge_option = 0
            self.deselect_node()
    
    def delete_edge(self):
        self.option_change()
        self.option = 4
            
    def _delete_edge(self, edge, f_recal_called):
        n1 = edge.node1
        n2 = edge.node2
        
        n1.remove_edge_from_list(edge)
        n2.remove_edge_from_list(edge)
        self.removeItem(edge)
        
        #delete edge from net.adj
        if not f_recal_called:
            node1, node2 = self.get_nodes_from_net(n1, n2)    
            if node1 != 0 and node2 != 0:
                self.delete_edge_from_adj(node1, node2)
                self.delete_edge_from_adj(node2, node1)
    
    def get_nodes_from_net(self, n1, n2):
        node1 = 0
        node2 = 0
        for n in self.net:
            if n.id == n1.node_id: 
                node1 = n
            if n2 != 0:
                if n.id == n2.node_id:
                    node2 = n
        return (node1, node2)
    
    def delete_edge_from_adj(self, node, del_n):
        del self.net.adj[node][del_n]
            
    def find_edge(self, node, n):
        for e in node.edges:
            if (n.get_X() == e.line().x1() and n.get_Y() == e.line().y1()) or (n.get_X() == e.line().x2() and n.get_Y() == e.line().y2()):
                return e
        return 0
    
    def select_node(self, node):
        self.last_pressed_node = node
        node.setBrush(self.pressed_color)
        
        if self.option == 0:
            self.show_pressed_item_data()
            
            if self.f_show_radius:
                self.draw_radius(node.get_X() + self.node_size/2, node.get_Y() + self.node_size/2, self.last_pressed_node.comm_range)
        
    def deselect_node(self):
        self.last_pressed_node.setBrush(self.node_color)
        self.last_pressed_node = 0
        
        self.hide_pressed_item_data()
        
        if self.radius != 0:
            self.delete_radius()
    
    def move_edges(self, node, x, y):
        for edge in node.edges:
            if edge.line().x1() == node.get_X() and edge.line().y1() == node.get_Y():
                edge.setLine(x, y, edge.line().x2(), edge.line().y2())
            else:
                edge.setLine(edge.line().x1(), edge.line().y1(), x, y)
        
    def mousePressEvent(self, e):
        mouseX = e.scenePos().x()
        mouseY = -e.scenePos().y()
        
        pressed_node = 0
        pressed_edge = 0
        
        self.f_move = True
        
        for item in self.items(e.scenePos()):
            if pressed_node == 0 and isinstance(item, Node):
                pressed_node = item
            if pressed_edge == 0 and isinstance(item, Edge):
                pressed_edge = item
        
        #on new mouse press deselect last node (only if option add edge is not selected)
        if self.last_pressed_node != 0:
            if self.edge_option != 1:
                self.deselect_node()
        
        if self.option == 1: #draw node
            self._add_node(mouseX, mouseY)
        
        elif self.option == 2: #delete node
            if pressed_node != 0:
                self._delete_node(pressed_node)
    
        elif self.option == 3: #add edge  
            self._add_edge(pressed_node)
                                
        elif self.option == 4: #delete edge
            if pressed_edge != 0:
                self._delete_edge(pressed_edge, False)
        
        #select new pressed node and save it
        if pressed_node != 0:
            if self.option == 0:
                self.select_node(pressed_node)
                self.spinCommRange.setValue(pressed_node.comm_range)
        else:
            self.last_pressed_node = 0
    
    def mouseMoveEvent(self, e):
        mouseX = e.scenePos().x()
        mouseY = e.scenePos().y()
        
        self.lblXY.setText('x: ' + str(mouseX) + '  y: ' + str(-mouseY))
        
        if self.last_pressed_node != 0 and self.f_move:
            node = self.last_pressed_node
            self.f_moved = True
            
            if self.option == 0:
                #when moving node, move his edges
                if not self.f_auto_edge:
                    self.move_edges(node, mouseX, mouseY)
                    
                #move node
                node.setX(mouseX - node.get_iniX())
                node.setY(mouseY - node.get_iniY())
                node.node_label.setPos(mouseX, mouseY)
                
                net_node, n = self.get_nodes_from_net(node, 0)
                self.net.pos[net_node][0] = mouseX
                self.net.pos[net_node][1] = -mouseY
                
                if self.f_auto_edge:
                    edges = list()
                    for edge in node.edges:
                        edges.append(edge)
                        
                    for edge in edges:
                        self._delete_edge(edge, True)
                
                self.spinX.setValue(mouseX)
                self.spinY.setValue(-mouseY)
                
        #move radius
        if self.f_show_radius and (self.option == 1 or (self.option == 0 and self.last_pressed_node != 0 and self.f_move)):
            if self.radius == 0 and self.option == 1:
                self.draw_radius(mouseX, mouseY, self.comm_range)
            elif self.radius != 0:
                self.radius.setX(mouseX - self.radius.get_iniX())
                self.radius.setY(mouseY - self.radius.get_iniY())
        
    def mouseReleaseEvent(self, e):        
        if self.f_auto_edge and self.last_pressed_node != 0 and self.option == 0 and self.f_moved:
            self.net.recalculate_edges([self.last_pressed_node.net_node])
            self.draw_recalc_edges(self.last_pressed_node.net_node)
            
        self.f_move = False
        self.f_moved = False