Example #1
0
 def result(self):
     ch = 0
     w = 0
     for i in self.wordslist:
         if ch >= self.countlength:
             break
         ch += len(i)
         w += 1
     print(w)
     print(self.countlength)
     print(ch)
     clearLayout(self.lay)
     tosend = []
     self.time = time() - self.firtime
     h = round(self.time)
     self.time = self.time / 60
     self.time = round(w / self.time)
     tosend.append(self.time)
     tosend.append(self.name)
     h = str(h) + ' seconds'
     tosend.append(h)
     self.errorcount = str(self.errorcount) + ' errors'
     tosend.append(self.errorcount)
     QSound.play(self.success)
     self.socket.sendall(pickle.dumps(tosend))
     ss = []
     for i in tosend:
         i = str(i)
     label = QLabel('  '.join(ss))
     label2 = QLabel('Wait for others, it may take maximum 30 sec')
     self.lay.addWidget(label)
     self.lay.addWidget(label2)
     self.typing = []
Example #2
0
 def sec(self):
     text1 = self.editline.text()
     if len(self.before) < len(text1):
         if text1[-1] == self.mainlist[0]:
             self.counter += 1
             typed = self.typing[:self.counter]
             future = self.typing[self.counter:]
             text = '''<font color='blue' size=8>{}</font>
                       <font size=8>{}</font>'''.format(typed, future)
             self.textline.setText(text)
             if self.mainlist[0] == ' ':
                 self.editline.setText('')
                 self.before = ''
             else:
                 self.countlength += 1
                 self.before = text1
             self.mainlist = self.mainlist[1:]
             if not len(self.mainlist):
                 self.result()
         else:
             self.errorcount += 1
             self.before = text1
             QSound.play(self.success)
     else:
         self.before = text1
 def keyPressEvent(self, e):
     upperText = e.text().upper()
     if QApplication.focusWidget().accessibleName() == 'citationCodeEdit':
         if upperText in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
             QSound.play("sounds/" + upperText + ".wav")
     newEvent = QKeyEvent(QEvent.KeyPress, e.key(), e.modifiers(), text=upperText)
     return super(CodeLineEdit, self).keyPressEvent(newEvent)
    def __init__(self, collection=None, currentPuzzleIndex=-1, parent=None):
        print('Initializing AddEditPuzzle')
        super(AddEditPuzzle, self).__init__(parent)

        # Turn off the context help button (The ? in the title bar.)
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)

        self._collection = collection
        self._currentPuzzleIndex = currentPuzzleIndex
        self._puzzles = collection.puzzles()
        self._puzzleWords = {}                  # used to compare lengths of words puzzleCode and puzzleSolution
        self._codeKeys = {}                     # used to make sure the code is consistent throughout the puzzle
        self._errorSound = QSound('sounds/error-01.wav')
        self.codeKeys = {}
        self.puzzleWords = {}

        self.setupUI()
        self.puzzleCodeEdit.installEventFilter(self)
        self.citationCodeEdit.installEventFilter(self)
        self.puzzleSolutionEdit.installEventFilter(self)
        self.citationSolutionEdit.installEventFilter(self)

        if self._currentPuzzleIndex >= 0:
            self.setPuzzleSelector(self._currentPuzzleIndex)
            self._mode = "Edit"
        else:
            self._mode = None
    def __init__(self, *, taskModel, frontendSettings, parent):
        super().__init__(parent)
        self.__taskModel = taskModel
        self.__frontendSettings = frontendSettings
        self._conn = QDBusConnection("Xware Desktop").sessionBus()

        self._interface = QDBusInterface(_DBUS_NOTIFY_SERVICE, _DBUS_NOTIFY_PATH, _DBUS_NOTIFY_INTERFACE, self._conn)

        self._notified = {}  # a dict of notifyId: taskDict
        self.__taskModel.taskCompleted.connect(self.notifyTaskCompleted, Qt.DirectConnection)

        self._capabilities = self._getCapabilities()
        if "actions" in self._capabilities:
            successful = self._conn.connect(
                _DBUS_NOTIFY_SERVICE, _DBUS_NOTIFY_PATH, _DBUS_NOTIFY_INTERFACE, "ActionInvoked", self.slotActionInvoked
            )
            if not successful:
                logging.error("ActionInvoked connect failed.")

        self._qSound_complete = QSound(":/sound/download-complete.wav", self)
Example #6
0
    def __init__(self, parent):
        super().__init__(parent)
        self._conn = QDBusConnection("Xware Desktop").sessionBus()

        self._interface = QDBusInterface(_DBUS_NOTIFY_SERVICE,
                                         _DBUS_NOTIFY_PATH,
                                         _DBUS_NOTIFY_INTERFACE,
                                         self._conn)

        self._notifications = {}
        self._completedTasksStat = app.etmpy.completedTasksStat
        self._completedTasksStat.sigTaskCompleted.connect(self.notifyTask)

        successful = self._conn.connect(_DBUS_NOTIFY_SERVICE,
                                        _DBUS_NOTIFY_PATH,
                                        _DBUS_NOTIFY_INTERFACE,
                                        "ActionInvoked", self.slotActionInvoked)
        if not successful:
            logging.error("ActionInvoked connect failed.")

        self._qSound_complete = QSound(":/sound/download-complete.wav", self)
    def runWithArguments(self, arguments):
        for _context in self.contexts:
            if _context.isActive():
                return

        argValues = processArguments(arguments)
        delay = argValues["delay"]

        self._sound = QSound(SOUND_FILE)
        self._sound.setLoops(1)

        context = AppContext(argValues)
        context.settings = self._createContextSettings()
        context.finished.connect(self._contextFinished)
        context.needSound.connect(self._contextNeedSound)
        context.needOSD.connect(self._contextNeedOSD)
        self.contexts.append(context)

        if delay > 0:
            notificationsInterface.notify(_("Deepin Screenshot"),
            _("Deepin Screenshot will start after %s seconds.") % delay)

        QTimer.singleShot(max(0, delay * 1000), context.main)
class main(QtWidgets.QOpenGLWidget):
    # Cria as variaveis necessarias
    # self.started = Indica se o jogo foi iniciado ou nao
    # self.in_scene = Vetor para a cena (tudo que faz parte do jogo e sera desenhado)
    # self.ornaments = Vetor para a beleza da cena (tudo que sao apenas "flores")
    #
    # Temporizadores
    # self.elapsed_time_shoot = Tempo desde o ultimo tiro do player
    # self.elapsed_time_asteroide = Tempo desde o ultimo asteroide criado
    # self.elapsed_time_inimigo = Tempo desde o ultimo inimigo criado
    # self.elapsed_time_flower = Tempo desde a ultima flor criada
    # self.elapsed_time_planet = Tempo desde o ultimo planeta criado
    # self.elapsed_time_stars = = Tempo desde a ultima estrela criada
    #
    # Sons
    # self.sound_laser = Tiro do player
    # self.sound_laser_enemy = Tiro do inimigo
    # self.sound_explosion = Explosao
    # self.sound_1000pts = 1000 pontos alcancados
    # self.sound_inGame = Fundo do jogo
    # self.sound_death = Morte
    #
    # Filas para pre carregamento dos objetos
    # self.enemy_queue = Fila dos inimigos
    # self.asteroid_queue = Fila dos Asteroides
    # self.bullets_queue = Fila das balas
    # self.flowers_queue = Fila das flores
    # self.planets_queue = Fila dos planetas
    # self.explosion_queue = Fila das explosoes
    # self.propellant_queue = Fila dos propulsores
    #
    # Variaveis para pre carregamento das texturas
    # self.animation_explosion
    # self.animation_propellant_enemy
    # self.img_nave_azul
    # self.img_nave_amarela
    # self.img_nave_preta
    # self.img_tiro_azul
    # self.img_tiro_preto
    # self.img_tiro_amarelo
    # self.img_tiro
    # self.logo_init
    # self.logo_end
    # self.imageID_back
    # self.myLogo_i = Logo()
    # self.myLogo_e = Logo()
    #
    # self.myNave = Nave do jogador
    def __init__(self, parent):
        QtWidgets.QOpenGLWidget.__init__(self, parent)
        self.started = False
        self.imageID_back = None
        self.in_scene = []
        self.ornaments = []
        self.elapsed_time_shoot = 0
        self.elapsed_time_asteroide = 0
        self.elapsed_time_inimigo = 0
        self.elapsed_time_flower = 500000000000 / 2
        self.elapsed_time_planet = 920000000000 / 3
        self.elapsed_time_stars = 0
        self.elapsed_time_powers = 0
        self.elapsed_time_power_shoot = 0
        self.elapsed_time_power_speed = 0
        self.hack = False
        self.speed = False
        self.sound_laser = QSound("sound/laser.wav", self)
        self.sound_laser_enemy = QSound("sound/laserenemy.wav", self)
        self.sound_explosion = QSound("sound/explos.wav", self)
        self.sound_1000pts = QSound("sound/1000pts.wav", self)
        self.sound_inGame = QSound("sound/startScene.wav", self)
        self.sound_death = QSound("sound/nooo.wav", self)
        self.sound_power = QSound("sound/powerUp.wav", self)
        self.enemy_queue = Queue_rotative()
        self.asteroid_queue = Queue_rotative()
        self.bullets_queue = Queue_rotative()
        self.flowers_queue = Queue_rotative()
        self.planets_queue = Queue_rotative()
        self.explosion_queue = Queue_rotative()
        self.propellant_queue = Queue_rotative()
        self.power_queue = Queue_rotative()
        self.animation_explosion = [None for i in range(EXPLOSION_FRAMES)]
        self.animation_propellant_enemy = [
            None for i in range(PROPELLANT_FRAMES)
        ]
        self.img_planets = [None for i in range(10)]
        self.img_nave_azul = None
        self.img_nave_amarela = None
        self.img_nave_preta = None
        self.img_tiro_azul = None
        self.img_tiro_preto = None
        self.img_tiro_amarelo = None
        self.img_tiro = None
        self.logo_init = None
        self.logo_end = None
        self.power_up_vida = None
        self.power_up_shoot = None
        self.power_up_speed = None
        self.myLogo_i = Logo()
        self.myLogo_e = Logo()
        self.myNave = None

    # Inicializa as filas de pre carregamentos
    def init_queue(self):

        for i in range(20):
            new = Enemy()
            self.enemy_queue.push(new)

        for i in range(50):
            new = Asteroide()
            self.asteroid_queue.push(new)

        for i in range(100):
            new = Shoot()
            self.bullets_queue.push(new)

        for i in range(10):
            new = Flor()
            self.flowers_queue.push(new)

        for i in range(10):
            new = Planeta()
            self.planets_queue.push(new)

        for i in range(50):
            new = Explode()
            self.explosion_queue.push(new)

        for i in range(30):
            new = Propellant()
            self.propellant_queue.push(new)

        for i in range(20):
            new = Power_up()
            self.power_queue.push(new)

    # Prepara a cena e carrega as texturas
    def initializeGL(self):
        glClearColor(0.0, 0.0, 0.0, 0.0)
        glShadeModel(GL_SMOOTH)

        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        glEnable(GL_ALPHA_TEST)
        glAlphaFunc(GL_NOTEQUAL, 0.0)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(-50.0, 50.0, -50.0, 50.0, -1, 1)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        self.myNave = Nave(self.animation_propellant_enemy, 0)
        self.in_scene.append(self.myNave)

        self.imageID_back = self.loadImage("img/Background.png")

        for i in range(EXPLOSION_FRAMES):
            self.animation_explosion[i] = self.loadImage("img/explosion/Comp" +
                                                         str(i) + ".png")

        for i in range(PROPELLANT_FRAMES):
            self.animation_propellant_enemy[i] = self.loadImage(
                "img/fire/Comp" + str(i) + ".png")

        for i in range(10):
            self.img_planets[i] = self.loadImage("img/planets/planeta" +
                                                 str(i) + ".png")

        self.img_nave_amarela = self.loadImage("img/nave4.png")
        self.img_nave_azul = self.loadImage("img/nave1.png")
        self.img_nave_preta = self.loadImage("img/nave3.png")
        self.img_tiro_amarelo = self.loadImage("img/nave4_pow.png")
        self.img_tiro_preto = self.loadImage("img/nave3_pow.png")
        self.img_tiro_azul = self.loadImage("img/nave1_pow.png")
        self.img_tiro = self.loadImage("img/nave2_pow.png")
        self.logo_init = self.loadImage("img/SpaceCute.png")
        self.logo_end = self.loadImage("img/YouDied.png")
        self.power_up_vida = self.loadImage("img/power_up_life.png")
        self.power_up_shoot = self.loadImage("img/power_up_shot.png")
        self.power_up_speed = self.loadImage("img/power_up_speed.png")

        self.myLogo_i.load("inicio", self.logo_init, self.logo_end)
        self.ornaments.append(self.myLogo_i)
        self.myLogo_i.inited = True

        self.myLogo_e.load("fim", self.logo_init, self.logo_end)

        self.init_queue()

        # Arrumando erros de frict
        fix_p = self.propellant_queue.pop()
        fix_p.load(self.animation_propellant_enemy, 70, 70, "fix")
        self.ornaments.append(fix_p)

        new_explosion = self.explosion_queue.pop()
        new_explosion.load(self.animation_explosion, 70, 70, "fix")
        self.ornaments.append(new_explosion)

    # Funcao para carregar imagens a partir de um caminho
    def loadImage(self, path):
        im = Image.open(path)

        ix, iy, image = im.size[0], im.size[1], im.tobytes()

        ID = glGenTextures(1)
        glBindTexture(GL_TEXTURE_2D, ID)
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA,
                     GL_UNSIGNED_BYTE, image)
        return ID

    # funcoes para acoes no teclado
    # A = move para esquerda
    # D = move para direita
    # W = atira
    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Left:
            self.myNave.moving_left = True
        if event.key() == QtCore.Qt.Key_A:
            self.myNave.moving_left = True

        if event.key() == QtCore.Qt.Key_Right:
            self.myNave.moving_right = True
        if event.key() == QtCore.Qt.Key_D:
            self.myNave.moving_right = True

        if event.key() == QtCore.Qt.Key_Up:
            self.myNave.shooting = True
        if event.key() == QtCore.Qt.Key_W:
            self.myNave.shooting = True

        # if event.key() == QtCore.Qt.Key_T:
        #     self.hack = True

    def keyReleaseEvent(self, event):
        if event.key() == QtCore.Qt.Key_Left:
            self.myNave.moving_left = False
        if event.key() == QtCore.Qt.Key_A:
            self.myNave.moving_left = False

        if event.key() == QtCore.Qt.Key_Right:
            self.myNave.moving_right = False
        if event.key() == QtCore.Qt.Key_D:
            self.myNave.moving_right = False

        if event.key() == QtCore.Qt.Key_Up:
            self.myNave.shooting = False
        if event.key() == QtCore.Qt.Key_W:
            self.myNave.shooting = False

        if event.key() == QtCore.Qt.Key_T:
            self.hack = False

    # Funcao de desenhar a cena
    def paintGL(self):

        # Checa se a musica de fundo acabou e reinicia
        self.check_end_backm()
        self.update()
        # Se o player morreu, entao o jogo acaba
        if self.myNave.dead:
            self.started = False

        glClear(GL_COLOR_BUFFER_BIT)
        glLoadIdentity()

        # Desenha o background
        ''''' Inicio do background ''' ''
        glColor3f(1.0, 1.0, 1.0)
        glDisable(GL_LIGHTING)
        glEnable(GL_TEXTURE_2D)

        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE)
        glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)

        glBindTexture(GL_TEXTURE_2D, self.imageID_back)

        glPushMatrix()

        glBegin(GL_QUADS)
        glTexCoord2f(0, 1)
        glVertex3f(50, -50, 1)
        glTexCoord2f(1, 1)
        glVertex3f(-50, -50, 1)
        glTexCoord2f(1, 0)
        glVertex3f(-50, 50, 1)
        glTexCoord2f(0, 0)
        glVertex3f(50, 50, 1)
        glEnd()

        glPopMatrix()
        glDisable(GL_TEXTURE_2D)
        ''''' Fim do background ''' ''

        self.update_time()
        self.spawn_flowers()
        self.spawn_planets()
        self.spawn_stars()

        # Desenha os ornamentos ( "Flores" )
        # e retira os objetos "mortos" retornando eles para a fila
        for obj in self.ornaments:
            if not obj == None:
                if obj.dead:
                    if isinstance(obj, Flor):
                        self.flowers_queue.push(obj)
                        self.ornaments.remove(obj)
                    elif isinstance(obj, Planeta):
                        self.planets_queue.push(obj)
                        self.ornaments.remove(obj)
                    elif isinstance(obj, Star):
                        self.ornaments.remove(obj)
                    elif isinstance(obj, Explode):
                        self.explosion_queue.push(obj)
                        self.ornaments.remove(obj)
                    elif isinstance(obj, Propellant):
                        self.propellant_queue.push(obj)
                        self.ornaments.remove(obj)
                obj.draw()
                obj.act()
                obj.check_dead()

        # print (self.enemy_queue.tam())
        # Verifica se o jogo foi iniciado
        if (not self.started):
            return

        # Desenha a cena
        # e retira os objetos mortos retornando ele para a fila
        # e instancia uma explosao no lugar
        for obj in self.in_scene:
            if not obj == None:
                if obj.dead:
                    if isinstance(obj, Enemy):
                        new_explosion = self.explosion_queue.pop()
                        new_explosion.load(self.animation_explosion,
                                           obj.move_x + obj.position_x,
                                           obj.move_y + 6, "enemy")
                        self.in_scene.append(new_explosion)
                        self.enemy_queue.push(obj)
                        self.in_scene.remove(obj)
                    elif isinstance(obj, Asteroide):
                        new_explosion = self.explosion_queue.pop()
                        new_explosion.load(self.animation_explosion,
                                           obj.move_x + obj.position_x,
                                           obj.move_y + 5, "enemy")
                        self.in_scene.append(new_explosion)
                        self.asteroid_queue.push(obj)
                        self.in_scene.remove(obj)
                    elif isinstance(obj, Shoot):
                        self.bullets_queue.push(obj)
                        self.in_scene.remove(obj)
                    elif isinstance(obj, Explode):
                        obj.dead = False
                        self.explosion_queue.push(obj)
                        self.in_scene.remove(obj)
                    elif isinstance(obj, Power_up):
                        self.power_queue.push(obj)
                        self.in_scene.remove(obj)
                if isinstance(obj, Nave):
                    if obj.shooting:
                        self.create_shoot(obj.move_x + obj.position_x)
                obj.draw()
                obj.act()
                obj.check_dead()

        # Testa as colisoes e aplica os efeitos (ganhar pontos, ou perder vida)
        for obj_A in self.in_scene:
            if isinstance(obj_A, Asteroide):
                for obj_B in self.in_scene:
                    if not (obj_A == obj_B):
                        if isinstance(obj_B, Nave) and self.collide(
                                obj_B, obj_A):
                            ui.down_life()
                            obj_A.dead = True
                        elif isinstance(obj_B, Shoot) and self.collide(
                                obj_B, obj_A):
                            if not obj_B.is_enemy:
                                obj_A.dead = True
                                if not self.hack:
                                    obj_B.dead = True
                                self.sound_explosion.play()
                                ui.up_point(10)
                                if ui.score % 1000 == 0:
                                    self.sound_1000pts.play()
            elif isinstance(obj_A, Enemy):
                obj_A.elapsed_shoot_time += time()
                if obj_A.elapsed_shoot_time >= SHOOT_TIME_ENEMY:
                    if obj_A.nave_type == 0:
                        self.create_shoot(obj_A.move_x + obj_A.position_x,
                                          obj_A.move_y, obj_A.move_y + 6, True,
                                          obj_A.nave_type, obj_A.shoot_type,
                                          self.img_tiro_azul)
                    elif obj_A.nave_type == 1:
                        self.create_shoot(obj_A.move_x + obj_A.position_x,
                                          obj_A.move_y, obj_A.move_y + 6, True,
                                          obj_A.nave_type, obj_A.shoot_type,
                                          self.img_tiro_amarelo)
                    elif obj_A.nave_type == 2:
                        self.create_shoot(obj_A.move_x + obj_A.position_x,
                                          obj_A.move_y, obj_A.move_y + 6, True,
                                          obj_A.nave_type, obj_A.shoot_type,
                                          self.img_tiro_preto)

                    obj_A.elapsed_shoot_time = 0
                for obj_B in self.in_scene:
                    if not (obj_A == obj_B):
                        if isinstance(obj_B, Nave) and self.collide(
                                obj_B, obj_A):
                            ui.down_life()
                            obj_A.dead = True
                        elif isinstance(obj_B, Shoot) and self.collide(
                                obj_B, obj_A):
                            if not obj_B.is_enemy:
                                obj_A.dead = True
                                if self.hack:
                                    obj_B.dead = False
                                else:
                                    obj_B.dead = True
                                self.sound_explosion.play()
                                ui.up_point(10)
                                if ui.score % 1000 == 0:
                                    self.sound_1000pts.play()
            elif isinstance(obj_A, Shoot):
                if obj_A.is_enemy:
                    for obj_B in self.in_scene:
                        if not (obj_A == obj_B):
                            if isinstance(obj_B, Nave) and self.collide(
                                    obj_B, obj_A):
                                ui.down_life()
                                obj_A.dead = True
            elif isinstance(obj_A, Nave):
                if self.speed:
                    obj_A.speed = 3
                else:
                    obj_A.speed = 0
                for obj_B in self.in_scene:
                    if not (obj_A == obj_B):
                        if isinstance(obj_B, Power_up) and self.collide(
                                obj_B, obj_A):
                            obj_B.dead = True
                            self.sound_power.play()
                            if obj_B.skin == 0:
                                ui.up_life()
                            elif obj_B.skin == 1:
                                self.hack = True
                                self.elapsed_time_power_shoot = 0
                            elif obj_B.skin == 2:
                                self.speed = True
                                self.elapsed_time_power_speed = 0

        self.spawn_asteroide()
        self.spawn_inimigos()
        self.spawn_powers()
        self.update()

    # Checa se a musica de fundo acabou e reinicia caso positivo
    def check_end_backm(self):
        if self.sound_inGame.isFinished():
            self.sound_inGame.play()

    # Atualiza o tempo dos temporizadores
    def update_time(self):
        self.elapsed_time_shoot += time()
        self.elapsed_time_asteroide += time()
        self.elapsed_time_inimigo += time()
        self.elapsed_time_flower += time()
        self.elapsed_time_planet += time()
        self.elapsed_time_stars += time()
        self.elapsed_time_powers += time()
        if self.hack:
            self.elapsed_time_power_shoot += time()
        if self.elapsed_time_power_shoot >= POWER_UP_SHOOT:
            self.hack = False
        if self.speed:
            self.elapsed_time_power_speed += time()
        if self.elapsed_time_power_speed >= POWER_UP_SPEED:
            self.speed = False

    # Faz a criacao das estrelas, com uma posicao e escala aleatoria
    def spawn_stars(self):
        if self.elapsed_time_stars >= SPAWN_TIME_STARS:
            position = randint(-49, 49)
            scale = self.rand_tam_star()
            new_star = Star(position, scale)
            self.ornaments.append(new_star)
            self.elapsed_time_stars = 0

    # Faz a criacao dos planetas, com uma posicao e escala aleatoria
    def spawn_planets(self):
        if self.elapsed_time_planet >= SPAWN_TIME_PLANET:
            position = randint(-50, 50)
            scale = self.rand_tam()
            new_planet = self.planets_queue.pop()
            new_planet.load(position, scale, self.img_planets)
            self.ornaments.append(new_planet)
            self.elapsed_time_planet = 0

    # Retorna um tamanho aleatorio para os planetas
    def rand_tam(self):
        return float(str(randint(0, 2)) + "." + str(randint(1, 5)))

    # Retorna um tamanho aleatorio para as estrelas
    def rand_tam_star(self):
        return float("0." + str(randint(1, 3)))

    # Faz a criacao das flores, com uma posicao aleatoria
    def spawn_flowers(self):
        if self.elapsed_time_flower >= SPAWN_TIME_FLOWER:
            position = randint(-50, 50)
            new_flower = self.flowers_queue.pop()
            new_flower.load(position)
            self.ornaments.append(new_flower)
            self.elapsed_time_flower = 0

    # Faz a criacao dos asteroides, com uma posicao aleatioria
    def spawn_asteroide(self):
        if self.elapsed_time_asteroide >= SPAWN_TIME:
            new_aste = self.asteroid_queue.pop()
            new_aste.load(randint(-49, 43))
            self.in_scene.append(new_aste)
            self.elapsed_time_asteroide = 0

    # Faz a criacao dos power ups, com uma posicao aleatioria
    def spawn_powers(self):
        if self.elapsed_time_powers >= POWER_UP_TIME:
            new_power = self.power_queue.pop()
            new_power.load(randint(-49, 43), 60, self.power_up_vida,
                           self.power_up_shoot, self.power_up_speed)
            self.in_scene.append(new_power)
            self.elapsed_time_powers = 0

    # Faz a criacao dos inimigos, com uma posicao aleatoria
    def spawn_inimigos(self):
        if self.elapsed_time_inimigo >= SPAWN_TIME_ENEMY:
            new_inimigo = self.enemy_queue.pop()
            new_inimigo.load(randint(-49, 43), self.animation_propellant_enemy,
                             self.img_nave_azul, self.img_nave_amarela,
                             self.img_nave_preta)
            self.in_scene.append(new_inimigo)
            self.elapsed_time_inimigo = 0

    # Funcao para criacao dos tiros, tanto dos inimigos quanto do player
    def create_shoot(self,
                     position,
                     position_y=None,
                     position_y_2=None,
                     is_enemy=False,
                     type="player",
                     qtd=None,
                     tiro_respectivo=None):
        if is_enemy:
            if qtd == 1:
                new_shoot = self.bullets_queue.pop()
                new_shoot.load(tiro_respectivo, position, position_y,
                               position_y_2, True, type)
                self.in_scene.append(new_shoot)
            elif qtd == 2:
                new_shoot = self.bullets_queue.pop()
                new_shoot.load(tiro_respectivo, position - 2.5, position_y,
                               position_y_2, True, type)
                new_shoot2 = self.bullets_queue.pop()
                new_shoot2.load(tiro_respectivo, position + 2.5, position_y,
                                position_y_2, True, type)
                self.in_scene.append(new_shoot)
                self.in_scene.append(new_shoot2)
            elif qtd == 3:
                new_shoot = self.bullets_queue.pop()
                new_shoot.load(tiro_respectivo, position - 5, position_y,
                               position_y_2, True, type)
                new_shoot2 = self.bullets_queue.pop()
                new_shoot2.load(tiro_respectivo, position, position_y,
                                position_y_2, True, type)
                new_shoot3 = self.bullets_queue.pop()
                new_shoot3.load(tiro_respectivo, position + 5, position_y,
                                position_y_2, True, type)
                self.in_scene.append(new_shoot)
                self.in_scene.append(new_shoot2)
                self.in_scene.append(new_shoot3)
            self.sound_laser_enemy.play()
            return
        if self.elapsed_time_shoot >= SHOOT_TIME:
            if self.hack:
                new_shoot = self.bullets_queue.pop()
                new_shoot.load(self.img_tiro, position + 5, -46.0, -40.0,
                               False, 1)
                new_shoot2 = self.bullets_queue.pop()
                new_shoot2.load(self.img_tiro, position - 5, -46.0, -40.0,
                                False, 1)
                new_shoot3 = self.bullets_queue.pop()
                new_shoot3.load(self.img_tiro, position, -46.0, -40.0, False,
                                1)
                self.in_scene.append(new_shoot)
                self.in_scene.append(new_shoot2)
                self.in_scene.append(new_shoot3)
                self.sound_laser.play()
            else:
                new_shoot = self.bullets_queue.pop()
                new_shoot.load(self.img_tiro, position, -46.0, -40.0, False, 1)
                self.in_scene.append(new_shoot)
                self.sound_laser.play()
            self.elapsed_time_shoot = 0

    # Checagem de colisao
    def collide(self, A, B):
        A_colliding_B_in_x = (A.get_x()[1] >= B.get_x()[0]
                              and A.get_x()[1] <= B.get_x()[1])
        #or
        B_colliding_A_in_x = (B.get_x()[1] >= A.get_x()[0]
                              and B.get_x()[1] <= A.get_x()[1])

        A_colliding_B_in_y = (A.get_y()[1] >= B.get_y()[0]
                              and A.get_y()[1] <= B.get_y()[1])
        #or
        B_colliding_A_in_y = (B.get_y()[1] >= A.get_y()[0]
                              and B.get_y()[1] <= A.get_y()[1])

        return (A_colliding_B_in_x or B_colliding_A_in_x) and \
               (A_colliding_B_in_y or B_colliding_A_in_y)

    def active_hack(self):
        self.hack = not self.hack

    # Reinicia o jogo, seta todas as variaveis para o inicio
    def reestart(self):
        self.reloc()
        self.started = False
        self.player_move_left = False
        self.player_move_right = False
        self.myNave = Nave(self.animation_propellant_enemy, 0)
        self.elapsed_time_shoot = 0
        self.elapsed_time_asteroide = 0
        self.elapsed_time_inimigo = 0
        self.hack = False
        self.in_scene = []
        self.in_scene.append(self.myNave)
        self.sound_inGame.stop()
        self.sound_inGame = QSound("sound/inGame.wav", self)
        self.sound_inGame.play()
        if self.myLogo_i.inited:
            self.ornaments.remove(self.myLogo_i)
            self.myLogo_i.inited = False
        if self.myLogo_e.inited:
            self.ornaments.remove(self.myLogo_e)
            self.myLogo_e.inited = False

    # Realoca os objetos atualmente na cena para suas respectivas filas
    def reloc(self):
        for obj in self.in_scene:
            if isinstance(obj, Enemy):
                self.enemy_queue.push(obj)
                self.in_scene.remove(obj)
            elif isinstance(obj, Asteroide):
                self.asteroid_queue.push(obj)
                self.in_scene.remove(obj)
            elif isinstance(obj, Shoot):
                self.bullets_queue.push(obj)
                self.in_scene.remove(obj)
            elif isinstance(obj, Explode):
                self.explosion_queue.push(obj)
                self.in_scene.remove(obj)
            elif isinstance(obj, Power_up):
                self.power_queue.push(obj)
                self.in_scene.remove(obj)

        for obj in self.ornaments:
            if isinstance(obj, Flor):
                self.flowers_queue.push(obj)
                self.ornaments.remove(obj)
            elif isinstance(obj, Planeta):
                self.planets_queue.push(obj)
                self.ornaments.remove(obj)

    # Para o jogo
    def stop(self):
        self.reloc()
        self.started = False
        self.sound_inGame.stop()
        self.sound_inGame = QSound("sound/startScene.wav", self)
        self.sound_inGame.play()
        self.in_scene = []
        self.ornaments.append(self.myLogo_i)
        if self.myLogo_e.inited:
            self.ornaments.remove(self.myLogo_e)
            self.myLogo_e.inited = False
        self.myLogo_i.inited = True

    #  Quando o jogador morre
    def dead(self):
        self.reloc()
        self.myNave.dead = True
        self.sound_inGame.stop()
        self.sound_inGame = QSound("sound/gameOver.wav", self)
        self.sound_death.play()
        if self.sound_death.isFinished():
            self.sound_inGame.play()
        self.ornaments.append(self.myLogo_e)
        self.myLogo_e.inited = True
Example #9
0
class CrawlWindow(QWidget):
    def __init__(self):
        super(CrawlWindow, self).__init__()
        self.resize(800, 600)
        self.setWindowTitle('猫眼Top100电影爬取软件')
        self.setWindowIcon(QIcon(':res/maoyan.png'))

        self.start_btn = QPushButton(self)
        self.stop_btn = QPushButton(self)
        self.save_combobox = QComboBox(self)
        self.table = QTableWidget(self)
        self.log_browser = QTextBrowser(self)
        self.progressbar = QProgressBar(self)

        self.h_layout = QHBoxLayout()
        self.v_layout = QVBoxLayout()

        self.crawl_thread = CrawlThread()
        self.db = None
        self.btn_sound = QSound(':res/btn.wav', self)
        self.finish_sound = QSound(':res/finish.wav', self)

        self.btn_init()
        self.combobox_init()
        self.table_init()
        self.progressbar_init()
        self.layout_init()
        self.crawl_init()
        self.db_connect()

    def btn_init(self):
        self.start_btn.setText('开始爬取')
        self.stop_btn.setText('停止爬取')
        self.stop_btn.setEnabled(False)

        self.start_btn.clicked.connect(lambda: self.btn_slot(self.start_btn))
        self.stop_btn.clicked.connect(lambda: self.btn_slot(self.stop_btn))

    def combobox_init(self):
        save_list = ['另存到', 'MySQL', 'csv', 'txt', 'json']
        self.save_combobox.addItems(save_list)
        self.save_combobox.setEnabled(False)

        self.save_combobox.currentTextChanged.connect(self.combobox_slot)  # 1

    def table_init(self):
        self.table.setColumnCount(5)
        self.table.setHorizontalHeaderLabels(
            ['图片链接', '电影名称', '主演人员', '上映时间', '电影评分'])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

    def progressbar_init(self):
        self.progressbar.setRange(0, 100)
        self.progressbar.setValue(0)

    def layout_init(self):
        self.h_layout.addWidget(self.start_btn)
        self.h_layout.addWidget(self.stop_btn)
        self.h_layout.addWidget(self.save_combobox)
        self.v_layout.addWidget(self.table)
        self.v_layout.addWidget(self.log_browser)
        self.v_layout.addWidget(self.progressbar)
        self.v_layout.addLayout(self.h_layout)
        self.setLayout(self.v_layout)

    def crawl_init(self):
        self.crawl_thread.finished_signal.connect(self.finish_slot)
        self.crawl_thread.log_signal.connect(self.set_log_slot)
        self.crawl_thread.result_signal.connect(self.set_table_slot)

    def btn_slot(self, btn):
        self.btn_sound.play()
        if btn == self.start_btn:
            self.log_browser.clear()
            self.log_browser.append('<font color="red">开始爬取</font>')
            self.table.clearContents()
            self.table.setRowCount(0)
            self.start_btn.setEnabled(False)
            self.stop_btn.setEnabled(True)
            self.save_combobox.setEnabled(False)

            self.crawl_thread.start()
        else:
            self.log_browser.append('<font color="red">停止爬取</font>')
            self.stop_btn.setEnabled(False)
            self.start_btn.setEnabled(True)
            self.save_combobox.setEnabled(True)

            self.crawl_thread.terminate()

    def finish_slot(self):
        self.start_btn.setEnabled(True)
        self.stop_btn.setEnabled(False)
        self.save_combobox.setEnabled(True)

    def set_log_slot(self, new_log):
        self.log_browser.append(new_log)

    def set_table_slot(self, img, name, star, time, score):
        row = self.table.rowCount()
        self.table.insertRow(row)

        self.table.setItem(row, 0, QTableWidgetItem(img))
        self.table.setItem(row, 1, QTableWidgetItem(name))
        self.table.setItem(row, 2, QTableWidgetItem(star))
        self.table.setItem(row, 3, QTableWidgetItem(time))
        self.table.setItem(row, 4, QTableWidgetItem(score))

        self.progressbar.setValue(row + 1)
        if self.progressbar.value() == 100:
            self.finish_sound.play()

    def combobox_slot(self, text):
        if text == 'MySQL':
            self.save_to_MySQL()
        elif text == 'csv':
            self.save_to_csv()
        elif text == 'txt':
            self.save_to_txt()
        elif text == 'json':
            self.save_to_json()

    def db_connect(self):
        self.db = QSqlDatabase.addDatabase('QMYSQL')
        self.db.setHostName('localhost')
        self.db.setDatabaseName('test_db')
        self.db.setUserName('root')
        self.db.setPassword('pwd')
        if not self.db.open():
            QMessageBox.critical(self, 'Database Connection',
                                 self.db.lastError().text())

    def closeEvent(self, QCloseEvent):
        self.db.close()

    def save_to_MySQL(self):
        query = QSqlQuery()

        query.exec_("CREATE TABLE IF NOT EXISTS movie "
                    "(img VARCHAR(100), name VARCHAR(50), star VARCHAR(100),"
                    " time VARCHAR(50), score VARCHAR(5))")

        for row in range(self.table.rowCount()):
            img = self.table.item(row, 0).text()
            name = self.table.item(row, 1).text()
            star = self.table.item(row, 2).text()
            time = self.table.item(row, 3).text()
            score = self.table.item(row, 4).text()
            query.prepare("INSERT INTO movie (img, name, star, time, score) "
                          "VALUES (?, ?, ?, ?, ?)")
            query.addBindValue(img)
            query.addBindValue(name)
            query.addBindValue(star)
            query.addBindValue(time)
            query.addBindValue(score)
            query.exec_()

        QMessageBox.information(self, '保存到MySQL', '保存成功!', QMessageBox.Ok)

    def save_to_csv(self):
        content = []
        for row in range(self.table.rowCount()):
            img = self.table.item(row, 0).text()
            name = self.table.item(row, 1).text()
            star = self.table.item(row, 2).text()
            time = self.table.item(row, 3).text()
            score = self.table.item(row, 4).text()
            content.append([img, name, star, time, score])

        with open('./猫眼Top100电影.csv', 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerow(['图片链接', '电影名称', '主演人员', '上映时间', '电影评分'])
            writer.writerows(content)

        QMessageBox.information(self, '保存到csv', '保存成功!', QMessageBox.Ok)

    def save_to_txt(self):
        content = ''
        for row in range(self.table.rowCount()):
            img = '图片链接:{}\n'.format(self.table.item(row, 0).text())
            name = '电影名称:{}\n'.format(self.table.item(row, 1).text())
            star = '主演人员:{}\n'.format(self.table.item(row, 2).text())
            time = '上映时间:{}\n'.format(self.table.item(row, 3).text())
            score = '电影评分:{}\n'.format(self.table.item(row, 4).text())
            content += img + name + star + time + score + '\n'

        with open('./猫眼Top100电影.txt', 'w', encoding='utf-8') as f:
            f.write(content)

        QMessageBox.information(self, '保存到txt', '保存成功!', QMessageBox.Ok)

    def save_to_json(self):
        content = []
        for row in range(self.table.rowCount()):
            img = self.table.item(row, 0).text()
            name = self.table.item(row, 1).text()
            star = self.table.item(row, 2).text()
            time = self.table.item(row, 3).text()
            score = self.table.item(row, 4).text()
            content.append({
                '图片链接': img,
                '电影名称': name,
                '主演人员': star,
                '上映时间': time,
                '电影评分': score
            })

        with open('./猫眼Top100电影.json', 'w', encoding='utf-8') as f:
            json.dump(content, f, ensure_ascii=False)

        QMessageBox.information(self, '保存到json', '保存成功!', QMessageBox.Ok)
Example #10
0
 def bgm(self):
     while True:
         QSound.play('source/bgm.wav')
Example #11
0
class CrawlWindow(QWidget):
    def __init__(self):
        super(CrawlWindow, self).__init__()
        self.resize(300, 150)
        self.setWindowTitle('毒APP数据采集')
        self.setWindowIcon(QIcon(':reson/maoyan.ico'))

        # 初始化获取所有数据按钮
        self.start_btn = QPushButton(self)
        # 初始化获取xlsx按钮
        self.xlsx_btn = QPushButton(self)
        # 初始化输出文本框
        # self.log_browser = QTextBrowser(self)

        # 初始化水平布局
        self.h_layout = QHBoxLayout()
        # 初始化垂直布局
        self.v_layout = QVBoxLayout()

        # 初始化音频播放
        self.btn_sound = QSound(':reson/btn.wav', self)
        self.finish_sound = QSound(':reson/finish.wav', self)

        # 实例化线程
        self.threads = MyThread()
        # self.worker = MyThread()
        self.config = None

        # 实例化
        self.start_btn_init()
        self.xlsx_btn_init()
        self.layout_init()

    def start_btn_init(self):
        """ 获取所有数据按钮 配置"""
        self.start_btn.setText('获取所有数据')
        self.start_btn.clicked.connect(self.start_btn_slot)

    def xlsx_btn_init(self):
        """获取xlsx按钮 配置"""
        self.xlsx_btn.setText('获取xlsx文档')
        self.xlsx_btn.clicked.connect(self.xlsx_btn_slot)

    def layout_init(self):
        """页面布局"""
        self.h_layout.addWidget(self.start_btn)
        self.h_layout.addWidget(self.xlsx_btn)

        self.v_layout.addLayout(self.h_layout)
        self.setLayout(self.v_layout)

    def start_btn_slot(self):
        """获取所有数据"""

        self.btn_sound.play()
        print('<font color="red">获取所有数据</font>')
        print('<font color="red">下载中...</font>')
        self.threads.download_img(True)
        self.threads.start()
        # self.threads.waitForFinished(-1)
        self.finish_sound.play()
        self.start_btn.setEnabled(False)
        self.xlsx_btn.setEnabled(False)

    def xlsx_btn_slot(self):
        """获取xlsx汇总文档"""

        self.start_btn.setEnabled(False)
        self.xlsx_btn.setEnabled(False)
        self.btn_sound.play()
        print('<font color="red">获取xlsx汇总文档</font>')
        print('<font color="red">下载中...</font>')
        self.threads.download_img(False)
        self.threads.start()
        # self.threads.waitForFinished(-1)  # TODO
        self.finish_sound.play()
        self.start_btn.setEnabled(False)
        self.xlsx_btn.setEnabled(False)
Example #12
0
class CrawlWindow(QWidget):
    def __init__(self):
        super(CrawlWindow, self).__init__()
        self.resize(500, 500)
        self.setWindowTitle('toptoon漫画更新监测')
        self.setWindowIcon(QIcon(':reson/maoyan.ico'))

        # 初始化启动按钮
        self.start_btn = QPushButton(self)
        # 初始化输出文本框
        self.log_browser = QTextBrowser(self)
        # 初始化表格控件
        self.table = QTableWidget(self)

        # 初始化水平布局
        self.h_layout = QHBoxLayout()
        # 初始化垂直布局
        self.v_layout = QVBoxLayout()

        # 初始化音频播放
        self.btn_sound = QSound(':reson/btn.wav', self)
        self.finish_sound = QSound(':reson/finish.wav', self)

        # 实例化线程
        self.worker = MyThread()

        # 实例化
        self.start_btn_init()
        self.layout_init()
        self.set_log_init()
        self.table_init()

    def start_btn_init(self):
        """ 启动按钮按钮 配置"""
        self.start_btn.setText('启动')
        self.start_btn.setEnabled(True)
        # self.start_btn.setFixedSize(300, 30)
        self.start_btn.clicked.connect(self.start_btn_slot)

    def table_init(self):
        """表格控件 配置"""
        self.table.setColumnCount(3)
        self.table.setHorizontalHeaderLabels(['漫画名', '更新章节', 'URL地址'])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

    def set_log_init(self):
        """输出控件 配置"""
        # 输出至输出文本框
        self.worker.log_signal.connect(self.set_log_slot)
        # 输出至表格控件
        self.worker.result_signal.connect(self.set_table_slot)
        # 调用清屏槽
        # self.worker.start_q.connect(self.set_start_slot)

    def layout_init(self):
        """页面布局"""
        self.h_layout.addWidget(self.start_btn)
        self.v_layout.addWidget(self.table)
        self.v_layout.addWidget(self.log_browser)
        self.v_layout.addLayout(self.h_layout)
        self.setLayout(self.v_layout)

    def start_btn_slot(self):
        """程序启动"""
        self.btn_sound.play()
        self.log_browser.append('<font color="green">{}程序启动{}</font>'.format(
            '*' * 20, '*' * 20))
        # 启动线程
        self.worker.start()
        self.finish_sound.play()
        # 改变设置按钮状态 输入框 下拉框
        self.start_btn.setEnabled(False)

    def set_log_slot(self, log):
        self.log_browser.append(log)

    def set_start_slot(self):
        # 表格清空 输出框窗口清空
        # self.table.clearContents()
        # self.table.setRowCount(0)
        self.log_browser.clear()

    def set_table_slot(self, article_name, total, url):
        """表格控件输出"""
        row = self.table.rowCount()
        self.table.insertRow(row)
        self.table.setItem(row, 0, QTableWidgetItem(article_name))
        self.table.setItem(row, 1, QTableWidgetItem(total))
        self.table.setItem(row, 2, QTableWidgetItem(url))
class AppController(QObject):
    """The main controller of this application."""
    def __init__(self):
        super(AppController, self).__init__()
        ServiceAdaptor(self)

        self.contexts = []
        self._osdVisible = False
        self._initQuitTimer()

    def _initQuitTimer(self):
        self._quitTimer = QTimer()
        self._quitTimer.setInterval(10 * 1000)
        self._quitTimer.setSingleShot(True)
        self._quitTimer.timeout.connect(self._checkContexts)

    def _checkContexts(self):
        if (self.contexts) or self._osdVisible:
            self._quitTimer.start()
        else:
            qApp.quit()

    def _contextNeedSound(self):
        self._sound.play()

    def _contextFinished(self):
        sender = self.sender()
        if sender in self.contexts:
            # TODO: the remove _doesn't_ get the sender object
            # garbage collected, there must be some reference cycles.
            self.contexts.remove(sender)
        self._checkContexts()

    def _contextNeedOSD(self, area):
        def _osdClosed():
            self._osdVisible = False

        self._osdVisible = True
        self._qmlEngine = QQmlApplicationEngine()
        self._qmlEngine.load(QUrl(OSD_QML))
        osd = self._qmlEngine.rootObjects()[0]
        osd.setX(area.x() + (area.width() - osd.width()) / 2)
        osd.setY(area.y() + (area.height() - osd.height()) / 2)
        osd.showTips()
        osd.closed.connect(_osdClosed)

    def _createContextSettings(self):
        settings = ScreenshotSettings()
        settings.tmpImageFile = "%s.png" % tempfile.mktemp()
        settings.tmpBlurFile = "%s-blur.png" % tempfile.mktemp()
        settings.tmpMosaiceFile = "%s-mosaic.png" % tempfile.mktemp()
        settings.tmpSaveFile = "%s-save.png" % tempfile.mktemp()

        return settings

    def runWithArguments(self, arguments):
        for _context in self.contexts:
            if _context.isActive():
                return

        argValues = processArguments(arguments)
        delay = argValues["delay"]

        self._sound = QSound(SOUND_FILE)
        self._sound.setLoops(1)

        context = AppContext(argValues)
        context.settings = self._createContextSettings()
        context.finished.connect(self._contextFinished)
        context.needSound.connect(self._contextNeedSound)
        context.needOSD.connect(self._contextNeedOSD)
        self.contexts.append(context)

        if delay > 0:
            notificationsInterface.notify(_("Deepin Screenshot"),
            _("Deepin Screenshot will start after %s seconds.") % delay)

        QTimer.singleShot(max(0, delay * 1000), context.main)
class ImageStitchingController(Controller):
    def __init__(self, router):
        super(ImageStitchingController, self).__init__(router,
                                                       ImageStitchingWindow())
        self.current_image = None
        self.preview_image_file = None
        self.preview_mode = 0
        self.router.subscribe('snapshot', self)
        self.files = []
        self.text_detector = TextDetector()
        self.magicSound = QSound(
            QtUtil.resource_path(
                os.path.join("windows", "stitching", "magic.wav")))
        self.__bind(self.view)

    def __bind(self, view):
        view.goBackButton.clicked.connect(self.on_go_back)
        view.addButton.clicked.connect(self.on_add_item)
        view.autoDetectButton.clicked.connect(self.on_auto_detect)
        view.removeButton.clicked.connect(self.on_remove_item)
        view.saveButton.clicked.connect(self.on_save)
        view.imageListWidget.itemSelectionChanged.connect(
            self.on_item_selected)
        view.upVerticalSlider.sliderMoved.connect(self.on_up_moved)
        view.downVerticalSlider.sliderMoved.connect(self.on_down_moved)
        view.tabWidget.tabBarClicked.connect(self.on_tab_clicked)
        view.imageWidget.resizeEvent = self.on_item_preview_resize
        view.previewWidget.resizeEvent = self.on_output_preview_resize
        view.addAction.triggered.connect(self.on_add_item)
        view.autoDetectSelectedAction.triggered.connect(self.on_auto_detect)
        view.removeSelectedAction.triggered.connect(self.on_remove_item)
        view.previewSelectedAction.triggered.connect(self.on_preview_selected)
        view.previewAllAction.triggered.connect(self.on_preview_all)
        view.saveSelectedAction.triggered.connect(self.on_save_selected)
        view.saveAllAction.triggered.connect(self.on_save_all)

    def show(self):
        super(ImageStitchingController, self).show()
        if len(self.files) > 0:
            for image in self.files:
                self.add_image(image)
            self.files = []

    def notify(self, topic, message):
        if topic == 'snapshot':
            self.files.append(message)

    def on_go_back(self):
        self.go('player')

    def on_add_item(self):
        file_names, _ = QFileDialog.getOpenFileNames(
            self.view,
            "Open Images",
            QDir.homePath(),
            filter="*.jpg;*.jpeg;*.png")
        if file_names:
            for image in file_names:
                self.add_image(image)
            self.view.statusBar().showMessage("%s images added." %
                                              len(file_names))

    def on_remove_item(self):
        items = self.view.imageListWidget.selectedItems()
        if len(items) == 0:
            return
        result = QMessageBox.question(
            self.view, 'Run Auto Snapshort',
            'Remove selected [%s] items?' % len(items), QMessageBox.Yes,
            QMessageBox.No)
        if result == QMessageBox.Yes:
            for item in items:
                index = self.view.imageListWidget.indexFromItem(item)
                self.view.imageListWidget.takeItem(index.row())
            self.view.imageListWidget.repaint()
            self.view.statusBar().showMessage('Removed %s images.' %
                                              len(items))
            self.view.update_view()

    def add_image(self, image_file):
        try:
            image = ImageModel(image_file)
            item = ListWidgetItem()
            icon = QIcon()
            icon.addFile(image_file)
            item.setTextAlignment(1)
            item.setIcon(icon)
            item.setData(Qt.DisplayRole, str(image))
            item.setData(Qt.StatusTipRole, image_file)
            item.set_storage(image)
            self.view.imageListWidget.addItem(item)
            self.view.update_view()
        except:
            traceback.print_exc()

    def on_item_selected(self):
        items = self.view.imageListWidget.selectedItems()
        if len(items) == 0:
            self.view.upVerticalSlider.setValue(0)
            self.view.upVerticalSlider.setEnabled(False)
            self.view.downVerticalSlider.setEnabled(False)
            self.view.downVerticalSlider.setValue(0)
            self.view.imageLabel.hide()
            self.view.upImageLabel.hide()
            self.view.downImageLabel.hide()
            self.current_image = None
            self.view.statusBar().showMessage('')
        else:
            item = items[0]
            image = item.get_storage()
            self.current_image = image

            self.render_preview()
            self.view.imageLabel.show()
            self.view.upImageLabel.show()
            self.view.downImageLabel.show()
            self.view.upVerticalSlider.setEnabled(True)
            self.view.downVerticalSlider.setEnabled(True)
            self.view.statusBar().showMessage("%s images selected." %
                                              len(items))
        self.view.update_view()

    def render_preview(self):
        image = self.current_image
        if image is None:
            return
        QtUtil.preview_image(image.image_file, self.view.imageLabel,
                             self.view.imageWidget)
        self.set_image_up_shade(image)
        self.set_image_down_shade(image)
        self.view.upVerticalSlider.setRange(0, image.height)
        self.view.downVerticalSlider.setRange(0, image.height)
        self.view.upVerticalSlider.setValue(image.up)
        self.view.downVerticalSlider.setValue(image.height - image.down)

    def set_image_up_shade(self, image):
        height = int(self.view.imageLabel.height() *
                     (image.up * 1.0 / image.height))
        self.view.upImageLabel.setGeometry(self.view.imageLabel.x(),
                                           self.view.imageLabel.y(),
                                           self.view.imageLabel.width(),
                                           height)
        # print 'up x, y, width, height', self.view.upImageLabel.geometry()

    def set_image_down_shade(self, image):
        height = int(self.view.imageWidget.height() *
                     ((image.height - image.down) * 1.0 / image.height))
        self.view.downImageLabel.setGeometry(
            self.view.imageLabel.x(),
            self.view.imageLabel.y() + self.view.imageLabel.height() - height,
            self.view.imageLabel.width(), height)
        # print 'down x, y, width, height', self.view.downImageLabel.geometry()

    def on_up_moved(self, position):
        updated = False
        for item in self.view.imageListWidget.selectedItems():
            image = item.get_storage()
            if position < image.down:
                image.up = position
                item.setData(0, str(image))
                if not updated:
                    updated = True
                    self.set_image_up_shade(image)
            else:
                self.view.upVerticalSlider.setValue(image.up)
                break

    def on_down_moved(self, position):
        updated = False
        for item in self.view.imageListWidget.selectedItems():
            image = item.get_storage()
            val = image.height - position
            if val > image.up:
                image.down = val
                item.setData(0, str(image))
                if not updated:
                    updated = True
                    self.set_image_down_shade(image)
            else:
                self.view.downVerticalSlider.setValue(image.height -
                                                      image.down)
                break

    def on_save(self):
        filename, _ = QFileDialog.getSaveFileName(self.view,
                                                  "Save Image",
                                                  QDir.homePath(),
                                                  filter="*.jpg")
        if filename:
            images = self.get_images(self.preview_mode)
            ImageUtil.vertical_stitch(images, filename)
            self.view.statusBar().showMessage('Image %s saved.' % filename)
        else:
            self.view.statusBar().showMessage('Save cancelled.')

    def get_images(self, mode=0):
        images = []
        if mode == 0:
            for i in range(self.view.imageListWidget.count()):
                item = self.view.imageListWidget.item(i)
                images.append(item.get_storage())
        else:
            for item in self.view.imageListWidget.selectedItems():
                images.append(item.get_storage())

        return images

    def on_item_preview_resize(self, event):
        if self.current_image is not None:
            QtUtil.central(self.view.imageLabel, self.view.imageWidget,
                           self.current_image.width, self.current_image.height)
            self.set_image_up_shade(self.current_image)
            self.set_image_down_shade(self.current_image)

    def on_tab_clicked(self, index):
        self.view.model.preview = index == 1
        self.view.statusBar().showMessage(
            "Preview image." if self.view.model.preview else '')
        if self.view.model.preview:
            self.render_stitching_preview()
        self.view.update_view()

    def render_stitching_preview(self):
        images = self.get_images(self.preview_mode)
        if len(images) > 0:
            temp_file = TempFileUtil.get_temp_file(prefix="snapshot_preview_",
                                                   suffix=".jpg")
            self.preview_image_file = ImageUtil.vertical_stitch(
                images, temp_file)
            QtUtil.preview_image(temp_file, self.view.previewLabel,
                                 self.view.previewWidget)
            os.remove(temp_file)
        else:
            self.preview_image_file = None
            self.view.previewLabel.clear()

    def on_output_preview_resize(self, event):
        if self.preview_image_file is not None:
            QtUtil.central(self.view.previewLabel, self.view.previewWidget,
                           self.preview_image_file.width,
                           self.preview_image_file.height)

    def on_preview_selected(self):
        self.view.tabWidget.setCurrentIndex(1)
        self.preview_mode = 1
        self.on_tab_clicked(1)

    def on_preview_all(self):
        self.view.tabWidget.setCurrentIndex(1)
        self.preview_mode = 0
        self.on_tab_clicked(1)

    def on_save_selected(self):
        self.preview_mode = 1
        self.on_save()

    def on_save_all(self):
        self.preview_mode = 0
        self.on_save()

    def on_auto_detect(self):
        message = "Auto detect subtitle positions for "
        items = []
        skip_first = False
        if len(self.view.imageListWidget.selectedItems()) > 0:
            message += "selected images?"
            items = self.view.imageListWidget.selectedItems()
        else:
            message += "all images (except the head image)?"
            for i in range(self.view.imageListWidget.count()):
                items.append(self.view.imageListWidget.item(i))
            skip_first = True
        reply = QMessageBox.question(self.view, 'Auto detect', message,
                                     QMessageBox.Yes, QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.view.setEnabled(False)
            self.do_auto_detect(items, skip_first)
            QApplication.processEvents()
            self.magicSound.play()
            self.view.setEnabled(True)

    def do_auto_detect(self, items, skip_first=False):
        start = 1 if skip_first else 0
        for i in range(start, len(items)):
            img = items[i].get_storage()
            img.up, img.down = self.text_detector.detect_subtitle_range(
                img.image_file)
            # items[i].setData(0, str(img))
            items[i].refresh_ui()
        self.render_preview()
        self.view.statusBar().showMessage("Please preview final image.")
Example #15
0
class PlayerController(Controller):
    def __init__(self, router):
        super(PlayerController, self).__init__(router, PlayerWindow())
        self.model = SnapshotModel()
        self.snapshot = Snapshot()
        self.snapshotSound = QSound(
            QtUtil.resource_path(
                os.path.join("windows", "player", "snapshot.wav")))
        self.__bind(self.view)

    def __bind(self, view):
        view.openButton.clicked.connect(self.on_open)
        view.playButton.clicked.connect(self.on_play)
        view.snapshotButton.clicked.connect(self.on_snapshot)
        view.videoBackgroundWidget.mouseReleaseEvent = self.on_video_clicked
        view.videoWidget.mouseReleaseEvent = self.on_video_clicked

        view.outputButton.clicked.connect(self.on_set_output)
        view.subtitleSelectButton.clicked.connect(self.on_set_subtitle)

        view.startButton.clicked.connect(self.on_set_start)
        view.endButton.clicked.connect(self.on_set_end)
        view.autoSnapshotButton.clicked.connect(self.on_run_snapshots)
        view.imageStitchingButton.clicked.connect(self.on_stitch_snapshots)

        self.view.mediaPlayer.stateChanged.connect(self.on_media_state_changed)
        self.view.mediaPlayer.positionChanged.connect(self.on_position_changed)
        self.view.mediaPlayer.durationChanged.connect(self.on_duration_changed)
        self.view.mediaPositionSlider.sliderMoved.connect(self.on_set_position)

        self.view.videoBackgroundWidget.resizeEvent = self.on_video_resize

    def on_open(self):
        file_name, _ = QFileDialog.getOpenFileName(
            self.view,
            "Open Video",
            QDir.homePath(),
            filter="*.mp4;*.avi;*.mpeg;*.mpg;*.mov;*.m4v;*.mtk")
        if file_name != '':
            if not self.snapshot.load_video(file_name):
                QMessageBox.warning(self.view, 'Error',
                                    "Can't open this file.")
                return
            self.model = SnapshotModel()
            self.model.filename = file_name
            self.view.outputLineEdit.setText(self.model.output)
            self.view.playButton.setEnabled(True)
            self.view.snapshotButton.setEnabled(True)
            self.view.subtitleSelectButton.setEnabled(True)
            self.view.startButton.setEnabled(True)
            self.view.endButton.setEnabled(True)
            self.view.outputButton.setEnabled(True)
            if self.snapshot.srt_file:
                self.model.subtitle = self.snapshot.srt_file
                self.view.subtitleLineEdit.setText(self.snapshot.srt_file)
                self.view.autoSnapshotButton.setEnabled(True)
            self.set_video(file_name, self.snapshot.width,
                           self.snapshot.height)

    def on_video_clicked(self, *event):
        if self.model.filename:
            self.on_play()
        else:
            self.on_open()

    def on_play(self, ):
        self.view.mediaPositionSlider.setEnabled(True)
        if self.model.isPlaying:
            self.view.mediaPlayer.pause()
            self.view.update_icon(self.view.playButton, "play")
        else:
            self.view.mediaPlayer.play()
            self.view.update_icon(self.view.playButton, "pause")
        self.model.isPlaying = not self.model.isPlaying
        self.view.videoWidget.show()

    def on_set_output(self):
        folder = QFileDialog.getExistingDirectory(self.view,
                                                  "Select image output path",
                                                  self.model.output)
        if folder:
            self.model.output = folder
            self.view.outputLineEdit.setText(self.model.output)

    def on_set_subtitle(self):
        file_name, _ = QFileDialog.getOpenFileName(self.view,
                                                   "Open Subtitle",
                                                   QDir.homePath(),
                                                   filter="*.srt")
        if file_name != '':
            self.snapshot.load_srt(file_name)
            self.view.subtitleLineEdit.setText(file_name)
            self.model.subtitle = file_name
            self.view.autoSnapshotButton.setEnabled(True)

    def on_stitch_snapshots(self):
        if self.model.isPlaying:
            self.on_play()
        self.go('image')

    def set_video(self, file_name, width, height):
        self.view.mediaPlayer.setMedia(
            QMediaContent(QUrl.fromLocalFile(file_name)))
        QtUtil.central(self.view.videoWidget, self.view.videoBackgroundWidget,
                       width, height, 2, 2)
        self.on_play()

    def on_media_state_changed(self, state):
        # TODO: find a method to update view instead of these tricks
        # After pause, the video will re-scale to original size, this is used to fix this.
        QtUtil.central(self.view.videoWidget, self.view.videoBackgroundWidget,
                       self.snapshot.width, self.snapshot.height, 2, 2)
        if state == 0:
            # TODO: find a method to update view instead of these tricks
            self.view.videoWidget.hide()
            self.model.isPlaying = False
            self.view.update_icon(self.view.playButton, "play")
            self.view.mediaPositionSlider.hide()
            self.view.mediaPositionSlider.setValue(0)
            self.view.mediaPositionSlider.show()
        elif state == QMediaPlayer.PausedState:
            self.view.update_icon(self.view.playButton, "play")
        else:
            self.view.update_icon(self.view.playButton, "pause")

    def on_video_resize(self, event):
        QtUtil.central(self.view.videoWidget, self.view.videoBackgroundWidget,
                       self.snapshot.width, self.snapshot.height)

    def on_position_changed(self, position):
        # TODO: find a method to update view instead of these tricks
        QtUtil.central(self.view.videoWidget, self.view.videoBackgroundWidget,
                       self.snapshot.width, self.snapshot.height)
        self.view.mediaPositionSlider.setValue(position)
        self.view.progressLabel.setText(TimeUtil.format_ms(position))

    def on_duration_changed(self, duration):
        print(duration)
        self.view.mediaPositionSlider.setRange(0, duration)
        self.model.end = duration
        self.view.endLabel.setText(TimeUtil.format_ms(duration))

    def on_set_position(self, position):
        self.view.mediaPlayer.setPosition(position)

    def on_handle_error(self, error):
        self.view.playButton.setEnabled(False)
        self.view.snapshotButton.setEnabled(False)
        self.view.startButton.setEnabled(False)
        self.view.endButton.setEnabled(False)
        self.view.outputButton.setEnabled(False)
        self.view.subtitleButton.setEnabled(False)
        self.view.runTaskButton(False)
        self.view.messageLabel.setText("Error: " +
                                       self.view.mediaPlayer.errorString())
        print(error)

    def on_snapshot(self):
        position = self.view.mediaPlayer.position()
        output_file = os.path.join(
            self.model.output, self.model.file +
            "_manual_%s.jpg" % TimeUtil.format_ms(position).replace(":", "_"))
        # print(output_file)
        try:
            if self.snapshot.snapshot(position, output_file):
                self.snapshotSound.play()
                self.router.notify('snapshot', output_file)
                self.view.messageLabel.setText("Saved " + output_file)
        except:
            traceback.print_exc()
            QMessageBox.warning(self.view, 'Error', 'Snapshot failed.')

    def on_set_start(self):
        self.model.start = self.view.mediaPlayer.position()
        self.view.startLabel.setText(TimeUtil.format_ms(self.model.start))

    def on_set_end(self):
        self.model.end = self.view.mediaPlayer.position()
        self.view.endLabel.setText(TimeUtil.format_ms(self.model.end))

    def on_run_snapshots(self):
        if self.view.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.on_play()

        count = self.snapshot.estimate(self.model.start, self.model.end)
        quit_msg = "Are you sure you want to run auto snapshot (start %s ~ end %s )?\n" \
                   "Image count estimation %s" % (TimeUtil.format_ms(self.model.start),
                                                  TimeUtil.format_ms(self.model.end), count)
        reply = QMessageBox.question(self.view, 'Run Auto Snapshot', quit_msg,
                                     QMessageBox.Yes, QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.lock_ui(False)
            self.model.task_progress = 0
            try:
                self.snapshot.snapshot_range(self.model.output,
                                             self.model.start, self.model.end,
                                             self.show_progress,
                                             self.show_complete)
            except:
                traceback.print_exc()
                QMessageBox.warning(self.view, 'Error', 'Snapshot failed.')
            self.lock_ui(True)

    def show_progress(self, total, current, position, output_file,
                      output_result):
        QApplication.processEvents()
        self.router.notify('snapshot', output_file)
        percentage = int(current * 100 / total)
        if percentage != self.model.task_progress:
            self.model.task_progress = percentage
            self.view.messageLabel.setText("Progress %s%%" % percentage)
        print(
            "total=%s, current=%s, position=%s, output_file=%s, output_result=%s"
            % (total, current, position, output_file, output_result))

    def show_complete(self, total, success):
        self.view.messageLabel.setText(
            "Progress 100%%, all done, %s files expected, %s files saved" %
            (total, success))

    def lock_ui(self, locked_status):
        self.view.playButton.setEnabled(locked_status)
        self.view.openButton.setEnabled(locked_status)
        self.view.outputButton.setEnabled(locked_status)
        self.view.subtitleSelectButton.setEnabled(locked_status)
        self.view.snapshotButton.setEnabled(locked_status)
        self.view.startButton.setEnabled(locked_status)
        self.view.endButton.setEnabled(locked_status)
        self.view.autoSnapshotButton.setEnabled(locked_status)
        self.view.mediaPositionSlider.setEnabled(locked_status)
        self.view.imageStitchingButton.setEnabled(locked_status)
Example #16
0
 def Play(self):
    
     QSound.play("bike_horn.wav")
Example #17
0
class MainWidget(QWidget):
    def __init__(self, parent = None):
        super().__init__(parent)
        self.main_window: QMainWindow = parent
        self.left = 10
        self.top = 10
        self.width = 600
        self.height = 800
        self.leftPanelWidth = 250
        self.initUI()
        self.initMplWidget()
        self.sample = QSound(ConfigControl.get_disorderPath())

    def initUI(self):
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.recordButton = RecordButton()
        self.recordButton.clicked.connect(self.on_recordButton)

        self.playDisorder = QPushButton('Play disorder')
        self.playDisorder.setDisabled(False)
        self.playDisorder.clicked.connect(self.playSample)

        self.lcd_time_counter = TimeCounter()
        self.wavePlot = AudioWavePlot(self)

        labelsLayout = QHBoxLayout()
        labelsLayout.addWidget(self.recordButton)
        labelsLayout.addWidget(self.playDisorder)
        labelsLayout.addWidget(self.lcd_time_counter)
        labelsLayout.setAlignment(Qt.AlignLeft)

        mainLayout = QVBoxLayout(self)
        mainLayout.addLayout(labelsLayout)
        mainLayout.addWidget(self.wavePlot.toolbar)
        mainLayout.addWidget(self.wavePlot.canvas)

    def on_recordButton(self):
        if self.recordButton.isChecked():
            self.initData()
            self.initTimer()
            self.recordButton.setStyleSheet(self.recordButton.record_stylesheet)
            self.recordButton.setText('Recording ...')
            self.timer.timeout.connect(self.handleNewData)
            self.lcd_time_counter.start()
            self.main_window.statusBar().showMessage('Recording...')
            print(int(ConfigControl.get_disorder_autoPlayTime()))

            if self.main_window.menu_bar.autoPlay.isChecked():
                self.timer.singleShot(int(ConfigControl.get_disorder_autoPlayTime()) * 1000,self.playSample)

            self.timer.start(50)
        else:
            self.recordButton.setStyleSheet(self.recordButton.stop_stylesheet)
            self.recordButton.setText('Rec')
            self.main_window.statusBar().showMessage('Recording finish')
            self.lcd_time_counter.stop()
            self.main_window.statusBar().showMessage('Saving file')
            self.mic.write_to_wav(10)
            self.timer.stop()
            self.sample.stop()
            del self.mic
            self.main_window.statusBar().showMessage('Recording finish')


    def initMplWidget(self):
        """creates initial matplotlib plots in the main window and keeps
        references for further use"""
        # top plot
        self.time_vect_primary = np.arange(1024, dtype=np.float32) / 4000 * 1000
        self.ax_top = self.wavePlot.figure.add_subplot(111)
        self.ax_top.set_ylim(-32768, 32768)
        self.ax_top.set_xlim(0, self.time_vect_primary.max())
        self.ax_top.set_xlabel(u'time (ms)', fontsize=6)

        # line objects
        self.line_top, = self.ax_top.plot(self.time_vect_primary, np.ones_like(self.time_vect_primary))

    def handleNewData(self):
        """ handles the asynchroneously collected sound chunks """
        # gets the latest frames
        frames = self.mic.get_frames()

        if len(frames) > 0:
            # keeps only the last frame
            current_frame = frames[-1]

            # plots the time signal
            self.line_top.set_data(self.time_vect_primary, current_frame)

            # refreshes the plots
            self.wavePlot.canvas.draw()

    def initData(self):
        mic = MicrophoneRecorder()
        mic.start()
        self.mic = mic
        # computes the parameters that will be used during plotting
        self.time_vect_primary = np.arange(mic.chunksize, dtype=np.float32) / mic.rate * 1000

    def initTimer(self):
        self.timer = QTimer()
        self.timer.timeout.connect(self.handleNewData)

    def playSample(self):
        self.sample.play()
Example #18
0
    def initUI(self):  # UI初始化

        self.chessboard = ChessBoard()  # 棋盘类,详见chessboard.py

        palette1 = QPalette()  # 设置棋盘背景
        palette1.setBrush(self.backgroundRole(), QtGui.QBrush(QtGui.QPixmap('source/游戏界面1.png')))
        self.setPalette(palette1)

        # self.setCursor(Qt.PointingHandCursor)  # 鼠标变成手指形状
        self.sound_piece = QSound("sound/move.wav")  # 加载落子音效
        self.sound_win = QSound("sound/win.wav")  # 加载胜利音效
        self.sound_defeated = QSound("sound/defeated.wav")  # 加载失败音效

        self.resize(WIDTH, HEIGHT)  # 画布大小,设为固定值,不允许缩放
        self.setMinimumSize(QtCore.QSize(WIDTH, HEIGHT))
        self.setMaximumSize(QtCore.QSize(WIDTH, HEIGHT))

        self.setWindowTitle("GoBang")  # 窗口名称
        self.setWindowIcon(QIcon('source/icon.ico'))  # 窗口图标

        # 所有按钮的图标和布局
        self.backBtn = MyButton.MyButton('source/返回按钮_hover.png',
                                         'source/返回按钮_normal.png',
                                         'source/返回按钮_press.png',
                                         parent=self)
        self.backBtn.move(610, 80)

        self.startBtn = MyButton.MyButton('source/开始按钮_hover.png',
                                          'source/开始按钮_normal.png',
                                          'source/开始按钮_press.png',
                                          parent=self)
        self.startBtn.move(610, 180)

        self.returnBtn = MyButton.MyButton('source/悔棋按钮_hover.png',
                                           'source/悔棋按钮_normal.png',
                                           'source/悔棋按钮_press.png',
                                           parent=self)
        self.returnBtn.move(610, 400)

        self.loseBtn = MyButton.MyButton('source/认输按钮_hover.png',
                                         'source/认输按钮_normal.png',
                                         'source/认输按钮_press.png',
                                         parent=self)
        self.loseBtn.move(610, 500)

        # 绑定按钮
        self.backBtn.clicked.connect(self.goBack)
        self.startBtn.clicked.connect(self.restart)
        self.loseBtn.clicked.connect(self.lose)
        self.returnBtn.clicked.connect(self.returnOneStep)

        # self.gameStatu = []

        self.black = QPixmap('source/black.png')  # 黑白棋子
        self.white = QPixmap('source/white.png')

        self.piece_now = BLACK  # 黑棋先行



        self.step = 0  # 步数
        self.x, self.y = 1000, 1000



        self.pieces = [LaBel(self) for i in range(225)]  # 新建棋子标签,准备在棋盘上绘制棋子
        for piece in self.pieces:
            piece.setVisible(True)  # 图片可视
            piece.setScaledContents(True)  # 图片大小根据标签大小可变

        # self.mouse_point.raise_()  # 鼠标始终在最上层
        self.ai_down = True  # 主要是为了加锁,当值是False的时候在等待对方下棋,这时候己方鼠标点击失效,要忽略掉 mousePressEvent

        self.setMouseTracking(True)
        self.show()
Example #19
0
class GoBang(QWidget):
    backSignal = QtCore.pyqtSignal()  # 返回信号,用来和主界面连接

    def __init__(self):
        super().__init__()
        self.initUI()
        self.c = self.init_clent()


    def init_clent(self): # 客户端初始化
        # 创建 socket 对象
        c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 获取服务器ip地址 应该由界面输入 在这里直接用主机地址代替
        # host = input('please input the server IP address : ')
        host = socket.gethostname()
        # 设置端口号
        port = 9999
        # 连接服务,指定主机和端口
        c.connect((host, port))
        t1 = threading.Thread(target=self.client_recv)
        t1.start()
        return c

    def client_recv(self):
        '''接收数据'''
        while True:
            try:
                data = self.c.recv(1024).decode()
                str_list = data.split(' ')
                x, y = int(str_list[0]), int(str_list[1])
                print('xy')
                self.draw(x, y)
                self.ai_down = True  # 解锁 允许鼠标点击下棋
            except:
                pass



    def initUI(self):  # UI初始化

        self.chessboard = ChessBoard()  # 棋盘类,详见chessboard.py

        palette1 = QPalette()  # 设置棋盘背景
        palette1.setBrush(self.backgroundRole(), QtGui.QBrush(QtGui.QPixmap('source/游戏界面1.png')))
        self.setPalette(palette1)

        # self.setCursor(Qt.PointingHandCursor)  # 鼠标变成手指形状
        self.sound_piece = QSound("sound/move.wav")  # 加载落子音效
        self.sound_win = QSound("sound/win.wav")  # 加载胜利音效
        self.sound_defeated = QSound("sound/defeated.wav")  # 加载失败音效

        self.resize(WIDTH, HEIGHT)  # 画布大小,设为固定值,不允许缩放
        self.setMinimumSize(QtCore.QSize(WIDTH, HEIGHT))
        self.setMaximumSize(QtCore.QSize(WIDTH, HEIGHT))

        self.setWindowTitle("GoBang")  # 窗口名称
        self.setWindowIcon(QIcon('source/icon.ico'))  # 窗口图标

        # 所有按钮的图标和布局
        self.backBtn = MyButton.MyButton('source/返回按钮_hover.png',
                                         'source/返回按钮_normal.png',
                                         'source/返回按钮_press.png',
                                         parent=self)
        self.backBtn.move(610, 80)

        self.startBtn = MyButton.MyButton('source/开始按钮_hover.png',
                                          'source/开始按钮_normal.png',
                                          'source/开始按钮_press.png',
                                          parent=self)
        self.startBtn.move(610, 180)

        self.returnBtn = MyButton.MyButton('source/悔棋按钮_hover.png',
                                           'source/悔棋按钮_normal.png',
                                           'source/悔棋按钮_press.png',
                                           parent=self)
        self.returnBtn.move(610, 400)

        self.loseBtn = MyButton.MyButton('source/认输按钮_hover.png',
                                         'source/认输按钮_normal.png',
                                         'source/认输按钮_press.png',
                                         parent=self)
        self.loseBtn.move(610, 500)

        # 绑定按钮
        self.backBtn.clicked.connect(self.goBack)
        self.startBtn.clicked.connect(self.restart)
        self.loseBtn.clicked.connect(self.lose)
        self.returnBtn.clicked.connect(self.returnOneStep)

        # self.gameStatu = []

        self.black = QPixmap('source/black.png')  # 黑白棋子
        self.white = QPixmap('source/white.png')

        self.piece_now = BLACK  # 黑棋先行



        self.step = 0  # 步数
        self.x, self.y = 1000, 1000



        self.pieces = [LaBel(self) for i in range(225)]  # 新建棋子标签,准备在棋盘上绘制棋子
        for piece in self.pieces:
            piece.setVisible(True)  # 图片可视
            piece.setScaledContents(True)  # 图片大小根据标签大小可变

        # self.mouse_point.raise_()  # 鼠标始终在最上层
        self.ai_down = True  # 主要是为了加锁,当值是False的时候在等待对方下棋,这时候己方鼠标点击失效,要忽略掉 mousePressEvent

        self.setMouseTracking(True)
        self.show()

    # 返回键设计,回到主菜单
    def goBack(self):
        self.backSignal.emit()
        self.close()

    def closeEvent(self, a0: QtGui.QCloseEvent):
        self.backSignal.emit()

    def paintEvent(self, event):  # 画出指示箭头
        qp = QPainter()
        qp.begin(self)
        self.drawLines(qp)
        qp.end()

    # def mouseMoveEvent(self, e):  # 黑色棋子随鼠标移动
    #     # self.lb1.setText(str(e.x()) + ' ' + str(e.y()))
    #     self.mouse_point.move(e.x() - 16, e.y() - 16)

    def mousePressEvent(self, e):  # 玩家1下棋

        if e.button() == Qt.LeftButton and self.ai_down:
            x, y = e.x(), e.y()  # 鼠标坐标
            i, j = self.coordinate_transform_pixel2map(x, y)  # 对应棋盘坐标
            if not i is None and not j is None:  # 棋子落在棋盘上,排除边缘
                if self.chessboard.get_xy_on_logic_state(i, j) == EMPTY:  # 棋子落在空白处
                    t1 = (str(i), ' ', str(j))
                    t2 = ''.join(t1)
                    # 发送棋子坐标到服务器
                    self.c.send(t2.encode('utf-8'))
                    self.draw(i, j)
                    self.ai_down = False # 加锁 避免鼠标再点击


    def drawLines(self, qp):  # 绘制lines
        if self.step != 0:
            pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)
            qp.setPen(pen)
            qp.drawLine(self.x - 5, self.y - 5, self.x + 3, self.y + 3)
            qp.drawLine(self.x + 3, self.y, self.x + 3, self.y + 3)
            qp.drawLine(self.x, self.y + 3, self.x + 3, self.y + 3)

    # 落子代码
    def draw(self, i, j):

        x, y = self.coordinate_transform_map2pixel(i, j)

        if self.piece_now == BLACK:
            self.pieces[self.step].setPixmap(self.black)  # 放置黑色棋子
            self.piece_now = WHITE
            self.chessboard.draw_xy(i, j, BLACK)
        else:
            self.pieces[self.step].setPixmap(self.white)  # 放置白色棋子
            self.piece_now = BLACK
            self.chessboard.draw_xy(i, j, WHITE)

        self.pieces[self.step].setGeometry(x, y, PIECE, PIECE)  # 画出棋子
        self.sound_piece.play()  # 落子音效
        self.step += 1  # 步数+1

        winner = self.chessboard.anyone_win(i, j)  # 判断输赢
        if winner != EMPTY:
            # self.mouse_point.clear()
            self.gameover(winner)

    def coordinate_transform_map2pixel(self, i, j):
        # 从 chessMap 里的逻辑坐标到 UI 上的绘制坐标的转换
        return MARGINXL + j * GRID - PIECE / 2, MARGINY + i * GRID - PIECE / 2

    def coordinate_transform_pixel2map(self, x, y):
        # 从 UI 上的绘制坐标到 chessMap 里的逻辑坐标的转换
        i, j = int(round((y - MARGINY) / GRID)), int(round((x - MARGINXL) / GRID))
        # 有MAGIN, 排除边缘位置导致 i,j 越界
        if i < 0 or i >= 15 or j < 0 or j >= 15:
            return None, None
        else:
            return i, j

    # 这块代码后期还可以再改,用图片做出来应该会更好看
    def gameover(self, winner):
        if winner == BLACK:
            self.sound_win.play()
            reply = QMessageBox.question(self, 'You Win!', 'Continue?',
                                         QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        else:
            self.sound_defeated.play()
            reply = QMessageBox.question(self, 'You Lost!', 'Continue?',
                                         QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

        if reply == QMessageBox.Yes:  # 复位
            self.piece_now = BLACK
            self.mouse_point.setPixmap(self.black)
            self.step = 0
            for piece in self.pieces:
                piece.clear()
            self.chessboard.reset()
            self.update()
        else:
            self.close()

    # 认输功能键,不知道为什么卡的厉害。人机对战的认输还没写
    def lose(self):
        # if self.gameStatu == False:
        #     return
        if self.piece_now == BLACK:
            self.gameover(WHITE)
        # elif self.turnChessColor == "white":
        #     self.lbl = QLabel(self)
        #     self.lbl.setPixmap(QPixmap("source/黑棋胜利.png"))
        #     self.lbl.move(150,150)
        #     self.lbl.show()
        else:
            return

    # 重开,这个问题有点大,重新绘图我没实现。目前是把数组清空了,图没变(在上面重新画棋盘也太蠢了吧,刷新界面会比较好但是我没写出来:/)
    def restart(self):
        for i in range(15):
            for j in range(15):
                x, y = self.coordinate_transform_map2pixel(i, j)
                self.chessboard.draw_xy(i, j, EMPTY)
                self.pieces[self.step].setGeometry(x, y, 100, 100)
        # if self.lbl != None:
        #     self.lbl.close()
        self.chessboard.reset
        # self.close
        # ex = GoBang()

    # 这个理论上要做悔棋功能,看看写代码的同学是怎么实现的。
    def returnOneStep(self):
        return
 def initSounds(self):
     sounds = {
         "DetectionMode": QSound("resources/voices/detect_start.wav"),
         "SleepMode": QSound("resources/voices/sleep_mode.wav"),
         "Activation": QSound("resources/voices/activated.wav"),
         "Spotted": QSound("resources/voices/target_aquaired.wav"),
         "Shutdown": QSound("resources/voices/shutdown.wav"),
         "Searching": QSound("resources/voices/searching.wav"),
         "StartUp": QSound("resources/voices/startup.mp3"),
         "Login": QSound("resources/voices/login_sound.wav"),
         "Save": QSound("resources/voices/save_sound.wav"),
         "Error": QSound("resources/voices/error.wav"),
         "Moron": QSound("resources/voices/hey_moron.wav"),
         "Daft": QSound("resources/voices/daftPunk.wav")
     }
     return SoundManager(sounds)
Example #21
0
class GoBang(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        self.chessboard = ChessBoard()  # 棋盘类

        palette1 = QPalette()  # 设置棋盘背景
        palette1.setBrush(self.backgroundRole(),
                          QtGui.QBrush(QtGui.QPixmap('img/chessboard.jpg')))
        self.setPalette(palette1)
        # self.setStyleSheet("board-image:url(img/chessboard.jpg)")  # 不知道这为什么不行
        self.setCursor(Qt.PointingHandCursor)  # 鼠标变成手指形状
        self.sound_piece = QSound("sound/luozi.wav")  # 加载落子音效
        self.sound_win = QSound("sound/win.wav")  # 加载胜利音效
        self.sound_defeated = QSound("sound/defeated.wav")  # 加载失败音效

        self.resize(WIDTH, HEIGHT)  # 固定大小 540*540
        self.setMinimumSize(QtCore.QSize(WIDTH, HEIGHT))
        self.setMaximumSize(QtCore.QSize(WIDTH, HEIGHT))

        self.setWindowTitle("GoBang")  # 窗口名称
        self.setWindowIcon(QIcon('img/black.png'))  # 窗口图标

        # self.lb1 = QLabel('            ', self)
        # self.lb1.move(20, 10)

        self.black = QPixmap('img/black.png')
        self.white = QPixmap('img/white.png')

        self.piece_now = BLACK  # 黑棋先行
        self.my_turn = True  # 玩家先行
        self.step = 0  # 步数
        self.x, self.y = 1000, 1000

        self.mouse_point = LaBel(self)  # 将鼠标图片改为棋子
        self.mouse_point.setScaledContents(True)
        self.mouse_point.setPixmap(self.black)  #加载黑棋
        self.mouse_point.setGeometry(270, 270, PIECE, PIECE)
        self.pieces = [LaBel(self) for i in range(225)]  # 新建棋子标签,准备在棋盘上绘制棋子
        for piece in self.pieces:
            piece.setVisible(True)  # 图片可视
            piece.setScaledContents(True)  #图片大小根据标签大小可变

        self.mouse_point.raise_()  # 鼠标始终在最上层
        self.ai_down = True  # AI已下棋,主要是为了加锁,当值是False的时候说明AI正在思考,这时候玩家鼠标点击失效,要忽略掉 mousePressEvent

        self.setMouseTracking(True)
        self.show()

    def paintEvent(self, event):  # 画出指示箭头
        qp = QPainter()
        qp.begin(self)
        self.drawLines(qp)
        qp.end()

    def mouseMoveEvent(self, e):  # 黑色棋子随鼠标移动
        # self.lb1.setText(str(e.x()) + ' ' + str(e.y()))
        self.mouse_point.move(e.x() - 16, e.y() - 16)

    def mousePressEvent(self, e):  # 玩家下棋
        if e.button() == Qt.LeftButton and self.ai_down == True:
            x, y = e.x(), e.y()  # 鼠标坐标
            i, j = self.coordinate_transform_pixel2map(x, y)  # 对应棋盘坐标
            if not i is None and not j is None:  # 棋子落在棋盘上,排除边缘
                if self.chessboard.get_xy_on_logic_state(
                        i, j) == EMPTY:  # 棋子落在空白处
                    self.draw(i, j)
                    self.ai_down = False
                    board = self.chessboard.board()
                    self.AI = AI(board)  # 新建线程对象,传入棋盘参数
                    self.AI.finishSignal.connect(self.AI_draw)  # 结束线程,传出参数
                    self.AI.start()  # run

    def AI_draw(self, i, j):
        if self.step != 0:
            self.draw(i, j)  # AI
            self.x, self.y = self.coordinate_transform_map2pixel(i, j)
        self.ai_down = True
        self.update()

    def draw(self, i, j):
        x, y = self.coordinate_transform_map2pixel(i, j)

        if self.piece_now == BLACK:
            self.pieces[self.step].setPixmap(self.black)  # 放置黑色棋子
            self.piece_now = WHITE
            self.chessboard.draw_xy(i, j, BLACK)
        else:
            self.pieces[self.step].setPixmap(self.white)  # 放置白色棋子
            self.piece_now = BLACK
            self.chessboard.draw_xy(i, j, WHITE)

        self.pieces[self.step].setGeometry(x, y, PIECE, PIECE)  # 画出棋子
        self.sound_piece.play()  # 落子音效
        self.step += 1  # 步数+1

        winner = self.chessboard.anyone_win(i, j)  # 判断输赢
        if winner != EMPTY:
            self.mouse_point.clear()
            self.gameover(winner)

    def drawLines(self, qp):  # 指示AI当前下的棋子
        if self.step != 0:
            pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)
            qp.setPen(pen)
            qp.drawLine(self.x - 5, self.y - 5, self.x + 3, self.y + 3)
            qp.drawLine(self.x + 3, self.y, self.x + 3, self.y + 3)
            qp.drawLine(self.x, self.y + 3, self.x + 3, self.y + 3)

    def coordinate_transform_map2pixel(self, i, j):
        # 从 chessMap 里的逻辑坐标到 UI 上的绘制坐标的转换
        return MARGIN + j * GRID - PIECE / 2, MARGIN + i * GRID - PIECE / 2

    def coordinate_transform_pixel2map(self, x, y):
        # 从 UI 上的绘制坐标到 chessMap 里的逻辑坐标的转换
        i, j = int(round((y - MARGIN) / GRID)), int(round((x - MARGIN) / GRID))
        # 有MAGIN, 排除边缘位置导致 i,j 越界
        if i < 0 or i >= 15 or j < 0 or j >= 15:
            return None, None
        else:
            return i, j

    def gameover(self, winner):
        if winner == BLACK:
            self.sound_win.play()
            reply = QMessageBox.question(self, 'You Win!', 'Continue?',
                                         QMessageBox.Yes | QMessageBox.No,
                                         QMessageBox.No)
        else:
            self.sound_defeated.play()
            reply = QMessageBox.question(self, 'You Lost!', 'Continue?',
                                         QMessageBox.Yes | QMessageBox.No,
                                         QMessageBox.No)

        if reply == QMessageBox.Yes:  # 复位
            self.piece_now = BLACK
            self.mouse_point.setPixmap(self.black)
            self.step = 0
            for piece in self.pieces:
                piece.clear()
            self.chessboard.reset()
            self.update()
        else:
            self.close()
Example #22
0
class Notifier(QObject):
    _conn = None
    _interface = None
    _notifications = None  # a dict of notifyId: taskDict

    _completedTasksStat = None

    def __init__(self, parent):
        super().__init__(parent)
        self._conn = QDBusConnection("Xware Desktop").sessionBus()

        self._interface = QDBusInterface(_DBUS_NOTIFY_SERVICE,
                                         _DBUS_NOTIFY_PATH,
                                         _DBUS_NOTIFY_INTERFACE,
                                         self._conn)

        self._notifications = {}
        self._completedTasksStat = app.etmpy.completedTasksStat
        self._completedTasksStat.sigTaskCompleted.connect(self.notifyTask)

        successful = self._conn.connect(_DBUS_NOTIFY_SERVICE,
                                        _DBUS_NOTIFY_PATH,
                                        _DBUS_NOTIFY_INTERFACE,
                                        "ActionInvoked", self.slotActionInvoked)
        if not successful:
            logging.error("ActionInvoked connect failed.")

        self._qSound_complete = QSound(":/sound/download-complete.wav", self)

    @property
    def isConnected(self):
        return self._conn.isConnected()

    def notifyTask(self, taskId):
        task = self._completedTasksStat.getTask(taskId)

        if task.get("state", None) == 11:  # see definitions in class TaskStatistic.
            if app.settings.getbool("frontend", "notifybysound"):
                self._qSound_complete.play()
            self._dbus_notify(task)
        else:
            # TODO: Also notify if errors occur
            pass

    def _dbus_notify(self, task):
        if not app.settings.getbool("frontend", "popnotifications"):
            return

        qdBusMsg = self._interface.call(
            "Notify",
            QDBusArgument("Xware Desktop", QMetaType.QString),  # app_name
            QDBusArgument(0, QMetaType.UInt),  # replace_id
            QDBusArgument("/opt/xware_desktop/frontend/thunder.ico", QMetaType.QString),  # app_icon
            QDBusArgument("下载完成", QMetaType.QString),  # summary
            QDBusArgument(task["name"], QMetaType.QString),  # body
            QDBusArgument(["open", "打开", "openDir", "打开文件夹"], QMetaType.QStringList),  # actions,
            {
                "category": "transfer.complete",
            },  # hints
            QDBusArgument(5000, QMetaType.Int),  # timeout
        )

        if qdBusMsg.errorName():
            logging.error("DBus, notifyTask {}: {}".format(qdBusMsg.errorName(),
                                                           qdBusMsg.errorMessage()))
        else:
            # add it to the dict
            self._notifications[qdBusMsg.arguments()[0]] = task

    @pyqtSlot(QDBusMessage)
    def slotActionInvoked(self, msg):
        notifyId, action = msg.arguments()
        task = self._notifications.get(notifyId, None)
        if not task:
            # other applications' notifications
            return
        name = task["name"]  # filename
        path = task["path"]  # location

        if action == "open":
            openPath = os.path.join(path, name)
        elif action == "openDir":
            openPath = path
        else:
            raise Exception("Unknown action from slotActionInvoked.")

        nativeOpenPath = app.mountsFaker.convertToNativePath(openPath)
        qUrl = QUrl.fromLocalFile(nativeOpenPath)
        QDesktopServices().openUrl(qUrl)
Example #23
0
 def __init__(self):
     self.apple = QSound('sound.wav')
     self.lose = QSound('sound2.wav')
     self.lose2 = QSound('sound3.wav')
Example #24
0
 def wavplay(self):
     self.sound = QSound('./result/audio/outcome.wav')
     self.sound.play()
Example #25
0
    def __init__(self, parent=None, ynmOP=None):
        pass

        super(MyMainWindow, self).__init__(parent)

        self.CounterTimeBool = False
        self.CounterTimer = QTimer()
        self.CounterValueIntDefault = 8
        self.CounterValueInt = self.CounterValueIntDefault
        self.CounterTimer.timeout.connect(self.CounterTimeOperations)

        print("process...30%")
        self.ynmOP = ynmOP
        self.setupUi(self)
        self.initUI()
        self.createActions()
        self.createMenus()
        self.createToolBars()
        print("process...50%")
        # self.form=Ui_Form
        #global database temp
        self.op = GlobalOperator()
        print(self.op.ImageMaxWidth)
        self.op.ImageMaxWidth = self.scrollAreaWidgetContents.width(
        ) / self.op.ImageColumns
        print(self.op.ImageMaxWidth)
        # self.ShowAnsSignal=[True,""]
        self.downloadOP = xmlprocess.DownloadOperator()
        self.ShowAnsBool = True

        #获得一批单词,作为任务
        self.CurrentBatchWordList = []
        self.NextBatch()
        self.CurrentWord = self.GetANextWordFromBatch()
        # self.ynmOP=
        self.CurrentTrans = self.ynmOP.getWordTrans(self.CurrentWord)

        self.CurrentWordImgHistoryDF = pd.DataFrame()
        self.CurrentAlreadyMemNum = 0
        self.CurrentAlreadyMemList = []
        self.CurrentMemNoClicked = False

        #
        self.CurrentMatchMemYesList = []  #当前批已经记住的单词
        print(self.CurrentBatchWordList)

        print("process...80%")

        # self.OpenFarm()

        self.Sounds = [
            QSound("click.wav"),
            QSound("water.wav"),
            QSound("happy.wav")
        ]
        # self.clicksound=QSound("click.wav")

        # 初始化单词的显示
        self.GetWordButton.click()

        #主窗口隐藏 农场显示
        self.FarmWidget = MyFarmWidget(MainWindow=self)
        self.hide()
        self.OpenFarm()
        self.ClickSound(2)
        print("process...100%")
Example #26
0
 def wavplay(self):
     self.sound = QSound('./origin/choosemode.wav')
     self.sound.play()
Example #27
0
class CommandUi(QWidget):

    switch_window = QtCore.pyqtSignal()

    def __init__(self):
        super().__init__()
        self.initUI()
        self.wavplay()

    def initUI(self):
        self.setWindowTitle("CommandUi")

        layout = QtWidgets.QGridLayout()

        self.label = QtWidgets.QLabel()
        layout.addWidget(self.label)

        self.button = QtWidgets.QPushButton('Command')
        self.button.clicked.connect(self.command)

        #self.button2 = QtWidgets.QPushButton('Next')
        #self.button2.clicked.connect(self.switch)

        layout.addWidget(self.button)
        #layout.addWidget(self.button2)

        self.setLayout(layout)

        self.resize(250, 150)
        self.move(300, 300)
        pic = QPixmap('./origin/volume.png')
        self.lb = QLabel(self)
        self.lb.setGeometry(50, 50, 150, 30)
        self.lb.setPixmap(pic)

    def wavplay(self):
        self.sound = QSound('./origin/instruction.wav')
        self.sound.play()

    def command(self):
        self.switch_window.emit()

        r = speech_recognition.Recognizer()

        with speech_recognition.Microphone() as source:
            print("[INFO] Start speeking.")
            audio = r.listen(source)

        text = r.recognize_google(audio, language='zh-TW')
        #print(text)

        if os.path.exists('./result/audio/'):
            print("[INFO] ..OK")
        else:
            print("[INFO] audio directory is not exist, now create it.")
            os.mkdir('./result/audio/')
            print("[INFO] ..OK")

        if os.path.isfile('./result/audio/command.txt'):
            with open('./result/audio/command.txt', 'w') as f:
                f.write('%s' % text)
        else:
            with open('./result/audio/command.txt', 'w') as f:
                f.write('%s' % text)

        print("[INFO] command.txt is created success.")
        return text
Example #28
0
 def wavplay(self):
     self.sound = QSound('./origin/instruction.wav')
     self.sound.play()
Example #29
0
 def mousePressEvent(self, e):
     self._holes.append(e.pos())
     super().mousePressEvent(e)
     self.viewport().update()
     QSound.play("shot.wav")
Example #30
0
class playSound(QWidget):
    def __init__(self, parent=None):
        super(playSound, self).__init__(parent)
        self.fileName = ""
        self.getFileName()
        self.focusSound = QSound(self.fileName)
        self.focusSound.setLoops(10)

        self.finishedSound = QSound("config/ringring.wav")

        self.breakSound = QSound("config/happy.wav")
        self.breakSound.setLoops(10)

        self.accpetSound = QSound("config/accpet.wav")

        self.errorSound = QSound("config/error.wav")
        return

    def getFileName(self):
        file = open("config/currentBgm.txt", "r").readline()
        text = file.strip("\n")
        self.fileName = "audio/" + text
        return

    def playFocusSound(self):
        self.focusSound.play()
        return

    def playFinishedSound(self):
        self.finishedSound.play()
        return

    def playBreakSound(self):
        self.breakSound.play()
        return

    def playAcceptSound(self):
        self.accpetSound.play()
        return

    def playErrorSound(self):
        self.errorSound.play()
        return

    def stopFocusSound(self):
        self.focusSound.stop()

    def stopBreakSound(self):
        self.breakSound.stop()
Example #31
0
class Notifier(QObject):
    def __init__(self, *, taskModel, frontendSettings, parent):
        super().__init__(parent)
        self.__taskModel = taskModel
        self.__frontendSettings = frontendSettings
        self._conn = QDBusConnection("Xware Desktop").sessionBus()
        self._interface = QDBusInterface(_DBUS_NOTIFY_SERVICE,
                                         _DBUS_NOTIFY_PATH,
                                         _DBUS_NOTIFY_INTERFACE, self._conn)

        self._notified = {}  # a dict of notifyId: taskDict
        self.__taskModel.taskCompleted.connect(self.notifyTaskCompleted,
                                               Qt.DirectConnection)
        self._conn.registerObject(_DBUS_NOTIFY_PATH,
                                  self)  # you must register it before connect
        self._capabilities = self._getCapabilities()
        if "actions" in self._capabilities:
            successful = self._conn.connect(_DBUS_NOTIFY_SERVICE,
                                            _DBUS_NOTIFY_PATH,
                                            _DBUS_NOTIFY_INTERFACE,
                                            "ActionInvoked",
                                            self.slotActionInvoked)
            if not successful:
                logging.error("ActionInvoked connect failed.")

        self._qSound_complete = QSound(":/sound/download-complete.wav", self)

    @property
    def isConnected(self):
        return self._conn.isConnected()

    @pyqtSlot("QObject", result="void")
    def notifyTaskCompleted(self, taskItem):
        if self.__frontendSettings.getbool("notifybysound"):
            self._qSound_complete.play()

        if not self.__frontendSettings.getbool("popnotifications"):
            return

        self._dbus_notifyCompleted(taskItem)

    def _getCapabilities(self):
        # get libnotify server caps and remember it.
        qdBusMsg = self._interface.call("GetCapabilities")
        if qdBusMsg.errorName():
            logging.error(
                "cannot get org.freedesktop.Notifications.GetCapabilities")
            return []
        else:
            return qdBusMsg.arguments()[0]

    def _dbus_notifyCompleted(self, task: "TaskItem"):
        if "actions" in self._capabilities:
            actions = QDBusArgument(["open", "打开", "viewOneFile", "在文件夹中显示"],
                                    QMetaType.QStringList)
        else:
            actions = QDBusArgument([], QMetaType.QStringList)

        qdBusMsg = self._interface.call(
            "Notify",
            QDBusArgument("Xware Desktop", QMetaType.QString),  # app_name
            QDBusArgument(0, QMetaType.UInt),  # replace_id
            QDBusArgument("xware-desktop", QMetaType.QString),  # app_icon
            QDBusArgument("下载完成", QMetaType.QString),  # summary
            QDBusArgument(task.name, QMetaType.QString),  # body
            actions,
            {
                "category": "transfer.complete",
            },  # hints
            QDBusArgument(5000, QMetaType.Int),  # timeout
        )

        if qdBusMsg.errorName():
            logging.error("DBus, notifyTask {}: {}".format(
                qdBusMsg.errorName(), qdBusMsg.errorMessage()))
        else:
            # add it to the dict
            notificationId = qdBusMsg.arguments()[0]
            self._notified[notificationId] = task.id

    @pyqtSlot(QDBusMessage)
    def slotActionInvoked(self, msg):
        notifyId, action = msg.arguments()
        taskId = self._notified.get(notifyId, None)
        if not taskId:
            # other applications' notifications
            return

        taskItem = self.__taskModel.adapterMap.get(taskId, None)
        if not taskItem:
            logging.debug("taskItem cannot be found anymore in TaskModel.")
            return

        fullpath = taskItem.fullpath  # path + name

        if action == "open":
            return systemOpen(fullpath)
        elif action == "viewOneFile":
            return viewOneFile(fullpath)
        elif action == "default":  # Unity's notify osd always have a default action.
            return
        else:
            raise Exception(
                "Unknown action from slotActionInvoked: {}.".format(action))
class AddEditPuzzle(QDialog):

    def __init__(self, collection=None, currentPuzzleIndex=-1, parent=None):
        print('Initializing AddEditPuzzle')
        super(AddEditPuzzle, self).__init__(parent)

        # Turn off the context help button (The ? in the title bar.)
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)

        self._collection = collection
        self._currentPuzzleIndex = currentPuzzleIndex
        self._puzzles = collection.puzzles()
        self._puzzleWords = {}                  # used to compare lengths of words puzzleCode and puzzleSolution
        self._codeKeys = {}                     # used to make sure the code is consistent throughout the puzzle
        self._errorSound = QSound('sounds/error-01.wav')
        self.codeKeys = {}
        self.puzzleWords = {}

        self.setupUI()
        self.puzzleCodeEdit.installEventFilter(self)
        self.citationCodeEdit.installEventFilter(self)
        self.puzzleSolutionEdit.installEventFilter(self)
        self.citationSolutionEdit.installEventFilter(self)

        if self._currentPuzzleIndex >= 0:
            self.setPuzzleSelector(self._currentPuzzleIndex)
            self._mode = "Edit"
        else:
            self._mode = None
        # Commented out 9-22-2016
        # self._puzzleEdited = False
        # self.updateUI()
            # ToDo: Eliminate code that has been commented out for a while

    def eventFilter(self, source, event):

        # ToDo: Add explanation text to eventFilter, checkPuzzle, and checkCitation.
        # ToDo: Include code consistency checking to the eventFilter
        # ToDo: change function names to lower case as you work on each one - not eventFilter

        if (event.type() == QEvent.FocusOut):
            if source is self.puzzleTitleEdit:
                self.set_editing_access()
            if source is self.puzzleCodeEdit:
                self.set_editing_access()
                if self.puzzleCodeEdit.toPlainText() and self.puzzleSolutionEdit.toPlainText():
                    self.checkPuzzle()
            if source is self.citationCodeEdit:
                if self.citationCodeEdit.text() and self.citationSolutionEdit.text():
                    self.checkCitation()
            if source is self.puzzleSolutionEdit:
                if self.puzzleSolutionEdit.toPlainText() and self.puzzleCodeEdit.toPlainText():
                    self.checkPuzzle()
            if source is self.citationSolutionEdit:
                if self.citationSolutionEdit.text() and self.citationCodeEdit.text():
                    self.checkCitation()
            self.blockSignals(False)
        return super(AddEditPuzzle, self).eventFilter(source, event)

    def set_editing_access(self):
        """
        Manages the availability of the Save Puzzle button
        The Save Puzzle button is turned off if either puzzleTitleEdit or puzzleCodeEdit are empty.
        :return: None
        """
        # ToDo: modify or remove editBoxChanged routine and the connections to it in light of the new eventFilter
        if self.puzzleTitleEdit.text() == "" or self.puzzleCodeEdit.toPlainText() == "":
            self.puzzleSolutionEdit.setEnabled(False)
            self.citationCodeEdit.setEnabled(False)
            self.citationSolutionEdit.setEnabled(False)
            self.hintEdit.setEnabled(False)
            self.storePuzzleButton.setEnabled(False)
        else:
            self.puzzleSolutionEdit.setEnabled(True)
            self.citationCodeEdit.setEnabled(True)
            self.citationSolutionEdit.setEnabled(True)
            self.hintEdit.setEnabled(True)
            self.storePuzzleButton.setEnabled(True)

    def checkPuzzle(self):
        wordLengthsEqual, text1, text2 = self.compareWordLengths(self.puzzleCodeEdit.toPlainText(),
                                                                   self.puzzleSolutionEdit.toPlainText())
        if not wordLengthsEqual:
            msg = "There are problems between the puzzle code and its solution.<br>"
            msg += "See below."
            self.inputError(msg)
        else:
            self.resetErrorBox()
        self.puzzleCodeEdit.setText(text1)
        self.puzzleSolutionEdit.setText(text2)

    def checkCitation(self):
        wordLengthsEqual, text1, text2 = self.compareWordLengths(self.citationCodeEdit.text(),
                                                                 self.citationSolutionEdit.text())
        if not wordLengthsEqual:
            msg = "Citation code structure does not match the solution:<br>"
            msg += text1 + " does not match " + text2
            self.inputError(msg)
        else:
            self.resetErrorBox()

    def inputError(self, msg):
        self._errorSound.play()
        self.errorDisplayWindow.setStyleSheet("QLabel { background-color : white; }")
        self.errorDisplayWindow.setText(msg)

    def resetErrorBox(self):
        self.errorDisplayWindow.setStyleSheet("QLabel { background-color: rgb(240, 240, 240) }")
        self.errorDisplayWindow.setText("")

    def compareWordLengths(self, text1, text2):
        print("got to compareWordLengths with text1 =", text1, " and text2 =", text2)
        result = True
        msg = ""
        if len(text1) != len(text2):
            result = False
        index = 0
        wordList1 = text1.split()
        wordList2 = text2.split()
        newText1 = ""
        newText2 = ""
        for word in wordList1:
            if index < len(wordList2):
                if len(word) != len(wordList2[index]):
                    result = False
                    newText1 += "<font color=red>" + word + "</font> "
                    newText2 += "<font color=red>" + wordList2[index] + "</font> "
                else:
                    newText1 += "<font color=black>" + word + "</font> "
                    newText2 += "<font color=black>" + wordList2[index] + "</font> "
            else:
                result = False
                newText1 += "<font color=pink>" + word + "</font> "
            index += 1
        while index < len(wordList2):
            result = False
            newText2 += "<font color=blue>" + wordList2[index] + "</font> "
            index += 1

        return result, newText1.strip(), newText2.strip()

    def collection(self):
        return self._collection

    def currentPuzzleIndex(self):
        return self._currentPuzzleIndex

    def setCurrentPuzzleIndex(self, index):
        self._currentPuzzleIndex = index

    def puzzles(self):
        return self._puzzles

    def setPuzzles(self, puzzles):
        self._puzzles = puzzles

    def addPuzzle(self, puzzle):
        self._puzzles.append(puzzle)

    def insertPuzzle(self, index, puzzle):
        self._puzzles.insert(index, puzzle)
        # this function has not yet been used in the code below
        # ToDo: Alter the code to use insertPuzzle when needed

    def setupUI(self):

        print('in setupUI')

        self.setWindowIcon(QIcon("images/editpuzzleicon-2.png"))
        self.setWindowTitle("Add or Edit Puzzles")

        self.addPuzzleButton = QPushButton("Add New Puzzle")
        self.addPuzzleButton.clicked.connect(self.createNewPuzzle)
        addButtonLayout = QHBoxLayout()
        addButtonLayout.addSpacing(220)
        addButtonLayout.addWidget(self.addPuzzleButton)

        errorLabel = QLabel("Error Display")
        self.errorDisplayWindow = QLabel('')
        self.errorDisplayWindow.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.errorDisplayWindow.setMinimumHeight(50)
        self.errorDisplayWindow.setAlignment(Qt.AlignTop)
        self.errorDisplayWindow.setTextFormat(Qt.RichText)
        self.errorDisplayWindow.setStyleSheet("QLabel { background-color : rgb(240, 240, 240); }")

        errorDisplayLayout = QVBoxLayout()
        errorDisplayLayout.addWidget(errorLabel)
        errorDisplayLayout.addWidget(self.errorDisplayWindow)

        puzzleSelectorLabel = QLabel("Puzzle Selector:")
        self.puzzleSelector = QComboBox()
        self.puzzleSelector.currentIndexChanged.connect(self.addEditPuzzleSelectorChanged)

        puzzleTitleLabel = QLabel("Puzzle Name:")
        self.puzzleTitleEdit = QLineEdit()
        # self.puzzleTitleEdit.textChanged.connect(self.editBoxChanged)

        puzzleCodeLabel = QLabel("Puzzle Code:")
        self.puzzleCodeEdit = CodeTextEdit()
        self.puzzleCodeEdit.setAccessibleName("puzzleCodeEdit")
        self.puzzleCodeEdit.setTabChangesFocus(True)
        self.puzzleCodeEdit.setMaximumHeight(60)
        # self.puzzleCodeEdit.textChanged.connect(self.editBoxChanged)

        citationCodeLabel = QLabel("Citation Code (if any):")
        self.citationCodeEdit = CodeLineEdit()
        self.citationCodeEdit.setAccessibleName("citationCodeEdit")
        # self.citationCodeEdit.textChanged.connect(self.editBoxChanged)

        puzzleSolutionLabel = QLabel("Puzzle Solution (if any):")
        self.puzzleSolutionEdit = CodeTextEdit()
        self.puzzleSolutionEdit.setTabChangesFocus(True)
        self.puzzleSolutionEdit.setMaximumHeight(60)
        # self.puzzleSolutionEdit.textChanged.connect(self.editBoxChanged)

        citationSolutionLabel = QLabel("Citation Solution (if any):")
        self.citationSolutionEdit = CodeLineEdit()
        # self.citationSolutionEdit.textChanged.connect(self.editBoxChanged)

        hintLabel = QLabel("Hints (if any):")
        self.hintEdit = HintLineEdit()
        # self.hintEdit.textChanged.connect(self.editBoxChanged)

        puzzleButtonBox = QDialogButtonBox()
        self.storePuzzleButton = puzzleButtonBox.addButton("Store Puzzle", QDialogButtonBox.ActionRole)
        self.deleteButton = puzzleButtonBox.addButton("Delete", QDialogButtonBox.DestructiveRole)
        self.clearButton = puzzleButtonBox.addButton("Clear", QDialogButtonBox.ActionRole)
        self.cancelPuzzleButton = puzzleButtonBox.addButton("Cancel New Puzzle", QDialogButtonBox.RejectRole)

        self.storePuzzleButton.clicked.connect(self.storePuzzle)
        self.deleteButton.clicked.connect(self.deletePuzzle)
        self.clearButton.clicked.connect(self.clearPuzzle)
        self.cancelPuzzleButton.clicked.connect(self.cancelPuzzle)

        puzzleGrid = QGridLayout()
        puzzleGrid.addWidget(puzzleSelectorLabel, 0, 0, Qt.AlignRight)
        puzzleGrid.addWidget(self.puzzleSelector, 0, 1)
        puzzleGrid.addWidget(puzzleTitleLabel, 1, 0, Qt.AlignRight)
        puzzleGrid.addWidget(self.puzzleTitleEdit, 1, 1)
        puzzleGrid.addWidget(puzzleCodeLabel, 2, 0, Qt.AlignRight | Qt.AlignTop)
        puzzleGrid.addWidget(self.puzzleCodeEdit, 2, 1)
        puzzleGrid.addWidget(citationCodeLabel, 3, 0, Qt.AlignRight)
        puzzleGrid.addWidget(self.citationCodeEdit, 3, 1)
        puzzleGrid.addWidget(puzzleSolutionLabel, 4, 0, Qt.AlignRight | Qt.AlignTop)
        puzzleGrid.addWidget(self.puzzleSolutionEdit, 4, 1)
        puzzleGrid.addWidget(citationSolutionLabel, 5, 0)
        puzzleGrid.addWidget(self.citationSolutionEdit, 5, 1)
        puzzleGrid.addWidget(hintLabel, 6, 0, Qt.AlignRight)
        puzzleGrid.addWidget(self.hintEdit, 6, 1)

        puzzleEditLayout = QVBoxLayout()
        puzzleEditLayout.addLayout(errorDisplayLayout)
        puzzleEditLayout.addLayout(puzzleGrid)
        puzzleEditLayout.addWidget(puzzleButtonBox)

        self.puzzleEditControls = QGroupBox("Puzzle Editor")
        self.puzzleEditControls.setEnabled(False)
        self.puzzleEditControls.setLayout(puzzleEditLayout)

        cancelButton = QPushButton("Cancel")
        cancelButton.clicked.connect(self.cancelDialog)

        self.acceptButton = QPushButton("Accept Changes")
        self.acceptButton.setEnabled(False)
        self.acceptButton.clicked.connect(self.accept)

        dialogButtonLayout = QHBoxLayout()
        dialogButtonLayout.addSpacing(220)
        dialogButtonLayout.addWidget(self.acceptButton)
        dialogButtonLayout.addWidget(cancelButton)

        dialogLayout = QVBoxLayout(self)
        dialogLayout.addLayout(addButtonLayout)
        dialogLayout.addWidget(self.puzzleEditControls)
        dialogLayout.addLayout(dialogButtonLayout)

    def setPuzzleSelector(self, index):
        """
        Adds all the puzzles in the current collection to the puzzleSelector and sets the selector to the given index
        :return: None
        """
        # ToDo: Make sure puzzleSelector is properly set upon entry under all circumstances
        print("In setPuzzleSelector")
        currentCollection = self.collection()
        self.puzzleEditControls.setEnabled(True)
        self.cancelPuzzleButton.setEnabled(False)
        self.storePuzzleButton.setEnabled(False)
        self.puzzleSelector.blockSignals(True)
        self.puzzleSelector.clear()
        for puzzle in currentCollection.puzzles():
            self.puzzleSelector.addItem(puzzle.puzzleTitle())
        print("self.puzzleSelector.currentIndex() = ", self.puzzleSelector.currentIndex(), " just before being set to ", index)
        self.puzzleSelector.blockSignals(False)
        self.puzzleSelector.setCurrentIndex(self.currentPuzzleIndex())
        self.displayPuzzle(index)

    def displayPuzzle(self, index):
        """
        When there is a current puzzle, this method is called to populate the widgets of the puzzle editor group
        with the values of the current puzzle
        :return: None
        """
        print("Got to displayPuzzle")
        # index = self.currentPuzzleIndex()
        # self.setCurrentPuzzleIndex(index)
        currentPuzzle = self._puzzles[index]
        self.puzzleTitleEdit.blockSignals(True)
        self.puzzleTitleEdit.setText(currentPuzzle.puzzleTitle())
        self.puzzleTitleEdit.blockSignals(False)
        self.puzzleCodeEdit.blockSignals(True)
        self.puzzleCodeEdit.setText(currentPuzzle.puzzleCode())
        self.puzzleCodeEdit.blockSignals(False)
        self.citationCodeEdit.blockSignals(True)
        self.citationCodeEdit.setText(currentPuzzle.citationCode())
        self.citationCodeEdit.blockSignals(False)
        self.puzzleSolutionEdit.blockSignals(True)
        self.puzzleSolutionEdit.setText(currentPuzzle.puzzleSolution())
        self.puzzleSolutionEdit.blockSignals(False)
        self.citationSolutionEdit.blockSignals(True)
        self.citationSolutionEdit.setText(currentPuzzle.citationSolution())
        self.citationSolutionEdit.blockSignals(False)
        hintText = ""
        for hint in currentPuzzle.hints():
            hintText += hint + "; "
        self.hintEdit.blockSignals(True)
        self.hintEdit.setText(hintText)
        self.hintEdit.blockSignals(False)
        print("Got to end of displayPuzzle")

    # Commented Out 9-22-2016
    # def updateUI(self):
    #     """
    #     Sets the availability of the dialog box's controls according to its present state
    #     :return: None
    #     """
    #     if self._puzzleEdited:
    #         self.storePuzzleButton.setEnabled(True)
    #     else:
    #         self.storePuzzleButton.setEnabled(False)

    def createNewPuzzle(self):
        """
        If a puzzle is present (as indicated by a non-negative value of self.puzzleSelector.index)
        The contents of the input boxes are cleared and a suggested title, "Puzzle n", where n is an integer
        indicating the next available number, is placed in the puzzleTitleEdit control.
        :return: None
        """

        print("Got to createNewPuzzle")
        self.puzzleEditControls.setEnabled(True)
        self.addPuzzleButton.setEnabled(False)
        self.puzzleSelector.setEnabled(False)
        self.deleteButton.setEnabled(False)
        self.cancelPuzzleButton.setEnabled(True)
        self.clearPuzzle()
        nextNumber = len(self._puzzles) + 1
        self._oldPuzzleIndex = self._currentPuzzleIndex
        self._currentPuzzleIndex = nextNumber - 1
        self.puzzleTitleEdit.setText("Puzzle " + str(nextNumber))
        self.puzzleCodeEdit.setFocus()
        self._mode = "Add"

    def addEditPuzzleSelectorChanged(self):
        print("Got to addEditPuzzleSelectorChanged")
        self._currentPuzzleIndex = self.puzzleSelector.currentIndex()
        self.displayPuzzle(self._currentPuzzleIndex)
        self._mode = "Edit"

    def deletePuzzle(self):
        print("Got to deletePuzzle")

    def clearPuzzle(self):
        """
        Clears the current puzzle out of the puzzle editor and creates the puzzleWords and codeKeys dictionaries
        to assist in the spontaneous checking of the puzzle entry.  See the various error checking routines called
        by editBoxChanged to see how these are used.

        :return: None
        """
        print("Got to clearPuzzle")
        self.puzzleTitleEdit.setText("")
        self.puzzleCodeEdit.setText("")
        self.citationCodeEdit.setText("")
        self.puzzleSolutionEdit.setText("")
        self.citationSolutionEdit.setText("")
        self.hintEdit.setText("")
        self._puzzleWords = {}
        self._codeKeys = {}

    def cancelPuzzle(self):
        """
        If the user clicks this button he or she has decided NOT to add a new puzzle, but doesn't want to leave
        the dialog box entirely.  Perhaps to edit an existing puzzle.
        :return: None
        """
        print("Got to cancelPuzzle")
        self.addPuzzleButton.setEnabled(True)
        self.clearPuzzle()
        if self._oldPuzzleIndex >= 0:
            self.setPuzzleSelector(self._oldPuzzleIndex)
            self.puzzleSelector.setEnabled(True)
        else:
            self.puzzleEditControls.setEnabled(False)

    def storePuzzle(self):
        """
        Checks the edited puzzle for errors and, if there are none stores the puzzle in the collection and updates
        the user interface according to whether the puzzle was a new one being added or an old one being edited.
        If there are errors, prints an error message and returns focus to its best guess as to where the problem is.
        :return: None
        """
        print("Got to storePuzzle")

        # class LengthMismatchError(Exception):pass
        class InconsistentCodeError(Exception):pass
        class BadHintFormatError(Exception):pass
        class BadHintError(Exception):pass

        title = self.puzzleTitleEdit.text()
        puzzleTitle = self.puzzleTitleEdit.text()
        puzzleCode = self.puzzleCodeEdit.toPlainText().upper()
        citationCode = self.citationCodeEdit.text().upper()
        puzzleSolution = self.puzzleSolutionEdit.toPlainText().upper()
        citationSolution = self.citationSolutionEdit.text().upper()
        hints = self.cleanHints(self.hintEdit.text())
        # ToDo: Find ways to help the user find the errors: characteer position counts, character highlighting, etc.
        try:
            # Commented out 9-22-2016
            # results = self.lengthMismatchErrorTests(puzzleCode, puzzleSolution, citationCode, citationSolution)
            # if not results[0]:
            #     raise LengthMismatchError(results[1])
            #

            # InconsistentCodeError tests
            if puzzleSolution != "":
                codeDict = {}
                solutionDict = {}
                solutionIndex = 0
                for codeChar in puzzleCode:
                    solutionChar = puzzleSolution[solutionIndex]
                    if codeChar in codeDict.keys():
                        if codeDict[codeChar] != solutionChar:
                            msg = "The code letter, " + codeChar + " in the puzzle code, cannot represent both "
                            msg += codeDict[codeChar] + " and " + solutionChar + " in the solution.\n\n"
                            msg += "Check position " + str(solutionIndex + 1) + "."
                            raise InconsistentCodeError(msg)
                        else:
                            solutionIndex += 1
                    elif solutionChar in solutionDict.keys():
                        if solutionDict[solutionChar] != codeChar:
                            msg = "The solution letter, " + solutionChar + " in the puzzle solution,"
                            msg += " cannot be represented by both " + solutionDict[solutionChar] + " and "
                            msg += codeChar + " in the puzzle code.\n\n"
                            msg += "Check position " + str(solutionIndex+1) + "."
                            raise InconsistentCodeError(msg)
                        else:
                            solutionIndex += 1
                    else:
                        codeDict[codeChar] = solutionChar
                        solutionDict[solutionChar] = codeChar
                        solutionIndex += 1
                solutionIndex = 0
                for codeChar in citationCode:
                    solutionChar = citationSolution[solutionIndex]
                    if codeChar in codeDict.keys():
                        if codeDict[codeChar] != solutionChar:
                            msg = "The letter, " + codeChar + " in the citation code, cannot represent both "
                            msg += codeDict[codeChar] + " and " + solutionChar + " in the solution.\n\n"
                            msg += "Check position " + str(solutionIndex + 1) + "."
                            raise InconsistentCodeError(msg)
                        else:
                            solutionIndex += 1
                    elif solutionChar in solutionDict.keys():
                        if solutionDict[solutionChar] != codeChar:
                            msg = "The solution letter, " + solutionChar + " in the citation solution, "
                            msg += "cannot be represented by both " + solutionDict[solutionChar] + " and "
                            msg += codeChar + " in the citation code.\n\n"
                            msg += "Check position " + str(solutionIndex + 1) + "."
                            raise InconsistentCodeError(msg)
                        else:
                            solutionIndex += 1
                    else:
                        codeDict[codeChar] = solutionChar
                        solutionDict[solutionChar] = codeChar
                        solutionIndex += 1

            # BadHintFormatError Tests'
            print("hints = ", hints)
            if len(hints) != 0:
                for hint in hints:
                    print(hint)
                    if (len(hint.strip()) != 3) or (hint[1] != '='):
                        msg = "Hints must have the format '(code letter 1)=(solution letter 1); "
                        msg += "(code letter 2) = (solution letter 2)' etc.  For example:  A=C; H=W"
                        msg += "See the help files for further information."
                        raise BadHintFormatError(msg)

                # BadHintError Tests
                print("Got to BadHintError Tests with hints = ", hints)
                parsedHints = self.parseHints(hints)
                print("parsedHints = ", parsedHints)
                for hintpair in parsedHints:
                    print("codeDict: ", codeDict, " solutionDict: ", solutionDict, " hintpair: ", hintpair)
                    if hintpair[0] not in codeDict.keys():
                        print("B")
                        msg = "The hint for letter " + hintpair[0] + " does not help since it is not in the puzzle code."
                        raise BadHintError(msg)
                    elif hintpair[1] not in solutionDict.keys():
                        msg = "The hint that " + hintpair[0] + "=" + hintpair[1] + " makes no sense since " + hintpair[1]
                        msg += " does not appear in the solution."
                        raise BadHintError(msg)
                    elif codeDict[hintpair[0]] != hintpair[1]:
                        msg = "In the puzzle, " + hintpair[0] + " represents " + codeDict[hintpair[0]] + ".  "
                        msg += "The hint says it represents " + hintpair[1] + "."
                        raise BadHintError(msg)

        # Commented out 9-22-2016
        # except LengthMismatchError as e:
        #     QMessageBox.warning(self, "Length Mismatch Error", str(e))
        #     if "puzzle" in str(e):
        #         codeWords = puzzleCode.split()
        #         solutionWords = puzzleSolution.split()
        #         if len(codeWords) == len(solutionWords):
        #             index = 0
        #             for word in codeWords:
        #                 if len(word) != len(solutionWords[index]):
        #                     codeWords[index] = '<font color="red">' + word + '</font>'
        #                     solutionWords[index] = '<font color="red".' + solutionWords[index] + '</font>'
        #                 index += 1
        #             else:
        #                 # figure out what to do if not the same number of words
        #                 pass
        #             replacement = ""
        #             for word in codeWords:
        #                 replacement += word + " "
        #             self.puzzleCodeEdit.setHtml(replacement.strip())
        #             replacement = ""
        #             for word in solutionWords:
        #                 replacement += word + " "
        #             self.puzzleSolutionEdit.setHtml(replacement.strip())
        #
        #         self.puzzleCodeEdit.setFocus()
        #     else:
        #         self.citationCodeEdit.setFocus()
        #     return

        except InconsistentCodeError as e:
            QMessageBox.warning(self, "Insonsistent Code Error", str(e))
            if "puzzle" in str(e):
                self.puzzleCodeEdit.setFocus()
            else:
                self.citationCodeEdit.setFocus()
            return

        except BadHintFormatError as e:
            QMessageBox.warning(self, "Bad Hint Format Error", str(e))
            self.hintEdit.setFocus()

        except BadHintError as e:
            QMessageBox.warning(self, "Bad Hint Error", str(e))
            self.hintEdit.setFocus()
            return

        print("Got past the tests.")
        self.acceptButton.setEnabled(True)
        if self._mode == "Add":
            # new puzzle is added to the collection
            newpuzzle = data_structures.Puzzle(puzzleTitle, puzzleCode, citationCode,
                                               puzzleSolution, citationSolution, hints)
            self._collection.addPuzzle(newpuzzle)
            self.setPuzzleSelector(-1)
            self.createNewPuzzle()
            self.storePuzzleButton.setEnabled(False)
            self.deleteButton.setEnabled(False)
        else:
            # updated puzzle is altered in the collection
            correctedpuzzle = data_structures.Puzzle(puzzleTitle, puzzleCode, citationCode,
                                                     puzzleSolution, citationSolution, hints)
            self._collection.correctPuzzle(correctedpuzzle, self._currentPuzzleIndex)
            self.setPuzzleSelector(self._currentPuzzleIndex)
            # puzzle selector is updated if the puzzle title changed
            self.storePuzzleButton.setEnabled(False)

    def accept(self):
        print("got to accept")
        QDialog.accept(self)

    # Commented out 9-22-2016
    # def lengthMismatchErrorTests(self, puzzleCode, puzzleSolution, citationCode, citationSolution):
    #     print("Got to lengthMismatchErrorTests")
    #
    #     if puzzleSolution != "" and len(puzzleCode) != len(puzzleSolution):
    #         return False, "The puzzle's code and its solution are not the same length."
    #
    #     if citationSolution != "" and len(citationCode) != len(citationSolution):
    #         return False, "The citation's code and its solution are not the same length."
    #
    #     return True, ""

    def cancelDialog(self):
        QDialog.reject(self)

    #
    # def lengthMismatch(self, text1, text2):
    #     """
    #     Checks the length of each word in text1 and text2 and alerts the user if they are not the same.
    #     This routine is called when a space has been typed or an Edit widget has lost focus.
    #     :return: True if error found, False otherwise
    #     """
    #     # ToDo: Think the lengthMismatch routine through carefully and make it work!
    #     print("Checking for lengthMismatch")
    #     if len(text1) != 0:
    #         wordList1 = text1.split()
    #         wordList2 = text2.split()
    #         for index in range(min(len(wordList1), len(wordList2))):
    #             if len(wordList1[index]) != len(wordList2[index]):
    #                 self._errorSound.play()
    #                 self.errorDisplayWindow.setStyleSheet("QLabel { background-color : white; }")
    #                 msg = "The length of " + wordList1[-1] + " does not match " + wordList2[-1] + "."
    #                 self.errorDisplayWindow.setText(msg)
    #                 return True
    #
    #     self.errorDisplayWindow.setText('')
    #     self.errorDisplayWindow.setStyleSheet("QLabel { background-color : rgb(240, 240, 240); }")
    #     return False

    def cleanHints(self, hintstring):
        """
        cleans a hint string that may contain extra spaces or a trailing semicolon and converts it to a list of
        untested "hints" that do not contain spaces
        :param hintstring: string
        :return: list of strings
        """
        if hintstring == "":
            return []
        hintstring = hintstring.rstrip(";")
        hintlist = hintstring.split(";")
        newhintlist = []
        for hint in hintlist:
            newhint = ""
            for char in hint:
                if char != " ":
                    newhint += char
            newhintlist.append(newhint)
        return newhintlist

    def parseHints(self, hintlist):
        """
        Takes a list of hints, for instance, ['A=B', 'N=H'] and parses it
        into a list of tuples
        :param hints: list
        :return: list of lists with the format (code letter, solution letter)
        """
        print("Got to self.parseHints with hints = ", hintlist)
        parsed = []
        for hint in hintlist:
            parsed.append(hint.split('='))

        return parsed
Example #33
0
    def mouseReleaseEvent(self, a0: QtGui.QMouseEvent):

        QSound.play('source/luozisheng.wav')

        print(a0.pos())
        print('x:', a0.x())
        print('y', a0.y())
        # mychessman = QLabel(self)
        # mychessman.setPixmap(QPixmap('source/黑子.png'))
        # mychessman.move(a0.pos())
        # mychessman.show()

        if self.color_flag == 'black':
            self.chessman = Chessman(color='black', parent=self)
            self.color_flag = 'white'
        else:
            self.chessman = Chessman(color='white', parent=self)
            self.color_flag = 'black'

        pos = self.reversePos(a0.pos())
        if self.st_over == True:
            return
        if pos == None:
            return
        pos_x = pos.x()
        pos_y = pos.y()
        self.chessman.move(pos_x, pos_y)
        self.chessman.map_point_x = (self.chessman.y - 50) // 30
        self.chessman.map_point_y = (self.chessman.x - 50) // 30
        #      此时:0是白色
        #      1是黑色
        if self.chess_map[self.chessman.map_point_x][
                self.chessman.map_point_y] != None:
            if self.color_flag == 1:
                self.color_flag = 0
            else:
                self.color_flag = 1
            return
        self.chess_map[self.chessman.map_point_x][
            self.chessman.map_point_y] = self.chessman
        self.chessman.show()
        print(self.chess_map[self.chessman.map_point_x][
            self.chessman.map_point_y].color)

        # 显示标识
        self.focus_Point.move(pos_x, pos_y)
        self.focus_Point.show()
        self.focus_Point.raise_()

        self.qishou = QLabel('当前棋手:', self)
        self.qishou.move(790, 260)
        if self.color_flag == 'white':
            self.player.pic = QPixmap('source/白子2.png')
        else:
            self.player.pic = QPixmap('source/黑子2.png')
        self.player.setPixmap(self.player.pic)
        self.player.setFixedSize(self.player.pic.size())
        self.player.move(800, 290)
        self.player.show()

        self.history_chess.append(self.chessman)
        print(self.chessman.color)
        self.showWin()
Example #34
0
class GameWindow(QWidget):

    def __init__(self):
        super().__init__()
        self.shapes = back_color.get_shapes()
        self.generate_quiz()
        self.initUI()
        self.initTimer()
        self.initSound()


    def initSound(self):
        self.correctSound = QSound('sound/correct.wav')
        self.incorrectSound = QSound('sound/incorrect.wav')


    def initTimer(self):
        self.timer = QTimer()
        self.timer.setInterval(500)
        self.timer.timeout.connect(self.timerTick)


    def timerTick(self):
        self.timer.stop()
        self.generate_quiz()
        self.repaint()


    def initUI(self):
        self.text = "Back color"
        self.setGeometry(0, 0, 260, 340)
        self.setFixedSize(260, 340)
        self.show()


    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        qp.fillRect(event.rect(), QBrush(QColor("#FFFFFF")))

        for shape in self.shapes:
            brush = QBrush(QColor(shape['color']))
            rect = shape['rect']
            qp.fillRect(rect[0], rect[1], rect[2], rect[3], brush)
        qp.setPen(QColor(self.quiz_color))
        qp.setFont(QFont('Times New Roman', 20, QFont.Bold))
        if self.quiz_type:
            textRect = QRectF(0, 0, 260, 60)
        else:
            textRect = QRectF(0, 280, 260, 60)
        qp.drawText(textRect, Qt.AlignCenter, self.quiz_text)
        qp.end()


    def generate_quiz(self):
        [self.quiz_text, self.quiz_color, self.quiz_type] = back_color.generate_quiz()


    def mouseReleaseEvent(self, mouseEvent):
        x = mouseEvent.x()
        y = mouseEvent.y()
        if back_color.mouse_press(x, y, self.quiz_text, self.quiz_color, self.quiz_type):
            self.quiz_text = 'Correct'
            self.correctSound.play()
        else:
            self.quiz_text = 'Incorrect'
            self.incorrectSound.play()
        self.timer.start()
        self.repaint()
Example #35
0
 def sonido(self):
     self.soundtrack = QSound(self.ruta_sonido)
     self.soundtrack.play()
     self.soundtrack.setLoops(1000)
Example #36
0
 def initSound(self):
     self.correctSound = QSound('sound/correct.wav')
     self.incorrectSound = QSound('sound/incorrect.wav')
Example #37
0
class Notifier(QObject):
    def __init__(self, parent):
        super().__init__(parent)
        self._conn = QDBusConnection("Xware Desktop").sessionBus()

        self._interface = QDBusInterface(_DBUS_NOTIFY_SERVICE,
                                         _DBUS_NOTIFY_PATH,
                                         _DBUS_NOTIFY_INTERFACE,
                                         self._conn)

        self._notified = {}  # a dict of notifyId: taskDict
        app.taskModel.taskCompleted.connect(self.notifyTaskCompleted, Qt.DirectConnection)

        self._capabilities = self._getCapabilities()
        if "actions" in self._capabilities:
            successful = self._conn.connect(_DBUS_NOTIFY_SERVICE,
                                            _DBUS_NOTIFY_PATH,
                                            _DBUS_NOTIFY_INTERFACE,
                                            "ActionInvoked", self.slotActionInvoked)
            if not successful:
                logging.error("ActionInvoked connect failed.")

        self._qSound_complete = QSound(":/sound/download-complete.wav", self)

    @property
    def isConnected(self):
        return self._conn.isConnected()

    @pyqtSlot("QObject", result = "void")
    def notifyTaskCompleted(self, taskItem):
        if app.settings.getbool("frontend", "notifybysound"):
            self._qSound_complete.play()

        if not app.settings.getbool("frontend", "popnotifications"):
            return

        self._dbus_notifyCompleted(taskItem)

    def _getCapabilities(self):
        # get libnotify server caps and remember it.
        qdBusMsg = self._interface.call(
            "GetCapabilities"
        )
        if qdBusMsg.errorName():
            logging.error("cannot get org.freedesktop.Notifications.GetCapabilities")
            return []
        else:
            return qdBusMsg.arguments()[0]

    def _dbus_notifyCompleted(self, task: "TaskItem"):
        if "actions" in self._capabilities:
            actions = QDBusArgument(["open", "打开", "viewOneFile", "在文件夹中显示"], QMetaType.QStringList)
        else:
            actions = QDBusArgument([], QMetaType.QStringList)

        qdBusMsg = self._interface.call(
            "Notify",
            QDBusArgument("Xware Desktop", QMetaType.QString),  # app_name
            QDBusArgument(0, QMetaType.UInt),  # replace_id
            QDBusArgument("xware-desktop", QMetaType.QString),  # app_icon
            QDBusArgument("下载完成", QMetaType.QString),  # summary
            QDBusArgument(task.name, QMetaType.QString),  # body
            actions,
            {
                "category": "transfer.complete",
            },  # hints
            QDBusArgument(5000, QMetaType.Int),  # timeout
        )

        if qdBusMsg.errorName():
            logging.error("DBus, notifyTask {}: {}".format(qdBusMsg.errorName(),
                                                           qdBusMsg.errorMessage()))
        else:
            # add it to the dict
            notificationId = qdBusMsg.arguments()[0]
            self._notified[notificationId] = task.id

    @pyqtSlot(QDBusMessage)
    def slotActionInvoked(self, msg):
        notifyId, action = msg.arguments()
        taskId = self._notified.get(notifyId, None)
        if not taskId:
            # other applications' notifications
            return

        taskItem = app.taskModel.taskManager.get(taskId, None)
        if not taskItem:
            logging.debug("taskItem cannot be found anymore in TaskModel.")
            return

        fullpath = taskItem.fullpath  # path + name

        if action == "open":
            return systemOpen(fullpath)
        elif action == "viewOneFile":
            return viewOneFile(fullpath)
        elif action == "default":  # Unity's notify osd always have a default action.
            return
        else:
            raise Exception("Unknown action from slotActionInvoked: {}.".format(action))
Example #38
0
 def loadSounds(self):
     '''
     Loads any sounds required for the applicaiton and store them as QSound objects.
     '''
     self.alarmSound = QSound(
         os.path.abspath(os.path.join(self.soundPath, "shortAlarm.wav")))
Example #39
0
 def playSound(self):
     QSound.play('alert.wav')
Example #40
0
class VideoCapture(QWidget):
    faceCascade = cv2.CascadeClassifier(os.path.join(
        BASE_DIR, 'static', 'haarcascade_frontalface_default.xml'))

    def __init__(self, parent=None):
        super(QWidget, self).__init__()
        read_styles(os.path.join(BASE_DIR, 'demo',
                                 'styles', 'master.css'), self)
        self.cap = cv2.VideoCapture(0)
        self.video_frame = QLabel()
        self.video_frame.setObjectName("camera")
        self.setObjectName("camera-container")
        self.faces = 0
        self.raw_image = b''
        self.current = "current"
        self.data = ""
        self._concurrence = 0
        self.discurrence = 0
        self.calling = False
        parent.layout.addWidget(self.video_frame)

    def minion(self, bits):
        self.current = "Face found: calling API..."
        self.calling = True
        responce = ask_info(bits)
        if not "error" in responce:
            self.current = "Face detected"
            self.data = parse_info(responce)
            if responce["security_lvl"] == 'allowed':
                self.sound = QSound('test.wav')
                self.sound.play()
        else:
            self.current = "Error: {}".format(responce)
        self.calling = False

    def nextFrameSlot(self):
        ret, frame = self.cap.read()
        frame = cv2.flip(frame, 1)
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = self.faceCascade.detectMultiScale(
            gray,
            scaleFactor=1.1,
            minNeighbors=5,
            minSize=(30, 30)
        )
        if len(faces) > 0:
            if self.faces != len(faces) and not self.calling:
                self.discurrence += 1
                self._concurrence = 0
            else:
                if self._concurrence == 12:
                    self.raw_image = cv2.imencode('.bmp', frame)[1].tostring()
                    th = Thread(target=self.minion, args=(self.raw_image,))
                    th.start()
                    self.discurrence = 0
                elif self._concurrence < 12:
                    self.current = "Face found: preparing release data in {}".format(
                        12 - self._concurrence)
                self._concurrence += 1
                self.discurrence = 0
            self.faces = len(faces)
            for (x, y, w, h) in faces:
                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        elif not self.calling:
            self.discurrence += 1
            self.faces = 0
            self._concurrence = 0
            if self.discurrence > 12:
                self.current = "No face found: waiting..."
            else:
                self.current = "No face found: preparig API call in {}".format(
                    12 - self.discurrence)

        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        img = QImage(frame, frame.shape[1],
                     frame.shape[0], QtGui.QImage.Format_RGB888)
        pix = QPixmap.fromImage(img)
        self.video_frame.setPixmap(pix)

    def start(self):
        self.timer = QTimer()
        self.timer.timeout.connect(self.nextFrameSlot)
        self.timer.start(1000.0 / 30)

    def pause(self):
        self.timer.stop()

    def deleteLater(self):
        self.cap.release()
        super(QWidget, self).deleteLater()