Ejemplo n.º 1
0
    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)
Ejemplo n.º 2
0
    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()
Ejemplo n.º 3
0
    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)
Ejemplo n.º 4
0
    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)
Ejemplo n.º 5
0
 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'))
Ejemplo n.º 6
0
    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)
Ejemplo n.º 7
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.º 8
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.º 9
0
 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())
Ejemplo n.º 10
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.º 11
0
    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)
Ejemplo n.º 12
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.º 13
0
    def __init__(self, highscore_obj: highscores.Highscores, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Multiple inheritance allows us to have the ui and window together so
        # setupui can be given self in for a window
        self.setupUi(self)

        self.lineInput.textChanged.connect(self._on_input_text_changed)
        self.buttonNewText.clicked.connect(self.on_clicked_new)
        self.buttonRestart.clicked.connect(self.on_clicked_restart)

        # time and timer
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self._update_time)
        self.timer.setInterval(100)
        self._reset_time()

        # Object to handle saving and updating of highscore values
        self.highscore = highscore_obj

        # Defaults
        self.key_sound = QSoundEffect()
        self.set_colours(DEFAULT_COLOURS)
Ejemplo n.º 14
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.º 15
0
    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()
Ejemplo n.º 16
0
 def loadwav(self, volume):
     try:
         self.time = []
         for i in range(0, 113):
             self.time.append(QSoundEffect())
             self.time[i].setSource(
                 QUrl.fromLocalFile(
                     os.path.join(self.pathname, 'Languages', self.langage,
                                  str(i) + '.wav')))
             if i != self.index_entry and i != self.index_penalty:
                 self.time[i].playingChanged.connect(
                     self.slot_sound_playing_changed)
             self.time[i].setVolume(volume)
             self.sound_isplaying.append(False)
     except TypeError as e:
         print("QSoundError : ", e)
Ejemplo n.º 17
0
 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.º 18
0
 def play_audio(self, filepath):
     try:
         if self.sound.isPlaying():
             self.sound.setLoopCount(0)
             self.sound.stop()
             self.sound = None
     except:
         pass
     try:
         self.sound = QSoundEffect(self)
         self.sound.setSource(QtCore.QUrl.fromLocalFile(filepath))
         self.sound.setVolume(self.ui.volume_slider.value() / 100)
         if self.ui.loop_checkbox.isChecked():
             self.sound.setLoopCount(QSoundEffect.Infinite)
         self.sound.play()
     except:
         try:
             self.sound = QMediaPlayer(self)
             self.sound.setSource(QtCore.QUrl.fromLocalFile(filepath))
             self.sound.setVolume(self.ui.volume_slider.value() / 100)
             self.sound.play()
         except:
             pass
Ejemplo n.º 19
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.º 20
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.º 21
0
        key = CURSOR_SHAPE_SHAPE_PREFIX + file_name_except_extension(_file)
        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)
Ejemplo n.º 22
0
    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()
Ejemplo n.º 23
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.º 24
0
 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()
Ejemplo n.º 25
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.º 26
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.º 27
0
    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()
Ejemplo n.º 28
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.º 29
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.º 30
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.º 31
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.º 32
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'))