Ejemplo n.º 1
0
    def init_sounds():
        for sound_name, value in sounds_list.items():
            config = DEFAULT_CONFIG.copy()
            if isinstance(value, dict):
                config.update(value)
            else:
                config['file_name'] = value
            volume = float(config['volume'])
            volumes[sound_name] = volume
            vec = []
            for i in range(CHANNELS_PER_FILE):
                s = QSoundEffect(app)
                s.statusChanged.connect(
                    lambda i=i, s=s:
                        log('stateChanged: {}: {}: {}'.format(s.source().toLocalFile(), i, s.status()))
                )
                s.setLoopCount(int(config['loop_count']))
                s.setVolume(volume)
                s.setSource(QUrl.fromLocalFile(config['file_name']))
                vec.append(s)
            sounds[sound_name] = tuple(vec)
        
        #log('xxx: ' + str(sounds))

        # start polling for messages
        def proc():
            #while not queue.empty(): 
            #    queue.get(False)
            timer.start(10)
        QTimer.singleShot(500, proc)
Ejemplo n.º 2
0
class SoftKey(QLabel):
    def __init__(self, num, parent):
        assert num >= 0 and num <= 3

        labels = ['\u21ba', '\u25bc', '\u25b2', '\u23ce']
        xpositions = [0, 40, 80, 120]
        sfxfiles = ['sfx014.wav', 'sfx013.wav', 'sfx033.wav', 'sfx061.wav']
        label = labels[num]
        xpos = xpositions[num]
        sfx = sfxfiles[num]

        super().__init__(label, parent)

        self.sfx = QSoundEffect(self)
        self.sfx.setSource(QUrl.fromLocalFile(sfx))
        self.sfx.setVolume(0.5)

        self.resize(40, 27)
        self.move(xpos, 100)
        self.setFrameStyle(QFrame.Panel | QFrame.Raised)
        self.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.showPressed(False)
        self.show()

    def showPressed(self, pressed):
        if pressed:
            self.sfx.play()
            self.setLineWidth(4)
        else:
            self.setLineWidth(2)
Ejemplo n.º 3
0
class Sound(object):
    def __init__(self, filename, volume):
        super(Sound, self).__init__()
        file = os.path.join(BASEDIR, 'sounds', filename)
        self.volume = volume or 0
        self.effect = QSoundEffect()
        self.effect.setSource(QUrl.fromLocalFile(file))

    def play(self, volume=None, loop=True):
        volume = self.volume if volume is None else volume
        self.effect.setLoopCount(0)
        self.effect.setVolume(int(volume) / 100)

        if loop:
            self.effect.setLoopCount(QSoundEffect.Infinite)
        else:
            self.effect.setLoopCount(1)

        if not self.effect.isPlaying():
            self.effect.play()

    def stop(self):
        self.effect.stop()

    def setVolume(self, volume):
        self.volume = volume
Ejemplo n.º 4
0
 def setupSound(self):
     print(os.getcwd())
     good = QSoundEffect(self)
     good.setSource(QUrl.fromLocalFile(os.path.join("sound", "good.wav")))
     good.setLoopCount(1)
     bad = QSoundEffect(self)
     bad.setSource(QUrl.fromLocalFile(os.path.join("sound", "bad.wav")))
     bad.setLoopCount(1)
     self.sounds = {'good': good, 'bad': bad}
Ejemplo n.º 5
0
	def preload_sound_effect(cls, path):
		if not hasattr(cls, "sound_effects"):
			cls.sound_effects = {}
			cls.se_volume = 100
		if path not in cls.sound_effects:
			se = QSoundEffect()
			se.setVolume(cls.se_volume / 100)
			se.setSource(QUrl.fromLocalFile(path))
			cls.sound_effects[path] = (se)
Ejemplo n.º 6
0
class Models:
    def __init__(self, base):
        self.base = base
#======================== Images =======================

    images = []
    for file_ in os.listdir("./data"):
        x = 4
        if file_.endswith((".jpg", ".jpeg", ".png")):
            images.append(file_)

#======================== Sounds =======================

    def initSound(self):
        self.select_sound = QSoundEffect(self.base)
        self.next_set_sound = QSoundEffect(self.base)
        self.expand_sound = QSoundEffect(self.base)
        self.shrink_sound = QSoundEffect(self.base)
        self.select_sound.setSource(
            QUrl.fromLocalFile(os.path.join('./data/sounds', 'click.wav')))
        self.shrink_sound.setSource(
            QUrl.fromLocalFile(os.path.join('./data/sounds', 'click.wav')))
        self.next_set_sound.setSource(
            QUrl.fromLocalFile(os.path.join('./data/sounds',
                                            'camera-roll.wav')))
        self.expand_sound.setSource(
            QUrl.fromLocalFile(os.path.join('./data/sounds', 'expand.wav')))
        self.select_sound.setLoopCount(0)
        self.shrink_sound.setLoopCount(0)
        self.expand_sound.setLoopCount(0)
        self.next_set_sound.setLoopCount(0)
Ejemplo n.º 7
0
class noiseGenerator(QThread):
    def __init__(self, playnoise, volume):
        super().__init__()
        pathname = os.path.dirname(os.path.realpath('whitenoise.wav'))
        self.sound = QSoundEffect()
        self.sound.setSource(QUrl.fromLocalFile(pathname + '/whitenoise.wav'))

        self.sound.setLoopCount(QSoundEffect.Infinite)
        self.settings(playnoise, volume)

    def settings(self, playnoise, volume):
        self.playnoise = playnoise
        self.sound.setVolume(volume)

    def run(self):
        if self.playnoise:
            self.sound.play()

    def stop(self):
        self.sound.stop()
Ejemplo n.º 8
0
    def __init__(self, parent):
        """ Tab window for visualising Sorting Algorithms """
        super(SortingTab, self).__init__(parent)

        # Setup sounds
        self.sound_enabled = True
        self.sounds = []
        for i in range(64):
            sound = QSoundEffect()
            sound.setSource(
                QUrl.fromLocalFile(f"../assets/sounds/tone-{i}.wav"))
            sound.setVolume(0.3)
            self.sounds.append(sound)

        self.is_sound_playing = lambda: False

        # Setup sorting widgets
        self.layout = QGridLayout(self)
        self.layout.setAlignment(Qt.AlignCenter)

        self.rendering_type = SortRenderType.BarGraph
        self.rainbow = False
Ejemplo n.º 9
0
class CardGraphicsItem(QGraphicsPixmapItem):
    suitnames = {'Spades': 'S', 'Clubs': 'C', 'Diamonds': 'D', 'Hearts': 'H'}

    def __init__(self, card):
        super(CardGraphicsItem, self).__init__()
        self.path = 'img/' + str(
            card.value) + CardGraphicsItem.suitnames[card.suit]
        self.show_face()
        self.setScale(0.12)
        self.card = card
        self.click_sound = QSoundEffect()
        self.click_sound.setSource(QUrl.fromLocalFile('sound/playcard.wav'))

    def mousePressEvent(self, *args, **kwargs):
        self.click_sound.play()

        if not self.card.selected:
            self.select()

        else:
            self.deselect()

    def select(self):
        self.moveBy(0, -20)
        self.card.select()

    def deselect(self):
        self.moveBy(0, 20)
        self.card.deselect()

    def show_face(self):
        self.setPixmap(QPixmap(self.path))

    def show_back(self):
        self.setPixmap(QPixmap('img/red_back'))  #img/red_back

    def __str__(self):
        return '{} of {}'.format(self.card.value, self.card.suit)
Ejemplo n.º 10
0
class view(QWidget):
    def __init__(self, Model, width):
        super().__init__()

        # resize the width
        self.width = self.Resize(width)

        # pass the reference of model to self.model
        self.model = Model

        self.title = 'project 2.5 imge browser with sound effect and tags'
        self.mode = 1  # mode 1 is list of thumbnails, mode 2 is one large image
        self.idx = 0  # index to images for display
        self.center = 0  # index to highlight image
        self.w = self.width  # width of full screen image
        self.h = 0.75 * self.w  # height of full screen image
        self.b = 20  # border of full screen image
        self.h1 = self.h / 6.0  # height of thumbnail image
        self.w1 = self.w / 6.0  # width of thumbnail image
        self.b1 = 5  # border of thumbnail image
        self.margintop = self.w / 8.0  # margin of thumbnail to top
        self.marginleft = self.w / 8.0  # margin of thumbnail to left
        self.scaleratio = 0.75  # a parameter for scaling of full screen image

        # create a list of tags labels
        self.taglist = []
        self.tagsLeft = self.w * 0.8
        self.tagsTop = self.h * 0.1
        self.tagsW = self.w * 0.15
        self.tagsH = self.h * 0.1

        # create an editable label
        self.EditLabel = QLabel(self)
        self.EditLabel.setText("Edit the label: ")
        self.EditLabelMarginLeft = self.w * 0.2
        self.EditLabelMarginTop = self.h * 0.87

        self.line = QLineEdit(self)
        self.lineMarginLeft = self.w * 0.33
        self.lineMarginTop = self.h * 0.85
        self.lineWidth = self.w * 0.32
        self.lineHeight = self.h * 0.08

        # create a push button for add label
        self.button1 = QPushButton('Add Tag', self)
        self.button1.clicked.connect(self.Bclick1)
        self.btnTop = self.h * 0.85
        self.btnLeft = self.w * 0.7
        self.btnW = self.w * 0.1
        self.btnH = self.h * 0.08

        # create a push button for save all tags
        self.button2 = QPushButton('Save All Tags', self)
        self.button2.clicked.connect(self.Bclick2)
        self.btnTop2 = self.h * 0.85
        self.btnLeft2 = self.w * 0.82
        self.btnW2 = self.w * 0.15
        self.btnH2 = self.h * 0.08

        # create the label for full scree image
        self.fullabel = QLabel(self)
        # create a mouse click event to clear focus on input text box
        self.fullabel.mousePressEvent = self.mclickFull

        # create a list of labels for 5 thumbnails
        self.labels = []
        for i in range(5):
            self.labels.append(QLabel(self))

        # define mouse click functions to each thumbnail labels
        self.labels[0].mousePressEvent = self.mclick1
        self.labels[1].mousePressEvent = self.mclick2
        self.labels[2].mousePressEvent = self.mclick3
        self.labels[3].mousePressEvent = self.mclick4
        self.labels[4].mousePressEvent = self.mclick5

        # initialize sound effect
        self.sound1 = QSoundEffect()  # for arrow key
        self.sound2 = QSoundEffect()  # for < and >
        self.sound3 = QSoundEffect()  # for mouse click

        # begin the view
        self.initUI()

    # a function to resize the window according to user's input
    def Resize(self, width):
        if int(width) >= 1200:
            return 1200
        elif int(width) <= 600:
            return 600
        else:
            return int(width)

    # initialize the UI
    def initUI(self):
        # set up the window
        self.setWindowTitle(self.title)
        self.setGeometry(100, 100, self.w, self.h)

        # set up the full screen label
        self.fullabel.setGeometry(0, 0, self.w * 0.75, self.h * 0.75)
        self.fullabel.setStyleSheet("border: " + str(self.b) +
                                    "px solid blue;background-color:grey")

        # set up the edit label for full screen image
        self.line.move(self.lineMarginLeft, self.lineMarginTop)
        self.line.resize(self.lineWidth, self.lineHeight)
        self.EditLabel.move(self.EditLabelMarginLeft, self.EditLabelMarginTop)
        self.EditLabel.setStyleSheet("font:15px")
        self.line.clearFocus()

        # set up the push button for add tag
        self.button1.setGeometry(self.btnLeft, self.btnTop, self.btnW,
                                 self.btnH)

        # set up the push button for save all tags
        self.button2.setGeometry(self.btnLeft2, self.btnTop2, self.btnW2,
                                 self.btnH2)

        # set up the thumbnail labels
        for i in range(5):
            self.labels[i].setGeometry(self.w1 * 0.45 + self.w1 * i,
                                       self.h * 0.4, self.w1, self.h1)
            self.labels[i].setStyleSheet(
                "border: " + str(self.b1) +
                "px solid green;background-color:grey")

        self.DisplayImg()

        # a function to rescale the image

    def RescaleImg(self, pixmap):
        # rescale for full screen label image
        if self.mode == 2:
            if pixmap.size().height() / float(
                    self.h) > pixmap.size().width() / float(self.w):
                pixmap = pixmap.scaledToHeight(
                    (self.h - 2 * self.b) *
                    self.scaleratio)  # rescale according to height
            else:
                pixmap = pixmap.scaledToWidth(
                    (self.w - 2 * self.b) *
                    self.scaleratio)  # rescale according to width
        # rescale for thumbnail label image
        else:
            if pixmap.size().height() / float(
                    self.h1) > pixmap.size().width() / float(self.w1):
                pixmap = pixmap.scaledToHeight(
                    self.h1)  # rescale according to height
            else:
                pixmap = pixmap.scaledToWidth(
                    self.w1)  # rescale according to width
        return pixmap

    # a function to display the pixmap in full size or in thumbnail list
    def DisplayImg(self):

        # determine mode
        if self.mode == 2:
            # print("show the full size image")
            # hide the thumbnail list
            for i in range(5):
                self.labels[i].hide()

            # set up the tag label list for full screen image
            for tag in self.taglist:
                tag.hide()
            self.taglist = []  # clear previous tag list

            taglen = len(self.model.tags[self.idx % len(self.model.imgs)])
            for i in range(taglen):
                self.taglist.append(QLabel(self))
                self.taglist[i].setText(
                    self.model.tags[self.idx % len(self.model.tags)][i])
                self.taglist[i].setGeometry(self.tagsLeft,
                                            self.tagsTop + i * self.tagsH,
                                            self.tagsW, self.tagsH)
                self.taglist[i].setStyleSheet("font: 20px")
                self.taglist[i].show()  # show the tag label

            # show the full screen image
            self.fullabel.show()
            self.line.show()
            self.EditLabel.show()
            self.button1.show()
            self.button2.show()

            # rescale the image as needed
            pixmap = self.RescaleImg(self.model.imgs[self.idx %
                                                     len(self.model.imgs)])

            # load image onto label
            self.fullabel.setPixmap(pixmap)

            # apply style to label
            self.fullabel.setAlignment(Qt.AlignCenter)
            self.fullabel.setStyleSheet("border: " + str(self.b) +
                                        "px solid red;background-color:grey")

            self.show()

        else:
            # hide the full screen image and other tags
            self.fullabel.hide()
            self.line.hide()
            self.EditLabel.hide()
            self.button1.hide()
            self.button2.hide()
            for tag in self.taglist:
                tag.hide()

            # show the thumbnails
            for i in range(5):
                self.labels[i].show()
                self.labels[i].setPixmap(
                    self.RescaleImg(self.model.imgs[(self.idx + i) %
                                                    len(self.model.imgs)]))
                self.labels[i].setAlignment(Qt.AlignCenter)
                #                print("idx: ", self.idx,"center: ", self.center)
                #                print((self.idx+i) % 5, self.center)
                if i == self.center:
                    self.labels[i].setStyleSheet(
                        "border: " + str(self.b1) +
                        "px solid red;background-color:grey")
                else:
                    self.labels[i].setStyleSheet(
                        "border: " + str(self.b1) +
                        "px solid green;background-color:grey")

            self.show()

            # add tag button click function, append user input to tag file

    def Bclick1(self, event):
        self.model.tags[self.idx % len(self.model.tags)].append(
            self.line.text())
        self.taglist.append(QLabel(self))
        self.taglist[len(self.taglist) - 1].setText(self.line.text())
        self.DisplayImg()

    # save tag button click function
    def Bclick2(self, event):
        fout = open(
            self.model.tagpath +
            self.model.taglist[self.idx % len(self.model.taglist)], 'w')
        #        print(self.model.tags[self.idx % len(self.model.tags)])
        for line in self.model.tags[self.idx % len(self.model.tags)]:
            fout.write(line + '\n')
        fout.close()

        # click on the full window image to clear focus on qline

    def mclickFull(self, event):
        self.line.clearFocus()

    def mclick1(self, event):
        self.ShortSound3()
        #        print("label 1 clicked!!!")
        self.mode = 2
        self.center = 0
        self.idx += self.center
        self.DisplayImg()

    def mclick2(self, event):
        #        print("label 2 clicked!!!")
        self.ShortSound3()
        self.mode = 2
        self.center = 1
        self.idx += self.center
        self.DisplayImg()

    def mclick3(self, event):
        #        print("label 3 clicked!!!")
        self.ShortSound3()
        self.mode = 2
        self.center = 2
        self.idx += self.center
        self.DisplayImg()

    def mclick4(self, event):
        #        print("label 4 clicked!!!")
        self.ShortSound3()
        self.mode = 2
        self.center = 3
        self.idx += self.center
        self.DisplayImg()

    def mclick5(self, event):
        #        print("label 5 clicked!!!")
        self.ShortSound3()
        self.mode = 2
        self.center = 4
        self.idx += self.center
        self.DisplayImg()

    def LeftArrowEvent(self):
        if self.mode == 1:
            self.center -= 1
            if self.center < 0:
                self.idx -= 5
                self.center = 4
        else:
            self.idx -= 1
        self.DisplayImg()

    def RightArrowEvent(self):
        if self.mode == 1:
            self.center += 1
            if self.center >= 5:
                self.idx += 5
                self.center = 0
        else:
            self.idx += 1
        self.DisplayImg()

    def DownArrowEvent(self):
        if self.mode == 1:
            return
        # change to thumbnail list
        self.mode = 1
        self.idx -= 2
        self.center = 2
        self.DisplayImg()

    def UpArrowEvent(self):
        if self.mode == 2:
            return
        # change to full image
        self.mode = 2
        self.idx += self.center
        self.DisplayImg()

    def SmallerThanEvent(self):
        if self.mode == 2:
            return
        self.idx -= 5
        self.center = 0
        self.DisplayImg()

    def LargerThanEvent(self):
        if self.mode == 2:
            return
        self.idx += 5
        self.center = 0
        self.DisplayImg()

        # a short for arrow keypress event

    def ShortSound1(self):
        self.sound1.setSource(
            QUrl.fromLocalFile(
                os.path.join('sounds', '191617__dwsd__jhd-bd-35.wav')))
        self.sound1.play()

        # a short sound for < and > key event

    def ShortSound2(self):
        self.sound2.setSource(
            QUrl.fromLocalFile(
                os.path.join('sounds',
                             '195937__michimuc2__short-wind-noise.wav')))
        self.sound2.play()

        # a short sound for mouse click

    def ShortSound3(self):
        self.sound3.setSource(
            QUrl.fromLocalFile(os.path.join('sounds', 'keyevent2.wav')))
        self.sound3.play()

    def keyPressEvent(self, event):
        #        print(event.key())
        #        print(event)
        #        print(event.modifiers())

        if event.key() == 16777234:  # left arrow key
            self.ShortSound1()
            self.LeftArrowEvent()
        elif event.key() == 16777236:  # right arrow key
            self.ShortSound1()
            self.RightArrowEvent()
        elif event.key() == 16777237:  # down arrow key
            self.ShortSound1()
            self.DownArrowEvent()
        elif event.key() == 16777235:  # up arrow key
            self.ShortSound1()
            self.UpArrowEvent()
        elif event.modifiers():
            #            print(event.key())
            if event.key() == 60:  # less than key
                self.ShortSound2()
                self.SmallerThanEvent()
            elif event.key() == 62:  # greater than key
                self.ShortSound2()
                self.LargerThanEvent()
        else:
            print("unknown key")
Ejemplo n.º 11
0
class VArcMain(QWidget):
    def __init__(self):
        global bgm, wheel_anims

        super().__init__()
        # Controls
        self.up = []
        self.down = []
        self.left = []
        self.right = []
        self.select = []

        self.labels = []

        # Wheel/Game List
        self.wheel = None
        self.center = None
        self.splash = None
        wheel_anims = QParallelAnimationGroup()
        self.games = populate_games()

        # Media
        self.click = QSoundEffect()
        self.click.setSource(QUrl.fromLocalFile(config['audio_path'] + 'wheelSFX.wav'))
        bgm = QMediaPlayer(self)
        bgm.setMedia(QMediaContent(QUrl.fromLocalFile(config['audio_path'] + 'bgm.mp3')))
        bgm.setVolume(30)
        bgm.play()

        # Startup
        read_conf()
        self.read_keys()

        if config['flip_scrolling'] == 'True':
            self.up, self.down = self.down, self.up

        self.init_ui()

    def init_ui(self):
        global v_player, cur_game, config, top_pos, bot_pos, wheel_anims

        backgrounds = []
        for file in os.listdir(config['image_path'] + 'background/'):
            if config['gif_bg'] == 'True':
                if file.endswith(".gif"):
                    backgrounds.append(file)
            elif file.endswith(('.png', '.jpg')):
                backgrounds.append(file)

        bg_mov = QMovie(config['image_path'] + 'background/' + random.choice(backgrounds))
        bg_mov.setScaledSize(QSize(1920, 1080))
        bg = QLabel(self)

        bg.setMovie(bg_mov)
        bg_mov.start()
        h_box = QHBoxLayout(bg)
        v_box = QVBoxLayout(bg)
        self.wheel = v_box
        h_box.addLayout(v_box)
        h_box.addStretch(1)

        v_player = VideoPlayer(640, 480)
        v_player.setFixedSize(640, 480)
        v_player.setEnabled(0)

        self.splash = QLabel()
        v_container = QVBoxLayout()
        v_container.addStretch(1)
        v_container.addWidget(self.splash, alignment=Qt.AlignCenter)
        v_container.addWidget(v_player, alignment=Qt.AlignAbsolute)
        v_container.addStretch(1)
        h_box.addLayout(v_container)
        h_box.addStretch(1)

        w_labels = []
        for a, x in enumerate(self.games):
            lbl = QLabel(self)
            lbl.hide()
            lbl.setFixedSize(400, 175)
            self.labels.append(lbl)
            if a < 5:
                if a == 2:
                    cur_game = [x, 2]
                    self.center = lbl
                    self.splash.setStyleSheet('color: white; font-size: 24pt;')
                    self.splash.setText(x.display + ' - ' + x.emu_info)
                    v_player.load(x.name + '.mp4')
                    v_player.play()
                lbl.show()
                v_box.addWidget(lbl)
                lbl.setFocus()

            w_label = QLabel(self)
            anim = WheelAnimation(w_label, b'pos', lbl)
            w_labels.append((w_label, lbl))
            wheel_anims.addAnimation(anim)

            anim.setEasingCurve(QEasingCurve.OutQuad)
            anim.setDuration(100)

            if os.path.isfile(config['image_path'] + x.name + '.png'):
                w_label.setPixmap(QPixmap(config['image_path'] + x.name + '.png')
                                  .scaled(400, 175, Qt.IgnoreAspectRatio))
            else:
                w_label.setStyleSheet('color: white; font-size 36pt;')
                w_label.setText(x.display)

        self.setWindowTitle('VArc')
        self.showFullScreen()

        top_pos = QPoint(10, -400)
        bot_pos = QPoint(10, 1480)

        for a in w_labels:
            pos = a[1].pos()
            if pos.x() is not 0:
                if a[1] == self.center:
                    a[0].move(pos.x() + 30, pos.y())
                else:
                    a[0].move(pos)

            else:
                a[0].hide()

    def keyPressEvent(self, e):
        if e.key() in self.down:
            self.move_wheel(False)
            try_preview()
        elif e.key() in self.up:
            self.move_wheel(True)
            try_preview()
        elif e.key() in self.select:
            start_game()
        elif e.key() in self.left:
            print('Going left!')
        elif e.key() in self.right:
            print('Going right!')

    def move_wheel(self, up: bool):
        global cur_game
        self.click.play()
        layout = self.wheel
        if up:
            to_show = self.labels[5]
            to_show.show()
            to_remove = layout.itemAt(0).widget()
            to_remove.hide()
            layout.removeWidget(to_remove)
            layout.addWidget(to_show)
            self.labels.append(self.labels.pop(0))
            cur_game[1] = (cur_game[1] + 1) % len(self.games)
            cur_game[0] = self.games[cur_game[1]]
            self.center = layout.itemAt(3).widget()

        else:
            to_show = self.labels.pop()
            to_show.show()
            to_remove = layout.itemAt(4).widget()
            to_remove.hide()
            layout.removeWidget(to_remove)
            layout.insertWidget(0, to_show)
            self.labels.insert(0, to_show)
            cur_game[1] = (cur_game[1] - 1) % len(self.games)
            cur_game[0] = self.games[cur_game[1]]
        self.center = layout.itemAt(2).widget()

        QApplication.instance().processEvents()
        self.anim_wheel(up)

        self.splash.setText(cur_game[0].display + ' - ' + cur_game[0].emu_info)
        self.center.resize(self.center.width() + 2000, self.center.height() + 2000)

    def anim_wheel(self, up: bool):
        global top_pos, bot_pos, wheel_anims
        for a in range(wheel_anims.animationCount()):
            anim = wheel_anims.animationAt(a)

            if anim.shadow_lbl.isVisible():
                pos = anim.shadow_lbl.pos()
                if anim.shadow_lbl == self.center:
                    pos.setX(pos.x() + 120)
                anim.targetObject().show()
                anim.setDuration(100)
                anim.setEndValue(pos)
            else:
                anim.targetObject().hide()
                if up:
                    anim.setEndValue(bot_pos)
                    anim.setDuration(0)
                    anim.targetObject().move(bot_pos)
                else:
                    anim.setEndValue(top_pos)
                    anim.setDuration(0)
                    anim.targetObject().move(top_pos)

        wheel_anims.start(QAbstractAnimation.KeepWhenStopped)

    def read_keys(self):
        root = elTree.parse('keybinds.xml').getroot()
        for bind in root:
            key = bind.find('key').text
            try:
                value = eval('Qt.' + bind.find('value').text)
            except AttributeError:
                print('Invalid keybind: ' + bind.find('value').text)
                value = None
            if value is not None:
                if key == 'Up':
                    self.up.append(value)
                elif key == 'Down':
                    self.down.append(value)
                elif key == 'Left':
                    self.left.append(value)
                elif key == 'Right':
                    self.right.append(value)
                elif key == 'Select':
                    self.select.append(value)
Ejemplo n.º 12
0
class Window(QWidget):
    def __init__(self, width, height):
        super().__init__()
        self.height = height
        self.width = width
        self.index = 0
        self.leftBreak = 0
        self.rightBreak = 4
        self.bigPixList = []
        self.pixList = []
        self.label = []
        self.tagLabels = []
        self.bigLabel = QLabel(self)
        self.bigLabel.resize(self.width * 3 / 4, self.height * 3 / 4)
        self.bigLabel.move(self.width / 8, self.height / 8)
        self.bigLabel.hide()
        #adding buttons and textbox
        self.textBox = QLineEdit(self)
        self.textBox.setStyleSheet("color: rgb(255, 255, 255);")
        self.textBox.move(self.width / 6, self.height * 7 / 8)
        self.textBox.resize(150, self.height / 16)
        self.textBox.hide()
        self.tagButton = QPushButton('Add Tag', self)
        self.tagButton.setStyleSheet("background-color: rgb(125,125,125);")
        self.tagButton.move(self.width / 6, self.height * 15 / 16)
        self.tagButton.clicked.connect(self.tagClick)
        self.tagButton.hide()
        self.saveTagButton = QPushButton('Save All Tags', self)
        self.saveTagButton.setStyleSheet(
            "background-color: rgb(125, 125, 125);")
        self.saveTagButton.move(self.width / 6 + 75, self.height * 15 / 16)
        self.saveTagButton.clicked.connect(self.saveClick)
        self.saveTagButton.hide()
        self.setFocus()
        #item that holds the current string to be stored as tag
        self.currentString = []
        self.mode = 0
        #Sets up the warning message for too long strings
        self.warningMessage = QLabel(self)
        self.warningMessage.resize(self.width / 5, self.height / 16)
        self.warningMessage.setStyleSheet(
            "background-color: red; font: bold 14px")
        self.warningMessage.setText("String too long")
        self.warningMessage.move(self.width / 2, self.height * 7 / 8)
        self.warningMessage.hide()
        #setting up the sounds to use
        self.soundClick = QSoundEffect()
        self.soundClickWah = QSoundEffect()
        self.soundLoop = QSoundEffect()
        self.soundLoopWah = QSoundEffect()
        self.soundShift = QSoundEffect()
        self.soundShiftWah = QSoundEffect()
        self.soundClick.setSource(
            QUrl.fromLocalFile(os.path.join('sounds', 'PianoNote.wav')))
        self.soundClickWah.setSource(
            QUrl.fromLocalFile(os.path.join('sounds', 'PianoNoteWah.wav')))
        self.soundShift.setSource(
            QUrl.fromLocalFile(os.path.join('sounds', 'PianoMultiNote.wav')))
        self.soundShiftWah.setSource(
            QUrl.fromLocalFile(os.path.join('sounds',
                                            'PianoMultiNoteWah.wav')))
        self.soundLoop.setSource(
            QUrl.fromLocalFile(os.path.join('sounds', 'loop08.wav')))
        self.soundLoopWah.setSource(
            QUrl.fromLocalFile(os.path.join('sounds', 'loop08Wah.wav')))
        self.soundLoop.setLoopCount(QSoundEffect.Infinite)
        self.soundLoopWah.setLoopCount(QSoundEffect.Infinite)
        self.soundLoop.play()
        self.soundLoopWah.play()
        self.soundLoopWah.setMuted(1)
        self.initUI()

    #Adds the tag to the list triggered by clicking on the button only if the string is less than 11 characters, otherwise shows warning message
    def tagClick(self):
        tagValue = self.textBox.text()
        if (len(tagValue) < 11):
            self.currentString[self.index % len(self.pixList)] += (tagValue +
                                                                   "\n")
            self.tagLabels[self.index % len(self.pixList)].setText(
                self.currentString[self.index % len(self.pixList)])
            self.textBox.setText("")
            self.setFocus()
            self.warningMessage.hide()
        else:
            self.warningMessage.show()

    def saveClick(self):
        f = open('SavedTags.txt', 'w')
        f.truncate()
        for i in range(0, len(self.pixList), 1):
            f.write(self.tagLabels[i].text())
            f.write("#")

    def initUI(self):
        # title of window
        self.setWindowTitle('PyQt5 Main Window')
        # place window on screen at x=0, y=0
        self.setGeometry(0, 0, self.width, self.height)
        self.setStyleSheet('background-color: black')
        #sets up QLabels for later input
        for i in range(0, 5, 1):
            self.label.append(QLabel(self))
            self.label[i].move(self.width / 12 + i * self.width / 6,
                               self.height / 3)
            self.label[i].resize(self.width / 6, self.height / 6)
            self.label[i].setStyleSheet('background-color: red')
            if (i == 0):
                self.label[i].setStyleSheet('background-color: blue')
        #places pictures into pixmap array
        i = 0
        for file in os.listdir('data'):
            self.pixList.append(QPixmap(os.path.join('data', file)))
            self.bigPixList.append(QPixmap(os.path.join('data', file)))
            self.tagLabels.append(QLabel(self))
            self.currentString.append("")
            self.tagLabels[i].resize(self.width / 8, self.height)
            self.tagLabels[i].move(self.width * 7 / 8, 0)
            self.tagLabels[i].setStyleSheet(
                'border-color: grey; border-style: outset; border-width: 5px; font: bold 14px; color: white'
            )
            self.tagLabels[i].setAlignment(Qt.AlignTop)
            self.tagLabels[i].hide()
            if (self.pixList[i].height() > self.height / 6 - 10):
                self.pixList[i] = self.pixList[i].scaledToHeight(self.height /
                                                                 6 - 10)
            if (self.pixList[i].width() > self.width / 6 - 10):
                self.pixList[i] = self.pixList[i].scaledToWidth(self.width /
                                                                6 - 10)
            if (self.bigPixList[i].width() > self.width * 3 / 4):
                self.bigPixList[i] = self.bigPixList[i].scaledToWidth(
                    self.width * 3 / 4)
            if (self.bigPixList[i].height() > self.height * 3 / 4):
                self.bigPixList[i] = self.bigPixList[i].scaledToHeight(
                    self.height * 3 / 4)
            i = i + 1
        self.bigLabel.setAlignment(Qt.AlignCenter)
        self.bigLabel.setPixmap(self.bigPixList[0])
        #puts initial pixmaps into the designated qlabels
        for i in range(0, 5, 1):
            self.label[i].setPixmap(self.pixList[i])
            self.label[i].setAlignment(Qt.AlignCenter)
        self.show()
        self.loadTags()

    def loadTags(self):
        f = open('SavedTags.txt', 'r')
        tempString = f.read()
        j = 0
        for i in range(0, len(tempString), 1):
            if (tempString[i] != "#"):
                self.currentString[j] += tempString[i]
            else:
                self.tagLabels[j].setText(self.currentString[j])
                j = j + 1

    #Moves the pointer to the picture one to the left.  If it breaks the bounds, it will move the frame
    def moveIndexLeft(self):
        j = 0
        if (self.mode == 1):
            self.tagLabels[self.index % len(self.pixList)].hide()
            self.tagLabels[(self.index - 1) % len(self.pixList)].show()
        self.label[self.index % 5].setStyleSheet('background-color:red')
        self.index = self.index - 1
        if (self.index < self.leftBreak):
            self.leftBreak = self.leftBreak - 5
            self.rightBreak = self.rightBreak - 5
            for i in range(self.leftBreak, 1 + self.rightBreak, 1):
                self.label[j].setPixmap(self.pixList[i % len(self.pixList)])
                self.label[j].setAlignment(Qt.AlignCenter)
                j = j + 1
        self.label[self.index % 5].setStyleSheet('background-color: blue')
        self.bigLabel.setPixmap(self.bigPixList[self.index %
                                                len(self.pixList)])
        self.textBox.setText("")

    #Moves the pointer one picture to the right.  If it breaks the bounds of QLabel it will move the frame
    def moveIndexRight(self):
        j = 0
        if (self.mode == 1):
            self.tagLabels[self.index % len(self.pixList)].hide()
            self.tagLabels[(self.index + 1) % len(self.pixList)].show()
        self.label[self.index % 5].setStyleSheet('background-color: red')
        self.index = self.index + 1
        if (self.index > self.rightBreak):
            self.leftBreak = self.leftBreak + 5
            self.rightBreak = self.rightBreak + 5
            for i in range(self.leftBreak, 1 + self.rightBreak, 1):
                self.label[j].setPixmap(self.pixList[i % len(self.pixList)])
                self.label[j].setAlignment(Qt.AlignCenter)
                j = j + 1
        self.label[self.index % 5].setStyleSheet('background-color: blue')
        self.bigLabel.setPixmap(self.bigPixList[self.index %
                                                len(self.pixList)])
        self.textBox.setText("")

    #Zooms in on the specific picture selected and puts it into a 700 x 500 frame
    def zoomIn(self):
        self.mode = 1
        for i in range(0, 5, 1):
            self.label[i].hide()
        self.bigLabel.setAlignment(Qt.AlignCenter)
        self.bigLabel.show()
        self.tagButton.show()
        self.saveTagButton.show()
        self.textBox.show()
        self.tagLabels[self.index % len(self.pixList)].show()

    #Goes back to default view
    def zoomOut(self):
        self.mode = 0
        self.bigLabel.hide()
        for i in range(0, 5, 1):
            self.label[i].show()
        self.tagButton.hide()
        self.saveTagButton.hide()
        self.textBox.hide()
        self.tagLabels[self.index % len(self.pixList)].hide()

    #shifts the frame 5 pictures to the left
    def shiftLeft(self):
        if (self.mode == 1):
            self.tagLabels[self.index % len(self.pixList)].hide()
        self.label[self.index % 5].setStyleSheet('background-color:red')
        j = 0
        self.index = self.leftBreak - 1
        if (self.mode == 1):
            self.tagLabels[self.index % len(self.pixList)].show()
        self.leftBreak = self.leftBreak - 5
        self.rightBreak = self.rightBreak - 5
        for i in range(self.leftBreak, 1 + self.rightBreak, 1):
            self.label[j].setPixmap(self.pixList[i % len(self.pixList)])
            j = j + 1
        self.label[self.index % 5].setStyleSheet('background-color: blue')
        self.bigLabel.setPixmap(self.bigPixList[self.index %
                                                len(self.pixList)])
        self.textBox.setText("")

    #shifts the frame 5 pictures to the right
    def shiftRight(self):
        if (self.mode == 1):
            self.tagLabels[self.index % len(self.pixList)].hide()
        self.label[self.index % 5].setStyleSheet('background-color: red')
        j = 0
        self.index = self.rightBreak + 1
        if (self.mode == 1):
            self.tagLabels[self.index % len(self.pixList)].show()
        self.rightBreak = self.rightBreak + 5
        self.leftBreak = self.leftBreak + 5
        for i in range(self.leftBreak, 1 + self.rightBreak, 1):
            self.label[j].setPixmap(self.pixList[i % len(self.pixList)])
            j = j + 1
        self.label[self.index % 5].setStyleSheet('background-color: blue')
        self.bigLabel.setPixmap(self.bigPixList[self.index %
                                                len(self.pixList)])
        self.textBox.setText("")

    #all of the key inputs and their responses in functions
    def keyPressEvent(self, event):
        if (event.key() == 16777234):
            self.moveIndexLeft()
            if (self.mode == 0):
                self.soundClick.play()
            else:
                self.soundClickWah.play()
        if (event.key() == 16777236):
            self.moveIndexRight()
            if (self.mode == 0):
                self.soundClick.play()
            else:
                self.soundClickWah.play()
        if (event.key() == 16777235):
            self.zoomIn()
            self.soundLoop.setMuted(1)
            self.soundLoopWah.setMuted(0)
        if (event.key() == 16777237):
            self.zoomOut()
            self.soundLoopWah.setMuted(1)
            self.soundLoop.setMuted(0)
        if (event.key() == 44):
            self.shiftLeft()
            if (self.mode == 0):
                self.soundShift.play()
            else:
                self.soundShiftWah.play()
        if (event.key() == 46):
            self.shiftRight()
            if (self.mode == 0):
                self.soundShift.play()
            else:
                self.soundShiftWah.play()

    def mousePressEvent(self, QMouseEvent):
        if (QMouseEvent.y() < self.height / 7 * 8
                or QMouseEvent.y() > self.height / 15 * 16
                and QMouseEvent.x() < self.width / 6
                or QMouseEvent.x() > self.width / 3):
            self.setFocus()
        if (self.mode == 0):
            setPicTo = -1
            if (QMouseEvent.y() > self.height / 3 - 1
                    and QMouseEvent.y() < self.height / 2 + 1):
                if (QMouseEvent.x() > self.width / 12
                        and QMouseEvent.x() < self.width * 3 / 12 + 1):
                    setPicTo = 0
                if (QMouseEvent.x() > self.width * 3 / 12
                        and QMouseEvent.x() < self.width * 5 / 12 + 1):
                    setPicTo = 1
                if (QMouseEvent.x() > self.width * 5 / 12
                        and QMouseEvent.x() < self.width * 7 / 12 + 1):
                    setPicTo = 2
                if (QMouseEvent.x() > self.width * 7 / 12
                        and QMouseEvent.x() < self.width * 9 / 12 + 1):
                    setPicTo = 3
                if (QMouseEvent.x() > self.width * 9 / 12
                        and QMouseEvent.x() < self.width * 11 / 12 + 1):
                    setPicTo = 4
                if (setPicTo > -1):
                    self.label[self.index %
                               5].setStyleSheet('background-color:red')
                    self.mode = 1
                    self.index = self.leftBreak + setPicTo
                    self.label[self.index %
                               5].setStyleSheet('background-color:blue')
                    self.bigLabel.setPixmap(self.bigPixList[self.index %
                                                            len(self.pixList)])
                    for i in range(0, 5, 1):
                        self.label[i].hide()
                    self.bigLabel.setAlignment(Qt.AlignCenter)
                    self.bigLabel.show()
Ejemplo n.º 13
0
    def paintEvent(self, event):
        painter = QPainter(self)
        if self.show_menu:
            painter.setFont(QFont("Times", 50))
            painter.drawText(50, 50, "Welcome to my maze!")

            painter.setFont(QFont("Times", 20))

            painter.drawRoundedRect(30, 80, 25, 25, 5, 5)
            painter.drawText(33, 100, "W")
            painter.drawRoundedRect(5, 105, 25, 25, 5, 5)
            painter.drawText(10, 125, "A")
            painter.drawRoundedRect(30, 105, 25, 25, 5, 5)
            painter.drawText(35, 125, "S")
            painter.drawRoundedRect(55, 105, 25, 25, 5, 5)
            painter.drawText(60, 125, "D")

            painter.drawText(100, 125,
                             "Move your character with the WASD keys")

            painter.drawRoundedRect(10, 155, 60, 20, 5, 5)
            painter.drawText(75, 170, "Toggle flight by pressing the spacebar")

            painter.setPen(Qt.yellow)
            painter.setBrush(Qt.yellow)
            painter.drawEllipse(400, 150, 30, 30)
            painter.setPen(Qt.black)
            painter.setBrush(Qt.black)
            painter.drawEllipse(410, 155, 5, 5)
            painter.drawEllipse(420, 155, 5, 5)
            painter.drawArc(415, 165, 6, 4, 180 * 16, 180 * 16)

            painter.setPen(Qt.yellow)
            painter.setBrush(Qt.yellow)
            painter.drawEllipse(470, 150, 35, 35)
            painter.setPen(Qt.black)
            painter.setBrush(Qt.black)
            painter.drawEllipse(480, 155, 5, 5)
            painter.drawEllipse(490, 155, 5, 5)
            painter.drawEllipse(485, 165, 6, 4)

            painter.drawLine(435, 155, 465, 155)
            painter.drawLine(465, 155, 455, 145)
            painter.drawLine(465, 155, 455, 165)

            painter.drawLine(465, 175, 435, 175)
            painter.drawLine(435, 175, 445, 165)
            painter.drawLine(435, 175, 445, 185)
            # draw the smiley face guy

            painter.drawText(75, 220, "You can walk under green walls")
            painter.setPen(QPen(Qt.green, 4, Qt.SolidLine))
            painter.drawLine(60, 195, 60, 235)

            painter.setPen(Qt.black)
            painter.drawText(75, 270, "You can fly under blue walls")
            painter.setPen(QPen(Qt.blue, 4, Qt.SolidLine))
            painter.drawLine(60, 245, 60, 285)

            painter.setPen(Qt.black)
            painter.drawText(
                75, 320,
                "Press 0 if you're stuck. It'll show you what path to take :-)"
            )
            painter.drawText(
                75, 360,
                "Alternatively, press 9 if you want to see how the path is found!"
            )
            painter.setFont(QFont("Times", 10))
            painter.drawText(
                75, 380,
                "(Although some might call this cheating! This will also reset your points to 0)"
            )

            painter.setPen(Qt.red)
            painter.setFont(QFont("Times", 20))

            if not self.challenge_mode:
                painter.drawText(
                    75, 410,
                    "Press 'C' to play in challenge mode!! (Includes zombies)")
            else:
                painter.drawText(
                    75, 410,
                    "Scared? Press 'C' again to not play in challenge mode :-)"
                )

            painter.setPen(Qt.black)

            painter.drawText(
                75, 440,
                f"Maze size is currently {self.grid.get_width()} by {self.grid.get_height()}."
            )
            painter.drawText(75, 470,
                             "Press the + and - buttons to change the size,")
            painter.drawText(
                75, 490,
                "or press I for a custom input and U for a random input")

            if not self.show_animation:
                painter.drawText(
                    75, 520,
                    "Press the enter key to show the maze's animation")
                painter.drawText(75, 550, "(this might take a while)")
            else:
                painter.drawText(75, 520, "Animation toggled on!")
                painter.drawText(
                    75, 550,
                    "Press the enter key to remove the maze's animation")

            painter.drawText(75, 590, "Left click to start the game")
            painter.drawText(75, 620, "Press F to read a file of your choice")
            painter.setFont(QFont("Times", 10))
            painter.drawText(
                75, 630, "Make sure you have saved it in the right directory!")
        else:
            painter.setPen(Qt.black)

            if not self.challenge_mode:
                painter.setFont(QFont("Times", 18))
                painter.drawText(
                    75, 530,
                    f"Press R at anytime to save your progress onto a file!")

                if self.file_successful:
                    painter.setFont(QFont("Times", 10))
                    painter.drawText(75, 540, f"File saved successfully!")

                if self.msg == "":
                    painter.setFont(QFont("Times", 14))
                    painter.drawText(75, 555, f"Current points: {self.points}")
                else:
                    painter.drawText(75, 550, f"{self.msg}")
                    painter.setFont(QFont("Times", 14))
                    if not self.msg.endswith("Did you type it in correctly?"):
                        #painter.drawText(75, 570, "(Please note that we do not check whether or not "
                        #                          "mazes from files are possible to complete)")
                        painter.drawText(75, 590,
                                         f"Current points: {self.points}")
                    else:
                        painter.drawText(75, 570,
                                         f"Current points: {self.points}")
                painter.drawText(
                    75, 610,
                    f"Lost? Press 0 to find the way to the goal! (resets points to 0)"
                )
                painter.drawText(
                    75, 630, f"If you want to see how a recursive search "
                    f"algorithm finds the route to the goal, press 9!")

            else:
                painter.drawText(
                    75, 550,
                    f"No saving or finding solutions in challenge mode! Sorry!"
                )

            s = self.square_size

            # The following code looks janky becuase drawing on PyQt is a pain

            if self.challenge_mode and self.maze_done:
                if any(self.player_is_on_square == i
                       for i in self.zombie_positions) or any(
                           self.player_is_on_square == i
                           for i in self.previous_zombie_positions):
                    painter.setFont(QFont("Times", 34))
                    painter.drawText(50, 300, "you died!")
                    self.player_is_dead = True
                else:

                    def draw_zombie(paintr, pos):
                        painter.setBrush(Qt.green)
                        painter.setPen(Qt.black)
                        paintr.drawEllipse(pos[0] * s + 12, pos[1] * s + 12,
                                           s / 1.2, s / 1.2)
                        painter.setBrush(Qt.black)
                        painter.drawEllipse(pos[0] * s + 12,
                                            pos[1] * s + (s / 3.5) + 12, s / 5,
                                            s / 5)
                        painter.drawEllipse(pos[0] * s + (s / 3.5) + 12,
                                            pos[1] * s + (s / 3.5) + 12, s / 5,
                                            s / 5)
                        painter.drawLine(12 + pos[0] * s + s / 4,
                                         12 + pos[1] * s + s / 3,
                                         12 + pos[0] * s + s / 2.5,
                                         12 + pos[1] * s + s / 6)
                        painter.drawLine(12 + pos[0] * s + s / 10,
                                         12 + pos[1] * s + s / 6,
                                         12 + pos[0] * s + s / 4.5,
                                         12 + pos[1] * s + s / 3)
                        painter.setPen(Qt.white)
                        painter.setBrush(Qt.white)
                        painter.drawEllipse(pos[0] * s + 12,
                                            pos[1] * s + (s / 1.7) + 12, s / 3,
                                            s / 4)
                        painter.setPen(Qt.black)
                        painter.drawLine(pos[0] * s + 12 + s / 20,
                                         pos[1] * s + (s / 1.7) + 12 + s / 20,
                                         pos[0] * s + 12 + s / 10,
                                         pos[1] * s + (s / 1.7) + 12 + s / 10)
                        painter.drawLine(pos[0] * s + 12 + s / 10,
                                         pos[1] * s + (s / 1.7) + 12 + s / 10,
                                         pos[0] * s + 12 + s / 8,
                                         pos[1] * s + (s / 1.7) + 12)

                    for i in range(len(self.zombie_positions)):
                        draw_zombie(painter, self.zombie_positions[i])
                    self.previous_zombie_positions = self.zombie_positions

                    def get_next_zombie_square(current_square):
                        ret, ignore = solve_maze(self.grid, self.walls,
                                                 current_square,
                                                 self.player_is_on_square)
                        return ret[1][::-1]

                    self.zombie_positions = [
                        get_next_zombie_square(i)
                        for i in self.zombie_positions
                    ]

                    painter.setBrush(Qt.white)
                    painter.setPen(Qt.black)

            def draw_key(pos, colour):
                painter.setBrush(colour)
                painter.drawEllipse(pos[0] * s + 12 + s / 3, pos[1] * s + 12,
                                    s / 2.5, s / 2.5)
                painter.drawRect(pos[0] * s + 12 + s / 2.2,
                                 pos[1] * s + 12 + s / 2.6, s / 8, s / 3)
                painter.drawRect(pos[0] * s + 12 + s / 3,
                                 pos[1] * s + 12 + s / 2.2, s / 8, s / 15)
                painter.drawRect(pos[0] * s + 12 + s / 3,
                                 pos[1] * s + 12 + s / 1.7, s / 8, s / 15)
                painter.setBrush(Qt.white)
                painter.drawEllipse(pos[0] * s + 12 + s / 2.1,
                                    pos[1] * s + 12 + s / 20, s / 8, s / 8)

            if self.challenge_mode:
                if self.player_is_on_square == self.challenge_key[::-1]:
                    self.challenge_mode_key_found = True
                if not self.challenge_mode_key_found:
                    draw_key(self.challenge_key[::-1], Qt.yellow)

            if not self.maze_done:
                for i in range(len(self.grid.get_grid())):
                    for j in range(len(self.grid.get_grid()[i])):
                        if not self.grid.get_grid()[i][j].get_active():
                            color = QColor(220, 220, 220)
                            painter.setBrush(color)
                            painter.setPen(color)
                            painter.drawRect(i * s + 11, j * s + 11, s, s)
                painter.setPen(QPen(QColor(150, 120, 150), 3, Qt.SolidLine))
                painter.drawRect(self.the_chosen_one[1] * s + 10,
                                 self.the_chosen_one[0] * s + 10, s, s)
                # sleep(1 / (self.x_squares + self.y_squares))
                painter.setPen(Qt.black)
                painter.setBrush(Qt.white)

            horizontal_walls = self.walls.get_horizontal()
            vertical_walls = self.walls.get_vertical()
            for i in range(len(horizontal_walls)):
                for j in range(len(horizontal_walls[i])):
                    if horizontal_walls[i][j].get_activity():
                        if horizontal_walls[i][j].get_activity() == 3:
                            if max(self.x_squares, self.y_squares) <= 15:
                                painter.setPen(QPen(Qt.green, 2, Qt.SolidLine))
                            else:
                                painter.setPen(Qt.green)
                            painter.drawLine(i * s + 10, j * s + 10,
                                             i * s + 10, (j + 1) * s + 10)
                            painter.setPen(QPen(Qt.black, 1, Qt.SolidLine))
                        elif horizontal_walls[i][j].get_activity() == 2:
                            if max(self.x_squares, self.y_squares) <= 15:
                                painter.setPen(QPen(Qt.blue, 2, Qt.SolidLine))
                            else:
                                painter.setPen(Qt.blue)
                            painter.drawLine(i * s + 10, j * s + 10,
                                             i * s + 10, (j + 1) * s + 10)
                            painter.setPen(QPen(Qt.black, 1, Qt.SolidLine))
                        else:
                            painter.drawLine(i * s + 10, j * s + 10,
                                             i * s + 10, (j + 1) * s + 10)
            for i in range(len(vertical_walls)):
                for j in range(len(vertical_walls[i])):
                    if vertical_walls[i][j].get_activity():
                        if vertical_walls[i][j].get_activity() == 3:
                            if max(self.x_squares, self.y_squares) <= 15:
                                painter.setPen(QPen(Qt.green, 2, Qt.SolidLine))
                            else:
                                painter.setPen(Qt.green)
                            painter.drawLine(i * s + 10, j * s + 10,
                                             (i + 1) * s + 10, j * s + 10)
                            painter.setPen(QPen(Qt.black, 1, Qt.SolidLine))
                        elif vertical_walls[i][j].get_activity() == 2:
                            if max(self.x_squares, self.y_squares) <= 15:
                                painter.setPen(QPen(Qt.blue, 2, Qt.SolidLine))
                            else:
                                painter.setPen(Qt.blue)
                            painter.drawLine(i * s + 10, j * s + 10,
                                             (i + 1) * s + 10, j * s + 10)
                            painter.setPen(QPen(Qt.black, 1, Qt.SolidLine))
                        else:
                            painter.drawLine(i * s + 10, j * s + 10,
                                             (i + 1) * s + 10, j * s + 10)
            # Draw walls, some with blue and some with green colors
            # yeah it's kinda ugly

            self.goal_is_on_square = self.get_goal_square()
            if self.goal_is_on_square != [-1, -1]:
                painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
                painter.setBrush(Qt.white)
                goal_x = self.goal_is_on_square[0]
                goal_y = self.goal_is_on_square[1]
                painter.drawRect(goal_x * s + 12, goal_y * s + 12, s / 1.2,
                                 s / 1.2)
                if self.challenge_mode and not self.challenge_mode_key_found:
                    painter.setBrush(Qt.gray)
                    painter.setPen(QPen(Qt.red, 1, Qt.SolidLine))
                    painter.drawRect(goal_x * s + 12, goal_y * s + 12, s / 1.2,
                                     s / 1.2)  # to get a grey square
                    draw_key(self.goal_is_on_square, Qt.black)

            player_x = self.player_is_on_square[0]
            player_y = self.player_is_on_square[1]

            if not self.player_is_dead:
                if self.player_is_on_ground:
                    painter.setPen(Qt.yellow)
                    painter.setBrush(Qt.yellow)
                    painter.drawEllipse(player_x * s + 12, player_y * s + 12,
                                        s / 1.2, s / 1.2)
                    painter.setPen(Qt.black)
                    painter.setBrush(Qt.black)
                    painter.drawEllipse(player_x * s + (s / 2.7) + 12,
                                        player_y * s + (s / 4) + 12, s / 6,
                                        s / 6)
                    painter.drawEllipse(player_x * s + (s / 1.6) + 12,
                                        player_y * s + (s / 4) + 12, s / 6,
                                        s / 6)
                    painter.drawArc(player_x * s + (s / 2.7) + 12,
                                    player_y * s + (s / 2) + 12, s / 4, s / 6,
                                    180 * 16, 180 * 16)
                else:
                    painter.setPen(Qt.yellow)
                    painter.setBrush(Qt.yellow)
                    painter.drawEllipse(player_x * s + 12, player_y * s + 12,
                                        s, s)
                    painter.setPen(Qt.black)
                    painter.setBrush(Qt.black)
                    painter.drawEllipse(player_x * s + (s / 2.7) + 12,
                                        player_y * s + (s / 3.5) + 12, s / 5,
                                        s / 5)
                    painter.drawEllipse(player_x * s + (s / 1.6) + 12,
                                        player_y * s + (s / 3.5) + 12, s / 5,
                                        s / 5)
                    painter.drawEllipse(player_x * s + (s / 2.6) + 12,
                                        player_y * s + (s / 1.5) + 12, s / 3.5,
                                        s / 5)
                    # mouth open vs mouth closes (space bar animation)
            else:
                painter.setPen(QColor(150, 190, 50))
                painter.setBrush(QColor(150, 190, 50))
                painter.drawEllipse(player_x * s + 12, player_y * s + 12,
                                    s / 1.2, s / 1.2)
                painter.setPen(Qt.black)
                painter.setBrush(Qt.black)
                painter.drawEllipse(player_x * s + (s / 2.7) + 12,
                                    player_y * s + (s / 4) + 12, s / 6, s / 6)
                painter.drawEllipse(player_x * s + (s / 1.6) + 12,
                                    player_y * s + (s / 4) + 12, s / 6, s / 6)
                painter.drawArc(player_x * s + (s / 2.7) + 12,
                                player_y * s + (s / 2) + 12, s / 4, s / 6, 0,
                                180 * 16)
                # dead player after zombie eats it
            # Yes, i should really be working more with percentages here. Yes, the +12 is also
            # HORRIBLE coding practice. Please forgive me. I'll try to fix this later
            if self.show_animation and not self.maze_done:
                self.grid, self.walls, self.maze_done, self._grid_inactive_neighbours, self.the_chosen_one = \
                    maze.construct_maze(self.grid, self.walls, self._grid_inactive_neighbours, self.show_animation,
                                        self.player_is_on_square)
                self.goal_is_on_square = self.get_goal_square()

                if self.maze_done:
                    self.my_maze_solution = solve_maze(
                        self.grid, self.walls, self.player_is_on_square,
                        self.goal_is_on_square)
                    self.points = len(self.my_maze_solution) + 22
                self.update()

            if self.display_solution:

                def draw_solution(route):
                    prev = route[0]
                    for square in route:
                        painter.drawLine(prev[1] * s + 10 + s / 2,
                                         prev[0] * s + 10 + s / 2,
                                         square[1] * s + 10 + s / 2,
                                         square[0] * s + 10 + s / 2)
                        prev = square

                painter.setPen(Qt.red)
                if len(
                        self.all_answer_routes
                ) > self.count + 1:  # draw the routes taken to find answer, if animation is toggled
                    draw_solution(self.all_answer_routes[self.count])
                    self.count += 1
                    self.update()
                else:
                    draw_solution(self.my_maze_solution)
                painter.setPen(Qt.black)

            if self.player_is_on_square == self.goal_is_on_square:

                self.allow_movement = False
                explosion = QSoundEffect()
                explosion.setSource(
                    QUrl("explosion.wav"
                         ))  # TODO: fix sound not playing (needs a loop?)
                explosion.play()

                painter.setOpacity(0.7)
                for i in range(100):  # draw the "explosion" at the end
                    painter.setBrush(
                        choice([Qt.red, Qt.yellow, Qt.darkRed, Qt.white]))
                    s = randint(2, 250)
                    painter.drawEllipse(randint(0, 400), randint(0, 400), s, s)
                painter.setPen(Qt.black)
                painter.setOpacity(1)
                painter.setFont(QFont("Times", 65))
                painter.drawText(150, 270, "You won!")
                if not self.challenge_mode:
                    painter.drawText(50, 350, f"Your points: {self.points}")
                    if self.points >= 20:
                        painter.setFont(QFont("Times", 35))
                        painter.drawText(50, 400,
                                         "You are a true master of mazes!")
                    elif self.points >= 18:
                        painter.drawText(50, 400, "Well done!")
                    elif self.points > 0:
                        painter.drawText(50, 400, "Good try!")
                    else:
                        if not self.display_solution:
                            painter.setFont(QFont("Times", 25))
                            painter.drawText(
                                50, 400,
                                "Everyone solves mazes at their own pace :)")
                        else:
                            painter.drawText(50, 400, "I saw you cheat!")
Ejemplo n.º 14
0
class UI(Tk):
    def __init__(self):

        Tk.__init__(self)

        self.geometry('%dx%d+100+100' % (1200, 600))
        self.title('Crowdtour')
        self.audioCount = 0
        self.WAVE_OUTPUT_FILENAME = ''
        self.button_list = []
        self.current_places = []

        app = QApplication(sys.argv)

        self.canvas = Canvas(self, width=WIDTH, height=HEIGHT)

        self.canvas.pack()
        self.canvas.place(relx=0, rely=0)
        self.bind("<Key>", self.check_quit)
        self.bind('<B1-Motion>', self.drag)
        self.bind('<Button-1>', self.click)

        self.label = Label(self.canvas)

        self.radiogroup = Frame(self.canvas)
        self.radiovar = IntVar()
        self.maptypes = ['roadmap', 'terrain', 'satellite', 'hybrid']
        self.add_radio_button('Road Map', 0)
        self.add_radio_button('Terrain', 1)
        self.add_radio_button('Satellite', 2)
        self.add_radio_button('Hybrid', 3)

        #input
        self.entry = Entry(self, bd=3)
        self.button = Button(self, text="Location", command=self.geolocation)
        self.button.place(relx=.18, rely=.90, anchor="c")
        self.entry.place(relx=.05, rely=.80)

        #buttons
        self.recordButton = Button(self, text="Record", command=self.record)
        self.recordButton.place(relx=.30, rely=.75, anchor="c")

        self.uploadButton = Button(self, text="Upload", command=self.upload)
        self.uploadButton.place(relx=.30, rely=.80, anchor="c")

        self.playButton = Button(self, text="Play", command=self.play)
        self.playButton.place(relx=.30, rely=.85, anchor="c")

        self.deleteButton = Button(self, text="Delete", command=self.delete)
        self.deleteButton.place(relx=.30, rely=.90, anchor="c")
        ### adding part here ###
        self.sound = QSoundEffect()
        # This is where you set default sound source
        if not os.path.exists('sounds'):
            os.makedirs('sounds')

        defaultBytes = b'27\xe5\xb2\x81\xe5'
        waveTest = wave.open(os.path.join('sounds', 'DefaultSound.wav'), 'w')
        waveTest.setparams((2, 2, 44100, 440320, 'NONE', 'not compressed'))
        waveTest.writeframes(defaultBytes)

        self.sound.setSource(
            QUrl.fromLocalFile(os.path.join('sounds', 'DefaultSound.wav')))

        ### adding part here ###

        self.zoom_in_button = self.add_zoom_button('+', +1)
        self.zoom_out_button = self.add_zoom_button('-', -1)

        self.zoomlevel = ZOOM

        maptype_index = 0
        self.radiovar.set(maptype_index)
        MARKER = "markers=size:tiny|label:B|color:blue|" + str(
            LATITUDE) + "," + str(LONGITUDE)
        self.goompy = GooMPy(WIDTH, HEIGHT, LATITUDE, LONGITUDE, ZOOM, MAPTYPE,
                             MARKER)

        self.restart()

    def add_zoom_button(self, text, sign):

        button = Button(self.canvas,
                        text=text,
                        width=1,
                        command=lambda: self.zoom(sign))
        return button

    def reload(self):

        self.coords = None
        self.redraw()

        self['cursor'] = ''

    def restart(self):

        # A little trick to get a watch cursor along with loading
        self['cursor'] = 'watch'
        self.after(1, self.reload)

    def add_radio_button(self, text, index):

        maptype = self.maptypes[index]
        Radiobutton(self.radiogroup,
                    text=maptype,
                    variable=self.radiovar,
                    value=index,
                    command=lambda: self.usemap(maptype)).grid(row=0,
                                                               column=index)

    def click(self, event):

        self.coords = event.x, event.y

    def drag(self, event):

        self.goompy.move(self.coords[0] - event.x, self.coords[1] - event.y)
        self.image = self.goompy.getImage()
        self.redraw()
        self.coords = event.x, event.y

    def redraw(self):

        self.image = self.goompy.getImage()
        self.image_tk = ImageTk.PhotoImage(self.image)
        self.label['image'] = self.image_tk

        self.label.place(x=0, y=0, width=WIDTH, height=HEIGHT)

        self.radiogroup.place(x=0, y=0)

        x = int(self.canvas['width']) - 50
        y = int(self.canvas['height']) - 80

        self.zoom_in_button.place(x=x, y=y)
        self.zoom_out_button.place(x=x, y=y + 30)

    def usemap(self, maptype):

        self.goompy.useMaptype(maptype)
        self.restart()

    def zoom(self, sign):

        newlevel = self.zoomlevel + sign
        if newlevel > 0 and newlevel < 22:
            self.zoomlevel = newlevel
            self.goompy.useZoom(newlevel)
            self.restart()

    def check_quit(self, event):

        if ord(event.char) == 27:  # ESC
            exit(0)

    #input
    def geolocation(self):
        self.maplist = []
        self.buttonHeightCounter = .05
        API_KEY = 'AIzaSyBPGAbevdKkeXaZT0ZsR0qbO30Bpqqm0Mc'

        google_places = GooglePlaces(API_KEY)

        self.query_result = google_places.nearby_search(
            location=self.entry.get(),
            radius=700,
            types=[types.TYPE_RESTAURANT])
        self.current_places = self.query_result

        if self.query_result.has_attributions:
            print(self.query_result.html_attributions)

        for place in self.query_result.places:
            place.get_details()

            markers = "&markers=size:big|label:S|color:red|" + str(
                place.details['geometry']['location']['lat']) + "," + str(
                    place.details['geometry']['location']['lng']) + "|"
            self.maplist.append(markers)
            print(place.name)
            self.button_list.append(
                Button(self,
                       text=place.name,
                       command=lambda pname=place.name: self.on_click(pname),
                       width=25))
            self.button_list[-1].place(relx=.70,
                                       rely=self.buttonHeightCounter,
                                       anchor="c")
            self.buttonHeightCounter += .035
            print(place.formatted_address + "\n")

        google_maps = GoogleMaps(
            api_key='AIzaSyDlJqxwlOWWAPwf54ivrpAZw4R1Yb5j6Yk')

        location = google_maps.search(
            location=self.entry.get())  # sends search to Google Maps.

        my_location = location.first()  # returns only first location.

        #MARKER = '&markers=color:blue' + '%' + str(7) + 'Clabel:S%' + str(7) + 'C' + str(my_location.lat) + ',' + str(my_location.lng)
        #MARKER = "&markers=size:big|label:S|color:blue|" + str(my_location.lat) + "," + str(my_location.lng) + "|" + \

        MARKER = self.maplist[1] + self.maplist[2] + self.maplist[3]

        self.zoomlevel = ZOOM

        maptype_index = 0
        self.radiovar.set(maptype_index)

        self.goompy = GooMPy(WIDTH, HEIGHT, my_location.lat, my_location.lng,
                             ZOOM, MAPTYPE, MARKER)

        self.restart()
        print(self.query_result)
        print(str(my_location.lat))
        print(str(my_location.lng))
        #print(self.button_list)

    def record(self):
        print("Hello Anthony")
        #audioCount = 0
        CHUNK = 1024
        FORMAT = pyaudio.paInt16
        CHANNELS = 2
        RATE = 44100
        RECORD_SECONDS = 10
        self.WAVE_OUTPUT_FILENAME = "output" + str(self.audioCount) + ".wav"
        self.audioCount += 1

        p = pyaudio.PyAudio()

        stream = p.open(format=FORMAT,
                        channels=CHANNELS,
                        rate=RATE,
                        input=True,
                        frames_per_buffer=CHUNK)

        print("recording...")

        frames = []

        for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
            data = stream.read(CHUNK)
            frames.append(data)

        print("...done recording")

        stream.stop_stream()
        stream.close()
        p.terminate()

        wf = wave.open(os.path.join('sounds', self.WAVE_OUTPUT_FILENAME), 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()

        label = Label(self, text="recording is 10 seconds...done recording")
        #this creates a new label to the GUI
        label.place(relx=.35, rely=.80)

    def upload(self):
        #Convert .Wav into Binary
        self.w = wave.open(os.path.join('sounds', 'output0.wav'))

        #Parameters of the source file (keep this)
        #print(self.w.getparams())

        #Write the binary as a string...
        self.binary_data = self.w.readframes(self.w.getnframes())
        self.w.close()

        #Store binary into SQL
        cursorTest = connection.cursor()
        #TEST INSERT
        cursorTest.execute(
            "INSERT INTO `MARKERS` (`id`, `name`, `address`, `lat`, `lng`, `type`,`sound`) VALUES (%s, %s, %s, %s, %s, %s, %s)",
            ('9', 'Test Human', '999 Test Street, Rozelle, NSW', '-33.861034',
             '151.171936', 'restaurant', self.binary_data))
        #       cursorTest.execute("INSERT INTO `MARKERS` (`name`) VALUES (%s)", ('10'))
        #       cursorTest.execute("INSERT INTO `MARKERS` (`address`) VALUES (%s)", ('Insert Name Here'))
        #       cursorTest.execute("INSERT INTO `MARKERS` (`lat`) VALUES (%s)", ('0'))
        #       cursorTest.execute("INSERT INTO `MARKERS` (`lng`) VALUES (%s)", ('0'))
        #       cursorTest.execute("INSERT INTO `MARKERS` (`type`) VALUES (%s)", ('Insert Type Here'))
        #       cursorTest.execute("INSERT INTO `MARKERS` (`sound`) VALUES (%s)", ('Insert Sound Here'))

        #Read Binary from SQL
        cursors = connection.cursor(pymysql.cursors.DictCursor)
        cursors.execute("SELECT sound FROM MARKERS")
        result_set = cursors.fetchall()
        x = 0
        listSoundbytes = [None] * 1
        for row in result_set:
            listSoundbytes.insert(0, row["sound"])
            x += 1

        #Convert string to .wav file
        stringToByte = bytes(listSoundbytes[0])
        waveSave = wave.open(os.path.join('sounds', 'testFile.wav'), 'w')

        #Set parameters for writing
        waveSave.setparams((2, 2, 44100, 440320, 'NONE', 'not compressed'))
        waveSave.writeframes(stringToByte)
        connection.close()

        #Set sound source to soundbyte from SQL
        self.sound.setSource(
            QUrl.fromLocalFile(os.path.join('sounds', 'testFile.wav')))

        #The "All clear"
        print("Upload Successful")

        label1 = Label(self, text="Upload Successful!")
        #this creates a new label to the GUI
        label1.place(relx=.35, rely=.85)

    def play(self):
        pygame.init()
        pygame.mixer.init()
        sounda = pygame.mixer.Sound("./sounds/testFile.wav")
        sounda.play()

        #self.isPlaying = not self.isPlaying
        #self.isPlaying = True;
        #if self.isPlaying:
        #    self.sound.play()
        #    print('Play')
        #else:
        #    self.sound.stop()
        #    print('Stop')
        #print("play/stop")

    def delete(self):
        print("File Deleted from local device")
        try:
            os.remove('sounds/' + self.WAVE_OUTPUT_FILENAME)
            if self.audioCount < 0:
                self.audioCount -= 1
        except OSError as e:
            print("Error: %s - %s." % (e.filename, e.strerror))

    def on_click(self, pname):
        for place in self.query_result.places:
            if (place.name == pname):
                place.get_details()
                if (place.photos):
                    place.photos[0].get(200, 200)
                    place.photos[2].get(200, 200)
                    url = place.photos[0].url
                    url1 = place.photos[2].url
                    print(url)
                    resource = urllib.request.urlopen(url)
                    im = resource.read()
                    resource.close()
                    self.img = Image.open(BytesIO(im))
                    resource1 = urllib.request.urlopen(url1)
                    im1 = resource1.read()
                    resource1.close()
                    self.img1 = Image.open(BytesIO(im1))
                    canvas = Canvas(width=200, height=200, bg='black')
                    canvas1 = Canvas(width=200, height=200, bg='black')
                    canvas.pack()
                    canvas1.pack()
                    canvas.place(relx=.81, rely=.1)
                    canvas1.place(relx=.81, rely=.5)
                    img = self.img.resize((200, 200), Image.ANTIALIAS)
                    self.photo = ImageTk.PhotoImage(img)
                    img1 = self.img1.resize((200, 200), Image.ANTIALIAS)
                    self.photo1 = ImageTk.PhotoImage(img1)
                    canvas.create_image(105, 105, image=self.photo, anchor="c")
                    canvas1.create_image(105,
                                         105,
                                         image=self.photo1,
                                         anchor="c")

        self.restart()
Ejemplo n.º 15
0
 def on_btnEffect_File_clicked(self):
     url = QUrl.fromLocalFile("Ak47.wav")
     player = QSoundEffect(self)
     player.setLoopCount(2)  #播放循环次数
     player.setSource(url)  #设置源文件
     player.play()
Ejemplo n.º 16
0
 def on_btnEffect_Resource_clicked(self):
     url = QUrl.fromLocalFile(":/Wave/sound/blast.wav")
     player = QSoundEffect(self)
     player.setLoopCount(2)
     player.setSource(url)
     player.play()  #无法播放资源文件
Ejemplo n.º 17
0
class Window(QWidget):
 
    def __init__(self,width,height):
        super().__init__()
        self.height = height
        self.width = width
        #index for the navigation
        self.index = 0
        #index for changing the color of the selected image
        self.colorIndex = 0
        #determines when to load new images
        self.leftBreak = 0
        self.rightBreak = 4
        #large zoomed in image list
        self.bigPixList = []
        #thumbnail image list
        self.pixList = []
        #labels to store thumbnails
        self.label = []
        #labels to store tags
        self.tagLabels = []
        #big label for zoomed in image
        self.bigLabel = QLabel(self)
        self.bigLabel.resize(self.width * 3 / 4, self.height * 3 / 4)
        self.bigLabel.move(self.width / 8, self.height / 8)
        self.bigLabel.hide()
        #for saving all of the search images
        self.saveURL = ""
        #adding buttons and textbox
        self.textBox = QLineEdit(self)
        self.textBox.setStyleSheet("color: rgb(255, 255, 255);")
        self.textBox.move(self.width / 6, self.height * 7 / 8)
        self.textBox.resize(150,self.height / 16)
        self.textBox.hide()
        self.tagButton = QPushButton('Add Tag', self)
        self.tagButton.setStyleSheet("background-color: rgb(125,125,125);")
        self.tagButton.move(self.width / 6, self.height * 15 / 16)
        self.tagButton.clicked.connect(self.tagClick)
        self.tagButton.hide()
        self.saveTagButton = QPushButton('Save All Tags', self)
        self.saveTagButton.setStyleSheet("background-color: rgb(125, 125, 125);")
        self.saveTagButton.move(self.width / 6 + 75, self.height * 15 / 16)
        self.saveTagButton.clicked.connect(self.saveTagClick)
        self.saveTagButton.hide()
        self.searchBar = QLineEdit(self)
        self.searchBar.setStyleSheet("color: rgb(255, 255,255);")
        self.searchBar.move(self.width/6, self.height * 7 / 8)
        self.searchBar.resize(300, self.height / 16)
        self.setFocus()
        self.testButton  = QPushButton('Test', self)
        self.testButton.setStyleSheet("background-color: rgb(125, 125, 125);")
        self.testButton.move(self.width / 6, self.height * 15 / 16)
        self.testButton.clicked.connect(self.testClick)
        self.saveButton = QPushButton('Save', self)
        self.saveButton.setStyleSheet("background-color: rgb(125, 125, 125);")
        self.saveButton.move(self.width / 6 + 75, self.height * 15 / 16)
        self.saveButton.clicked.connect(self.saveClick)
        self.exitButton = QPushButton('Exit',self)
        self.exitButton.setStyleSheet("background-color: rgb(125, 125, 125);")
        self.exitButton.move(self.width / 6 + 150, self.height * 15 / 16)
        self.exitButton.clicked.connect(self.exitClick)
        self.deleteButton = QPushButton('Delete', self)
        self.deleteButton.setStyleSheet("background-color: rgb(125, 125, 125);")
        self.deleteButton.move(self.width / 6 + 225, self.height * 15 / 16)
        self.deleteButton.clicked.connect(self.deleteClick)
        self.searchButton = QPushButton('Search', self)
        self.searchButton.setStyleSheet("background-color: rgb(125, 125, 125);")
        self.searchButton.clicked.connect(self.searchClick)
        self.searchButton.move(self.width/6 +325, self.height * 29 / 32)
        self.searchResults = QLineEdit(self)
        self.searchResults.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.searchResults.resize(25, self. height / 16)
        self.searchResults.move(self.width/6 + 425, self.height * 29 / 32)
        self.searchResults.setText("10")
        self.searchText = QLabel(self)
        self.searchText.resize(150, 50)
        self.searchText.move(self.width/6 + 455, self.height * 29 / 32)
        self.searchText.setText("Max Search Results")
        self.searchText.setStyleSheet("color: rgb(255, 255, 255);")
        #item that holds the current string to be stored as tag
        self.currentString = []
        self.mode = 0
        #Sets up the warning message for too long strings
        self.warningMessage = QLabel(self)
        self.warningMessage.resize(self.width / 5, self.height / 16)
        self.warningMessage.setStyleSheet("background-color: red; font: bold 14px")
        self.warningMessage.setText("String too long")
        self.warningMessage.move(self.width / 2, self.height * 7 / 8)
        self.warningMessage.hide()
        #setting up the sounds to use
        self.soundClick = QSoundEffect()
        self.soundClickWah = QSoundEffect()
        self.soundLoop = QSoundEffect()
        self.soundLoopWah = QSoundEffect()
        self.soundShift = QSoundEffect()
        self.soundShiftWah = QSoundEffect()
        self.soundClick.setSource(QUrl.fromLocalFile(os.path.join('sounds','PianoNote.wav')))
        self.soundClickWah.setSource(QUrl.fromLocalFile(os.path.join('sounds','PianoNoteWah.wav')))
        self.soundShift.setSource(QUrl.fromLocalFile(os.path.join('sounds','PianoMultiNote.wav')))
        self.soundShiftWah.setSource(QUrl.fromLocalFile(os.path.join('sounds','PianoMultiNoteWah.wav')))
        self.soundLoop.setSource(QUrl.fromLocalFile(os.path.join('sounds','loop08.wav')))
        self.soundLoopWah.setSource(QUrl.fromLocalFile(os.path.join('sounds','loop08Wah.wav')))
        self.soundLoop.setLoopCount(QSoundEffect.Infinite)
        self.soundLoopWah.setLoopCount(QSoundEffect.Infinite)
        self.soundLoop.play()
        self.soundLoopWah.play()
        self.soundLoopWah.setMuted(1)
        self.initUI()
    #Adds the tag to the list triggered by clicking on the button only if the string is less than 11 characters, otherwise shows warning message
    def tagClick(self):
        tagValue = self.textBox.text()
        if(len(tagValue) < 11):
            self.currentString[self.index % len(self.pixList)] += (tagValue + "\n")
            self.tagLabels[self.index % len(self.pixList)].setText(self.currentString[self.index % len(self.pixList)])
            self.textBox.setText("")
            self.setFocus()
            self.warningMessage.hide()
        else:
            self.warningMessage.show()
    def saveTagClick(self):
        f = open('SavedTags.txt','w')
        f.truncate()
        for i in range(0, len(self.pixList), 1):
            f.write(self.tagLabels[i].text())
            f.write("#")
        self.setFocus()
    #takes a URL entered into the search bar and adds an image to the two pixmap lists.  It also appends the URL onto the saved URLs string if the user wants to save them later    
    def testClick(self):
        path = self.searchBar.text()
        self.searchBar.setText("")
        self.saveURL = self.saveURL + path + "\n"
        url_data = urllib.request.urlopen(path).read()
        tmpPixmap = QPixmap()
        tmpPixmap.loadFromData(url_data)
        if(tmpPixmap.height() > self.height * 3 / 4):
            tmpPixmap = tmpPixmap.scaledToHeight(self.height * 3 / 4)
        if(tmpPixmap.width() > self.width * 3 / 4):
            tmpPixmap = tmpPixmap.scaledToWidth(self.width * 3 / 4)
        self.bigPixList.append(tmpPixmap)
        if(tmpPixmap.height() > self.height / 6 - 10):
            tmpPixmap = tmpPixmap.scaledToHeight(self.height / 6 - 10)
        if(tmpPixmap.width() > self.width / 6 - 10):
            tmpPixmap = tmpPixmap.scaledToWidth(self.width / 6 - 10)
        self.pixList.append(tmpPixmap)
        for i in range(-1,4,1):
            self.label[i + 1].setPixmap(self.pixList[i % len(self.pixList)])
        self.label[self.colorIndex].setStyleSheet('background-color: red')
        self.index = -1
        self.colorIndex = 0
        self.leftBreak = -1
        self.rightBreak = 3
        self.label[self.colorIndex].setStyleSheet('background-color: blue')
        self.tagLabels.append(self.tagLabels[i])
        self.tagLabels[-1 % len(self.pixList)].setText("")
        self.bigLabel.setPixmap(self.bigPixList[-1 % len(self.pixList)])
        self.setFocus()
    #saves all the URLS searched for into a text file separated by a new line
    def saveClick(self):
        f = open('SavedURLS.txt','w')
        f.truncate()
        f.write(self.saveURL)
        self.saveTags()
        self.setFocus()
    #exits the program
    def exitClick(self):
        sys.exit()
    #simply deletes the image out of the array and fixes it so that the images get truncated to fit
    def deleteClick(self):
        del self.pixList[self.index % len(self.pixList)]
        del self.bigPixList[self.index % len(self.pixList)]
        self.bigLabel.setPixmap(self.bigPixList[self.index % len(self.pixList)])
        for i in range(0, 5, 1):
            self.label[i].setPixmap(self.pixList[i + self.leftBreak])
        self.setFocus()
    #searches using the flickr API and json responses. Stores those images in the same two pixmap lists and appends the URLS to the saved urls string if the user wants to save them
    def searchClick(self):
        self.index = len(self.pixList)
        self.leftBreak = self.index
        self.rightBreak = self.index + 4
        self.label[self.colorIndex].setStyleSheet('background-color: red')
        self.colorIndex = 0
        self.label[0].setStyleSheet('background-color: blue')
        tempStr = self.searchBar.text()
        tempStr.replace(" ", "%20")
        self.searchBar.setText("")
        req = 'https://api.flickr.com/services/rest/'
        req = req + '?method=flickr.photos.search'
        req = req + '&per_page=' + self.searchResults.text()
        req = req + '&format=json&nojsoncallback=1'
        req = req + '&api_key=a0ab0abe9800e8352ae0364a9b595cd2'
        req = req + '&tags=' + tempStr
        jsonRespDict = requests.get(req).json()
        photoset = jsonRespDict['photos']
        for p in photoset['photo']:
            farm = p['farm']
            server = p['server']
            eyedee = p['id']
            secret = p['secret']
            tempStr = "http://farm" +str(farm) + ".static.flickr.com/" + str(server) + "/" + str(eyedee) + "_" + str(secret) + ".jpg"
            print(tempStr)
            self.saveURL = self.saveURL + tempStr + "\n"
            url_data = urllib.request.urlopen(tempStr).read()
            tmpPixmap = QPixmap()
            tmpPixmap.loadFromData(url_data)
            if(tmpPixmap.height() > self.height * 3 / 4):
                tmpPixmap = tmpPixmap.scaledToHeight(self.height * 3 / 4)
            if(tmpPixmap.width() > self.width * 3 / 4):
                tmpPixmap = tmpPixmap.scaledToWidth(self.width * 3 / 4)
            self.bigPixList.append(tmpPixmap)
            if(tmpPixmap.height() > self.height / 6 - 10):
                tmpPixmap = tmpPixmap.scaledToHeight(self.height / 6 - 10)
            if(tmpPixmap.width() > self.width / 6 - 10):
                tmpPixmap = tmpPixmap.scaledToWidth(self.width / 6 - 10)
            self.pixList.append(tmpPixmap)
            self.tagLabels.append(self.tagLabels[0])
        for i in range(self.index, len(self.pixList), 1):
            self.tagLabels[i].setText("")
        for i in range(self.index, self.index + 5, 1):
            self.label[i-self.index].setPixmap(self.pixList[i % len(self.pixList)])
        self.bigLabel.setPixmap(self.bigPixList[self.index % len(self.pixList)])
        self.setFocus()
    def initUI(self):
        # title of window
        self.setWindowTitle('PyQt5 Main Window')
        # place window on screen at x=0, y=0
        self.setGeometry(0, 0, self.width, self.height)
        self.setStyleSheet('background-color: black')
        #sets up QLabels for later input
        for i in range(0, 5, 1):
            self.label.append(QLabel(self))
            self.label[i].move(self.width / 12 + i * self.width / 6, self.height / 3)
            self.label[i].resize(self.width / 6, self.height / 6)
            self.label[i].setStyleSheet('background-color: red')
            if(i == 0):
                self.label[i].setStyleSheet('background-color: blue')
        #places pictures into pixmap array
        i = 0
        for file in os.listdir('data'):
            self.pixList.append(QPixmap(os.path.join('data', file)))
            self.bigPixList.append(QPixmap(os.path.join('data',file)))
            self.tagLabels.append(QLabel(self))
            self.currentString.append("")
            self.tagLabels[i].resize(self.width / 8, self.height)
            self.tagLabels[i].move(self.width * 7 / 8, 0)
            self.tagLabels[i].setStyleSheet('border-color: grey; border-style: outset; border-width: 5px; font: bold 14px; color: white')
            self.tagLabels[i].setAlignment(Qt.AlignTop)
            self.tagLabels[i].hide()
            if(self.pixList[i].height() > self.height / 6 - 10):
                self.pixList[i] = self.pixList[i].scaledToHeight(self.height / 6 - 10)
            if(self.pixList[i].width() > self.width / 6 - 10):
                self.pixList[i] = self.pixList[i].scaledToWidth(self.width / 6 - 10)
            if(self.bigPixList[i].width() > self.width*3/4 ):
                self.bigPixList[i] = self.bigPixList[i].scaledToWidth(self.width*3/4)
            if(self.bigPixList[i].height() > self.height*3/4):
                self.bigPixList[i] = self.bigPixList[i].scaledToHeight(self.height*3/4)
            i = i + 1
        self.bigLabel.setAlignment(Qt.AlignCenter)
        self.bigLabel.setPixmap(self.bigPixList[0])
        #puts initial pixmaps into the designated qlabels
        for i in range(0, 5, 1):
            self.label[i].setPixmap(self.pixList[i])
            self.label[i].setAlignment(Qt.AlignCenter)
        self.loadURLS()
        self.show()
        self.loadTags()
    #Loads URLS from the text file and places them into the pixmap array
    def loadURLS(self):
        f = open('SavedURLS.txt','r')
        tempString = f.read()
        self.savedURLS = tempString
        tempString2 = tempString.split("\n")
        for i in range(0, len(tempString2)-1, 1):
            url_data = urllib.request.urlopen(tempString2[i]).read()
            tmpPixmap = QPixmap()
            tmpPixmap.loadFromData(url_data)
            if(tmpPixmap.height() > self.height * 3 / 4):
                tmpPixmap = tmpPixmap.scaledToHeight(self.height * 3 / 4)
            if(tmpPixmap.width() > self.width * 3 / 4):
                tmpPixmap = tmpPixmap.scaledToWidth(self.width * 3 / 4)
            self.bigPixList.append(tmpPixmap)
            if(tmpPixmap.height() > self.height / 6 - 10):
                tmpPixmap = tmpPixmap.scaledToHeight(self.height / 6 - 10)
            if(tmpPixmap.width() > self.width / 6 - 10):
                tmpPixmap = tmpPixmap.scaledToWidth(self.width / 6 - 10)
            self.pixList.append(tmpPixmap)
            self.tagLabels.append(QLabel(self))
            self.currentString.append("")
            self.tagLabels[len(self.pixList)-1].resize(self.width / 8, self.height)
            self.tagLabels[len(self.pixList)-1].move(self.width * 7 / 8, 0)
            self.tagLabels[len(self.pixList)-1].setStyleSheet('border-color: grey; border-style: outset; border-width: 5px; font:bold 14px; color: white')
            self.tagLabels[len(self.pixList)-1].setAlignment(Qt.AlignTop)
            self.tagLabels[len(self.pixList)-1].hide()

    #loads all saved tags
    def loadTags(self):
        f = open('SavedTags.txt','r')
        tempString = f.read()
        j = 0
        for i in range(0, len(tempString), 1):
            if(tempString[i] != "#"):
                self.currentString[j]+=tempString[i]
            else:
                self.tagLabels[j].setText(self.currentString[j])
                j = j + 1
    #Moves the pointer to the picture one to the left.  If it breaks the bounds, it will move the frame
    def moveIndexLeft(self):
        j = 0
        if(self.mode == 1):
            self.tagLabels[self.index % len(self.pixList)].hide()
            self.tagLabels[(self.index - 1) % len(self.pixList)].show()
        self.label[self.colorIndex].setStyleSheet('background-color:red')
        self.colorIndex = self.colorIndex -1
        if(self.colorIndex < 0):
            self.colorIndex = 4
        self.index = self.index - 1
        if(self.index < self.leftBreak):
            self.leftBreak = self.leftBreak - 5
            self.rightBreak = self.rightBreak - 5
            for i in range(self.leftBreak, 1 + self.rightBreak, 1):
                self.label[j].setPixmap(self.pixList[i % len(self.pixList)])
                self.label[j].setAlignment(Qt.AlignCenter)
                j = j + 1
        self.label[self.colorIndex].setStyleSheet('background-color: blue')
        self.bigLabel.setPixmap(self.bigPixList[self.index % len(self.pixList)])
        self.textBox.setText("")
    #Moves the pointer one picture to the right.  If it breaks the bounds of QLabel it will move the frame
    def moveIndexRight(self):
        j = 0
        if(self.mode == 1):
            self.tagLabels[self.index % len(self.pixList)].hide()
            self.tagLabels[(self.index + 1) % len(self.pixList)].show()
        self.label[self.colorIndex].setStyleSheet('background-color: red')
        self.colorIndex = self.colorIndex + 1
        if(self.colorIndex > 4):
            self.colorIndex = 0
        self.index = self.index + 1
        if(self.index > self.rightBreak):
            self.leftBreak = self.leftBreak + 5
            self.rightBreak = self.rightBreak + 5
            for i in range(self.leftBreak, 1 + self.rightBreak, 1):
                self.label[j].setPixmap(self.pixList[i % len(self.pixList)])
                self.label[j].setAlignment(Qt.AlignCenter)
                j = j + 1
        self.label[self.colorIndex].setStyleSheet('background-color: blue')
        self.bigLabel.setPixmap(self.bigPixList[self.index % len(self.pixList)])
        self.textBox.setText("")
    #Zooms in on the specific picture selected and puts it into a 700 x 500 frame    
    def zoomIn(self):
        self.mode = 1
        for i in range(0, 5, 1):
            self.label[i].hide()
        self.bigLabel.setAlignment(Qt.AlignCenter)
        self.bigLabel.show()
        self.tagButton.show()
        self.saveTagButton.show()
        self.textBox.show()
        self.tagLabels[self.index % len(self.pixList)].show()
        self.searchBar.hide()
        self.testButton.hide()
        self.saveButton.hide()
        self.exitButton.hide()
        self.deleteButton.hide()
        self.searchButton.hide()
        self.searchResults.hide()
        self.searchText.hide()
    #Goes back to default view
    def zoomOut(self):
        self.mode = 0
        self.bigLabel.hide()
        for i in range(0, 5, 1):
            self.label[i].show()
        self.tagButton.hide()
        self.saveTagButton.hide()
        self.textBox.hide()
        self.tagLabels[self.index % len(self.pixList)].hide()
        self.searchBar.show()
        self.testButton.show()
        self.saveButton.show()
        self.exitButton.show()
        self.deleteButton.show()
        self.searchButton.show()
        self.searchResults.show()
        self.searchText.show()
    #shifts the frame 5 pictures to the left
    def shiftLeft(self):
        if(self.mode == 1):
            self.tagLabels[self.index % len(self.pixList)].hide()
        self.label[self.colorIndex].setStyleSheet('background-color:red')
        j = 0
        self.colorIndex = 0
        self.index = self.leftBreak - 5
        if(self.mode == 1):
            self.tagLabels[self.index % len(self.pixList)].show()
        self.leftBreak = self.leftBreak - 5
        self.rightBreak = self.rightBreak - 5
        for i in range(self.leftBreak, 1 + self.rightBreak, 1):
            self.label[j].setPixmap(self.pixList[i % len(self.pixList)])
            j = j + 1
        self.label[0].setStyleSheet('background-color: blue')
        self.bigLabel.setPixmap(self.bigPixList[self.index % len(self.pixList)])
        self.textBox.setText("")
    #shifts the frame 5 pictures to the right
    def shiftRight(self):
        if(self.mode == 1):
            self.tagLabels[self.index % len(self.pixList)].hide()
        self.label[self.colorIndex].setStyleSheet('background-color: red')
        self.colorIndex = 0
        j = 0
        self.index = self.rightBreak + 1
        if(self.mode == 1):
            self.tagLabels[self.index % len(self.pixList)].show()
        self.rightBreak = self.rightBreak + 5
        self.leftBreak = self.leftBreak + 5
        for i in range(self.leftBreak, 1 + self.rightBreak, 1):
            self.label[j].setPixmap(self.pixList[i % len(self.pixList)])
            j = j + 1
        self.label[0].setStyleSheet('background-color: blue')
        self.bigLabel.setPixmap(self.bigPixList[self.index % len(self.pixList)])
        self.textBox.setText("")
    #all of the key inputs and their responses in functions
    def keyPressEvent(self, event):
        if(event.key() == 16777234):
            self.moveIndexLeft()
            if(self.mode == 0):
                self.soundClick.play()
            else:
                self.soundClickWah.play()
        if(event.key() == 16777236):
            self.moveIndexRight()
            if(self.mode == 0):
                self.soundClick.play()
            else:
                self.soundClickWah.play()
        if(event.key() == 16777235):
            self.zoomIn()
            self.soundLoop.setMuted(1)
            self.soundLoopWah.setMuted(0)
        if(event.key() == 16777237):
            self.zoomOut()
            self.soundLoopWah.setMuted(1)
            self.soundLoop.setMuted(0)
        if(event.key() == 44):
            self.shiftLeft()
            if(self.mode == 0):
                self.soundShift.play()
            else:
                self.soundShiftWah.play()
        if(event.key() == 46):
            self.shiftRight()
            if(self.mode == 0):
                self.soundShift.play()
            else:
                self.soundShiftWah.play()
    def mousePressEvent(self, QMouseEvent):
        if(QMouseEvent.y() < self.height / 7 * 8 or QMouseEvent.y() > self.height / 15 * 16 and QMouseEvent.x() < self.width / 6 or QMouseEvent.x() > self.width / 3):
            self.setFocus()
        if(self.mode == 0):
            setPicTo = -1
            if(QMouseEvent.y() > self.height / 3 - 1 and QMouseEvent.y() < self.height / 2 + 1):
                if(QMouseEvent.x() > self.width / 12 and QMouseEvent.x() < self.width * 3 / 12 + 1):
                    setPicTo = 0
                if(QMouseEvent.x() > self.width * 3 / 12  and QMouseEvent.x() < self.width * 5 / 12 + 1):
                    setPicTo = 1
                if(QMouseEvent.x() > self.width * 5 / 12  and QMouseEvent.x() < self.width * 7 / 12 + 1):
                    setPicTo = 2
                if(QMouseEvent.x() > self.width * 7 / 12  and QMouseEvent.x() < self.width * 9 / 12 + 1):
                    setPicTo = 3
                if(QMouseEvent.x() > self.width * 9 / 12  and QMouseEvent.x() < self.width * 11 / 12 + 1):
                    setPicTo = 4
                if(setPicTo > -1):
                    self.label[self.index % 5].setStyleSheet('background-color:red')
                    self.mode = 1
                    self.index = self.leftBreak + setPicTo
                    self.colorIndex = setPicTo
                    self.label[self.index % 5].setStyleSheet('background-color:blue')
                    self.bigLabel.setPixmap(self.bigPixList[self.index % len(self.pixList)])
                    for i in range(0, 5, 1):
                        self.label[i].hide()
                    self.bigLabel.setAlignment(Qt.AlignCenter)
                    self.bigLabel.show()
Ejemplo n.º 18
0
class PlayWidget(QWidget):
    def __init__(self, parent):
        super(PlayWidget, self).__init__(parent)
        self.setAutoFillBackground(True)
        self.hlayout = QHBoxLayout(self)

        self.table_view = CardView(self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.table_view.sizePolicy().hasHeightForWidth())
        self.table_view.setSizePolicy(sizePolicy)
        self.table_view.setMinimumHeight(200)
        self.table_view.setBackgroundBrush(Qt.darkGreen)
        self.table_view.setGeometry(0, 0, 1028, 200)

        self.hand_view = HandCardView(self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.hand_view.sizePolicy().hasHeightForWidth())
        self.hand_view.setSizePolicy(sizePolicy)
        self.hand_view.setMinimumHeight(200)
        self.hand_view.setBackgroundBrush(Qt.darkGreen)
        self.hand_view.setGeometry(0, 0, 1028, 200)

        self.show_button = Button(self, 'Show Hand')
        self.show_button.setText("Show hand")
        self.show_button.clicked.connect(self.hand_view.show_cards)
        self.show_button.hide()

        self.move_button = Button(self, 'Make Move')
        self.move_button.setMinimumSize(300, 100)
        self.move_button.clicked.connect(self.attempt_move)
        self.move_button.hide()

        self.start_button = Button(self, 'Start Round')
        self.start_button.setMinimumHeight(100)
        self.start_button.clicked.connect(self.start_round)

        self.next_button = Button(self, 'Continue')
        self.next_button.setMinimumHeight(100)
        self.next_button.clicked.connect(self.goto_next_round)
        self.next_button.hide()

        self.quit_button = Button(self, 'Quit to menu')

        self.save_button = Button(self, 'Save')

        self.show_button.setMaximumWidth(150)
        self.move_button.setMaximumWidth(150)
        self.quit_button.setMaximumWidth(150)

        self.btnlayout = QHBoxLayout()
        self.btnlayout.addWidget(self.start_button)

        self.btn2layout = QHBoxLayout()
        self.btn2layout.addWidget(self.save_button)
        self.btn2layout.addWidget(self.quit_button)

        self.playlayout = QVBoxLayout()
        self.playlayout.addWidget(self.table_view)
        self.playlayout.addLayout(self.btnlayout)
        self.playlayout.addWidget(self.hand_view)
        self.playlayout.addLayout(self.btn2layout)
        self.hlayout.addLayout(self.playlayout)

        self.sidelayout = QVBoxLayout()
        self.log = QPlainTextEdit()
        self.log.setReadOnly(True)
        self.log.setPalette(QPalette(Qt.white))
        self.log.setMaximumWidth(300)
        self.log.setMaximumHeight(200)
        self.sidelayout.addWidget(self.log)

        self.playerinfolayout = QVBoxLayout()
        self.sidelayout.addLayout(self.playerinfolayout)

        self.sidelayout.addItem(
            QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))

        self.hlayout.addLayout(self.sidelayout)

        self.setup_sound()

        self.move_count = 0
        self.speed = 3
        self.game = None

    def init_game(self, game):
        self.game = game
        self.game.logSignal.connect(self.update_log)
        self.game.sweepSignal.connect(self.sweep_sound.play)

        self.game.new_round()
        self.shuffle_sound.play()
        self.game.initial_deal()

        self.move_count = 0

        for player in self.game.players:
            self.playerinfolayout.addWidget(PlayerInfo(self, player))

    def start_round(self):
        self.btnlayout.removeWidget(self.start_button)
        self.btnlayout.insertWidget(0, self.show_button)
        self.btnlayout.insertWidget(1, self.move_button)
        self.start_button.hide()
        self.show_button.show()
        self.move_button.show()

        self.table_view.update_scene(self.game.table)
        self.hand_view.update_scene(self.game.current_player.hand)

        self.hand_view.hide_cards()

        if type(self.game.current_player
                ) is not AIPlayer and self.game.one_human:
            self.hand_view.show_cards()

        self.playerinfolayout.itemAt(
            self.game.players.index(
                self.game.current_player)).widget().set_active()
        self.update_log('\n----------\n{}\'s turn\n'.format(
            self.game.current_player))

        if type(self.game.current_player) is AIPlayer:
            self.move_button.setDisabled(True)
            self.show_button.setDisabled(True)
            self.save_button.setDisabled(True)
            self.make_ai_move()

    def resume_from_save(self, game, logmsg, movecount):
        self.game = game
        self.game.logSignal.connect(self.update_log)
        self.game.sweepSignal.connect(self.sweep_sound.play)

        self.log.insertPlainText(logmsg)
        self.log.insertPlainText(
            '\n----------------\n    Resuming from save\n----------------\n\n')

        self.move_count = movecount

        for player in self.game.players:
            self.playerinfolayout.addWidget(PlayerInfo(self, player))

        self.playerinfolayout.itemAt(
            self.game.players.index(
                self.game.current_player)).widget().set_active()

    def make_ai_move(self):
        self.game.select_move_for_ai()
        QTimer.singleShot(1500 // self.speed, self.show_ai_move)

    def show_ai_move(self):
        self.hand_view.auto_select()
        self.table_view.auto_select()
        self.card_sound.play()
        self.game.do_action()
        QTimer.singleShot(3000 // self.speed, self.after_ai_move_done)

    def after_ai_move_done(self):
        self.move_sound.play()
        self.playerinfolayout.itemAt(
            self.game.players.index(
                self.game.current_player)).widget().update_info()
        self.game.deal()
        self.table_view.update_scene(self.game.table)
        self.hand_view.update_scene(self.game.current_player.hand)
        self.hand_view.hide_cards()
        QTimer.singleShot(3000 // self.speed, self.end_turn)

    def attempt_move(self):
        if self.game.do_action():
            self.move_sound.play()
            self.playerinfolayout.itemAt(
                self.game.players.index(
                    self.game.current_player)).widget().update_info()
            self.move_button.setDisabled(True)
            self.table_view.update_scene(self.game.table)
            self.hand_view.update_scene(self.game.current_player.hand)
            QTimer.singleShot(1800 // self.speed, self.after_move_done)

        else:
            self.error_sound.play()

    def after_move_done(self):
        self.game.deal()
        self.hand_view.update_scene(self.game.current_player.hand)
        QTimer.singleShot(3000 // self.speed, self.end_turn)

    def end_turn(self):
        self.playerinfolayout.itemAt(
            self.game.players.index(
                self.game.current_player)).widget().set_inactive()
        self.game.next_player()
        self.playerinfolayout.itemAt(
            self.game.players.index(
                self.game.current_player)).widget().set_active()

        self.move_button.setDisabled(False)
        self.show_button.setDisabled(False)
        self.table_view.deselect_all()

        self.move_count += 1
        if self.move_count == 48:
            self.end_round()
            return

        self.update_log('\n----------\n{}\'s turn\n'.format(
            self.game.current_player))
        self.hand_view.update_scene(self.game.current_player.hand)
        self.hand_view.hide_cards()

        #if there is only one human player, his/her cards are shown automatically
        if type(self.game.current_player
                ) is not AIPlayer and self.game.one_human:
            self.hand_view.show_cards()
            self.alert_sound.play()

        if type(self.game.current_player) is AIPlayer:
            self.move_button.setDisabled(True)
            self.show_button.setDisabled(True)
            self.save_button.setDisabled(True)
            self.make_ai_move()
            return

        self.save_button.setDisabled(False)

    def end_round(self):
        self.save_button.setDisabled(True)
        self.playerinfolayout.itemAt(
            self.game.players.index(
                self.game.current_player)).widget().set_inactive()
        self.end_sound.play()
        game_ended = self.game.end_round()
        for i in range(self.playerinfolayout.count()):
            self.playerinfolayout.itemAt(i).widget().update_info()
            self.playerinfolayout.itemAt(i).widget().update_score()

        self.table_view.update_scene(self.game.table)

        self.btnlayout.removeWidget(self.show_button)
        self.btnlayout.removeWidget(self.move_button)
        self.btnlayout.insertWidget(0, self.next_button)
        self.next_button.show()
        self.show_button.hide()
        self.move_button.hide()
        if game_ended:
            self.next_button.setDisabled(True)

    def goto_next_round(self):
        self.save_button.setDisabled(False)
        self.btnlayout.removeWidget(self.next_button)
        self.btnlayout.insertWidget(0, self.start_button)
        self.start_button.show()
        self.next_button.hide()

        #rotate playerinfo
        mov = self.playerinfolayout.itemAt(0).widget()
        self.playerinfolayout.removeWidget(mov)
        self.playerinfolayout.addWidget(mov)

        self.game.new_round()
        self.shuffle_sound.play()

        for i in range(self.playerinfolayout.count()):
            self.playerinfolayout.itemAt(i).widget().update_info()

        self.game.new_round()
        self.game.initial_deal()

        self.move_count = 0

    def setup_sound(self):
        self.shuffle_sound = QSoundEffect()
        self.shuffle_sound.setSource(QUrl.fromLocalFile('sound/shuffle.wav'))

        self.error_sound = QSoundEffect()
        self.error_sound.setSource(QUrl.fromLocalFile('sound/error.wav'))

        self.move_sound = QSoundEffect()
        self.move_sound.setSource(QUrl.fromLocalFile('sound/draw.wav'))

        self.card_sound = QSoundEffect()
        self.card_sound.setSource(QUrl.fromLocalFile('sound/playcard.wav'))

        self.sweep_sound = QSoundEffect()
        self.sweep_sound.setSource(QUrl.fromLocalFile('sound/sweep.wav'))

        self.alert_sound = QSoundEffect()
        self.alert_sound.setSource(QUrl.fromLocalFile('sound/alert.wav'))

        self.end_sound = QSoundEffect()
        self.end_sound.setSource(QUrl.fromLocalFile('sound/endturn.wav'))

    def reset(self):
        self.game = None

    def update_log(self, msg):
        self.log.insertPlainText(msg)
        self.log.ensureCursorVisible()  #auto-scrolls to bottom of log

    def export_log(self):
        return self.log.toPlainText()
Ejemplo n.º 19
0
        cursor_shape_dict[key] = os.path.join(shape_dir, _file)

    for _file in os.listdir(color_pen_dir):
        key = CURSOR_SHAPE_COLOR_PEN_PREFIX + file_name_except_extension(_file)
        cursor_shape_dict[key] = os.path.join(color_pen_dir, _file)

CURSOR_SHAPE_SHAPE_PREFIX = "shape_"
CURSOR_SHAPE_COLOR_PEN_PREFIX = "color_pen_"
SAVE_DEST_TEMP = os.path.join(tempfile.gettempdir() or "/tmp",
                              "DeepinScreenshot-save-tmp.png")
ACTION_ID_OPEN = "id_open"
cursor_shape_dict = {}
init_cursor_shape_dict()

soundEffect = QSoundEffect()
soundEffect.setSource(QUrl(SOUND_FILE))
settings = ScreenShotSettings()

view = None
_notificationId = None
_fileSaveLocation = None

class Window(QQuickView):
    def __init__(self, settings, windowInfo):
        QQuickView.__init__(self)
        self._settings = settings

        surface_format = QSurfaceFormat()
        surface_format.setAlphaBufferSize(8)

        self.set_cursor_shape("shape_start_cursor")
Ejemplo n.º 20
0
class Window(QWidget):
    def __init__(self):
        super().__init__()
        
        self.title = 'CSC 690 - Project 1'
        self.model = Model('./data/')
        self.view_mode = 'thumbnails'
        self.mode = 'thumbnails'
        self.stylesheet = ''
        self.selected_thumbnail_stylesheet = 'border: 5px solid red;'
        
        self.window_width = 800
        self.window_height = 600

        if len(sys.argv) > 1:
        	self.window_width = int(sys.argv[1])
        	self.window_height = self.window_width * (3/4)

        self.thumbnail_labels = []
        self.thumbnail_pixmaps = []
        self.tag_labels = []

        self.window_width = 800
        self.window_height = 600

        if len(sys.argv) > 1:
        	if int(sys.argv[1]) >= 600 and int(sys.argv[1]) <= 1200:
        		self.window_width = int(sys.argv[1])
        		self.window_height = self.window_width * (3/4)
        	else:
        		print("Given width out of range. Defaulting to 600.")
        
        self.init_labels()
        self.init_controls()
        if len(self.model.nodes) > 0:
            self.init_UI()
        self.init_sounds()


    def init_UI(self):
        self.fullscreen_pixmap = QPixmap(self.model.get_current_filename())

        self.setWindowTitle(self.title)
        self.setGeometry(100, 100, self.window_width, self.window_height)
        self.setStyleSheet('background: #00C0FF;')

        self.load_thumbnails()

        # start with first thumbnail selected
        self.thumbnail_labels[0].setStyleSheet(self.selected_thumbnail_stylesheet)

        self.fullscreen_label.hide()
        for label in self.tag_labels:
            label.hide()
        self.show()


    def init_labels(self):
        self.fullscreen_label = QLabel(self)

        self.fullscreen_label.resize(self.window_width / 2, self.window_height / 2)
        self.fullscreen_label.setStyleSheet(self.selected_thumbnail_stylesheet)
        self.fullscreen_label.setAlignment(Qt.AlignCenter)
        self.fullscreen_label.setFocusPolicy(Qt.StrongFocus)
        self.fullscreen_label.move((self.window_width - (self.window_width / 2)) / 2, (self.window_height - (self.window_height/ 2)) /2)


        for index in range(0, CONST_NUM_TAGS):
            temp_label = QLabel(self)
            temp_label.move(650, 400 - (index * 30))
        
            self.tag_labels.append(temp_label)
        
            temp_label.hide()


    def init_controls(self):
        self.add_tag_button = QPushButton('Add tag', self)
        self.add_tag_button.setFocusPolicy(Qt.ClickFocus)
        self.add_tag_button.move((self.window_width / 2) - 180, self.window_height - 50)
        self.add_tag_button.clicked.connect(self.add_tag)

        self.add_tag_button.hide()

        self.search_button = QPushButton('Search', self)
        self.search_button.setFocusPolicy(Qt.ClickFocus)
        self.search_button.move(self.window_width / 3.7, self.window_height - (self.window_height / 10))
        self.search_button.clicked.connect(self.search_flickr)

        self.save_tags_button = QPushButton('Save all tags', self)
        self.save_tags_button.setFocusPolicy(Qt.ClickFocus)
        self.save_tags_button.move((self.window_width / 2) - 10, self.window_height - 50)
        self.save_tags_button.clicked.connect(self.save_tags)

        self.save_tags_button.hide()

        self.tag_field = QLineEdit(self)
        self.tag_field.setFocusPolicy(Qt.ClickFocus)
        self.tag_field.setAlignment(Qt.AlignCenter)
        self.tag_field.move((self.window_width / 2) - 90, self.window_height - 100)

        self.tag_field.hide()

        self.search_text_field = QLineEdit(self)
        self.search_text_field.setFocusPolicy(Qt.ClickFocus)
        self.search_text_field.move(self.window_width / 28, self.window_height - (self.window_height / 10))

        self.search_number_field = QLineEdit(self)
        self.search_number_field.setFocusPolicy(Qt.ClickFocus)
        self.search_number_field.move(self.window_width / 2.5, self.window_height - (self.window_height / 10))
        self.search_number_field.setFixedWidth(60)

        self.test_button = QPushButton('Test', self)
        self.test_button.setFocusPolicy(Qt.ClickFocus)
        self.test_button.move(self.window_width / 28, self.window_height - (self.window_height / 19))
        self.test_button.clicked.connect(self.test)

        self.save_photos_button = QPushButton('Save', self)
        self.save_photos_button.setFocusPolicy(Qt.ClickFocus)
        self.save_photos_button.move(self.window_width / 7.3, self.window_height - (self.window_height / 19))
        self.save_photos_button.clicked.connect(self.save_photos)

        self.exit_button = QPushButton('Exit', self)
        self.exit_button.setFocusPolicy(Qt.ClickFocus)
        self.exit_button.move(self.window_width / 4.2, self.window_height - (self.window_height / 19))
        self.exit_button.clicked.connect(self.close)

        self.delete_button = QPushButton('Delete', self)
        self.delete_button.setFocusPolicy(Qt.ClickFocus)
        self.delete_button.move(self.window_width / 2.95, self.window_height - (self.window_height / 19))
        self.delete_button.clicked.connect(self.delete)


    def init_sounds(self):
        self.train_sound = QSoundEffect()
        self.train_sound.setSource(QUrl.fromLocalFile('./audio/TRAIN06.WAV'))
        self.train_sound.setVolume(0.5)

        self.conk_sound = QSoundEffect()
        self.conk_sound.setSource(QUrl.fromLocalFile('./audio/CONK.WAV'))
        self.conk_sound.setVolume(0.5)
    

    def delete(self):
        self.model.delete()
        self.reload_thumbnails('forward')

        self.delete_button.clearFocus()


    def add_tag(self):
        self.model.add_tag(self.tag_field.text())
        self.tag_field.setText('')
        self.add_tag_button.clearFocus()
        self.show_tags()


    def hide_thumbnail_controls(self):
        self.search_text_field.hide()
        self.search_number_field.hide()


    def keyPressEvent(self, event):
        key_pressed = event.key()

        if key_pressed == Qt.Key_Right:
            
            if self.mode == 'thumbnails':
                self.next_image()

            elif self.mode == 'fullscreen':
                self.next_image()
                self.show_fullscreen_image()
                self.show_tags()
        
        elif key_pressed == Qt.Key_Left:
            
            if self.mode == 'thumbnails':
                self.prev_image()
          
            elif self.mode == 'fullscreen':
                self.prev_image()
                self.show_fullscreen_image()
                self.show_tags()
        
        elif key_pressed == Qt.Key_Up: 
            
            if self.mode == 'thumbnails':
                self.mode = 'fullscreen'

                #self.conk_sound.play()

                self.show_fullscreen_image()
                self.show_fullscreen_view()

        
        elif key_pressed == Qt.Key_Down:

            if self.mode == 'fullscreen':
                self.mode = 'thumbnails'

                #self.conk_sound.play()

                self.fullscreen_label.hide()
                self.show_thumbnails_view()
        
        elif key_pressed == 46:
            if self.mode == 'thumbnails':

                self.train_sound.play()

                for _ in range(0, CONST_THUMBNAIL_COUNT):
                    self.next_image()

                self.thumbnail_labels[self.model.get_current_index() % 5].setStyleSheet('')
                self.model.set_current_index(self.model.get_leftmost_index())
                self.thumbnail_labels[self.model.get_current_index() % 5].setStyleSheet(self.selected_thumbnail_stylesheet)

        elif key_pressed == 44:
            if self.mode == 'thumbnails':

                self.train_sound.play()

                for _ in range(0, CONST_THUMBNAIL_COUNT):
                    self.prev_image()

                self.thumbnail_labels[self.model.get_current_index() % 5].setStyleSheet('')
                self.model.set_current_index(self.model.get_leftmost_index())
                self.thumbnail_labels[self.model.get_current_index() % 5].setStyleSheet(self.selected_thumbnail_stylesheet)


    def load_thumbnails(self):
        # load images into pixmap array
        # for _ in self.model.image_files:
        #     self.thumbnail_pixmaps.append(QPixmap(self.model.get_current_filename()).scaled(CONST_THUMBNAIL_SIZE, CONST_THUMBNAIL_SIZE, Qt.KeepAspectRatio))
        #     self.model.next_filename()

        # create labels
        for index in range(0, CONST_THUMBNAIL_COUNT):
            # init thumbnail labels with corresponding pixmap
            self.thumbnail_labels.append(QLabel(self))
            if(index < len(self.model.nodes)):
                self.thumbnail_labels[index].setPixmap(self.model.nodes[index].get_image().scaled(CONST_THUMBNAIL_SIZE, CONST_THUMBNAIL_SIZE, Qt.KeepAspectRatio))

            # positioning labels
            self.thumbnail_labels[index].resize(CONST_THUMBNAIL_SIZE, CONST_THUMBNAIL_SIZE)
            self.thumbnail_labels[index].setAlignment(Qt.AlignCenter)
            # TODO: remove magic numbers below

            self.thumbnail_labels[index].move(self.window_width / (self.window_width / 30) + (index * self.window_width / 5), (self.window_height - CONST_THUMBNAIL_SIZE) / 2)
            #self.thumbnail_labels[index].move((self.window_width / (self.window_width / 10)) + index * self.window_width / 5, (self.window_height - CONST_THUMBNAIL_SIZE) / 2)


    def next_image(self):
        # remove red highlight from current selection
        self.thumbnail_labels[self.model.get_current_index() % 5].setStyleSheet('')

        self.model.select_next_node()

        self.reload_thumbnails('forward')


    def prev_image(self):       
        # remove red highlight from current 
        self.thumbnail_labels[self.model.get_current_index() % 5].setStyleSheet('')

        self.model.select_prev_node()

        self.reload_thumbnails('backward')


    def reload_thumbnails(self, direction):
        if (self.model.get_current_index() % 5 == 0):
            self.model.set_leftmost_index(self.model.get_current_index())
        
        elif (self.model.get_current_index() == self.model.get_leftmost_index() - 1):
            self.model.set_leftmost_index(self.model.get_leftmost_index() - 5)

        if direction == 'forward':
            temp_index = self.model.get_leftmost_index()

            for label in self.thumbnail_labels:
                temp_index = self.model.check_index_bounds(temp_index, direction)

                label.setPixmap(self.model.nodes[temp_index].get_image().scaled(CONST_THUMBNAIL_SIZE, CONST_THUMBNAIL_SIZE, Qt.KeepAspectRatio))
            
                temp_index += 1

            self.thumbnail_labels[self.model.get_current_index() % 5].setStyleSheet(self.selected_thumbnail_stylesheet)

        
        elif direction == 'backward':
            temp_index = self.model.get_leftmost_index() + 4
        
            for label in reversed(self.thumbnail_labels):
                temp_index = self.model.check_index_bounds(temp_index, direction)

                label.setPixmap(self.model.nodes[temp_index].get_image().scaled(CONST_THUMBNAIL_SIZE, CONST_THUMBNAIL_SIZE, Qt.KeepAspectRatio))
     
                temp_index -= 1

            if (self.model.get_current_index() == len(self.model.nodes) - 1):
                self.thumbnail_labels[4].setStyleSheet(self.selected_thumbnail_stylesheet)
            else:
                self.thumbnail_labels[self.model.get_current_index() % 5].setStyleSheet(self.selected_thumbnail_stylesheet)



    def save_photos(self):
        self.model.save_nodes()

        self.save_photos_button.clearFocus()


    def save_tags(self):
        self.model.save_tags('tags.txt')
        self.save_tags_button.clearFocus()


    def search_flickr(self):
        search_string = ''.join('%20' if char == ' ' else char for char in self.search_text_field.text())
        self.model.search_flickr(search_string, self.search_number_field.text())
        
        self.reload_thumbnails('forward')

        self.search_text_field.setText('')
        self.search_button.clearFocus()


    def show_fullscreen_image(self):
        self.fullscreen_pixmap = self.model.nodes[self.model.get_current_index()].get_image()       
        self.fullscreen_pixmap = self.fullscreen_pixmap.scaled(self.window_width / 2, self.window_height / 2, Qt.KeepAspectRatio)
        
        self.fullscreen_label.setPixmap(self.fullscreen_pixmap)
        self.fullscreen_label.show()

        self.show_tags()


    def show_fullscreen_view(self):
        self.add_tag_button.show()
        self.save_tags_button.show()
        self.tag_field.show()
        self.show_tags()
            
        for label in self.thumbnail_labels:
            label.hide()

        self.search_button.hide()
        self.search_text_field.hide()
        self.search_number_field.hide()
        self.test_button.hide()
        self.save_photos_button.hide()
        self.exit_button.hide()
        self.delete_button.hide()        


    def show_tags(self):
        tags = self.model.get_tags()

        for label in self.tag_labels:
            label.setText('')

        for label, tag in zip(self.tag_labels, tags):
            label.hide()
            label.setText(str(tag))
            label.show()


    def show_thumbnail_controls(self):
    	self.search_text_field.show()
    	self.search_number_field.show()


    def show_thumbnails_view(self):
        for label in self.thumbnail_labels:
            label.show()

        self.add_tag_button.hide()
        self.save_tags_button.hide()
        self.tag_field.hide()
        for label in self.tag_labels:
            label.hide()

        self.search_button.show()
        self.search_text_field.show()
        self.search_number_field.show()
        self.search_button.show()
        self.search_text_field.show()
        self.search_number_field.show()
        self.test_button.show()
        self.save_photos_button.show()
        self.exit_button.show()
        self.delete_button.show()


    def test(self):
        self.test_button.clearFocus()
Ejemplo n.º 21
0
class MainWindow(QtWidgets.QWidget, main_window.Ui_mainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.setupUi(self)
        self.ICON = QIcon(str(ICON_PATH))
        self.setWindowIcon(self.ICON)

        # BUTTONS
        self.buttonStart.clicked.connect(self.on_clicked_start)
        self.buttonSettings.clicked.connect(self.on_clicked_settings)
        self.buttonStatistics.clicked.connect(self.on_clicked_statistics)
        self.buttonExit.clicked.connect(QtWidgets.QApplication.instance().quit)
        self.comboBoxSelectMode.currentIndexChanged.connect(
            self.on_change_mode)

        # HIGHSCORES HANDLER
        self.highscore = highscores.Highscores()
        self.update_highscores()

        # DATA AND SETTINGS
        if DATA_FILE.is_file():
            self.load_data_from_file()
        else:
            self.data = settings.DEFAULT_DATA

        self.comboBoxSelectMode.setCurrentIndex(
            self.data.get("selected_mode", 0))

        # SOUND
        self.set_key_sound(self.get_setting("sound_filename"))

        # FONT
        self.inconsolata_bold = self.load_custom_font(str(FONT_PATH))

        # Stylesheet is set in the main program after instantiation

    # Button methods
    def on_clicked_start(self) -> None:
        self.make_mode_window(str(self.comboBoxSelectMode.currentText()))

        self.show_window(self.mode_window, self.isMaximized())
        self.mode_window.setStyleSheet(self.get_setting("stylesheet"))
        self.mode_window.set_colours(self.get_setting("rich_text_colours"))

        self.hide()

    def on_clicked_main_menu(self, window: QtWidgets.QWidget) -> None:
        self.update_highscores()

        self.show_window(self, window.isMaximized())

        window.close()
        del window

    def on_clicked_settings(self) -> None:
        self.make_settings_window()

        self.show_window(self.settings_window, self.isMaximized())
        self.settings_window.setStyleSheet(self.get_setting("stylesheet"))

        self.hide()

    def on_clicked_apply(self) -> None:
        """Executed when apply button in settings window is clicked."""

        self.data["settings"] = self.settings_window.get_settings()

        # Key sound
        self.set_key_sound(self.get_setting("sound_filename"))

        # Stylesheet
        self.settings_window.setStyleSheet(self.get_setting("stylesheet"))
        self.setStyleSheet(self.get_setting("stylesheet"))

        # Save
        self.save_data_to_file()

    def on_clicked_statistics(self) -> None:
        self.make_stats_window()

        self.show_window(self.stats_window, self.isMaximized())
        self.stats_window.setStyleSheet(self.get_setting("stylesheet"))

        self.hide()

    def on_clicked_reset_daily(self) -> None:
        """
        To be executed when 'Reset today's highscore' is pressed in the stats window.
        """

        self.highscore.delete_daily_highscore()

        self.update_highscores()
        self.update_stats_highscores()

    def on_clicked_reset_all_time(self) -> None:
        """
        To be executed when 'Reset all-time highscore' is pressed in the stats window.
        """

        self.highscore.delete_all_time_highscore()

        self.update_highscores()
        self.update_stats_highscores()

    def on_clicked_reset_all(self) -> None:
        """
        To be executed when 'Reset all highscores' is pressed in the stats window.
        """

        self.highscore.delete_all_highscores()

        self.update_highscores()
        self.update_stats_highscores()

    def on_change_mode(self):
        """
        Saves the selected mode to self.data and pickles self.data so the selection is
        remembered.
        """

        self.data["selected_mode"] = self.comboBoxSelectMode.currentIndex()
        self.save_data_to_file()

    # Helper Methods
    def get_setting(self, setting: str):
        """
        Convenience method for getting a specific setting from self.data, or a
        default value.
        """

        return self.data["settings"].get(
            setting, settings.DEFAULT_SETTINGS.get(setting))

    def load_custom_font(self, font: str) -> int:
        """Adds custom font to QFontDatabase, and returns its corresponding font id."""

        return QFontDatabase.addApplicationFont(font)

    def show_window(self, window: QtWidgets.QWidget, fullscreen: bool) -> None:
        """
        Used to show windows, with the option to have them maximised provided.
        """

        window.show()
        if fullscreen:
            window.setWindowState(QtCore.Qt.WindowMaximized)

    def make_mode_window(self, mode: str) -> None:
        self.mode_window = type_test.TypingWindow(self.highscore)
        self.mode_window.set_mode(mode)

        self.mode_window.setWindowIcon(self.ICON)

        self.mode_window.buttonMainMenu.clicked.connect(
            lambda: self.on_clicked_main_menu(self.mode_window))

        # Sets key sound if enabled
        if self.get_setting("play_sound"):
            self.mode_window.set_key_sound(self.key_sound)

    def make_settings_window(self) -> None:
        self.settings_window = settings.SettingsWindow()

        self.settings_window.setWindowIcon(self.ICON)

        self.settings_window.buttonMainMenu.clicked.connect(
            lambda: self.on_clicked_main_menu(self.settings_window))
        self.settings_window.buttonApply.clicked.connect(self.on_clicked_apply)

        # Keystroke sound toggle
        if self.get_setting("play_sound"):
            self.settings_window.toggleKeystrokeSound.setChecked(True)

        # Dark mode toggle
        if self.get_setting("dark_mode"):
            self.settings_window.toggleDarkMode.setChecked(True)

        self.set_settings_sounds_options()
        self.set_selected_sound_option(self.get_setting("sound_filename"))

    def make_stats_window(self) -> None:
        self.stats_window = statistics.StatsWindow()

        self.stats_window.setWindowIcon(self.ICON)

        # Update labels
        self.update_stats_highscores()
        self.update_stats_days_ago()

        # Set up graph
        self.stats_window.set_up_graph(self.highscore.get_stats_dailies(),
                                       self.get_setting("graph_colours"))

        # Connect buttons
        self.stats_window.buttonMainMenu.clicked.connect(
            lambda: self.on_clicked_main_menu(self.stats_window))
        self.stats_window.buttonResetDaily.clicked.connect(
            self.on_clicked_reset_daily)
        self.stats_window.buttonResetAllTime.clicked.connect(
            self.on_clicked_reset_all_time)
        self.stats_window.buttonResetAll.clicked.connect(
            self.on_clicked_reset_all)

    def update_highscores(self) -> None:
        self.today_wpm, self.all_time_wpm = self.highscore.get_wpm()

    def save_data_to_file(self) -> None:
        """Pickles self.data into a file in the data folder."""

        with open(DATA_FILE, "wb") as data_pickle:
            pickle.dump(self.data, data_pickle)

    def load_data_from_file(self) -> None:
        """Sets self.data to the values saved on the data.pkl file."""

        with open(DATA_FILE, "rb") as data_pickle:
            self.data = pickle.load(data_pickle)

    def get_sounds_list(self) -> list:
        """Returns a list of the sound files present in the sounds folder."""

        return os.listdir(SOUND_FOLDER)

    def set_settings_sounds_options(self) -> None:
        """
        Sets up options for the dropdown menu to select keystroke sounds in the
        settings menu.
        """

        for sound_file in self.get_sounds_list():
            # Add sound file name to dropdown menu
            self.settings_window.comboSelectSound.addItem(sound_file)

    def find_sound_file_index(self, sound_file: str) -> int:
        """
        Returns the index of the given file name within the settings window
        comboSelectSound object.
        """

        return self.settings_window.comboSelectSound.findText(
            sound_file, QtCore.Qt.MatchFixedString)

    def set_selected_sound_option(self, sound_file: str) -> None:
        """
        Sets the selected option for sound file from the settings window's
        comboSelectSound object to the given sound file name.
        """

        index: int = self.find_sound_file_index(sound_file)

        if index >= 0:
            self.settings_window.comboSelectSound.setCurrentIndex(index)

    def set_key_sound(self, sound_file: str) -> None:
        """
        Sets the given sound file to a QSoundEffect object which will be played on each
        keystroke in the mode window.
        """

        self.key_sound_path = os.path.join(SOUND_FOLDER, sound_file)
        self.key_sound_url = QtCore.QUrl.fromLocalFile(self.key_sound_path)

        self.key_sound = QSoundEffect()
        self.key_sound.setSource(self.key_sound_url)
        self.key_sound.setVolume(0.5)
        self.key_sound.setLoopCount(1)

    def update_stats_highscores(self) -> None:
        """Updates highscores displayed in the stats window."""

        self.stats_window.labelTodayScore.setText(f"{self.today_wpm} WPM")
        self.stats_window.labelAllTimeScore.setText(f"{self.all_time_wpm} WPM")

    def update_stats_days_ago(self) -> None:
        """
        Updates the labelDaysAgo element in the stats window with the
        number of days since the all-time highscore was set.
        """

        self.stats_window.update_days_ago(self.highscore.days_since_set())
Ejemplo n.º 22
0
class MainWindow(QWidget):
    processData = pyqtSignal(list, list, int, tuple)

    def __init__(self):
        super(self.__class__, self).__init__(None)

        self.reader = SerialPortReader()
        self.experimentData = ExperimentData(self)
        self.receivingStarted = False
        self.recordingStarted = False
        self.recordingTime = 0

        self.initGUI()

        sys.stdout = OutLog(self.console, sys.stdout)
        sys.stderr = OutLog(self.console, sys.stderr, QColor(255, 0, 0))

        self.initSound()

        self.createWorkerThread()

        self.reader.timeUpdate.connect(self.onTimeUpdate)
        self.reader.dataReady.connect(self.onDataReady)
        self.reader.locatorPacket.connect(self.onLocatorPacket)
        self.loadSettings()

        #self.writer = SerialPortWriter()

    @QtCore.pyqtSlot(list, list, list)
    def onDataReady(self, a_ch0, a_ch1, T_meas):
        if self.recordingStarted:
            if self.experimentLength < 5:
                self.experimentData.appendData(a_ch0, a_ch1, T_meas)
            else:
                self.experimentData.appentDataToTxt(a_ch0, a_ch1, T_meas,
                                                    self.txtFileName)
        self.processData.emit(a_ch0, a_ch1, self.intervalLength,
                              self.settingsWidget.getValues())

    @QtCore.pyqtSlot(float, float)
    def onLocatorPacket(self, val1, val2):
        self.locatorPlotWidget.appendPoint(0, val1)
        self.locatorPlotWidget.appendPoint(1, val2)

    @QtCore.pyqtSlot(int)
    def onTimeUpdate(self, time):
        if not self.recordingStarted:
            return

        self.recordingTime += time
        remainingTime = self.experimentLength * 60 * 1000 - self.recordingTime
        qtTime = QTime.fromMSecsSinceStartOfDay(remainingTime)
        self.timeLabel.setText(qtTime.toString())

        if remainingTime == 0:
            if self.soundCheckBox.isChecked():
                self.sound.play()
            self.startStopButton.toggle()

    def createWorkerThread(self):
        self.rascanWorker = RascanWorker()
        self.workerThread = QThread()
        self.rascanWorker.moveToThread(self.workerThread)
        self.workerThread.start()

        self.processData.connect(self.rascanWorker.doWork)
        self.rascanWorker.dataProcessed.connect(self.onRascanDataProcessed)

    def initSound(self):
        self.sound = QSoundEffect()
        base_url = QUrl.fromLocalFile(QDir(".").canonicalPath() + "/")
        file_path = base_url.resolved(QUrl("bzzz.wav"))

        self.sound.setSource(file_path)
        self.sound.setVolume(1)

    def initGUI(self):
        self.setWindowTitle('БиоРАСКАН-24')
        self.setWindowIcon(QIcon('Рисунок1.png'))

        self.settingsWidget = SettingsWidget(self)

        mainLayout = QGridLayout()
        self.setLayout(mainLayout)

        leftLayout = QVBoxLayout()
        leftLayout.setSpacing(20)
        mainLayout.addLayout(leftLayout, 1, 1, Qt.AlignCenter)

        tabWidget = QTabWidget()

        mainLayout.addWidget(tabWidget, 1, 3, Qt.AlignCenter)

        mainLayout.setRowStretch(0, 2)  # empty space above ui
        mainLayout.setRowStretch(1, 1)  # ui
        mainLayout.setRowStretch(2, 2)  # console
        mainLayout.setRowStretch(3, 2)  # empty space below ui
        mainLayout.setColumnStretch(0, 2)  # empty space to the right from ui
        mainLayout.setColumnStretch(
            2, 1)  # empty space between left layout and right layout
        mainLayout.setColumnStretch(4, 2)  # empty space to the left from ui

        # console output
        self.console = ConsoleWidget(self)
        self.console.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.console.setReadOnly(True)
        mainLayout.addWidget(self.console, 2, 1, 1, 3)

        # settings layout
        settingsLayout = QGridLayout()
        leftLayout.addLayout(settingsLayout)

        lengthSettingsText = QLabel('Длительность эксперимента')
        self.lengthSettingsEdit = QLineEdit('1')
        self.lengthSettingsEdit.setValidator(MyIntValidator(1, 30))
        lmin = QLabel('мин')
        lmin.setObjectName("secondary")

        settingsLayout.addWidget(lengthSettingsText, 0, 0)
        settingsLayout.addWidget(self.lengthSettingsEdit, 0, 2)
        settingsLayout.addWidget(lmin, 0, 3)

        settingsLayout.setColumnMinimumWidth(
            1, 30)  # middle column to add some sapace

        intervalLayoutText = QLabel('Интервал расчета')
        self.intervalLayoutEdit = QLineEdit('10')
        self.intervalLayoutEdit.setValidator(MyIntValidator(10, 300))
        imin = QLabel('сек')
        imin.setObjectName("secondary")
        settingsLayout.addWidget(intervalLayoutText, 1, 0)
        settingsLayout.addWidget(self.intervalLayoutEdit, 1, 2)
        settingsLayout.addWidget(imin, 1, 3)

        self.comBox = QComboBox(self)
        COMLayoutText = QLabel('Выбор COM-порта')
        COM_list = serial_ports()
        self.comBox.addItems(COM_list)
        settingsLayout.addWidget(COMLayoutText, 2, 0)
        settingsLayout.addWidget(self.comBox, 2, 2)

        # back to main layout

        settingsLayout.setRowMinimumHeight(3, 20)  # add some space vertically

        self.soundCheckBox = QCheckBox('Звуковое оповещение')
        settingsLayout.addWidget(self.soundCheckBox, 4, 0)

        self.settingsButton = QPushButton('ДОПОЛНИТЕЛЬНО')
        self.settingsButton.setObjectName('secondary')
        settingsLayout.addWidget(self.settingsButton, 4, 2, 1, 2, Qt.AlignLeft)
        self.settingsButton.clicked.connect(lambda: self.settingsWidget.open())

        self.timeLabel = QLabel('00:00:00')
        self.timeLabel.setObjectName('timeLabel')
        leftLayout.addWidget(self.timeLabel)
        leftLayout.setAlignment(self.timeLabel, Qt.AlignHCenter)

        infoLayout = QHBoxLayout()
        infoLayout.setSpacing(20)
        leftLayout.addLayout(infoLayout)
        infoLayout.addStretch()

        chss = QLabel('ЧСС')
        chss.setObjectName('leftBar')
        infoLayout.addWidget(chss)

        self.heartRateText = QLabel('0')
        self.heartRateText.setObjectName('primary')
        self.heartRateText.setAlignment(Qt.AlignRight)
        infoLayout.addWidget(self.heartRateText)

        udm = QLabel('уд/мин')
        udm.setObjectName('secondary')
        infoLayout.addWidget(udm)

        infoLayout.addSpacing(40)

        chd = QLabel('ЧД')
        chd.setObjectName('leftBar')
        infoLayout.addWidget(chd)

        self.breathRateText = QLabel('0')
        self.breathRateText.setObjectName('primary')
        self.breathRateText.setAlignment(Qt.AlignRight)
        infoLayout.addWidget(self.breathRateText)

        vdm = QLabel('вдох/мин')
        vdm.setObjectName('secondary')
        infoLayout.addWidget(vdm)

        infoLayout.addStretch()

        buttonLayout = QHBoxLayout()
        leftLayout.addLayout(buttonLayout)
        self.startStopButton = QPushButton('ЗАПУСК')
        self.startStopButton.setCheckable(True)
        self.saveButton = QPushButton('ЗАПИСЬ')
        self.saveButton.setCheckable(True)
        buttonLayout.addWidget(self.startStopButton)
        buttonLayout.addSpacing(20)
        buttonLayout.addWidget(self.saveButton)

        self.saveButton.toggled.connect(self.onSaveButtonClicked)
        self.startStopButton.toggled.connect(self.onButtonClick)

        # firs tab
        tabOneWidget = QWidget()
        tabOneLayout = QVBoxLayout()
        tabOneWidget.setLayout(tabOneLayout)
        tabWidget.addTab(tabOneWidget, "Сигнал локатора")

        self.locatorPlotWidget = PlotWidget(300, 20, 2)
        tabOneLayout.addWidget(self.locatorPlotWidget)

        tabOneButtonsLayout = QGridLayout()
        tabOneLayout.addLayout(tabOneButtonsLayout)
        locatorLeftCheckBox = QCheckBox('1-ая квадратура')
        tabOneButtonsLayout.addWidget(locatorLeftCheckBox, 0, 3)
        locatorRightCheckBox = QCheckBox('2-ая квадратура')
        tabOneButtonsLayout.addWidget(locatorRightCheckBox, 1, 3)
        locatorLeftCheckBox.setChecked(True)
        locatorRightCheckBox.setChecked(True)
        locatorLeftCheckBox.stateChanged.connect(
            lambda state: self.locatorPlotWidget.hideCurve(
                0, False if state == 1 or state == 2 else True))
        locatorRightCheckBox.stateChanged.connect(
            lambda state: self.locatorPlotWidget.hideCurve(
                1, False if state == 1 or state == 2 else True))

        # second tab
        tabTwoWidget = QWidget()
        tabTwoLayout = QVBoxLayout()
        tabTwoLayout.setContentsMargins(0, 0, 0, 0)
        tabTwoWidget.setLayout(tabTwoLayout)
        tabWidget.addTab(tabTwoWidget, "ЧСС/ЧД")

        self.heartRatePlotWidget = PlotWidget(30, 10000, 1)

        self.breathRatePlotWidget = PlotWidget(30, 10000, 1)
        tabTwoLayout.addWidget(self.heartRatePlotWidget)
        tabTwoLayout.addWidget(self.breathRatePlotWidget)

        # third tab
        tabThreeWidget = QWidget()
        tabThreeLayout = QVBoxLayout()
        tabThreeWidget.setLayout(tabThreeLayout)
        tabWidget.addTab(tabThreeWidget, "Отфильтрованный сигнал")

        self.heartFilteredPlotWidget = PlotWidget(300, 100, 2)
        self.breathFilteredPlotWidget = PlotWidget(300, 100, 2)
        tabThreeLayout.addWidget(self.heartFilteredPlotWidget)
        tabThreeLayout.addWidget(self.breathFilteredPlotWidget)

    @QtCore.pyqtSlot(bool)
    def onButtonClick(self, toggled):
        if toggled:
            #self.writer.startSend()
            portName = self.comBox.currentText()
            if portName == '':
                print("Устройство не подключено")
                self.uncheck(self.startStopButton)
                return

            print("Подождите, программа запускается...")

            self.intervalLength = int(self.intervalLayoutEdit.text())

            try:
                self.reader.startListen(self.intervalLength, portName)
            except IOError:
                print("Не удается открыть указанный COM порт")
                self.uncheck(self.startStopButton)
                return

            self.locatorPlotWidget.reset()
            self.startStopButton.setText('СТОП')
            self.receivingStarted = True
        else:
            #self.writer.stopSend()
            self.startStopButton.setText('ЗАПУСК')
            self.reader.stopListen()
            self.saveButton.setChecked(False)
            self.receivingStarted = False

    def uncheck(self, button):
        button.blockSignals(True)
        button.setChecked(False)
        button.blockSignals(False)

    @QtCore.pyqtSlot(bool)
    def onSaveButtonClicked(self, toggled):
        if toggled:
            if not self.receivingStarted:
                print("Прием не начат")
                self.uncheck(self.saveButton)
                return

            self.intervalLength = int(self.intervalLayoutEdit.text())
            self.experimentLength = int(self.lengthSettingsEdit.text())
            if self.experimentLength < self.intervalLength / 60:
                print("Интервал расчета больше длительности эксперимента")
                self.uncheck(self.saveButton)
                return

            if self.experimentLength >= 5:
                txtFileName, ok = QInputDialog.getText(
                    self, 'Ввод имени файла',
                    'Длительность эксперимента более 5 минут\n\n'
                    'Будет произведено сохранение в текстовый файл\n\n'
                    'Введите имя .txt файла без расширения')
                if ok:
                    self.txtFileName = str(txtFileName)
                    try:
                        open(txtFileName + '.txt', 'w').close()
                    except OSError:
                        print("Неправильное имя файла")
                        self.uncheck(self.saveButton)
                        return
                else:
                    self.uncheck(self.saveButton)
                    return

            self.recordingTime = 0
            self.experimentData.reset()
            self.saveButton.setText('СОХРАНИТЬ')

            self.recordingStarted = True

            self.heartRatePlotWidget.reset()
            self.breathRatePlotWidget.reset()
            self.breathFilteredPlotWidget.reset()
            self.heartFilteredPlotWidget.reset()
            self.heartRatePlotWidget.setDelta(self.intervalLength * 1000)
            self.breathRatePlotWidget.setDelta(self.intervalLength * 1000)
            self.heartRatePlotWidget.appendPoint(0, 0)
            self.breathRatePlotWidget.appendPoint(0, 0)

            self.reader.startIntervalSending(self.intervalLength)
            print("Запись данных начата")
            qtTime = QTime.fromMSecsSinceStartOfDay(self.experimentLength *
                                                    60 * 1000)
            self.timeLabel.setText(qtTime.toString())
        else:
            self.recordingStarted = False
            print("Запись данных окончена")
            self.experimentData.saveToFile()
            self.saveButton.setText('ЗАПИСЬ')
            self.timeLabel.setText('00:00:00')

    @QtCore.pyqtSlot(float, float, np.ndarray, np.ndarray, np.ndarray,
                     np.ndarray, np.ndarray, np.ndarray, np.ndarray,
                     np.ndarray)
    def onRascanDataProcessed(self, chss, chd, sig_hf1, sig_hf2, peaks_hf1,
                              peaks_hf2, sig_bf1, sig_bf2, peaks_bf1,
                              peaks_bf2):
        self.heartRateText.setText(str(int(chss)))
        self.breathRateText.setText(str(int(chd)))
        self.heartRatePlotWidget.appendPoint(0, chss)
        self.breathRatePlotWidget.appendPoint(0, chd)
        self.heartFilteredPlotWidget.appendData(0, sig_hf1.tolist(),
                                                peaks_hf1.tolist())
        self.heartFilteredPlotWidget.appendData(1, sig_hf2.tolist(),
                                                peaks_hf2.tolist())
        self.breathFilteredPlotWidget.appendData(0, sig_bf1.tolist(),
                                                 peaks_bf1.tolist())
        self.breathFilteredPlotWidget.appendData(1, sig_bf2.tolist(),
                                                 peaks_bf2.tolist())

    def closeEvent(self, event):
        self.experimentData.saveIfNeeded()
        self.saveSettings()
        event.accept()

    def saveSettings(self):
        settings = QSettings("BioRascan-24.ini", QSettings.IniFormat)

        if (self.isMaximized() == False):
            settings.setValue("geometry", self.geometry())

        settings.setValue("maximized", self.isMaximized())
        settings.setValue("length", self.lengthSettingsEdit.text())
        settings.setValue("interval", self.intervalLayoutEdit.text())
        settings.setValue("sound", self.soundCheckBox.isChecked())
        settings.setValue("port", self.comBox.currentText())

        lhf, hhf, lbf, hbf = self.settingsWidget.getValues()
        settings.setValue("lhf", lhf)
        settings.setValue("hhf", hhf)
        settings.setValue("lbf", lbf)
        settings.setValue("hbf", hbf)

    def loadSettings(self):
        settings = QSettings("BioRascan-24.ini", QSettings.IniFormat)

        screenRect = QApplication.desktop().screenGeometry()
        defaultWindowRect = QRect(screenRect.width() / 8,
                                  screenRect.height() * 1.5 / 8,
                                  screenRect.width() * 6 / 8,
                                  screenRect.height() * 5 / 8)

        self.setGeometry(settings.value("geometry", defaultWindowRect))

        if (settings.value("maximized", False) == "true"):
            self.setWindowState(self.windowState() ^ Qt.WindowMaximized)

        self.lengthSettingsEdit.setText(settings.value("length", "1"))
        self.intervalLayoutEdit.setText(settings.value("interval", "10"))

        if (settings.value("sound", False) == "true"):
            self.soundCheckBox.setChecked(True)

        portName = settings.value("port", "")
        itemIndex = self.comBox.findText(portName)
        if (itemIndex != -1):
            self.comBox.setCurrentIndex(itemIndex)

        lhf = settings.value("lhf", 0.7)
        hhf = settings.value("hhf", 2.5)
        lbf = settings.value("lbf", 0.01)
        hbf = settings.value("hbf", 0.4)

        self.settingsWidget.setValues(float(lhf), float(hhf), float(lbf),
                                      float(hbf))
Ejemplo n.º 23
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)

        self.shootDesktopBn.clicked.connect(self.shootFullScreen)
        self.shootAreaBn.clicked.connect(self.rectangularSelection)
        self.shootWindowBn.clicked.connect(self.enableWindowSelectionMode)
        self.loginBn.clicked.connect(self.loginUser)
        self.preferencesBn.clicked.connect(self.openPreferences)

        self.selectorWindows = []
        self.highlightWindows = []
        self.uploadThreads = []
        self.lastUpload = ""
        self.currentGeometry = QRect()
        self.currentWId = -1

        self.doneSound = QSoundEffect()
        self.doneSound.setSource(QUrl.fromLocalFile("done.wav"))
        self.errorSound = QSoundEffect()
        self.errorSound.setSource(QUrl.fromLocalFile("error.wav"))

        icon = QIcon(":static/angry.svg")
        icon.setIsMask(True)

        self.trayIcon = QSystemTrayIcon(self)
        self.trayIcon.setIcon(icon)
        self.trayIcon.show()
        self.trayIcon.setContextMenu(self.createMenu())
        self.trayIcon.messageClicked.connect(self.openLastUpload)

        self.settings = QSettings(QSettings.IniFormat, QSettings.UserScope,
                                  "GliTch_ Is Mad Studios", "PostIt")

        self.readSettings()

    def openLastUpload(self):
        webbrowser.open_new_tab(self.lastUpload)

    def createMenu(self):
        menu = QMenu(self)

        menu.addAction("Desktop Screenshot", self.shootFullScreen)
        menu.addAction("Window Screenshot", self.enableWindowSelectionMode)
        menu.addAction("Select Area", self.rectangularSelection)
        menu.addSeparator()
        menu.addAction("Open Gallery ...", self.openGallery)
        menu.addSeparator()
        menu.addAction("Preferences...", self.openPreferences)
        menu.addAction("Show", self.show)
        menu.addAction("Quit", qApp.exit)

        return menu

    def openGallery(self):

        webbrowser.open_new_tab(
            self.settings.value("internet/address") + "/gallery")

    def openPreferences(self):
        prefDiag = PreferencesDialog(self.settings, self)
        prefDiag.exec_()

    def readSettings(self):

        if self.settings.contains("internet/authToken"):
            self.authToken = self.settings.value("internet/authToken")
        else:
            self.loginUser()

        if not self.settings.contains("internet/address"):
            self.settings.setValue("internet/address", "https://nsfw.run")

    def loginUser(self):

        diag = LoginDialog(self)
        if diag.exec_():
            self.settings.setValue("internet/authToken", diag.loginToken)

    def shootWindowId(self, WId):
        screen = self.windowHandle().screen()
        pixmap = screen.grabWindow(WId)

        self.uploadHandle(pixmap2bytesIO(pixmap))

    def enableWindowSelectionMode(self):

        if RUNNING_IN_STEVE_JOBS:
            fn = wrappers.captureWindow()
            if fn:
                self.uploadFile(fn)

    def mouseIsMoving(self, pos):

        if not self.windowSelectionMode:
            return

        pos = self.mapFromGlobal(self.mapToGlobal(pos))
        print("cursor is at X: {}, Y: {}".format(pos.x(), pos.y()))

        if self.currentWId == -1:

            self.rememberWindowAtPos(pos)
            ## TODO: draw box here

        elif self.currentWId > 0 and not self.currentGeometry.contains(pos):
            print("moved outside of previous window dimensions")
            self.rememberWindowAtPos(pos)

    def rememberWindowAtPos(self, pos):

        WId = getWindowUnderCursor(pos)
        if WId == 0:
            print("cursor is on the desktop, ignored")
            return

        if WId == self.currentWId:
            print(
                "EH?! grabbed the same window even though the cursor moved outside of it..."
            )

        self.currentWId = WId
        self.currentGeometry = QRect(*getWindowDimensions(WId))

        print("stored WId {} ({}) @ {}".format(WId, getWindowText(WId),
                                               self.currentGeometry))

    def rectangularSelection(self):

        if RUNNING_IN_STEVE_JOBS:
            fn = wrappers.captureSelection()
            if fn:
                self.uploadFile(fn)

        else:
            self.showSelectors(RectangularSelectionWindow)

    def shootFullScreen(self):

        shots = []

        w = 0
        h = 0

        for screen in QGuiApplication.screens():

            rect = screen.geometry()
            shot = screen.grabWindow(0, rect.x(), rect.y(), rect.width(),
                                     rect.height())

            w += shot.width()
            if h < shot.height(
            ):  # in case one screen is larger than the other
                h = shot.height()

            shots.append(shot)

        pixmap = QPixmap(w, h)
        painter = QPainter(pixmap)
        pixmap.fill(Qt.black)

        p = 0

        for ss in shots:
            painter.drawPixmap(QPoint(p, 0), ss)
            p += ss.width()

        painter.end()

        self.uploadHandle(pixmap2bytesIO(pixmap))

    def showSelectors(self, selectorClass):

        self.selectorWindows = []
        desktop = qApp.desktop()

        for i in range(desktop.screenCount()):
            selector = selectorClass()
            self.selectorWindows.append(selector)

            selector.setGeometry(desktop.screenGeometry(i))

            selector.selectionCanceled.connect(self.hideSelectors)
            selector.selectionMade.connect(self.selectionMade)

            selector.showFullScreen()
            selector.windowHandle().setScreen(qApp.screens()[i])

    def hideSelectors(self):

        for selector in self.selectorWindows:
            selector.hide()

    def selectionMade(self, screen, x, y, w, h):

        self.hideSelectors()

        pixmap = screen.grabWindow(0, x, y, w, h)

        strIO = pixmap2bytesIO(pixmap)
        self.uploadHandle(strIO)

    def uploadFile(self, path):
        """ used for uploading a file on the file-system """
        thread = UploadThread(
            self.settings.value("internet/address") + "/api/upload",
            self.settings.value("internet/authToken"), path, self)

        thread.resultReady.connect(self.uploadComplete)
        thread.start()
        self.uploadThreads.append(thread)

    def uploadHandle(self, handle):
        """ used for uploading a file-like object that has a .read() method """
        thread = UploadHandleThread(
            self.settings.value("internet/address") + "/api/upload",
            self.settings.value("internet/authToken"), handle, self)

        thread.resultReady.connect(self.uploadComplete)
        thread.start()
        self.uploadThreads.append(thread)

    def uploadComplete(self, uri, error):

        if uri and not error:

            self.doneSound.play()

            URL = self.settings.value("internet/address") + uri

            clipboard = QGuiApplication.clipboard()
            clipboard.setText(URL)
            self.lastUpload = URL
            self.trayIcon.showMessage(
                "Upload Complete",
                "Image upload complete. The URL is in your clipboard.")

            if self.settings.value("preferences/openInBrowser"):
                logging.debug("opening in browser")
                webbrowser.open_new_tab(URL)
        else:

            self.errorSound.play()
            try:
                raise error
            except requests.exceptions.HTTPError as http_error:
                if http_error.response.status_code == 401:
                    logging.info(
                        "received 401 during upload request. need to login again"
                    )
                    self.trayIcon.showMessage(
                        "Invalid Login",
                        "Uh oh, invaild login token. Please login again.")
                    self.loginUser()
                    self.trayIcon.showMessage("Retry",
                                              "Try your upload again.")
                    return

            QMessageBox.critical(self, "Upload Error", str(error))
            raise error

    def purgeAllThreads(self):
        for thread in self.uploadThreads:
            if thread.isRunning():
                thread.terminate()

    def closeEvent(self, event):
        if self.isVisible():
            QMessageBox.information(
                self, "Systray", "I'm running in the system tray. "
                "Use Quit from the tray menu to end me.")
            event.ignore()
            self.hide()
        else:
            event.accept()
Ejemplo n.º 24
0
class QAVButton(QPushButton):
    def __init__(self, label):
        """ builds a custom button and displays it"""
        # calls super constuctor
        super(QAVButton, self).__init__(label)
        self.sound = QSoundEffect()
        self.volume = 1.
        self.color = QColor(Qt.gray)

        self.count = 0
        self.duration = 1000
        self.rate = 20

        self.timer = QTimer()
        self.timer.timeout.connect(self.update_anim)

        self.mode = "sin"

        self.pressed.connect(self.start)
        self.released.connect(self.stop)

        self.is_accelerating = False
        self.update_color_with_alha(1)

    def setSound(self, sound_file):
        self.sound.setSource(QUrl.fromLocalFile(sound_file))
        self.sound.setLoopCount(QSoundEffect.Infinite)

    def start(self):
        self.count = 0
        self.sound.play()
        self.timer.start(self.rate)

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

    def set_color(self, col):
        self.color = col
        self.update_color_with_alha(1)

    def update_color_with_alha(self, alpha):
        red = self.color.red()
        green = self.color.green()
        blue = self.color.blue()
        bg_style = f"background-color:rgba({red},{green},{blue}, {alpha})"
        self.setStyleSheet(bg_style)

    def update_anim(self):

        #logarithmic (check with perception of luminosity/brighness)
        #val = math.log(count + 1)
        #linear
        if self.mode == "sin":
            val = math.sin(self.count * 2 * math.pi) / 2 + 0.5
        elif self.mode == "lin":
            val = 1 - self.count
        else:
            val = math.log(self.count + 1)

        alpha = round(val * 100) + 155
        self.update_color_with_alha(alpha)

        amplitude = val * 0.8 + 0.2
        self.sound.setVolume(amplitude)

        self.count = self.count + self.rate / self.duration
        # print(count)
        if self.count >= 1 - self.rate / self.duration:
            self.count = 0

            if self.is_accelerating:
                self.duration = max(200, self.duration * 0.95)
Ejemplo n.º 25
0
class MainCentralWidget(QWidget, CentralWidget):
    """Main Central Widget.

    This is the main race operations window. It presents the results input box, and manages the
    various "floater" windows like racer and field table views.
    """

    RESULT_INPUT_SOUND_EFFECT_SOURCE = QUrl.fromLocalFile(
        os.path.join(common.app_path(), defaults.RESULT_INPUT_SOUND_EFFECT_FILE))

    def __init__(self, modeldb, parent=None):
        """Initialize the MainCentralWidget instance."""
        super().__init__(parent=parent)

        self.modeldb = modeldb

        self.remote = None

        # Top-level layout. Top to bottom.
        self.setLayout(QVBoxLayout())

        # Button row for race info, field, racer list.
        self.button_row = QWidget()
        self.button_row.setLayout(QHBoxLayout())

        # Race Info, Fields, Racers
        self.button_row.racer_button = QPushButton('Racers')
        self.button_row.racer_button.setCheckable(True)
        self.button_row.racer_button.setToolTip('Toggle racers table')
        self.button_row.field_button = QPushButton('Fields')
        self.button_row.field_button.setCheckable(True)
        self.button_row.field_button.setToolTip('Toggle fields table')
        # Add to button row.
        self.button_row.layout().addWidget(self.button_row.racer_button)
        self.button_row.layout().addWidget(self.button_row.field_button)

        # Wall times/reference times label.
        self.wall_times_label = QLabel()
        self.wall_times_label.setAlignment(Qt.AlignCenter)

        # Digital clock.
        self.digital_clock = DigitalClock(self.modeldb)

        # Result table.
        self.result_table_view = ResultTableView(self.modeldb)

        # Result line edit.
        self.result_input = QLineEdit()
        font = self.result_input.font()
        font.setPointSize(INPUT_TEXT_POINT_SIZE)
        self.result_input.setFont(font)
        self.result_input.setValidator(QRegExpValidator(QRegExp('[A-Za-z0-9]*')))

        # Submit button.
        self.submit_button = QPushButton()
        self.submit_button.setToolTip('Submit selected results')
        self.result_selection_changed(QItemSelection(), QItemSelection())

        # Add to top-level layout.
        self.layout().addWidget(self.button_row)
        self.layout().addWidget(self.wall_times_label)
        self.layout().addWidget(self.digital_clock)
        self.layout().addWidget(self.result_table_view)
        self.layout().addWidget(self.result_input)
        self.layout().addWidget(self.submit_button)

        # Floating windows. Keep then hidden initially.
        self.builder = Builder(self.modeldb)
        self.field_table_view = FieldTableView(self.modeldb)
        self.racer_table_view = RacerTableView(self.modeldb)
        self.cheat_sheet = CheatSheet()
        self.journal_table_view = JournalTableView(self.modeldb)

        # Sound effects.
        self.result_input_sound_effect = QSoundEffect()
        self.result_input_sound_effect.setSource(self.RESULT_INPUT_SOUND_EFFECT_SOURCE)

        # Try to keep focus on the result input.
        self.setFocusPolicy(Qt.StrongFocus)
        self.setFocusProxy(self.result_input)
        self.return_focus_to_result_input()

        # Signals/slots for button row toggle buttons.
        self.button_row.field_button.toggled.connect(self.field_table_view
                                                         .setVisible)
        self.field_table_view.visibleChanged.connect(self.button_row.field_button
                                                         .setChecked)
        self.button_row.racer_button.toggled.connect(self.racer_table_view
                                                         .setVisible)
        self.racer_table_view.visibleChanged.connect(self.button_row.racer_button
                                                         .setChecked)

        # Signals/slots for field name change notification.
        self.modeldb.field_table_model.dataChanged.connect(self.field_model_changed)

        # Signals/slots for result table.
        self.result_table_view.selectionModel().selectionChanged.connect(
                                                  self.result_selection_changed)
        self.result_table_view.resultDeleted.connect(self.return_focus_to_result_input)
        self.result_table_view.clicked_without_selection.connect(self.return_focus_to_result_input)

        # Signals/slots for result input.
        self.result_input.returnPressed.connect(self.new_result)
        self.result_input.returnPressed.connect(self.result_input_sound_effect.play)

        # Signals/slots for submit button.
        self.submit_button.clicked.connect(self.handle_result_submit)

        # Signals/slots for keyboard shortcuts.
        shortcut = QShortcut(QKeySequence(QKeySequence.HelpContents), self)
        shortcut.activated.connect(self.handle_cheat_sheet_shortcut)

        shortcut = QShortcut(QKeySequence('CTRL+S'), self)
        shortcut.activated.connect(self.handle_submit_shortcut)

        shortcut = QShortcut(QKeySequence('CTRL+A'), self)
        shortcut.activated.connect(self.handle_select_all_shortcut)

        shortcut = QShortcut(QKeySequence('CTRL+D'), self)
        shortcut.activated.connect(self.handle_deselect_all_shortcut)

        shortcut = QShortcut(QKeySequence('CTRL+R'), self)
        shortcut.activated.connect(self.handle_racer_shortcut)

        shortcut = QShortcut(QKeySequence('CTRL+F'), self)
        shortcut.activated.connect(self.handle_field_shortcut)

        shortcut = QShortcut(QKeySequence('CTRL+J'), self)
        shortcut.activated.connect(self.handle_journal_shortcut)
        shortcut = QShortcut(QKeySequence('CTRL+L'), self)
        shortcut.activated.connect(self.handle_journal_shortcut)

    def closeEvent(self, event): #pylint: disable=invalid-name
        """Clean up the MainCentralWidget instance.

        Hide all floater widgets, and cleanup (close) the race model.
        """
        self.builder.hide()
        self.field_table_view.hide()
        self.racer_table_view.hide()
        self.cheat_sheet.hide()
        self.journal_table_view.hide()

        racer_in_field_table_view_dict = self.field_table_view.racer_in_field_table_view_dict
        for _, racer_table_view in racer_in_field_table_view_dict.items():
            racer_table_view.hide()

        self.modeldb.cleanup()
        self.modeldb = None

        super().closeEvent(event)

    def has_model(self):
        """Return whether we have a race model."""
        return self.modeldb is not None

    def wall_times_checkbox_changed(self, state):
        """Slot for when the wall times check box state changes."""
        if state:
            self.wall_times_label.setText('Wall Clock')
        else:
            self.wall_times_label.setText('Reference Clock')

    def field_model_changed(self, top_left, bottom_right, roles):
        """Handle field table model change.

        When someone changes a field name, we have to update the racer model to get the field name
        change. In addition, there is a combo box in the racer table view that is a view for a
        relation model inside the racer model. That combo box needs to update as well, to get the
        field name change.

        Note that we only care if the DisplayRole content changes, and also if the change is in
        the field model's name column.
        """
        if roles and not Qt.DisplayRole in roles:
            return

        field_table_model = self.modeldb.field_table_model
        if not field_table_model.area_contains(top_left, bottom_right,
                                               field_table_model.name_column):
            return

        racer_table_model = self.modeldb.racer_table_model
        field_relation_model = racer_table_model.relationModel(racer_table_model.field_column)

        racer_table_model.select()
        field_relation_model.select()

    def result_selection_changed(self, selected, deselected):
        """Handle result selection change.

        Change the result submit button depending on selection in the result
        table view.
        """
        del selected, deselected

        selection_count = len(self.result_table_view.selectionModel().selectedRows())
        total_count = self.result_table_view.model().rowCount()

        if selection_count == 0:
            self.submit_button.setText('Submit')
            self.submit_button.setEnabled(False)
        elif selection_count == 1:
            self.submit_button.setText('Submit')
            self.submit_button.setEnabled(True)
        elif selection_count < total_count:
            self.submit_button.setText('Submit Selected')
            self.submit_button.setEnabled(True)
        else:
            self.submit_button.setText('Submit All')
            self.submit_button.setEnabled(True)

    def new_result(self):
        """Handle a new result being entered in the result scratch pad input box."""
        race_table_model = self.modeldb.race_table_model

        scratchpad = self.result_input.text()
        msecs = race_table_model.get_reference_clock_datetime().msecsTo(QDateTime.currentDateTime())
        self.modeldb.result_table_model.add_result(scratchpad, msecs)

        self.result_table_view.scrollToBottom()
        self.result_input.clear()
        self.result_table_view.setFocusProxy(None)

    def handle_result_submit(self):
        """Handle result submit.

        Need to intercept the result submit here so that we can give the input focus back to the
        result input.
        """
        self.result_table_view.handle_submit()
        self.return_focus_to_result_input()

    def return_focus_to_result_input(self):
        """Give focus back to the result input box.

        Also a good time to tweak focus policy and proxies.
        """
        self.result_input.setFocus()

        total_count = self.result_table_view.model().rowCount()
        if total_count:
            self.result_table_view.setFocusProxy(None)
        else:
            self.result_table_view.setFocusProxy(self.result_input)

    def handle_submit_shortcut(self):
        """Handle submit all shortcut.

        If there is no selection, then just try to submit everything in the results list.
        Otherwise, this is basically a shortcut to the submit button.
        """
        if not self.result_table_view.selectedIndexes():
            self.result_table_view.selectAll()

        self.handle_result_submit()

    def handle_select_all_shortcut(self):
        """Handle select all shortcut.

        Regardless of the current selection, this shortcut selects everything in the results list.
        """
        self.result_table_view.selectAll()

    def handle_deselect_all_shortcut(self):
        """Handle deselect all shortcut.

        Regardless of the current selection, this shortcut deselects everything in the results
        list.
        """
        self.result_table_view.clearSelection()

    def handle_racer_shortcut(self):
        """Handle show racer table shortcut."""
        self.button_row.racer_button.click()

    def handle_field_shortcut(self):
        """Handle show field table shortcut."""
        self.button_row.field_button.click()

    def handle_cheat_sheet_shortcut(self):
        """Handle show cheat sheet table shortcut."""
        self.cheat_sheet.setVisible(not self.cheat_sheet.isVisible())

    def handle_journal_shortcut(self):
        """Handle show journal table shortcut."""
        self.journal_table_view.setVisible(not self.journal_table_view.isVisible())

    def set_remote(self, remote):
        """Do everything needed for a remote that has just been connected."""
        self.remote = remote
        self.modeldb.racer_table_model.set_remote(remote)
        self.field_table_view.set_remote(remote)
        self.racer_table_view.set_remote(remote)

    def connect_preferences(self, preferences):
        """Connect preferences signals to the various slots that care."""
        self.digital_clock.connect_preferences(preferences)
        self.field_table_view.connect_preferences(preferences)
        self.racer_table_view.connect_preferences(preferences)
        self.result_table_view.connect_preferences(preferences)

        # Signals/slots for wall times/reference times label.
        preferences.wall_times_checkbox.stateChanged.connect(self.wall_times_checkbox_changed)
        self.wall_times_checkbox_changed(preferences.wall_times_checkbox.checkState())
Ejemplo n.º 26
0
    #build UI
    app = QApplication(sys.argv)
    widget = QWidget()
    widget.setGeometry(200, 200, 500, 500)
    layout = QHBoxLayout()
    widget.setLayout(layout)
    button = QPushButton("test")
    layout.addWidget(button)

    # audio
    sound_file = "../Sounds/alarms/al1.wav"
    sound_file = "../Sounds/alarms/al6-low.wav"
    #sound_file = "../Sounds/alarms/al6-medium.wav"
    #sound_file = "../Sounds/alarms/al6-high.wav"
    sound = QSoundEffect()
    sound.setSource(QUrl.fromLocalFile(sound_file))
    sound.setLoopCount(QSoundEffect.Infinite)

    #animate label background and sound
    count = 0

    def update_anim():
        global count

        #logarithmic (check with perception of luminosity/brighness)
        #val = math.log(count + 1)
        #linear
        val = 1 - count
        #sinus
        #val = math.sin(count*2*math.pi) / 2 + 0.5
        #print(val)
Ejemplo n.º 27
0
class Notification(QMainWindow):
    '''Transparent window containing an image or animated gif, used to display notifications.'''
    def __init__(self,
                 name,
                 notifier,
                 artPath,
                 link,
                 sound=None,
                 *args,
                 **kwargs):
        '''- name : a string
        - notifier : a Notifier object used to manage this notification
        - artPath : a string containing the path to the image file to be displayed
        - link : a string containing the link to be opened when left-clicking the notification
        - sound : a string containing the path to the object or None. Set to None for silent notifiations.'''
        super().__init__(*args, **kwargs)
        self.setCursor(QCursor(Qt.PointingHandCursor))
        self.name = name
        self.notifier = notifier
        self.link = link
        self.artPath = artPath
        self.isMovie = self.artPath.endswith(".gif")
        if sound == None:
            self.sound = None
        else:
            self.sound = QSoundEffect()
            self.sound.setSource(QUrl.fromLocalFile(sound))
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint
                            | Qt.Tool)
        self.setAttribute(Qt.WA_TranslucentBackground)
        imageLabel = QLabel()
        self.setCentralWidget(imageLabel)
        if self.isMovie:
            self.art = QMovie(self.artPath)
            self.art.jumpToNextFrame()
            imageLabel.setMovie(self.art)
            self.moveToBottomRight(self.art.frameRect().width(),
                                   self.art.frameRect().height())
        else:
            self.art = QPixmap(self.artPath)
            imageLabel.setPixmap(self.art)
            self.moveToBottomRight(self.art.width(), self.art.height())

    def moveToBottomRight(self, x, y):
        '''Moves the notification window to the bottom-right of the screen, above the taskbar'''
        screen = QDesktopWidget().availableGeometry()
        x_pos = screen.width() - x
        y_pos = screen.height() - y
        self.move(x_pos, y_pos)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.close()
            webbrowser.open_new_tab(self.link)
        elif event.button() == Qt.RightButton:
            self.close()

    def display(self, volume=1):
        '''Show the notification window and plays the sound.'''
        super().show()
        if self.isMovie:
            self.art.start()
        if self.sound:
            self.sound.setVolume(volume)
            self.sound.play()

    def close(self):
        '''Updates notifier and closes window'''
        super().close()
        self.notifier.update()