Exemple #1
0
class playSound(QWidget):
    def __init__(self, parent=None):
        super(playSound, self).__init__(parent)
        self.fileName = ""
        self.getFileName()
        self.focusSound = QSound(self.fileName)
        self.focusSound.setLoops(10)

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

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

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

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

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

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

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

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

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

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

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

    def stopBreakSound(self):
        self.breakSound.stop()
Exemple #2
0
class Hearthstone(
        QMainWindow
):  # the most important variables are defined here with their starting values
    moneyCount = 1000
    rankCount = 25
    goldCount = 0
    commonCards = 100
    rareCards = 25
    epicCards = 0
    legendaryCards = 0
    packCount = 0
    adventureCount = 0
    freeToPlay = True
    brawlPlayed = False
    questPlayed = False
    welcomeGift = False

    # the init function of the main class - setting up some sounds and timers that will be used later on, so that they can be used by other functions to not cause an AttributeError ##########################################################################

    def __init__(self):
        super(Hearthstone, self).__init__()
        self.initGUI()
        self.initMenu()
        self.theme = QSound("sounds/HearthstoneSoundtrack-MainTitle.wav")
        self.ping = QSound("sounds/WhatsApp_Original_Message.wav")
        self.sax = QSound("sounds/EpicSaxGuy-EpicSaxGuyCruzoRemix.wav")
        self.theme.play()  # starting the app out with the hearthstone theme
        self.theme.setLoops(
            100
        )  # hopefully nobody will play this long... (does this cause python to crash when I close the application? Possible..)

        self.moneyTimer = QTimer(
            self
        )  # these timers are for use in the pay to win mode -> they make sure money is
        self.moneyTimer.timeout.connect(
            self.depleteMoney
        )  # taken out of the players account and ranks and gold are put in regularly

        self.rankTimer = QTimer(self)
        self.rankTimer.timeout.connect(self.increaseRank)

        self.goldTimer = QTimer(self)
        self.goldTimer.timeout.connect(self.increaseGold)

    def initGUI(self):
        self.popUpFriendsTimer = QTimer(self)
        self.popUpFriendsTimer.timeout.connect(self.popUpFriends)
        self.popUpFinancesTimer = QTimer(self)
        self.popUpFinancesTimer.timeout.connect(self.popUpFinances)

        self.popUpFriendsTimer.start(
            30000
        )  # this makes the 'whatsapp messages of friends' pop up, who worry about the player putting too much time into the game

        try:
            if self.moneyTimer.isActive(
            ) == True:  # so that the money, rank and gold values keep changing when the player returns to the main screen in pay to win mode
                self.moneyTimer.stop()
                self.rankTimer.stop()
                self.goldTimer.stop()
                self.moneyTimer.start(10000)
                self.rankTimer.start(15000)
                self.goldTimer.start(5000)
            else:
                pass
        except AttributeError:
            pass

# setting up allllll the GUI elements of the main screen and their signal/slot relationships ##########################################################################

        self.soloBut = QPushButton("Adventure")
        self.soloBut.setMinimumSize(100, 80)
        self.soloBut.clicked.connect(self.playAdventure)
        self.playBut = QPushButton("Play")
        self.playBut.setMinimumSize(100, 80)
        self.playBut.clicked.connect(self.play)
        self.brawlBut = QPushButton("Tavern Brawl")
        self.brawlBut.setMinimumSize(100, 80)
        self.brawlBut.clicked.connect(self.playBrawl)
        self.questBut = QPushButton("Quest")
        self.questBut.setMinimumSize(50, 80)
        self.questBut.clicked.connect(self.playQuest)
        self.shopBut = QPushButton("Shop")
        self.shopBut.setMinimumSize(50, 80)
        self.shopBut.clicked.connect(self.showShop)
        self.packBut = QPushButton("Packs")
        self.packBut.setMinimumSize(50, 80)

        self.packScreen = PackOpeningGraph(
            self.packCount
        )  # instance of the only other real custom widget class used in this app

        self.packBut.clicked.connect(self.updatePackOpenings)
        self.collectionBut = QPushButton("Collection")
        self.collectionBut.setMinimumSize(50, 80)
        self.collectionBut.clicked.connect(self.displayCollection)
        self.workBut = QPushButton("Work for a Month")
        self.workBut.setMinimumSize(100, 80)
        self.workBut.clicked.connect(self.work)

        mainBut_layout = QVBoxLayout()
        mainBut_layout.addWidget(self.soloBut)
        mainBut_layout.addStretch(2)
        mainBut_layout.addWidget(self.playBut)
        mainBut_layout.addStretch(2)
        mainBut_layout.addWidget(self.brawlBut)
        mainBut_layout.addStretch(2)
        mainBut_layout.addWidget(self.workBut)

        mainButtons = QGroupBox()
        mainButtons.setLayout(mainBut_layout)
        mainButtons.setMaximumSize(300, 370)

        leftBut_layout = QVBoxLayout()
        leftBut_layout.addWidget(self.questBut)
        leftBut_layout.addWidget(self.shopBut)

        leftButtons = QGroupBox()
        leftButtons.setLayout(leftBut_layout)
        leftButtons.setMaximumSize(300, 300)

        rightBut_layout = QVBoxLayout()
        rightBut_layout.addWidget(self.packBut)
        rightBut_layout.addWidget(self.collectionBut)

        rightButtons = QGroupBox()
        rightButtons.setLayout(rightBut_layout)
        rightButtons.setMaximumSize(300, 300)

        radios_layout = QHBoxLayout()
        self.f2p = QRadioButton("Free to Play")
        self.p2w = QRadioButton("Pay to Win")
        if Hearthstone.freeToPlay == True:
            self.f2p.setChecked(True)
        else:
            self.p2w.setChecked(True)
        self.f2p.clicked.connect(self.FreeToPlay)
        self.p2w.clicked.connect(self.PayToWin)
        radios_layout.addWidget(self.f2p)
        radios_layout.addStretch(2)
        radios_layout.addWidget(self.p2w)
        radiobuttons = QGroupBox()
        radiobuttons.setLayout(radios_layout)
        radiobuttons.setMaximumSize(300, 70)

        self.gold = QLineEdit()
        self.gold.setEnabled(False)  # so that one cannot cheat!
        self.goldLabel = QLabel("Gold")
        self.goldLabel.setObjectName("gold")

        self.money = QLineEdit()
        self.money.setEnabled(False)
        self.moneyLabel = QLabel("Money")
        self.moneyLabel.setObjectName("money")

        self.rank = QLineEdit()
        self.rank.setEnabled(False)
        self.rankLabel = QLabel("Rank")
        self.rankLabel.setObjectName("rank")

        money_layout = QHBoxLayout()
        money_layout.addWidget(self.moneyLabel)
        money_layout.addWidget(self.money)

        moneyBox = QGroupBox()
        moneyBox.setLayout(money_layout)
        moneyBox.setMaximumSize(300, 70)

        rank_layout = QHBoxLayout()
        rank_layout.addWidget(self.rankLabel)
        rank_layout.addWidget(self.rank)

        rankBox = QGroupBox()
        rankBox.setLayout(rank_layout)
        rankBox.setMaximumSize(300, 70)

        gold_layout = QHBoxLayout()
        gold_layout.addWidget(self.goldLabel)
        gold_layout.addWidget(self.gold)

        goldBox = QGroupBox()
        goldBox.setLayout(gold_layout)
        goldBox.setMaximumSize(300, 70)

        grid = QGridLayout()
        grid.addWidget(moneyBox, 0, 0, 1, 2)
        grid.addWidget(rankBox, 0, 2, 1, 2)
        grid.addWidget(goldBox, 0, 4, 1, 2)
        grid.addWidget(mainButtons, 1, 2, 4, 2)
        grid.addWidget(leftButtons, 3, 0, 2, 1)
        grid.addWidget(rightButtons, 3, 5, 2, 1)
        grid.addWidget(radiobuttons, 4, 2, 1, 3)

        mainScreen = QWidget()
        mainScreen.setLayout(grid)
        mainScreen.setObjectName("main")  # for the css

        self.setWindowTitle("Hearthstone")
        h = qApp.desktop().screenGeometry().height() - 100
        w = qApp.desktop().screenGeometry().width() - 350
        self.setGeometry(175, 0, w, h)
        self.setFixedSize(w, h)
        self.setCentralWidget(mainScreen)
        self.show()
        self.updateGoldCount(
        )  # so the numbers in the line edits up top are always accurate
        self.updateMoneyCount()
        self.updateRankCount()

    def updateGoldCount(self):
        try:
            self.gold.setText(str(Hearthstone.goldCount))
        except RuntimeError:
            pass

    def updateMoneyCount(self):
        try:
            self.money.setText(str(Hearthstone.moneyCount))
        except RuntimeError:
            pass

    def updateRankCount(self):
        try:
            if Hearthstone.rankCount <= 0:
                self.rank.setText(
                    "LEGEND")  # In Hearthstone, rank 0 is called legend
            else:
                self.rank.setText(str(Hearthstone.rankCount))
        except RuntimeError:
            pass

    def updatePackOpenings(
        self
    ):  # this exists so if the player buys 2 packs and only uses one, the next time he visits the open packs screen, he only has one pack left
        Hearthstone.packCount -= PackOpeningGraph.usedPacks
        PackOpeningGraph.usedPacks = 0
        self.packScreen.show()

    def Save(
        self
    ):  # saves all important variable values in text files inside the repository
        Hearthstone.packCount -= PackOpeningGraph.usedPacks
        PackOpeningGraph.usedPacks = 0

        gold = open("SaveGame/gold.txt", "w")
        gold.write(str(Hearthstone.goldCount))
        gold.close

        rank = open("SaveGame/rank.txt", "w")
        rank.write(str(Hearthstone.rankCount))
        rank.close

        money = open("SaveGame/money.txt", "w")
        money.write(str(Hearthstone.moneyCount))
        money.close

        common = open("SaveGame/common.txt", "w")
        common.write(str(Hearthstone.commonCards))
        common.close

        rare = open("SaveGame/rare.txt", "w")
        rare.write(str(Hearthstone.rareCards))
        rare.close

        epic = open("SaveGame/epic.txt", "w")
        epic.write(str(Hearthstone.epicCards))
        epic.close

        legendary = open("SaveGame/legendary.txt", "w")
        legendary.write(str(Hearthstone.legendaryCards))
        legendary.close

        packs = open("SaveGame/packs.txt", "w")
        packs.write(str(Hearthstone.packCount))
        packs.close

        adventures = open("SaveGame/adventures.txt", "w")
        adventures.write(str(Hearthstone.adventureCount))
        adventures.close

    def Load(
        self
    ):  # loads all those important values into their respective variables
        gold = open("SaveGame/gold.txt")
        Hearthstone.goldCount = int(gold.read())
        gold.close

        rank = open("SaveGame/rank.txt")
        Hearthstone.rankCount = int(rank.read())
        rank.close

        money = open("SaveGame/money.txt")
        Hearthstone.moneyCount = int(money.read())
        money.close

        common = open("SaveGame/common.txt")
        Hearthstone.commonCards = int(common.read())
        common.close

        rare = open("SaveGame/rare.txt")
        Hearthstone.rareCards = int(rare.read())
        rare.close

        epic = open("SaveGame/epic.txt")
        Hearthstone.epicCards = int(epic.read())
        epic.close

        legendary = open("SaveGame/legendary.txt")
        Hearthstone.legendaryCards = int(legendary.read())
        legendary.close

        packs = open("SaveGame/packs.txt")
        Hearthstone.packCount = int(packs.read())
        packs.close

        adventures = open("SaveGame/adventures.txt")
        Hearthstone.adventureCount = int(adventures.read())
        adventures.close

        self.updateGoldCount()  # so that the loaded numbers are showing
        self.updateMoneyCount()
        self.updateRankCount()
        self.packScreen = PackOpeningGraph(
            self.packCount
        )  # it used to not show the loaded packs at first, I thought this might help..it didnt hurt, so...
        self.update(
        )  # always good to throw this in from time to time I heard...
        self.initGUI(
        )  # just to make really sure all is loaded, load up the main screen again

    def initMenu(
        self
    ):  # this sets up the menu bar at the very top of the screen and allows the player to save and load
        self.menubar = self.menuBar()
        saveAct = QAction("Save Game", self)
        loadAct = QAction("Load Game", self)
        saveAct.triggered.connect(self.Save)
        loadAct.triggered.connect(self.Load)
        self.makeMenu = self.menubar.addMenu("Save")
        self.makeMenu.addAction(saveAct)
        self.makeMenu.addAction(loadAct)

    def displayCollection(
        self
    ):  # shows the player the numbers of cards of different rarities they have in a pop up window
        Hearthstone.commonCards += PackOpeningGraph.commonCards  # adds all cards obtained through pack openings to the cards already in the players collection
        Hearthstone.rareCards += PackOpeningGraph.rareCards
        Hearthstone.epicCards += PackOpeningGraph.epicCards
        Hearthstone.legendaryCards += PackOpeningGraph.legendaryCards
        PackOpeningGraph.commonCards = 0  # empties the variables for cards obtained through pack openings so that they arent constantly added on
        PackOpeningGraph.rareCards = 0
        PackOpeningGraph.epicCards = 0
        PackOpeningGraph.legendaryCards = 0
        text = "Your collection: \nCommon: %d\nRare: %d\nEpic: %d\nLEGENDARY: %d\n" % (
            Hearthstone.commonCards, Hearthstone.rareCards,
            Hearthstone.epicCards, Hearthstone.legendaryCards)
        collectionPopUp = QMessageBox()
        collectionPopUp.setText(text)
        collectionPopUp.exec_()  # shows the pop up window

# the window for playing an adventure ##########################################################################

    def playAdventure(self):
        if Hearthstone.adventureCount >= 1:  # you have to have bought at least one adventure!
            self.adventureTimer = QTimer(self)
            self.adventureTimer.setSingleShot(True)
            self.adventureTimer.timeout.connect(self.initGUI)

            self.helpTimer = QTimer(self)
            self.helpTimer.timeout.connect(
                self.updateProgressBar
            )  # these timers are for the progress bar

            self.adventureProgress = QProgressBar()
            self.adventureProgress.setInvertedAppearance(True)
            self.adventureProgress.setMinimum(0)
            if self.f2p.isChecked() == True:
                self.adventureProgress.setMaximum(25000)
            elif self.p2w.isChecked() == True:
                self.adventureProgress.setMaximum(
                    5000)  # in pay to win mode, everything is a lot faster
            else:
                pass

            self.progressLabel = QLabel(
                "Playing adventure.\nAcquiring:\n25 common cards\n15 rare cards\n10 epic cards\n5 legendary cards"
            )
            if Hearthstone.freeToPlay == False:
                self.progressLabel.setStyleSheet(
                    """
                    QLabel {
                        font-size: 18px;
                    	color: white;
                    	text-align : center;
                        font-family: "Apple Chancery";
                    }"""
                )  # so it looks different in pay to win mode - the white was most important for being readable with a background picture

            adventure_layout = QVBoxLayout()
            adventure_layout.addWidget(self.progressLabel)
            adventure_layout.addWidget(self.adventureProgress)

            adventureScreen = QWidget()
            adventureScreen.setLayout(adventure_layout)
            adventureScreen.setObjectName("adventure")

            self.setWindowTitle("Adventure")
            h = qApp.desktop().screenGeometry().height() - 550
            w = qApp.desktop().screenGeometry().width() - 1000
            self.setGeometry(20, 20, w, h)
            self.setFixedSize(w, h)
            self.setCentralWidget(adventureScreen)
            self.update()

            Hearthstone.commonCards += 25
            Hearthstone.rareCards += 15
            Hearthstone.epicCards += 10
            Hearthstone.legendaryCards += 5
            Hearthstone.adventureCount -= 1  # what a deal!

            if self.f2p.isChecked() == True:
                self.adventureTimer.start(25000)
            elif self.p2w.isChecked() == True:
                self.adventureTimer.start(5000)  # faster...
            else:
                pass
            self.helpTimer.start(100)
        else:
            self.displayWarning()

    def updateProgressBar(
            self
    ):  # updates the progress bars progress depending on the helpTimer
        if (self.adventureTimer.remainingTime()) >= 1:
            self.adventureProgress.setValue(
                self.adventureTimer.remainingTime())
        else:
            pass

    def displayWarning(
            self):  # in the case that the player should have 0 adventures
        text = "You must purchase an adventure first. Navigate to the shop to purchase an adventure!"
        warningPopUp = QMessageBox()
        warningPopUp.setText(text)
        warningPopUp.exec_()

# a lot of this is very similar to the playAdventure function ##########################################################################

    def playBrawl(self):
        if Hearthstone.brawlPlayed == False:
            self.brawlTimer = QTimer(self)
            self.brawlTimer.setSingleShot(True)
            self.brawlTimer.timeout.connect(self.initGUI)

            self.brawlHelpTimer = QTimer(self)
            self.brawlHelpTimer.timeout.connect(self.updateBrawlProgressBar)

            self.waitTilWednesday = QTimer(self)
            self.waitTilWednesday.setSingleShot(True)
            self.waitTilWednesday.timeout.connect(
                self.resetBrawl
            )  # this is so the player cannot immediately play tavern brawl again, just like in the original

            self.brawlProgress = QProgressBar()
            self.brawlProgress.setInvertedAppearance(True)
            self.brawlProgress.setMinimum(0)
            if self.f2p.isChecked() == True:
                self.brawlProgress.setMaximum(25000)
            elif self.p2w.isChecked() == True:
                self.brawlProgress.setMaximum(5000)
            else:
                pass

            self.brawlProgressLabel = QLabel(
                "Playing Tavern Brawl.\nAcquiring a card pack.")
            if Hearthstone.freeToPlay == False:
                self.brawlProgressLabel.setStyleSheet("""
                    QLabel {
                        font-size: 18px;
                    	color: white;
                    	text-align : center;
                        font-family: "Apple Chancery";
                    }""")

            brawl_layout = QVBoxLayout()
            brawl_layout.addWidget(self.brawlProgressLabel)
            brawl_layout.addWidget(self.brawlProgress)

            brawlScreen = QWidget()
            brawlScreen.setLayout(brawl_layout)
            brawlScreen.setObjectName("brawl")

            self.setWindowTitle("Tavern Brawl")
            h = qApp.desktop().screenGeometry().height() - 500
            w = qApp.desktop().screenGeometry().width() - 1000
            self.setGeometry(20, 20, w, h)
            self.setFixedSize(w, h)
            self.setCentralWidget(brawlScreen)
            self.update()

            Hearthstone.packCount += 1
            Hearthstone.brawlPlayed = True

            if self.f2p.isChecked() == True:
                self.brawlTimer.start(25000)
            elif self.p2w.isChecked() == True:
                self.brawlTimer.start(5000)
            else:
                pass
            self.brawlHelpTimer.start(100)
            self.waitTilWednesday.start(100000)
        else:
            self.displayBrawlWarning()

    def updateBrawlProgressBar(self):
        if (self.brawlTimer.remainingTime()) >= 1:
            self.brawlProgress.setValue(self.brawlTimer.remainingTime())
        else:
            pass

    def displayBrawlWarning(self):
        text = "It is not time for a new Tavern Brawl yet! Wait until Wednesday!"
        warningPopUp = QMessageBox()
        warningPopUp.setText(text)
        warningPopUp.exec_()

    def resetBrawl(self):
        Hearthstone.brawlPlayed = False  # resets the brawl so it can be played again after the timer waitTilWednesday has run out

# a lot of this is similar to the last two functions, especially playBrawl ##########################################################################

    def playQuest(self):
        if Hearthstone.questPlayed == False:
            self.questTimer = QTimer(self)
            self.questTimer.setSingleShot(True)
            self.questTimer.timeout.connect(self.initGUI)

            self.questHelpTimer = QTimer(self)
            self.questHelpTimer.timeout.connect(self.updateQuestProgressBar)

            self.waitTilTomorrow = QTimer(self)
            self.waitTilTomorrow.setSingleShot(True)
            self.waitTilTomorrow.timeout.connect(self.resetQuest)

            self.questProgress = QProgressBar()
            self.questProgress.setInvertedAppearance(True)
            self.questProgress.setMinimum(0)
            if self.f2p.isChecked() == True:
                self.questProgress.setMaximum(25000)
            elif self.p2w.isChecked() == True:
                self.questProgress.setMaximum(5000)
            else:
                pass
            questGold = choice([40, 50, 60, 80, 100])
            self.questProgressLabel = QLabel(
                "Playing Quest.\nAcquiring %d gold." % questGold)
            if Hearthstone.freeToPlay == False:
                self.questProgressLabel.setStyleSheet("""
                    QLabel {
                        font-size: 18px;
                    	color: white;
                    	text-align : center;
                        font-family: "Apple Chancery";
                    }""")

            quest_layout = QVBoxLayout()
            quest_layout.addWidget(self.questProgressLabel)
            quest_layout.addWidget(self.questProgress)

            questScreen = QWidget()
            questScreen.setLayout(quest_layout)
            questScreen.setObjectName("quest")

            self.setWindowTitle("Quest")
            h = qApp.desktop().screenGeometry().height() - 500
            w = qApp.desktop().screenGeometry().width() - 1000
            self.setGeometry(20, 20, w, h)
            self.setFixedSize(w, h)
            self.setCentralWidget(questScreen)
            self.update()

            Hearthstone.goldCount += questGold
            Hearthstone.questPlayed = True

            if self.f2p.isChecked() == True:
                self.questTimer.start(25000)
            elif self.p2w.isChecked() == True:
                self.questTimer.start(5000)
            else:
                pass
            self.questHelpTimer.start(100)
            self.waitTilTomorrow.start(50000)

        else:
            self.displayQuestWarning()

    def updateQuestProgressBar(self):
        if (self.questTimer.remainingTime()) >= 1:
            self.questProgress.setValue(self.questTimer.remainingTime())
        else:
            pass

    def displayQuestWarning(self):
        text = "It is not time for a new Quest yet! Wait until tomorrow!"
        warningPopUp = QMessageBox()
        warningPopUp.setText(text)
        warningPopUp.exec_()

    def resetQuest(self):
        Hearthstone.questPlayed = False

# still some is similar to the last 3 ##########################################################################

    def play(self):
        Hearthstone.commonCards += PackOpeningGraph.commonCards
        Hearthstone.rareCards += PackOpeningGraph.rareCards
        Hearthstone.epicCards += PackOpeningGraph.epicCards
        Hearthstone.legendaryCards += PackOpeningGraph.legendaryCards  # same as in displayCollection -> adds all previously acquired cards to the players collection
        PackOpeningGraph.commonCards = 0
        PackOpeningGraph.rareCards = 0
        PackOpeningGraph.epicCards = 0
        PackOpeningGraph.legendaryCards = 0
        self.playTimer = QTimer(self)
        self.playTimer.setSingleShot(True)
        self.playTimer.timeout.connect(self.initGUI)
        self.playTimer.timeout.connect(self.displayDecision)

        self.playHelpTimer = QTimer(self)
        self.playHelpTimer.timeout.connect(self.updatePlayProgressBar)

        self.playProgress = QProgressBar()
        self.playProgress.setInvertedAppearance(True)
        self.playProgress.setMinimum(0)
        if self.f2p.isChecked() == True:
            self.playProgress.setMaximum(25000)
        elif self.p2w.isChecked() == True:
            self.playProgress.setMaximum(5000)
        else:
            pass

        self.playProgressLabel = QLabel(
            "Playing a game versus\nan online opponent.")
        if Hearthstone.freeToPlay == False:
            self.playProgressLabel.setStyleSheet("""
                QLabel {
                    font-size: 18px;
                    color: white;
                    text-align : center;
                    font-family: "Apple Chancery";
                }""")

        play_layout = QVBoxLayout()
        play_layout.addWidget(self.playProgressLabel)
        play_layout.addWidget(self.playProgress)

        playScreen = QWidget()
        playScreen.setLayout(play_layout)
        playScreen.setObjectName("play")

        self.setWindowTitle("Ranked Game")
        h = qApp.desktop().screenGeometry().height() - 500
        w = qApp.desktop().screenGeometry().width() - 1000
        self.setGeometry(20, 20, w, h)
        self.setFixedSize(w, h)
        self.setCentralWidget(playScreen)
        self.update()

        self.chance = (Hearthstone.rankCount +
                       25) + Hearthstone.legendaryCards + (
                           Hearthstone.epicCards * 0.25)
        if self.chance >= 99:  # a calculation for the players percentage chance of winning
            self.chance = 98
        else:
            pass
        dieThrow = randint(0, 99)

        if self.chance >= dieThrow:  # setting up the possible outcomes of the game
            if Hearthstone.rankCount == 0:
                self.decision = "victorious"
                Hearthstone.goldCount += 10
            else:
                Hearthstone.rankCount -= 1
                self.decision = "victorious"
                Hearthstone.goldCount += 10
        else:
            if Hearthstone.rankCount == 25:  # cannot fall 'lower', numerically higher, than 25
                self.decision = "defeated"
            else:
                Hearthstone.rankCount += 1
                self.decision = "defeated"

        if self.f2p.isChecked() == True:
            self.playTimer.start(25000)
        elif self.p2w.isChecked() == True:
            self.playTimer.start(5000)
        else:
            pass
        self.playHelpTimer.start(100)

    def updatePlayProgressBar(self):
        if (self.playTimer.remainingTime()) >= 1:
            self.playProgress.setValue(self.playTimer.remainingTime())
        else:
            pass

    def displayDecision(self):
        text = "You were %s!" % self.decision
        if self.decision == "defeated":
            text = text + "\nBetter luck next time!\nMaybe you need more legendary cards."
        else:
            text = text + "\nGreat job!\nYou must have a large collection of powerful, expensive cards."
        warningPopUp = QMessageBox()
        warningPopUp.setText(text)
        warningPopUp.exec_()

# still similar... ##########################################################################

    def work(self):
        self.workTimer = QTimer(self)
        self.workTimer.setSingleShot(True)
        self.workTimer.timeout.connect(self.initGUI)

        self.workHelpTimer = QTimer(self)
        self.workHelpTimer.timeout.connect(self.updateWorkProgressBar)

        self.workProgress = QProgressBar()
        self.workProgress.setInvertedAppearance(True)
        self.workProgress.setMinimum(0)
        if self.f2p.isChecked() == True:
            self.workProgress.setMaximum(250000)
        elif self.p2w.isChecked() == True:
            self.workProgress.setMaximum(
                500000)  # this actually takes longer in pay to win mode!
        else:
            pass

        self.workProgressLabel = QLabel("Working.\nAcquiring 1000 Dollars")

        work_layout = QVBoxLayout()
        work_layout.addWidget(self.workProgressLabel)
        work_layout.addWidget(self.workProgress)

        workScreen = QWidget()
        workScreen.setLayout(work_layout)
        workScreen.setObjectName("work")

        self.setWindowTitle("Work")
        h = qApp.desktop().screenGeometry().height() - 500
        w = qApp.desktop().screenGeometry().width() - 1000
        self.setGeometry(20, 20, w, h)
        self.setFixedSize(w, h)
        self.setCentralWidget(workScreen)
        self.update()

        Hearthstone.moneyCount += 1000

        if self.f2p.isChecked() == True:
            self.workTimer.start(250000)
        elif self.p2w.isChecked() == True:
            self.workTimer.start(500000)
        else:
            pass
        self.workHelpTimer.start(100)

    def updateWorkProgressBar(self):
        if (self.workTimer.remainingTime()) >= 1:
            self.workProgress.setValue(self.workTimer.remainingTime())
        else:
            pass

# sets up the shop and its GUI elements ##########################################################################

    def showShop(self):
        if Hearthstone.freeToPlay == True:
            self.buyPackBut = QPushButton("Only 100 Gold")
            self.buyPacksBut = QPushButton("Only 100 Dollars")
            self.buyAdventureBut = QPushButton("Only 3.500 Gold")
            self.buyAdventureMoneyBut = QPushButton("Or 350 Dollars")
        else:
            self.buyPackBut = QPushButton("Discounted: 50 Gold")
            self.buyPacksBut = QPushButton("Discounted: 50 Dollars")
            self.buyAdventureBut = QPushButton("Discounted: 1000 Gold")
            self.buyAdventureMoneyBut = QPushButton("Or 100 Dollars")

        self.buyPackBut.setObjectName("pack")
        self.buyPacksBut.setObjectName("packs")
        self.buyAdventureBut.setObjectName("adventuregold")
        self.buyAdventureMoneyBut.setObjectName(
            "adventuremoney")  # all for css

        self.buyPackLabel = QLabel("1 Card-Pack")
        if Hearthstone.freeToPlay == False:  # guess i could have done this just like above...oops
            self.buyPackLabel.setStyleSheet("""
                QLabel {
                    font-size: 18px;
                    color: white;
                    font-family: "Apple Chancery";
                }""")
        self.buyPacksLabel = QLabel("50 Card-Packs")
        if Hearthstone.freeToPlay == False:
            self.buyPacksLabel.setStyleSheet("""
                QLabel {
                    font-size: 18px;
                    color: white;
                    font-family: "Apple Chancery";
                }""")
        self.buyAdventureLabel = QLabel("1 Adventure")
        if Hearthstone.freeToPlay == False:
            self.buyAdventureLabel.setStyleSheet("""
                QLabel {
                    font-size: 18px;
                    color: white;
                    font-family: "Apple Chancery";
                }""")
        self.buyPackBut.clicked.connect(self.buyPack)
        self.buyPacksBut.clicked.connect(self.buyPacks)
        self.buyAdventureBut.clicked.connect(self.buyAdventure)
        self.buyAdventureMoneyBut.clicked.connect(self.buyAdventureMoney)
        self.backLink = QPushButton("Go Back")
        self.backLink.setMaximumSize(100, 50)
        self.backLink.clicked.connect(self.initGUI)

        PackBox1 = QHBoxLayout()
        PackBox1.addWidget(self.buyPackLabel)
        PackBox1.addStretch(1)
        PackBox1.addWidget(self.buyPackBut)

        PackBox2 = QHBoxLayout()
        PackBox2.addWidget(self.buyPacksLabel)
        PackBox2.addStretch(1)
        PackBox2.addWidget(self.buyPacksBut)

        AdventureBox = QHBoxLayout()
        AdventureBox.addWidget(self.buyAdventureLabel)
        AdventureBox.addStretch(1)
        AdventureBox.addWidget(self.buyAdventureBut)
        AdventureBox.addStretch(1)
        AdventureBox.addWidget(self.buyAdventureMoneyBut)

        ShopLayout = QVBoxLayout()
        ShopLayout.addItem(PackBox1)
        ShopLayout.addStretch(2)
        ShopLayout.addItem(PackBox2)
        ShopLayout.addStretch(2)
        ShopLayout.addItem(AdventureBox)
        ShopLayout.addStretch(1)
        ShopLayout.addWidget(self.backLink)

        shopScreen = QWidget()
        shopScreen.setLayout(ShopLayout)
        shopScreen.setObjectName("shop")

        self.setWindowTitle("Shop")
        h = qApp.desktop().screenGeometry().height() - 500
        w = qApp.desktop().screenGeometry().width() - 900
        self.setGeometry(20, 20, w, h)
        self.setFixedSize(w, h)
        self.setCentralWidget(shopScreen)
        self.update()

    def buyAdventure(
        self
    ):  # all the possibilities when one wants to buy and adventure with gold, inluding current mode
        if Hearthstone.freeToPlay == True:
            if Hearthstone.goldCount >= 3500:
                Hearthstone.goldCount -= 3500
                Hearthstone.adventureCount += 1
            else:
                text = "You don't have enough gold!"
                warningPopUp = QMessageBox()
                warningPopUp.setText(text)
                warningPopUp.exec_()
        else:
            if Hearthstone.goldCount >= 1000:
                Hearthstone.goldCount -= 1000
                Hearthstone.adventureCount += 1
            else:
                text = "You don't have enough gold!"
                warningPopUp = QMessageBox()
                warningPopUp.setText(text)
                warningPopUp.exec_()

    def buyAdventureMoney(self):  # same as above with money instead of gold
        if Hearthstone.freeToPlay == True:
            if Hearthstone.moneyCount >= 350:
                Hearthstone.moneyCount -= 350
                Hearthstone.adventureCount += 1
            else:
                text = "You don't have enough money!"
                warningPopUp = QMessageBox()
                warningPopUp.setText(text)
                warningPopUp.exec_()
        else:
            if Hearthstone.moneyCount >= 100:
                Hearthstone.moneyCount -= 100
                Hearthstone.adventureCount += 1
            else:
                text = "You don't have enough money!"
                warningPopUp = QMessageBox()
                warningPopUp.setText(text)
                warningPopUp.exec_()

    def buyPack(self):  # same as two above except with a pack
        if Hearthstone.freeToPlay == True:
            if Hearthstone.goldCount >= 100:
                Hearthstone.goldCount -= 100
                Hearthstone.packCount += 1
            else:
                text = "You don't have enough gold!"
                warningPopUp = QMessageBox()
                warningPopUp.setText(text)
                warningPopUp.exec_()
        else:
            if Hearthstone.goldCount >= 50:
                Hearthstone.goldCount -= 50
                Hearthstone.packCount += 1
            else:
                text = "You don't have enough gold!"
                warningPopUp = QMessageBox()
                warningPopUp.setText(text)
                warningPopUp.exec_()

    def buyPacks(self):  # same as above, just with 50 packs and money
        if Hearthstone.freeToPlay == True:
            if Hearthstone.moneyCount >= 100:
                Hearthstone.moneyCount -= 100
                Hearthstone.packCount += 50
            else:
                text = "You don't have enough money!"
                warningPopUp = QMessageBox()
                warningPopUp.setText(text)
                warningPopUp.exec_()
        else:
            if Hearthstone.moneyCount >= 50:
                Hearthstone.moneyCount -= 50
                Hearthstone.packCount += 50
            else:
                text = "You don't have enough money!"
                warningPopUp = QMessageBox()
                warningPopUp.setText(text)
                warningPopUp.exec_()

# the function that starts the craziness that is pay to win mode ##########################################################################

    def PayToWin(self):
        if Hearthstone.moneyCount > 0:  # only possible if the player has at least some money
            if Hearthstone.freeToPlay == True:  # and the mode is not yet engaged
                Hearthstone.freeToPlay = False
                self.popUpFriendsTimer.stop()
                self.popUpFinancesTimer.start(
                    17500
                )  # starts the pop up messages regarding a defficiency of finances on the players end

                styleSheet = open("css/p2w.css")  # opens the main stlyesheet
                qApp.setStyleSheet(styleSheet.read())
                styleSheet.close()

                self.theme.stop()
                self.sax.play(
                )  # changes the music - FOR YOUR INFORMATION: THIS MUSIC IS COMMONLY PLAYED IN THE HEARTHSTONE COMMUNITY,
                self.sax.setLoops(
                    100
                )  # WHEN IMPRESSIVE FEATS SUCH AS MASSIVE COMBOS ARE SHOWN! THAT IS WHY I CHOSE IT TO REPRESENT
                if Hearthstone.welcomeGift == False:  # THE PLAYER WHO SPENDS MONEY ON THE GAME TO BE AS GOOD AS POSSIBLE
                    text = "Congratulations for chosing to\nspend your money on this game!\nHave 5 complimentary adventures for your commitment."
                    congratsPopUp = QMessageBox()
                    congratsPopUp.setGeometry(500, 500, 500, 500)
                    congratsPopUp.setText(text)
                    congratsPopUp.exec_()
                    Hearthstone.adventureCount += 5  # the first time a player enters pay to win mode, he gets 5 adventures
                    Hearthstone.welcomeGift = True
                else:
                    pass

                Hearthstone.moneyCount -= 100  # so there can't be gold farming, 100 dollars are subtracted immediately upon selection of pay to win mode
                self.updateMoneyCount()

                self.moneyTimer.start(
                    10000
                )  # starts the constant subtraction/addition of values
                self.goldTimer.start(5000)
                self.rankTimer.start(15000)
            else:
                pass

        else:
            self.f2p.setChecked(True)

    def depleteMoney(self):
        try:
            Hearthstone.moneyCount -= 100
            if Hearthstone.moneyCount <= 0:  # this happens when the player runs out of money before pressing the free to play button again
                self.moneyTimer.stop(
                )  # everything changes back into free to play mode
                self.rankTimer.stop()
                self.goldTimer.stop()
                self.popUpFriendsTimer.start(30000)
                self.popUpFinancesTimer.stop()
                qApp.setStyleSheet("")
                self.sax.stop()
                self.theme.play()
                self.theme.setLoops(100)
                Hearthstone.moneyCount = 0
                Hearthstone.freeToPlay = True
                self.f2p.setChecked(True)
                self.initGUI
                self.update()
                text = "It seems that you have run out of money...\nToo bad that we had to set you\nback to the free-to-play status."
                warningPopUp = QMessageBox()
                warningPopUp.setText(text)
                warningPopUp.exec_()
            else:
                pass
            self.updateMoneyCount()
            self.update()
        except RuntimeError:  # I had some errors when the player was still in another window than the main screen when they ran out of money..
            self.popUpFriendsTimer.start(30000)
            self.popUpFinancesTimer.stop()
            qApp.setStyleSheet("")
            self.sax.stop()
            self.theme.play()
            self.theme.setLoops(100)
            self.moneyTimer.stop()
            self.rankTimer.stop()
            self.goldTimer.stop()
            Hearthstone.moneyCount = 0
            Hearthstone.freeToPlay = True
            text = "It seems that you have run out of money...\nToo bad that we had to set you\nback to the free-to-play status."
            warningPopUp = QMessageBox()
            warningPopUp.setText(text)
            warningPopUp.exec_()

    def increaseRank(self):
        Hearthstone.rankCount -= 1
        self.updateRankCount()
        self.update()

    def increaseGold(self):
        Hearthstone.goldCount += 100
        self.updateGoldCount()
        self.update()

# this connects to the free to play button being pressed and does basically all that depleteMoney does, when the player runs out of money ##########################################################################

    def FreeToPlay(self):
        if Hearthstone.moneyCount <= 0:
            self.moneyTimer.stop()
            self.rankTimer.stop()
            self.goldTimer.stop()
        else:
            pass
        self.popUpFriendsTimer.start(30000)
        self.popUpFinancesTimer.stop()
        qApp.setStyleSheet("")
        self.sax.stop()
        self.theme.play()
        self.theme.setLoops(100)
        try:
            self.moneyTimer.stop()
            self.rankTimer.stop()
            self.goldTimer.stop()
            Hearthstone.freeToPlay = True
            self.f2p.setChecked(True)
            text = "We are sad to see you\ngo back to that place.\nCome back some time."
            byePopUp = QMessageBox()
            byePopUp.setText(text)
            byePopUp.exec_()
            self.initGUI
            self.update()
        except AttributeError:
            pass

# randomly selects one of the 10 / 7 messages and makes them pop up ##########################################################################

    def popUpFriends(self):
        message = randint(0, 9)
        messages = [
            "Hey dude, why aren't you at the hockey game?",
            "Come on out here, man!",
            "This is your mother. You have not come out of your room for 3 days. What are you doing in there?!",
            "I miss you, we should hang out again some time!",
            "Haven't seen you at school in some time, are you on vacation or something?",
            "You are playing Hearthstone again, aren't you?",
            "The concert last night was awesome! Why didn't you come again?",
            "Dude! Did you sleep through the exam this morning?!",
            "The weather is nice out, want to go for a hike?",
            "Last chance! If you want to come with me to Spain tomorrow, you gotta decide NOW!"
        ]
        self.ping.play()
        text = messages[message]
        self.friendPopUp = QMessageBox()
        self.friendPopUp.setText(text)
        self.friendPopUp.setWindowTitle("New Message")
        self.friendPopUp.setGeometry(0, 0, 300, 200)
        self.friendPopUp.setObjectName("friend")
        self.friendPopUp.exec_()

    def popUpFinances(self):
        message = randint(0, 6)
        messages = [
            "Your credit card has been denied due to insuficcient funds.",
            "Dude, I like you, but I need you to pay the rent on time. Don't let me down..",
            "WHERE'S MY MONEY?!",
            "Hey, just checking in about the 12$ you're still owing me. I'd appreciate them back.",
            "Dear customer, you just went over the limit of your bank account. Thus it was closed until further notice.",
            "Dear, I'm so glad your mom and I can support you going to college. I hope the money lasts the month!",
            "Hey, just wanted to inform you that the interest for last month's loan went up to 8%, because I still don't have the money from you.."
        ]
        self.ping.play()
        text = messages[message]
        self.financePopUp = QMessageBox()
        self.financePopUp.setText(text)
        self.financePopUp.setWindowTitle("New Message")
        self.financePopUp.setGeometry(0, 0, 300, 200)
        self.financePopUp.setObjectName("finance")
        self.financePopUp.exec_()
Exemple #3
0
class MainWindow(widget[0], widget[1]):
    nombre = pyqtSignal()
    pedir = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.labels = {}
        self.botones = {}
        self.labels_puntajes = []
        self.opciones = []
        self.labels_otros = {}
        self.otros = {}
        self.mitimer = None
        self.cancion = None
        self.la_proxima1 = False
        self.setupUi(self)
        self.initGui()
        self.fondo = QImage("fondo.png").scaled(
            QSize(
                self.frameGeometry().width(),
                self.frameGeometry().height()))  # resize Image to widgets size
        palette = QPalette()
        palette.setBrush(10, QBrush(self.fondo))
        self.setPalette(palette)
        self.primera_cancion = True
        self.la_proxima = False
        self.boton_ingreso.clicked.connect(self.crear_cliente)
        self.boton_puntajes.clicked.connect(self.abrir_puntajes)

    def initGui(self):
        self.show()

    def keyPressEvent(self, key):
        if key.key() == 16777220:
            self.crear_cliente()

    def avanzar(self):
        self.label_usuario.setText("Usuario: " + self.nombre_usuario.text())
        self.label_puntaje.setText("Puntaje: " + str(self.cliente.puntaje))
        self.label_puntaje_2.setText("Puntaje: " + str(self.cliente.puntaje))
        self.stackedWidget.setCurrentIndex(1)

    def crear_cliente(self):
        self.boton_ingreso.clicked.disconnect()
        nombre = self.nombre_usuario.text()
        self.cliente = Client(port, host, nombre, self)
        self.boton_ingreso.clicked.connect(self.cambiar_nombre)
        self.volver_puntajes.clicked.connect(self.volver_sala)

    def cambiar_nombre(self):
        self.ingrese_nombre.setText("Nombre ya usado, intente nuevamente:")
        for i in self.salas:
            self.labels[i].hide()
            self.labels[i + "tiempo"].hide()
            self.labels[i + "cancion"].hide()
            self.botones[i].hide()
            self.labels[i + "contador"].hide()
        self.stackedWidget.setCurrentIndex(0)
        self.boton_ingreso.clicked.connect(self.enviar_nombre)

    def enviar_nombre(self):
        nombre = self.nombre_usuario.text()
        self.cliente.nombre(nombre)

    def post_cambio(self):
        for i in self.salas:
            self.labels[i].show()
            self.labels[i + "tiempo"].show()
            self.labels[i + "cancion"].show()
            self.botones[i].show()
            self.labels[i + "contador"].show()

    def reproducir(self, tupla):
        if self.primera_cancion:
            self.primera_cancion = False
        else:
            self.cancion.stop()
        self.cancion = QSound("songs/" + tupla[0], self)
        self.cancion.play()

    def recibir_salas(self, salas):
        self.salas = salas
        n = 100
        for i in self.salas:
            self.labels[i] = QLabel(self)
            self.labels[i].setText(i)
            self.labels[i].setGeometry(50, n, 100, 50)
            self.labels[i].show()
            self.labels[i + "tiempo"] = QLabel(self)
            self.labels[i + "tiempo"].setText("")
            self.labels[i + "tiempo"].setGeometry(150, n, 100, 50)
            self.labels[i + "tiempo"].show()
            self.labels[i + "cancion"] = QLabel(self)
            art = choice(self.salas[i]["canciones"], 2, False)
            self.labels[i + "cancion"].setText(art[0].split("-")[0] + ", " +
                                               art[1].split("-")[0])
            self.labels[i + "cancion"].setGeometry(200, n, 250, 100)
            self.labels[i + "cancion"].show()
            self.botones[i] = QPushButton(self)
            self.botones[i].setText(i)
            self.botones[i].setGeometry(500, n, 100, 50)
            self.botones[i].show()
            self.labels[i + "contador"] = QLabel(self)
            self.labels[i + "contador"].setText("")
            self.labels[i + "contador"].setGeometry(600, n, 100, 50)
            self.labels[i + "contador"].show()
            n += 100
        for i in self.botones:
            self.botones[i].clicked.connect(partial(self.abrir_sala, i))

    def actualizar_salas(self, tupla):
        self.salas = tupla[0]
        self.otros = tupla[1]
        contador = 0
        for sala in self.salas:
            self.labels[sala + "tiempo"].setText(
                str(self.salas[sala]["tiempo"]) + " segundos")
            for otro in self.otros:
                if self.otros[otro]["sala"] == sala:
                    contador += 1
            self.labels[sala +
                        "contador"].setText(str(contador) + " jugadores")
            contador = 0

    def abrir_sala(self, nombre):
        self.nombre_sala = nombre
        self.cliente.sala = nombre
        self.timer.setText(str(self.salas[nombre]["tiempo"]))
        self.nombre_sala_label.setText(nombre)
        for i in self.botones:
            self.botones[i].hide()
        for i in self.labels:
            self.labels[i].hide()
        self.n = 150
        for otros in self.otros:
            if self.otros[otros]["sala"] == self.nombre_sala:
                self.labels_otros[otros] = QLabel(self)
                self.labels_otros[otros].setText(
                    otros + "\n--> " + str(self.otros[otros]["puntos"]) +
                    " puntos\n--> " + str(self.otros[otros]["tiempo"]))
                self.labels_otros[otros].setGeometry(650, self.n, 140, 50)
                self.labels_otros[otros].show()
                self.n += 60
        self.stackedWidget.setCurrentIndex(2)
        self.opciones = [
            self.opcion1, self.opcion2, self.opcion3, self.opcion4
        ]
        pregunta = random.randint(0, 1)
        if pregunta == 0:
            self.pregunta.setText("¿Qué canción está sonando?")
        else:
            self.pregunta.setText("¿Qué artista está tocando?")
        ops = choice(self.salas[nombre]["canciones"], 4, False)
        if self.salas[nombre]["cancion_actual"] not in ops:
            la_buena = randint(0, 3)
            ops[la_buena] = self.salas[nombre]["cancion_actual"]
        print("correcta", self.salas[nombre]["cancion_actual"])
        for i in range(4):
            print(ops[i])
            if pregunta == 0:
                self.opciones[i].setText(ops[i].split("-")[1].strip(".wav"))
            else:
                self.opciones[i].setText(ops[i].split("-")[0].strip(".wav"))
            if ops[i] != self.salas[nombre]["cancion_actual"]:
                self.opciones[i].clicked.connect(partial(self.puntaje, 0))
            else:
                self.opciones[i].clicked.connect(partial(self.puntaje, 1))
            self.opciones[i].hide()
        self.cliente.reproducir(nombre, self.salas[nombre]["cancion_actual"])
        self.boton_volver.clicked.connect(self.volver_sala)
        self.mitimer = QTimer(self)
        self.mitimer.timeout.connect(self.en_sala)
        self.mitimer.start(1000)

    def en_sala(self):
        if self.la_proxima and str(
                self.salas[self.nombre_sala]["tiempo"]) != "0":
            self.cliente.caracteristicas["tiempo"] = "-"
            self.la_proxima = False
            self.la_proxima1 = False
            self.correcto.hide()
            self.cliente.reproducir(
                self.nombre_sala,
                self.salas[self.nombre_sala]["cancion_actual"])
            pregunta = random.randint(0, 1)
            if pregunta == 0:
                self.pregunta.setText("¿Qué canción está sonando?")
            else:
                self.pregunta.setText("¿Qué artista está tocando?")
            ops = choice(self.salas[self.nombre_sala]["canciones"], 4, False)
            if self.salas[self.nombre_sala]["cancion_actual"] not in ops:
                la_buena = randint(0, 3)
                ops[la_buena] = self.salas[self.nombre_sala]["cancion_actual"]
            print("correcta", self.salas[self.nombre_sala]["cancion_actual"])
            for i in range(4):
                print(ops[i])
                if pregunta == 0:
                    self.opciones[i].setText(
                        ops[i].split("-")[1].strip(".wav"))
                else:
                    self.opciones[i].setText(
                        ops[i].split("-")[0].strip(".wav"))
                if ops[i] != self.salas[self.nombre_sala]["cancion_actual"]:
                    self.opciones[i].clicked.disconnect()
                    self.opciones[i].clicked.connect(partial(self.puntaje, 0))
                else:
                    self.opciones[i].clicked.disconnect()
                    self.opciones[i].clicked.connect(partial(self.puntaje, 1))
                self.opciones[i].show()
        if str(self.salas[self.nombre_sala]
               ["tiempo"]) == "0" or self.la_proxima1:
            self.la_proxima = True
        if str(self.salas[self.nombre_sala]["tiempo"]) == "1":
            self.la_proxima1 = True
        for otros in self.otros:
            if self.otros[otros][
                    "sala"] == self.nombre_sala and otros not in self.labels_otros:
                self.labels_otros[otros] = QLabel(self)
                self.labels_otros[otros].setGeometry(650, self.n, 140, 50)
                self.labels_otros[otros].show()
                self.n += 60
        for otros in self.labels_otros:
            if self.otros[otros]["sala"] != self.nombre_sala:
                self.labels_otros[otros].hide()
            self.labels_otros[otros].setText(otros + "\n--> " +
                                             str(self.otros[otros]["puntos"]) +
                                             " puntos\n--> " +
                                             str(self.otros[otros]["tiempo"]))
        self.timer.setText(str(self.salas[self.nombre_sala]["tiempo"]))

    def puntaje(self, a):
        if a == 1:
            self.correcto.setText(
                "Respuesta correcta!\n" +
                str(int(self.salas[self.nombre_sala]["tiempo"]) * 100) +
                " puntos")
            self.cliente.caracteristicas["tiempo"] = self.salas[
                self.nombre_sala]["tiempo"]
            self.cliente.caracteristicas["record"][
                self.nombre_sala]["correctas"] += 1
        else:
            self.cliente.caracteristicas["record"][
                self.nombre_sala]["incorrectas"] += 1
            self.correcto.setText("Respuesta incorrecta..")
        print(self.cliente.caracteristicas["record"][self.nombre_sala])
        self.cliente.puntaje += a * int(
            self.salas[self.nombre_sala]["tiempo"]) * 100
        self.label_puntaje_2.setText("Puntaje: " + str(self.cliente.puntaje))
        self.label_puntaje.setText("Puntaje: " + str(self.cliente.puntaje))
        for i in self.opciones:
            i.hide()
        self.correcto.show()

    def volver_sala(self):
        if self.mitimer:
            self.mitimer.stop()
        self.cliente.sala = "-"
        self.cliente.caracteristicas["tiempo"] = "-"
        self.la_proxima = False
        if self.cancion:
            self.cancion.stop()
        self.correcto.setText("Esperando canción\nsiguiente...")
        self.correcto.show()
        self.n = 150
        for i in self.labels_otros:
            self.labels_otros[i].hide()
        self.labels_otros = {}
        for i in self.botones:
            self.botones[i].show()
        for i in self.labels:
            self.labels[i].show()
        for i in self.opciones:
            i.show()
        for i in self.labels_puntajes:
            for label in self.labels_puntajes[i]:
                label.hide()
        self.stackedWidget.setCurrentIndex(1)

    def abrir_puntajes(self):
        for i in self.botones:
            self.botones[i].hide()
        for i in self.labels:
            self.labels[i].hide()
        self.y = 120
        self.stackedWidget.setCurrentIndex(3)
        self.labels_puntajes = {}
        self.lista = []
        puntajes = []
        for i in self.otros:
            puntajes.append(self.otros[i]["puntos"])
        puntajes.sort(reverse=True)
        print(self.otros)
        for puntaje in puntajes:
            print(puntaje)
            for cliente in self.otros:
                if puntaje == self.otros[cliente]["puntos"]:
                    if cliente not in self.lista:
                        self.lista.append(cliente)
                    if cliente not in self.labels_puntajes:
                        self.labels_puntajes[cliente] = [
                            QLabel(self),
                            QLabel(self),
                            QLabel(self),
                            QLabel(self)
                        ]
                    self.labels_puntajes[cliente][0].setText(cliente)
                    self.labels_puntajes[cliente][1].setText(
                        str(self.otros[cliente]["puntos"]))
                    mejor = []
                    print(self.otros[cliente])
                    for sala in self.otros[cliente]["record"]:
                        mejor.append(
                            self.otros[cliente]["record"][sala]["correctas"])
                    mejor.sort(reverse=True)
                    for lasala in self.otros[cliente]["record"]:
                        if mejor[0] == self.otros[cliente]["record"][lasala][
                                "correctas"]:
                            mejorsala = lasala
                    self.labels_puntajes[cliente][2].setText(mejorsala)
                    peor = []
                    for sala in self.otros[cliente]["record"]:
                        peor.append(
                            self.otros[cliente]["record"][sala]["incorrectas"])
                    peor.sort(reverse=True)
                    for lasala in self.otros[cliente]["record"]:
                        if peor[0] == self.otros[cliente]["record"][lasala][
                                "incorrectas"]:
                            peorsala = lasala
                    self.labels_puntajes[cliente][3].setText(peorsala)
                    #self.lista.append(self.labels_puntajes[cliente])
        print(self.lista)
        for cliente in self.lista:
            self.labels_puntajes[cliente][0].setGeometry(10, self.y, 100, 100)
            self.labels_puntajes[cliente][1].setGeometry(300, self.y, 100, 100)
            self.labels_puntajes[cliente][2].setGeometry(500, self.y, 100, 100)
            self.labels_puntajes[cliente][3].setGeometry(700, self.y, 100, 100)
            self.labels_puntajes[cliente][0].show()
            self.labels_puntajes[cliente][1].show()
            self.labels_puntajes[cliente][2].show()
            self.labels_puntajes[cliente][3].show()
            self.y += 35
Exemple #4
0
class GameWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(GameWindow, self).__init__(parent)
        self.params = ParamsWindow(self)
        self.params.accepted.connect(self.create_lines_widget)
        self.params.show()

        self.connection = Connection()
        self.connection.hints_signal.connect(self.update_hint)

        self.best_score = QtWidgets.QPushButton('Scores', self)

        self.lcd = QtWidgets.QLCDNumber(self)
        self.lcd.setDigitCount(4)

        sound_file = filename = os.path.abspath(
            os.path.join(os.path.dirname(__file__), "Sound.wav"))
        self.player = QSound(sound_file, self)

        self.statusBar()
        self.menu_bar = self.menuBar()

        self.layout = QtWidgets.QGridLayout()
        self.layout.setSpacing(8)
        self.layout.addWidget(self.lcd, 0, 1)

        window = QtWidgets.QWidget()
        window.setLayout(self.layout)
        self.setCentralWidget(window)
        self.setWindowTitle("Lines")
        self.setStyleSheet("background-color: khaki")

    def create_lines_widget(self):
        next_colors = self.params.settings[1]
        self.linesWidget = LinesWidget(*self.params.settings, self)

        self.scores = ScoresDialog(
            (self.params.settings[0][0], self.params.settings[0][1]), self)
        self.scores.scoresWindow.get_scores()
        text = self.scores.scoresWindow.players[0][1] \
            if self.scores.scoresWindow.players else '0'
        self.best_score.setText('Best Score: {}'.format(text))
        self.best_score.clicked.connect(self.scores.show)

        self.hint = HintsWidget(20, next_colors, self)
        self.connection.hints_signal.emit()

        self.layout.addWidget(self.linesWidget, 1, 0, 1, 4)
        self.layout.addWidget(self.hint, 0, 0)
        self.layout.addWidget(self.best_score, 0, 2)

        self.resize(QSize(640, 640))
        self.create_menu()

        self.update_window()
        self.resize(QSize(650, 650))

    def update_window(self):
        self.norm_size = self.linesWidget.width() + 100, \
                         self.linesWidget.height() + 100
        self.setMinimumSize(*self.norm_size)
        self.move(QtWidgets.QApplication.desktop().screen().rect().center() -
                  self.rect().center())
        self.show()

    def resizeEvent(self, event):
        if self.linesWidget:
            param1 = min(event.size().height(), event.size().width())
            param2 = min(self.linesWidget.field.height - 1,
                         self.linesWidget.field.width - 1)
            scale = (param1 - 150 - self.linesWidget.scale) // param2
            self.linesWidget.scale = scale
            self.hint.scale = scale
            self.linesWidget.resize_widget()
            self.hint.resize_widget()
            self.resize(event.size())

    def create_menu(self):
        self.blocker = QtWidgets.QAction('Turn ON Block cells', self)
        hint = QtWidgets.QAction('Show Hint', self)
        scores = QtWidgets.QAction('Show Scores', self)
        self.sound_action = QtWidgets.QAction('Play Music', self)
        scores_cheat = QtWidgets.QAction('Score cheat', self)

        self.blocker.triggered.connect(self.set_blocking_mode)
        hint.triggered.connect(self.switch_hints)
        scores.triggered.connect(self.scores.show)
        self.sound_action.triggered.connect(self.play_music)
        scores_cheat.triggered.connect(
            lambda: self.linesWidget.open_save_scores_dialog(True))

        menu = self.menu_bar.addMenu('Menu')
        menu.addAction(self.blocker)
        menu.addAction(hint)
        menu.addAction(scores)
        menu.addAction(self.sound_action)
        asd = menu.addMenu('Cheats')
        asd.addAction(scores_cheat)

    def set_blocking_mode(self):
        if self.blocker.text() == 'Turn ON Block cells':
            self.linesWidget.blocking = True
            self.blocker.setText('Turn OFF Block cells')
        else:
            self.linesWidget.blocking = False
            self.blocker.setText('Turn ON Block cells')

    def play_music(self):
        if self.player.isFinished():
            self.sound_action.setText('Stop Music')
            self.player.play()
        else:
            self.sound_action.setText('Play Music')
            self.player.stop()

    def update_hint(self):
        self.hint.next_colors = self.linesWidget.field.colors_to_spawn
        self.hint.update()

    def switch_hints(self):
        if self.hint.enabled and \
                        self.linesWidget.field.scores_coefficient != 1:
            self.linesWidget.field.scores_coefficient = 2
            self.hint.enabled = False
        else:
            self.linesWidget.field.scores_coefficient = 1
            self.hint.enabled = True

        self.hint.update()

    def closeEvent(self, *args, **kwargs):
        sys.exit(0)
Exemple #5
0
class Game(QMainWindow):
    width = 10
    height = 22
    shapes = [
        Tetraminoe.ShapeG, Tetraminoe.ShapeLine, Tetraminoe.ShapeReverseG,
        Tetraminoe.ShapeSquare, Tetraminoe.ShapeT, Tetraminoe.ShapeZ,
        Tetraminoe.ShapeReverseZ
    ]

    # window нужна для того, чтобы потом открыть меню
    def __init__(self, window, music_play):
        super().__init__()
        self.window = window
        # Значения окна
        self.setWindowIcon(QIcon('source/img/tetris_icon.png'))
        self.setFixedSize(self.width * 20 + 10 * 2 + 50,
                          (self.height - 2) * 20)
        self.setWindowTitle('Tetris')
        self.score_text = QLabel(self)
        self.score_text.move(205, 350)
        self.level_text = QLabel(self)
        self.level_text.move(205, 325)
        self.pause_status = QLabel(self)
        self.pause_status.move(205, 15)
        self.pause_status.setText('Pause')
        self.pause_status.hide()
        text = QLabel(self)
        text.move(208, 80)
        text.setText('Next Figure')
        # Инициализация очков
        self.score = 0
        self.score_text.setText(f'Lines: {self.score}      ')
        # Уровни
        self.level = 1
        self.speed = (10 - self.level) * 40
        self.level_text.setText(f'Level: {self.level}')
        # Для проверки в дальнейшем
        self.full_string = [2 for _ in range(self.width)]
        self.paused = False
        if music_play:
            self.music = QSound('source/music/music.wav')
            self.music.play()
            self.music.setLoops(self.music.Infinite)
        self.music_play = music_play
        self.start()

    # Старт
    def start(self):
        self.next_shape = choice(self.shapes)()
        # Игровое поле в виде списка
        self.board = [[0 for _ in range(self.width)]
                      for _ in range(self.height)]
        self.timer = QBasicTimer()
        self.add_new_shape()
        self.timer.start(self.speed, self)

    def timerEvent(self, event):
        if 2 in self.board[1]:
            self.game_over()
        elif self.new_shape:
            self.move_down()
        else:
            self.clear_lines()
            self.add_new_shape()

    # Куски кода отвечающие за перемещение фигур.
    # Падение
    def move_down(self):
        break_flag = False
        for y in range(self.bottomY, self.topY - 1, -1):
            for x in range(self.leftX, self.rightX + 1):
                if y >= 21 or self.board[y + 1][x] == 2 and \
                        self.board[y][x] == 1 or \
                        self.board[self.topY + 1][x] == 2 and \
                        self.board[self.topY][x] == 1 or \
                        self.topY + 2 <= 21 and \
                        self.board[self.topY + 2][x] == 2 and \
                        self.board[self.topY + 1][x] == 1:
                    break_flag = True
                    # Если убрать, то мгновенное падение будет работать, но не так как надо
                    self.timer.start(self.speed, self)
                    self.new_shape = False
                    break
            if break_flag:
                for i in range(self.bottomY, self.topY - 1, -1):
                    for j in range(self.leftX, self.rightX + 1):
                        if self.board[i][j] == 1:
                            self.board[i][j] = 2
                break
            for x in range(self.leftX, self.rightX + 1):
                if self.board[y][x] == 1:
                    self.board[y + 1][x] = self.board[y][x]
                    self.board[y][x] = 0
        self.bottomY += 1
        self.topY += 1
        self.update()

    # Движение влево
    def move_left(self):
        if self.leftX > 0 and not self.paused:
            _break = False
            for y in range(self.topY, self.bottomY + 1):
                for x in range(self.leftX, self.rightX + 1):
                    if not self.new_shape or x > 0 and self.board[y][x - 1] == 2 and \
                            self.board[y][x] == 1:
                        _break = True
                        break
                if _break:
                    break

            if not _break:
                for y in range(self.topY, self.bottomY + 1):
                    for x in range(self.leftX, self.rightX + 1):
                        if x > 0 and self.board[y][
                                x - 1] == 0 and self.board[y][x] == 1:
                            self.board[y][x - 1] = self.board[y][x]
                            self.board[y][x] = 0
                self.leftX -= 1
                self.rightX -= 1
                self.update()

    # Движение вправо
    def move_right(self):
        if self.rightX < self.width - 1 and not self.paused:
            _break = False
            for y in range(self.topY, self.bottomY + 1):
                for x in range(self.rightX, self.leftX - 1, -1):
                    if not self.new_shape or self.board[y][x + 1] == 2 and \
                            self.board[y][x] == 1:
                        _break = True
                        break
                if _break:
                    break

            if not _break:
                for y in range(self.topY, self.bottomY + 1):
                    for x in range(self.rightX, self.leftX - 1, -1):
                        if self.board[y][x + 1] == 0 and self.board[y][x] == 1:
                            self.board[y][x + 1] = self.board[y][x]
                            self.board[y][x] = 0
                self.leftX += 1
                self.rightX += 1
                self.update()

    # Поворот
    def rotate(self):
        if self.new_shape and not self.paused:
            rotated_shape = []
            can_rotate = True
            for x in range(self.rightX, self.leftX - 1, -1):
                rotated_shape.append([])
                for y in range(self.topY, self.bottomY + 1):
                    if self.board[y][x] == 2:
                        rotated_shape[-1].append(0)
                    else:
                        rotated_shape[-1].append(self.board[y][x])
            for y in range(len(rotated_shape)):
                for x in range(len(rotated_shape[y])):
                    if (self.topY + y > 21 or self.leftX + x > 9) or \
                            self.board[self.topY + y][self.leftX + x] == 2 and \
                            rotated_shape[y][x] != 0:
                        can_rotate = False
            if can_rotate:
                for y in range(self.topY, self.bottomY + 1):
                    for x in range(self.leftX, self.rightX + 1):
                        if self.board[y][x] == 1:
                            self.board[y][x] = 0
                for y in range(len(rotated_shape)):
                    for x in range(len(rotated_shape[y])):
                        if rotated_shape[y][x] == 1:
                            self.board[self.topY + y][self.leftX +
                                                      x] = rotated_shape[y][x]
                self.bottomY = self.topY + len(rotated_shape) - 1
                self.rightX = self.leftX + len(rotated_shape[-1]) - 1
                self.update()

    # Мгновенное падение
    def fast_move(self):
        if not self.paused:
            self.timer.start(0, self)

    # Конец куска кода с методами перемещения фигур

    # Добавление новой фигуры на экран
    def add_new_shape(self):
        # Определяем фигуру
        self.active_shape = self.next_shape
        self.next_shape = choice(self.shapes)()
        # Добавляем ее на поле
        for i in range(self.active_shape.get_height()):
            for j in range(self.active_shape.get_width()):
                self.board[i][4 + j] = self.active_shape.shape[i][j]
        # Координаты фигуры
        self.topY, self.bottomY = 0, self.active_shape.get_height() - 1
        self.rightX, self.leftX = self.active_shape.get_width() + 3, 4
        self.new_shape = True

    # Очищение заполненных линий, начисление очков, уровней
    def clear_lines(self):
        while self.full_string in self.board:
            string = self.board.index(self.full_string)
            self.board[1:string + 1] = self.board[0:string]
            self.board[0] = [0 for _ in range(self.width)]
            self.score += 1
            if self.level < 9 and self.score % 10 == 0:
                self.level += 1
                self.level_text.setText(f'Level: {self.level}')
                self.speed = (10 - self.level) * 40
                self.timer.start(self.speed, self)
            self.score_text.setText(f'Lines: {self.score}')

    # Пауза
    def pause(self):
        self.paused = not self.paused
        if self.paused:
            self.pause_status.show()
            self.timer.stop()
        else:
            self.pause_status.hide()
            self.timer.start(self.speed, self)

    # Отрисовщик
    def paintEvent(self, event):
        self.painter = QPainter()
        self.painter.begin(self)
        self.draw_grid(self.painter, QColor(255, 255, 255))
        self.draw_next_figure(self.painter)
        self.draw_board(self.painter)
        self.painter.end()

    # Метод, отрисовывающий список board
    def draw_board(self, painter):
        for i in range(2, len(self.board)):
            for j in range(len(self.board[i])):
                if self.board[i][j] != 0:
                    color1 = QColor(255, 255, 255)
                    color2 = QColor(255, 255, 255)
                    color1.setNamedColor('#000000')
                    if self.board[i][j] == 1:
                        color2.setNamedColor('#f3ca20')
                    elif self.board[i][j] == 2:
                        color2.setNamedColor('#808080')
                    self.draw_square(painter, color1, 20 * j, 20 * i - 40, 20)
                    self.draw_square(painter, color2, 2 + 20 * j,
                                     2 + 20 * i - 40, 16)

    # Метод рисования квадрата
    @staticmethod
    def draw_square(painter, color, x, y, size):
        painter.setBrush(color)
        painter.drawRect(x, y, size, size)

    # Метод рисования сетки
    def draw_grid(self, painter, color):
        painter.setBrush(color)
        for x in range(0, self.width * 20 + 1, 20):
            painter.drawLine(x, 0, x, self.height * 20)
        for y in range(0, self.height * 20 + 1, 20):
            painter.drawLine(0, y, self.width * 20, y)

    # Метод отрисовки следующей фигуры
    def draw_next_figure(self, painter):
        for string in range(len(self.next_shape.shape)):
            for block in range(len(self.next_shape.shape[string])):
                if self.next_shape.shape[string][block] == 1:
                    self.draw_square(painter, QColor(255, 215, 0),
                                     212 + 14 * block, 50 + 14 * string, 14)

    # Проигрыш
    def game_over(self):
        self.timer.stop()
        if self.music_play:
            self.music.stop()
        game_over_dialogue = GameOver.GameOver(self.score, self.level)
        game_over_dialogue.exec()
        self.close()

    # Что делать при закрытии программы
    def closeEvent(self, event):
        self.window.show()
        if self.music_play:
            self.music.stop()
        self.close()

    # Обработчик нажатий клавиш
    def keyPressEvent(self, event):
        key1 = event.nativeVirtualKey()
        key = event.key()

        if key == Qt.Key_Down or key1 == Qt.Key_S:
            self.fast_move()
        elif key == Qt.Key_Left or key1 == Qt.Key_A:
            self.move_left()
        elif key == Qt.Key_Right or key1 == Qt.Key_D:
            self.move_right()
        elif key == Qt.Key_Up or key1 == Qt.Key_W:
            self.rotate()
        elif key == Qt.Key_Space:
            self.pause()
Exemple #6
0
class PredictionPopup(QtWidgets.QWidget):
    def __init__(self, path):
        QtWidgets.QWidget.__init__(self)
        self.path = path
        self.setWindowTitle("Prediction for " + path)
        self.setWindowIcon(QtGui.QIcon('logo.png'))

        self.showOutput()

    def showPopup(self, message):
        QtWidgets.QMessageBox.about(self, "Hello there", message)

    def showOutput(self):
        self.layout = QtWidgets.QVBoxLayout(self)
        self.layout.setAlignment(QtCore.Qt.AlignCenter)

        self.label = QtWidgets.QLabel(self)
        self.png = [
            os.path.join(self.path, x) for x in os.listdir(self.path)
            if x.startswith("predict_sheet")
        ]
        print(self.png)

        self.i = 0
        self.pageCountLabel = QtWidgets.QLabel(self)
        self.pageCountLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.pageCountLabel.setText("{0}/{1}".format(self.i + 1,
                                                     len(self.png)))

        self.pixMap = QtGui.QPixmap(self.png[0])
        self.label.setPixmap(self.pixMap)

        # page scrolling layout
        self.btnLayout = QtWidgets.QHBoxLayout(self)
        self.btn1 = QtWidgets.QPushButton("<", self)
        self.btn1.clicked.connect(self.goLeft)
        self.btn2 = QtWidgets.QPushButton(">", self)
        self.btn2.clicked.connect(self.goRight)

        self.btn1.resize(10, 10)
        self.btn2.resize(10, 10)

        # audio playing layout
        self.btnPlay = QtWidgets.QPushButton("Play", self)
        self.btnPlay.clicked.connect(self.playPredict)
        self.btnStop = QtWidgets.QPushButton("Stop", self)
        self.btnStop.clicked.connect(self.stopPredict)

        self.btnPlay.resize(10, 10)
        self.btnStop.resize(10, 10)

        self.audioLayout = QtWidgets.QHBoxLayout(self)

        self.audioLayout.setAlignment(QtCore.Qt.AlignCenter)
        self.audioW = QtWidgets.QWidget(self)
        self.audioLayout.addWidget(self.btnPlay)
        self.audioLayout.addWidget(self.btnStop)
        self.audioW.setLayout(self.audioLayout)

        self.btnLayout.setAlignment(QtCore.Qt.AlignCenter)
        self.w = QtWidgets.QWidget(self)
        self.btnLayout.addWidget(self.btn1)
        self.btnLayout.addWidget(self.btn2)
        self.w.setLayout(self.btnLayout)

        self.layout.addWidget(self.audioW)
        self.layout.addWidget(self.w)
        self.layout.addWidget(self.pageCountLabel)
        self.layout.addWidget(self.label)

        self.setLayout(self.layout)

        self.sound = QSound(os.path.join(self.path, "predict.wav"))
        self.show()

    def goLeft(self):
        if self.i == 0:
            self.showPopup("You're already at the first page")
            return

        self.i -= 1
        self.refreshSheet()

    def goRight(self):
        if self.i == len(self.png) - 1:
            self.showPopup("You're already at the last page")
            return

        self.i += 1
        self.refreshSheet()

    def refreshSheet(self):
        self.pageCountLabel.setText("{0}/{1}".format(self.i + 1,
                                                     len(self.png)))
        self.pixMap = QtGui.QPixmap(self.png[self.i])
        self.label.setPixmap(self.pixMap)

    def playPredict(self):
        self.sound.play()

    def stopPredict(self):
        self.sound.stop()
Exemple #7
0
class MainWindow(QMainWindow):
    """Main application class for Crocpad++."""
    def __init__(self, ctx: ApplicationContext, app: QApplication, *args,
                 **kwargs):
        """Set up the single instance of the application."""
        super(MainWindow, self).__init__(*args, **kwargs)
        self.app = app
        self.ctx = ctx

        # Set up the QTextEdit editor configuration
        self.text_window = QPlainTextEdit()  # the actual editor pane
        self.text_window.setTabStopWidth(
            800)  # Set the tabstop to a nice pretty 800 pixels
        fixed_font = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        fixed_font.setPointSize(24)
        self.text_window.setFont(QFont('Comic Sans MS', 30))
        self.text_window.installEventFilter(self)
        click_sound = self.ctx.get_resource('sounds/click.wav')
        self.sound = QSound(click_sound)
        enter_sound = self.ctx.get_resource('sounds/scream.wav')
        self.enter_sound = QSound(enter_sound)
        backspace_sound = self.ctx.get_resource('sounds/wrong.wav')
        self.backspace_sound = QSound(backspace_sound)

        # Main window layout. Most of the dialogs in Crocpad++ are converted to .py from
        # Qt Designer .ui files in the ui/ directory, but the main app window is built here.
        layout = QVBoxLayout()
        layout.addWidget(self.text_window)
        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)
        self.status = QStatusBar()
        self.setStatusBar(self.status)

        # Update title and centre window
        self.filename = "** Untitled **"
        self.setGeometry(50, 50, 800, 600)
        rectangle = self.frameGeometry()
        center_point = QDesktopWidget().availableGeometry().center()
        rectangle.moveCenter(center_point)
        self.move(rectangle.topLeft())
        window_icon = self.ctx.get_resource('crocpad.ico')
        self.setWindowIcon(QIcon(window_icon))
        self.create_menus()
        styles = {
            'light': crocpad.stylesheets.light,
            'dark': crocpad.stylesheets.dark,
            'hotdogstand': crocpad.stylesheets.hotdogstand,
            'quitedark': crocpad.stylesheets.quitedark
        }
        self.app.setStyleSheet(styles[app_config['Editor']['visualmode']])
        self.show()

        # Post-startup tasks
        if app_config['License']['eulaaccepted'] != 'yes':
            self.do_eula()
        self.show_tip()  # tip of the day
        if app_config['Editor']['linewrap'] == 'off':
            self.text_window.setLineWrapMode(0)
            self.wrap_action.setChecked(False)

    def create_menus(self):
        """Build the menu structure for the main window."""
        main_menu = self.menuBar()
        help_menu = main_menu.addMenu('H&elp')
        view_menu = main_menu.addMenu('Vi&ew')
        file_menu = main_menu.addMenu('R&ecent Files')
        edit_menu = main_menu.addMenu('&Edit')
        search_menu = main_menu.addMenu('S&earch')
        tools_menu = main_menu.addMenu('Sp&ecial Tools')

        # Help menu
        action_tip = QAction("Tip of th&e Day", self)
        action_tip.triggered.connect(self.show_tip)
        help_menu.addAction(action_tip)

        # View menu
        theme_menu = view_menu.addMenu("Th&emes")
        action_light_theme = QAction("Light mod&e", self)
        action_light_theme.triggered.connect(self.set_light_theme)
        theme_menu.addAction(action_light_theme)
        action_dark_theme = QAction("Dark mod&e", self)
        action_dark_theme.triggered.connect(self.set_dark_theme)
        theme_menu.addAction(action_dark_theme)
        accessibility_menu = view_menu.addMenu("Acc&essibility")
        action_hotdogstand_theme = QAction("High visibility th&eme", self)
        action_hotdogstand_theme.triggered.connect(self.set_hotdogstand_theme)
        accessibility_menu.addAction(action_hotdogstand_theme)
        action_quitedark_theme = QAction("Th&eme for blind users", self)
        action_quitedark_theme.triggered.connect(self.set_quitedark_theme)
        accessibility_menu.addAction(action_quitedark_theme)

        # Special Tools menu
        font_menu = QAction("Chang&e font", self)
        font_menu.triggered.connect(self.change_font)
        tools_menu.addAction(font_menu)
        self.wrap_action = QAction("Lin&e wrap",
                                   self)  # class attribute so we can toggle it
        self.wrap_action.setCheckable(True)
        self.wrap_action.setChecked(True)
        self.wrap_action.triggered.connect(self.toggle_wrap)
        tools_menu.addAction(self.wrap_action)
        self.sound_action = QAction("Sound &effects", self)
        self.sound_action.setCheckable(True)
        self.sound_action.setChecked(True if app_config['Sound']['sounds'] ==
                                     'on' else False)
        self.sound_action.triggered.connect(self.toggle_sound)
        tools_menu.addAction(self.sound_action)

        # Edit menu
        action_insert_symbol = QAction("Ins&ert symbol", self)
        action_insert_symbol.triggered.connect(self.insert_emoji)
        edit_menu.addAction(action_insert_symbol)
        action_open_settings = QAction("Op&en settings file", self)
        action_open_settings.triggered.connect(self.open_settings)
        edit_menu.addAction(action_open_settings)

        # Search menu
        action_open = QAction("S&earch for file to open", self)
        action_open.triggered.connect(self.open_file)
        search_menu.addAction(action_open)
        action_save = QAction("S&earch for file to save", self)
        action_save.triggered.connect(self.save_file)
        search_menu.addAction(action_save)
        action_new = QAction("S&earch for a new file", self)
        action_new.triggered.connect(self.new_file)
        search_menu.addAction(action_new)

        # SubMenu Test
        testmenu = []
        for i in range(0, 200):
            testmenu.append(file_menu.addMenu(f'{i}'))

    def do_eula(self):
        """Display the End-User License Agreement and prompt the user to accept."""
        eula_file = self.ctx.get_resource('EULA.txt')
        with open(eula_file, 'r', encoding='utf8') as f:
            eula = f.read()
        eula_dialog = EulaDialog(self.ctx, eula)
        eula_quiz_dialog = EulaQuizDialog(self.ctx)
        # run the EULA quiz, to make sure they read and understand
        while not eula_quiz_dialog.quiz_correct():
            eula_dialog.exec_(
            )  # exec_ makes dialog modal (user cannot access main window)
            eula_quiz_dialog.exec_()

    def show_tip(self):
        """Randomly choose one tip of the day and display it."""
        tips_file = self.ctx.get_resource('tips.txt')
        with open(tips_file, 'r', encoding='utf8') as f:
            tips = f.readlines()
        tip = random.choice(tips)
        dlg = QMessageBox(self)
        dlg.setWindowTitle("Tip of the Day")
        dlg.setText(tip.strip())
        dlg.setIcon(QMessageBox.Information)
        dlg.show()

    def change_font(self):
        """Prompt the user for a font to change to."""
        # Do the users REEEEEALY need to change font :D
        font, ok = QFontDialog.getFont()
        if ok:
            print(font.toString())

    def eventFilter(self, source: QObject, event: QEvent) -> bool:
        """Override the eventFilter method of QObject to intercept keystrokes."""
        if event.type() == QEvent.KeyPress:
            if app_config['Sound']['sounds'] == 'on':
                if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
                    self.sound.stop()
                    self.enter_sound.play()
                if event.key() == Qt.Key_Backspace:
                    self.sound.stop()
                    self.backspace_sound.play()
                else:
                    self.sound.play()
            if event.key(
            ) == Qt.Key_Space:  # prank user with instant disappearing dialog
                if random.random() > 0.8:
                    dlg = QMessageBox(self)
                    dlg.setWindowTitle("Are you sure?")
                    dlg.setText("_" * 100)
                    dlg.show()
                    dlg.close()
            if random.random() > 0.97:
                troubleshooter = Troubleshooter(
                    self.ctx)  # pester the user with a troubleshooter
                troubleshooter.exec()
        return False  # imitate overridden method

    @property
    def filename(self):
        """Return the name of the current file being edited."""
        return self._filename

    @filename.setter
    def filename(self, name: str):
        """Update the title of the main window when filename changes."""
        self._filename = name
        self.setWindowTitle(f"Crocpad++ - {self.filename}")

    def toggle_wrap(self):
        """Toggle the line wrap flag in the text editor."""
        self.text_window.setLineWrapMode(not self.text_window.lineWrapMode())
        if self.text_window.lineWrapMode():
            app_config['Editor']['linewrap'] = 'on'
        else:
            app_config['Editor']['linewrap'] = 'off'
        save_config(app_config)

    def toggle_sound(self):
        """Toggle the sound effects flag."""
        if app_config['Sound']['sounds'] == 'off':
            app_config['Sound']['sounds'] = 'on'
        else:
            app_config['Sound']['sounds'] = 'off'
        save_config(app_config)

    def open_file(self):
        """Ask the user for a filename to open, and load it into the text editor.

        Called by the Open File menu action."""
        filename = QFileDialog.getOpenFileName()[0]
        if filename != '':
            with open(filename, 'r', encoding='utf-8') as file:
                self.text_window.setPlainText(file.read())
            self.filename = filename

    def save_file(self):
        """Ask the user for a filename to save to, and write out the text editor.

        Called by the Save File menu action."""
        filename = QFileDialog.getSaveFileName()[0]
        if filename != '':
            text = self.text_window.document().toPlainText()
            with open(filename, 'w', encoding='utf-8') as file:
                file.write(text)
            self.filename = filename

    def new_file(self):
        """Clear the text editor and insert a helpful message.

        Called by the New File menu action."""
        self.filename = "** Untitled **"
        self.text_window.document().clear()
        self.text_window.insertPlainText(
            """To remove this message, please make sure you have entered
your full credit card details, made payable to:
Crocpad++ Inc
PO BOX 477362213321233
Cheshire Cheese
Snekland
Australia""")

    def open_settings(self):
        settings_file = 'notepad.ini'
        with open(settings_file, 'r', encoding='utf-8') as file:
            self.text_window.setPlainText(file.read())
        self.filename = settings_file

    def set_light_theme(self):
        """Set the text view to the light theme."""
        self.app.setStyleSheet(crocpad.stylesheets.light)
        app_config['Editor']['visualmode'] = 'light'
        save_config(app_config)

    def set_dark_theme(self):
        """Set the text view to the dark theme."""
        self.app.setStyleSheet(crocpad.stylesheets.dark)
        app_config['Editor']['visualmode'] = 'dark'
        save_config(app_config)

    def set_hotdogstand_theme(self):
        """Set the text view to the High Contrast theme."""
        self.app.setStyleSheet(crocpad.stylesheets.hotdogstand)
        app_config['Editor']['visualmode'] = 'hotdogstand'
        save_config(app_config)

    def set_quitedark_theme(self):
        """Set the text view to the Quite Dark theme for the legally blind."""
        self.app.setStyleSheet(crocpad.stylesheets.quitedark)
        app_config['Editor']['visualmode'] = 'quitedark'
        save_config(app_config)

    def insert_emoji(self):
        """Open a modal EmojiPicker dialog which can insert arbitrary symbols at the cursor."""
        picker = EmojiPicker(self.text_window.textCursor())
        picker.exec_()
Exemple #8
0
class MainWindow(DATA[0], DATA[1]):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.scrollArea.hide()
        self.label_6.hide()
        self.pushButton.clicked.connect(self.iniciar_sesion)
        self.setWindowTitle("PrograPop")
        self.scrollArea_2.hide()
        self.label_tiempo = QLabel("20", self)
        self.label_tiempo.move(500, 300)
        self.label_tiempo.resize(100,100)
        self.label_tiempo.setFont(QFont("SansSerif", 20))
        self.label_tiempo.hide()
        self.song_name = None
        self.song = None
        self.salas = [{"name": "Recibiendo Canciones, pulsa actualizar!", "usuarios":[], "artistas": "None", "tiempo_restante": 0}]
        self.a = 0
        self.chat = QListWidget(self)
        self.chat.resize(1000, 300)
        self.chat.move(30,370)
        self.chat.hide()
        self.puntajes = None
        self.login = False


    def iniciar_sesion(self):
        self.name = self.lineEdit.text()
        self.setWindowTitle("PrograPop ({})".format(self.name))
        self.usuario_back = BE_Client.Client_Back(self)
        while not self.login:
            pass
        time.sleep(2)
        self.usuario_back.get_salas()
        time.sleep(2)
        self.usuario_back.get_info()
        time.sleep(0.2)
        self.label_6.setText("Bienvenido {}\nTienes {} puntos".format(self.name, self.usuario_back.puntos))
        self.label_6.show()
        self.lineEdit.hide()
        self.label_2.hide()
        self.pushButton.hide()
        self.titulo.setText("Elige una Sala")
        self.label_inferior = QLabel("Haz click sobre una sala para ingresar", self)
        self.label_inferior.move(500,200)
        self.label_inferior.show()

        self.lista_items = QListWidget(self)

        for item in self.salas:
            self.lista_items.addItem("Sala : {}, Usuarios: {}, artistas: {}, tº restante: {}".format(item["name"],
                                                                                    len(item["usuarios"]), item["artistas"], item["tiempo_restante"]))

        self.lista_items.show()
        self.lista_items.resize(600,200)
        self.lista_items.move(300,200)

        self.lista_items.itemClicked.connect(self.conectarse_sala)
        self.actualizar = QPushButton("Actualizar", self)
        self.actualizar.move(1000, 100)
        self.actualizar.show()
        self.actualizar.clicked.connect(self.actualizar_salas)

        self.tabla_de_puntos = QPushButton("Tabla de puntajes", self)
        self.tabla_de_puntos.move(40, 600)
        self.tabla_de_puntos.resize(200,20)
        self.tabla_de_puntos.show()
        self.tabla_de_puntos.clicked.connect(self.puntos_dialog)

    def conectarse_sala(self, item):

        self.label_inferior.hide()
        self.tabla_de_puntos.hide()
        self.lista_items.hide()
        name = item.text().split(",")[0].split(":")[1].replace(" ", "")

        self.sala_actual = name
        self.usuario_back.connect_sala(name)

        self.usuario_back.get_info()
        self.scrollArea.hide()
        self.titulo.setText(name)
        self.label_6.hide()
        self.actualizar.hide()
        self.volver = QPushButton("Salir", self)
        self.volver.move(30, 30)
        self.volver.clicked.connect(self.volver_menu)
        self.volver.show()

        # Tabla de puntajes

        self.tabla_puntajes_sala = QListWidget(self)
        self.tabla_puntajes_sala.resize(200, 100)
        self.tabla_puntajes_sala.move(930, 200)
        self.tabla_puntajes_sala.addItem("Puntajes")
        self.tabla_puntajes_sala.show()

        # CHAT

        self.chat.show()
        self.chat.addItem("Chat")
        self.line_chat = QLineEdit(self)
        self.line_chat.move(40, 690)
        self.line_chat.resize(1000, 30)
        self.chatButton = QPushButton("Enviar", self)
        self.chatButton.move(1050, 690)
        self.chatButton.show()
        self.line_chat.show()
        self.chatButton.clicked.connect(self.enviar_mensaje)

        # Tabla de tiempos

        self.sala_tabla = QListWidget(self)
        self.sala_tabla.resize(200,100)
        self.sala_tabla.move(930,30)
        self.sala_tabla.addItem("Tiempos")
        self.sala_tabla.show()


        # Juego
        self.opcion1 = QPushButton("opcion1", self)
        self.opcion2 = QPushButton("opcion2", self)
        self.opcion3 = QPushButton("opcion3 ", self)



        self.opcion1.move(30, 200)
        self.opcion2.move(400, 200)
        self.opcion3.move(700, 200)

        self.opcion1.resize(200,30)
        self.opcion2.resize(200, 30)
        self.opcion3.resize(200, 30)

        self.opcion1.clicked.connect(self.opcion_selecta)
        self.opcion2.clicked.connect(self.opcion_selecta)
        self.opcion3.clicked.connect(self.opcion_selecta)

        while self.sala_actual != None:
            while not self.song_name:
                pass
            self.song = QSound(self.song_name)
            self.song_name = None
            self.song.play()
            self.label_tiempo.show()
            self.opcion1.show()
            self.opcion2.show()
            self.opcion3.show()
            QTest.qWait(1000)
            QTest.qWait(1000)
            self.label_tiempo.setText("19")
            QTest.qWait(1000)
            self.label_tiempo.setText("19")
            QTest.qWait(1000)
            self.label_tiempo.setText("17")
            QTest.qWait(1000)
            self.label_tiempo.setText("16")
            QTest.qWait(1000)
            self.label_tiempo.setText("15")
            QTest.qWait(1000)
            self.label_tiempo.setText("14")
            QTest.qWait(1000)
            self.label_tiempo.setText("13")
            QTest.qWait(1000)
            self.label_tiempo.setText("12")
            QTest.qWait(1000)
            self.label_tiempo.setText("11")
            QTest.qWait(1000)
            self.label_tiempo.setText("10")
            QTest.qWait(1000)
            self.label_tiempo.setText("9")
            QTest.qWait(1000)
            self.label_tiempo.setText("8")
            QTest.qWait(1000)
            self.label_tiempo.setText("7")
            QTest.qWait(1000)
            self.label_tiempo.setText("6")
            QTest.qWait(1000)
            self.label_tiempo.setText("5")
            QTest.qWait(1000)
            self.label_tiempo.setText("4")
            QTest.qWait(1000)
            self.label_tiempo.setText("3")
            QTest.qWait(1000)
            self.label_tiempo.setText("2")
            QTest.qWait(1000)
            self.label_tiempo.setText("1")
            QTest.qWait(1000)
            self.opcion1.hide()
            self.opcion2.hide()
            self.opcion3.hide()
            self.sala_tabla.clear()
            self.sala_tabla.addItem("Tiempos")
            self.label_tiempo.hide()
            self.label_tiempo.setText("20")
            self.chat.addItem("Server: Preparate para la siguiente ronda")
            self.song.stop()
            QTest.qWait(1000)

    def actualizar_salas(self):
        self.lista_items.clear()
        self.usuario_back.get_salas()
        time.sleep(0.2)
        for item in self.salas:
            self.lista_items.addItem("Sala : {}, Usuarios: {}, artistas: {}, tº restante : {}".format(item["name"],
                                                                                    len(item["usuarios"]),
                                                                                    item["artistas"], item["tiempo_restante"]))
    def volver_menu(self):
        self.tabla_puntajes_sala.clear()
        self.tabla_puntajes_sala.addItem("Puntajes")
        self.tabla_puntajes_sala.hide()
        self.sala_tabla.clear()
        self.sala_tabla.hide()
        self.tabla_de_puntos.show()
        self.chat.clear()
        self.chat.hide()
        self.usuario_back.get_salas()
        time.sleep(0.2)
        self.usuario_back.disconnect_sala(self.sala_actual)
        time.sleep(0.2)
        self.usuario_back.get_info()
        time.sleep(0.2)
        self.sala_actual = None
        self.song.stop()
        self.titulo.setText("Elige una Sala")
        self.label_6.setText("Bienvenido {}\nTienes {} puntos".format(self.name, self.usuario_back.puntos))
        self.label_6.show()
        self.label.setText("Nombre: {} - Usuarios : {} - Artistas : {}"
                           .format(self.salas[0]["name"], len(self.salas[0]["usuarios"]), self.salas[0]["artistas"]))
        self.lista_items.show()
        self.actualizar.show()
        self.volver.hide()
        self.line_chat.hide()
        self.chatButton.hide()
        self.scrollArea_2.hide()

        self.opcion1.hide()
        self.opcion2.hide()
        self.opcion3.hide()

    def enviar_mensaje(self):
        mensaje = self.line_chat.text()
        self.line_chat.setText("")
        self.usuario_back.chat(mensaje, self.sala_actual)

    def opcion_selecta(self):
        boton = self.sender()
        self.opcion1.hide()
        self.opcion2.hide()
        self.opcion3.hide()
        self.usuario_back.desicion(boton.text())

    def puntos_dialog(self):
        dialog = QDialog(self)
        dialog.resize(500,500)
        tabla1 = QListWidget(dialog)
        tabla1.resize(150,400)
        tabla1.move(20,20)
        tabla1.addItem("Tabla de Puntajes")
        dialog.setWindowTitle("Puntajes - Presiona Esc para salir")

        self.usuario_back.get_puntajes()
        while not self.puntajes:
            pass
        for item in self.puntajes:
            tabla1.addItem("{} : {} puntos".format(item[0], item[1]))
        tabla1.show()

        label_facil = QLabel("Sala mas facil : {}".format(self.sala_facil), dialog)
        label_dificil = QLabel("Sala mas dificl: {}".format(self.sala_dificl), dialog)

        label_dificil.move(300,50)
        label_facil.move(300, 250)
        label_dificil.show()
        label_facil.show()
        dialog.show()
class VentanaInicio(ventana_principal, QtClass):

    send_info = core.pyqtSignal(dict)
    close_window = core.pyqtSignal(bool)

    def __init__(self, cliente):
        super().__init__()
        self.setupUi(self)
        self.init_widgets()
        self.cliente = cliente
        self.send_info.connect(self.cliente.send)
        self.close_window.connect(self.cliente.close_mm)
        self.WindowSwitcher.setCurrentIndex(0)
        self.soundtrack = QSound('black_core.wav')
        self.soundtrack.play()
        self.show()

    def init_widgets(self):
        self.IngresarButton.clicked.connect(self.next_page)
        self.RegistrarseButton.clicked.connect(self.to_registrar)
        self.CreditosButton.clicked.connect(self.to_creditos)
        self.VolverButtonLogIn.clicked.connect(self.main_page)
        self.VolverButtonSignIn.clicked.connect(self.main_page)
        self.VolverButtonCreditos.clicked.connect(self.main_page)
        self.SiguienteButtonCreditos.clicked.connect(self.main_page)
        self.SiguienteButtonSignIn.clicked.connect(self.sign_in_checker)
        self.SiguienteButtonLogIn.clicked.connect(self.log_in_checker)
        self.SalirButton.clicked.connect(sys.exit)

    def clear_inputs(self):
        self.InputUsuarioLogIn.setText('')
        self.InputClaveLogIn.setText('')
        self.InputUsuarioSignIn.setText('')
        self.ErrorDisplayerLogIn.setText('')
        self.InputClaveSignIn.setText('')
        self.InputConfirmarClaveSignIn.setText('')
        self.ErrorDisplayerSignIn.setText('')

    def to_registrar(self):
        self.WindowSwitcher.setCurrentIndex(2)

    def to_creditos(self):
        self.WindowSwitcher.setCurrentIndex(3)

    def next_page(self):
        page = self.WindowSwitcher.currentIndex()
        if self.WindowSwitcher.count() - 1 < page + 1:
            page = -1
        self.WindowSwitcher.setCurrentIndex(page + 1)

    def main_page(self):
        self.WindowSwitcher.setCurrentIndex(0)
        self.clear_inputs()

    def sign_in_checker(self):
        input_usuario = self.InputUsuarioSignIn.text()
        input_clave = self.InputClaveSignIn.text()
        input_clave_confirm = self.InputConfirmarClaveSignIn.text()
        nuevo_usuario = self.InputUsuarioSignIn.text()
        if input_clave != input_clave_confirm:
            self.ErrorDisplayerSignIn.setText('La clave no es la misma')
        else:
            msg = { "type" : "sign_in", \
                    "username" : nuevo_usuario, \
                    "clave" : input_clave}
            self.send_info.emit(msg)

    def log_in_checker(self):
        usuario = self.InputUsuarioLogIn.text()
        clave = self.InputClaveLogIn.text()
        msg = { "type" : "log_in", \
                "username" : usuario, \
                "clave" : clave}
        self.send_info.emit(msg)

    def update_display(self, msg):
        if msg["place"] == "sign_in":
            self.ErrorDisplayerSignIn.setText(msg["info"])
        elif msg["place"] == "log_in":
            self.ErrorDisplayerLogIn.setText(msg["info"])
            if "Bienvenido" in msg["info"]:
                self.close_window.emit(True)
                self.hide()
                self.soundtrack.stop()
            # widgets.qApp.quit()

    def keyPressEvent(self, event):
        if event.key() == core.Qt.Key_Return:
            if self.WindowSwitcher.currentIndex() == 1:
                if  self.InputUsuarioLogIn.text() != '' and \
                    self.InputClaveLogIn.text() != '':
                    self.log_in_checker()
            elif self.WindowSwitcher.currentIndex() == 2:
                if  self.InputUsuarioSignIn.text() != '' and \
                    self.InputClaveSignIn.text() != '' and \
                    self.InputConfirmarClaveSignIn.text() != '':
                    self.sign_in_checker()

    def mouseMoveEvent(self, event):
        pass
class Ui_Printing(object):
    def __init__(self, change_screen):
        self.change_screen = change_screen
        self.sound_effect = QSound(":/sounds/3d printer sounds.wav")
        self.playing = False

    def toggle_sound_effect(self):
        if self.sound_effect.isFinished(): self.playing = False

        if not self.playing:
            self.sound_effect.play()
            self.playing = True
        else:
            self.sound_effect.stop()
            self.playing = False

    def stop_sound_effect(self):
        if self.playing:
            self.sound_effect.stop()
        self.playing = False

    def add_buttons(self):
        self.pushButton.clicked.connect(lambda: self.change_screen.open_uses())
        self.pushButton.clicked.connect(lambda: self.stop_sound_effect())

        self.pushButton_2.clicked.connect(
            lambda: self.change_screen.open_plastics())
        self.pushButton_2.clicked.connect(lambda: self.stop_sound_effect())

        self.pushButton_3.clicked.connect(lambda: self.toggle_sound_effect())

    def setupUi(self, Printing):
        Printing.setObjectName("Printing")
        Printing.resize(402, 300)
        self.verticalLayout = QtWidgets.QVBoxLayout(Printing)
        self.verticalLayout.setObjectName("verticalLayout")
        self.label = QtWidgets.QLabel(Printing)
        #       self.label.setPixmap(QtGui.QPixmap(":/sounds/3d printer sounds.wav"))
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setWordWrap(True)
        self.label.setObjectName("main_label")
        self.verticalLayout.addWidget(self.label)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setContentsMargins(20, 20, 20, 20)
        self.horizontalLayout.setSpacing(50)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton = QtWidgets.QPushButton(Printing)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.pushButton_2 = QtWidgets.QPushButton(Printing)
        self.pushButton_2.setEnabled(True)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout.addWidget(self.pushButton_2)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        spacerItem = QtWidgets.QSpacerItem(40, 20,
                                           QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem)
        self.pushButton_3 = QtWidgets.QPushButton(Printing)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.pushButton_3.sizePolicy().hasHeightForWidth())
        self.pushButton_3.setSizePolicy(sizePolicy)
        self.pushButton_3.setObjectName("pushButton_3")
        self.horizontalLayout_2.addWidget(self.pushButton_3)
        spacerItem1 = QtWidgets.QSpacerItem(40, 20,
                                            QtWidgets.QSizePolicy.Expanding,
                                            QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem1)
        self.verticalLayout.addLayout(self.horizontalLayout_2)

        self.retranslateUi(Printing)
        self.add_buttons()
        QtCore.QMetaObject.connectSlotsByName(Printing)

    def retranslateUi(self, Printing):
        _translate = QtCore.QCoreApplication.translate
        Printing.setWindowTitle(_translate("Printing", "Form"))
        self.label.setText(
            _translate(
                "Printing",
                "3D printing is cool. This app, which has taken 3.2 billion man-hours and $87 trillion USD to develop, will teach you literally everything you need to know about it."
            ))
        self.pushButton.setText(_translate("Printing", "Uses"))
        self.pushButton_2.setText(_translate("Printing", "Plastics"))
        self.pushButton_3.setText(
            _translate("Printing", "Listen to a 3D printer"))
Exemple #11
0
class UI(QtWidgets.QMainWindow):

    signal_choix_fait = QtCore.pyqtSignal(str)

    def __init__(self):
        super().__init__()
        # Configuration de l'interface utilisateur.
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Ajout du fond d'écran
        indice_background = str(np.random.randint(0, 4))
        print(indice_background)
        self.setStyleSheet(
            "QMainWindow{ background-image: url(images/textures/texture_" +
            indice_background + "); }")

        self.put_sound = QSound("sounds/effect/put.wav")
        self.background_sound = QSound(None)

        # Création d'une partie
        #self.game = Game(UI = self)

        #création du thread gérant le jeu lui même
        self.thread = ThreadGame(UI=self)

        #connection des signaux provenant du thread
        self.thread.signal_init_grid.connect(self.init_grid_void)
        self.thread.signal_poser.connect(self.poser)
        self.thread.signal_main.connect(self.afficher_main)
        self.thread.signal_choix_domino.connect(self.calque_choix_domino)
        self.thread.signal_choix_extremite.connect(self.calque_choix_extremite)
        self.thread.signal_refresh_plateau.connect(self.refresh_plateau)
        self.thread.signal_choix_orientation.connect(
            self.calque_choix_orientation)
        self.thread.signal_choix_mode.connect(self.calque_choix_mode)
        self.thread.signal_choix_pseudo.connect(self.calque_choix_pseudo)
        self.thread.signal_message_box.connect(self.afficher_message_box)
        self.thread.signal_choix_recommencer.connect(self.choix_recommencer)
        self.thread.signal_init_main.connect(self.init_main)
        self.thread.signal_terminus.connect(self.terminus)
        self.thread.signal_background_sound.connect(self.init_background_sound)
        self.thread.signal_sound_fx.connect(self.sound_fx)
        self.thread.signal_nb_joueur.connect(self.choix_nombre_joueur)
        self.thread.signal_go.connect(self.go)

        #démarage du thread et donc de Game
        self.thread.start()

        #Liste des layouts de dominos de la main
        self.hand_layout_container = []

        # # on lance la musique du jeu !
        # self.background_sound.play()

    def init_grid_void(self, Nb_ligne, Nb_colonne):
        """
        initialisation d'une grille totalement transparante
        """
        print("Nettoyage")
        self.clearLayout(self.ui.gridlayout)
        self.ui.gridlayout.setSpacing(0)
        self.ui.gridlayout.setContentsMargins(0, 0, 0, 0)

        # initialisation de la grille
        for i in range(Nb_ligne):
            for j in range(Nb_colonne):
                pixmap = QtGui.QPixmap(None)
                label = QtWidgets.QLabel()
                label.setPixmap(pixmap)
                label.setFixedSize(30, 30)
                self.ui.gridlayout.addWidget(label, i, j)

    def init_grid(self):
        '''
        initialisation d'une grille avec des cases grises en transparance
        '''

        Nb_ligne = self.thread.game.plateau.Nb_ligne
        Nb_colonne = self.thread.game.plateau.Nb_colonne

        self.clearLayout(self.ui.gridlayout)
        self.ui.gridlayout.setSpacing(0)
        self.ui.gridlayout.setContentsMargins(0, 0, 0, 0)

        # initialisation de la grille
        for i in range(Nb_ligne):
            for j in range(Nb_colonne):
                pixmap = QtGui.QPixmap("images/calque_gris")
                label = QtWidgets.QLabel()
                label.setPixmap(pixmap)
                label.setFixedSize(49, 49)
                self.ui.gridlayout.addWidget(label, i, j)

    def refresh_plateau(self):
        plateau = self.thread.game.plateau
        self.init_grid()
        """
        Méthode permettant de réafficher l'état du plateau proprement, ce qui permet de ce debarasser des layout clickables et autres ajouts temporaires
        """
        for domino in plateau:
            self.poser(domino)

    def init_main(self):
        self.clearLayout(self.ui.handlayout)

    def terminus(self):
        self.close()

    def clearLayout(self, layout):
        """
        Méthode permettant de vider un layout de ces widgets
        """
        while layout.count():
            child = layout.takeAt(0)
            if child.widget():
                child.widget().deleteLater()

    def poser(self, domino):
        """
        Méthode permettant d'afficher un domino à l'ecran

        """

        pixmap = QtGui.QPixmap("images/" + str(domino.vala) + "/" +
                               domino.couleur + ".png")
        label = QtWidgets.QLabel()
        label.setPixmap(pixmap)
        label.setFixedSize(49, 49)
        self.ui.gridlayout.addWidget(label, domino.posa[0] - 1,
                                     domino.posa[1] - 1)

        pixmap = QtGui.QPixmap("images/" + str(domino.valb) + "/" +
                               domino.couleur + ".png")
        label = QtWidgets.QLabel()
        label.setPixmap(pixmap)
        label.setFixedSize(49, 49)
        self.ui.gridlayout.addWidget(label, domino.posb[0] - 1,
                                     domino.posb[1] - 1)

        self.put_sound.play()

    def afficher_main(self, num, name, main, couleur):

        self.clearLayout(self.ui.handlayout)
        self.hand_layout_container = []
        # self.ui.handlayout.setSpacing(0)
        # self.ui.handlayout.setContentsMargins(0, 0, 0, 0)

        spacerItem = QtWidgets.QSpacerItem(40, 20,
                                           QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Minimum)
        self.ui.handlayout.addItem(spacerItem)
        label = QtWidgets.QLabel("Joueur {0} [{1}]".format(num, name))
        label.setStyleSheet(
            "QLabel { background-color : rgb(71,55,55,129); color : black; font: bold 20px;}"
        )
        self.ui.handlayout.addWidget(label)

        for domino in main:
            dominowidget = QtWidgets.QWidget(self.ui.handwidget)
            dominowidget.setObjectName("widget_" + str(domino))
            domino_layout = QtWidgets.QVBoxLayout(dominowidget)
            domino_layout.setObjectName(str(domino))
            domino_layout.setSpacing(0)
            domino_layout.setContentsMargins(0, 0, 0, 0)
            self.ui.handlayout.addWidget(dominowidget)

            self.hand_layout_container.append(domino_layout)

            label = self.label_pixmap("images/" + str(domino.vala) + "/" +
                                      couleur + ".png")
            domino_layout.addWidget(label)

            label = self.label_pixmap("images/" + str(domino.valb) + "/" +
                                      couleur + ".png")
            domino_layout.addWidget(label)

        spacerItem = QtWidgets.QSpacerItem(40, 20,
                                           QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Minimum)
        self.ui.handlayout.addItem(spacerItem)

    def calque_choix_domino(self, joueur):
        dominos_jouables = [str(domino) for domino in joueur.domino_jouable()]
        cnt_layout = 0  # compte l'indice des layout jouables
        for domino_layout in self.hand_layout_container:
            if domino_layout.objectName() in dominos_jouables:
                object_name = domino_layout.objectName()
                vala, valb = object_name[1], object_name[3]
                self.clearLayout(domino_layout)
                label = self.label_pixmap_surligne(
                    "images/" + str(vala) + "/" + joueur.couleur + ".png",
                    message=str(cnt_layout))
                domino_layout.addWidget(label)
                label = self.label_pixmap_surligne(
                    "images/" + str(valb) + "/" + joueur.couleur + ".png",
                    message=str(cnt_layout))
                domino_layout.addWidget(label)
                cnt_layout += 1

    def calque_choix_extremite(self, plateau):
        extr_a = plateau.extr_a
        extr_b = plateau.extr_b
        pos_extr_a = plateau.pos_extr_a
        pos_extr_b = plateau.pos_extr_b
        couleur_a = plateau[0].couleur
        couleur_b = plateau[-1].couleur

        label = self.label_pixmap_surligne("images/" + str(extr_a) + "/" +
                                           couleur_a + ".png",
                                           message=str(0))
        self.ui.gridlayout.addWidget(label, pos_extr_a[0] - 1,
                                     pos_extr_a[1] - 1)

        label = self.label_pixmap_surligne("images/" + str(extr_b) + "/" +
                                           couleur_b + ".png",
                                           message=str(1))
        self.ui.gridlayout.addWidget(label, pos_extr_b[0] - 1,
                                     pos_extr_b[1] - 1)

    def calque_choix_orientation(self, extr_choisit):

        orientations_legales = self.thread.game.orientations_legales(
            extr_choisit)
        plateau = self.thread.game.plateau

        for orientation in orientations_legales:
            if extr_choisit == "a":
                pos_extr = plateau.pos_extr_a
                extr_orientation = plateau.orientation_extr_a
            if extr_choisit == "b":
                pos_extr = plateau.pos_extr_b
                extr_orientation = plateau.orientation_extr_b
            i, j = plateau.position_demi_domino(
                pos_extr, extr_orientation, domino_orientation=orientation)[1]
            label = self.label_pixmap_surligne("images/arrow/" + orientation +
                                               ".png",
                                               message=orientation)
            self.ui.gridlayout.addWidget(label, i - 1, j - 1)

    def calque_choix_mode(self, num):

        Nb_ligne = self.thread.game.plateau.Nb_ligne
        Nb_colonne = self.thread.game.plateau.Nb_colonne

        self.init_grid_void(
            Nb_ligne, Nb_colonne
        )  # on s'assure que la grille ne contient des cases totalement tranparantes

        pixmap = QtGui.QPixmap("images/human.png")
        label = ClickableLabel(message="human")
        label.clicked.connect(self.envoyer)
        label.setPixmap(pixmap)
        label.setFixedSize(99, 99)
        self.ui.gridlayout.addWidget(label, Nb_ligne // 2,
                                     (Nb_colonne // 2) - 1)

        pixmap = QtGui.QPixmap("images/bot.png")
        label = ClickableLabel(message="IA_equilibre_global")
        label.clicked.connect(self.envoyer)
        label.setPixmap(pixmap)
        label.setFixedSize(99, 99)
        self.ui.gridlayout.addWidget(label, Nb_ligne // 2,
                                     (Nb_colonne // 2) + 1)

        # if num == 0 :
        #     self.init_intro_sound()
        #     self.intro_sound.play()

    def calque_choix_pseudo(self):
        pseudo = QtWidgets.QInputDialog.getText(self, "Choix du Pseudo",
                                                "Entrer votre Pseudo :")[0]
        self.signal_choix_fait.emit(pseudo)

    def choix_nombre_joueur(self):
        nb_joueur = QtWidgets.QInputDialog.getItem(
            self, "Choix du nombre de Joueurs", "Nombre de Joueurs :",
            ("2", "3", "4"))[0]
        self.signal_choix_fait.emit(str(nb_joueur))

    def afficher_message_box(self, message):
        msg = QtWidgets.QMessageBox.question(self, None, message,
                                             QtWidgets.QMessageBox.Ok)
        self.signal_choix_fait.emit("ok")

    def choix_recommencer(self):
        message = QtWidgets.QInputDialog.getItem(
            self, "Voulez-vous recommencer la partie ?", "Choix :",
            ("Yes", "No", "Maybe", "I don't know",
             "can you repeat the question ?"))[0]
        self.signal_choix_fait.emit(message)

    def label_pixmap(self, image_adresse):
        pixmap = QtGui.QPixmap(image_adresse)
        label = QtWidgets.QLabel()
        label.setPixmap(pixmap)
        label.setFixedSize(49, 49)
        return (label)

    def label_pixmap_surligne(self, image_adresse, message):

        image = QtGui.QImage(image_adresse)
        overlay = QtGui.QImage("images/calque_selection.png")
        painter = QtGui.QPainter()
        painter.begin(image)
        painter.drawImage(0, 0, overlay)
        painter.end()
        label = ClickableLabel(message)
        label.clicked.connect(self.envoyer)
        label.setPixmap(QtGui.QPixmap.fromImage(image))
        label.setFixedSize(49, 49)
        return (label)

    def envoyer(self, message):
        self.signal_choix_fait.emit(message)

    def init_intro_sound(self):

        indice_background = str(np.random.randint(0, 4))
        print(indice_background)
        self.setStyleSheet(
            "QMainWindow{ background-image: url(images/textures/texture_" +
            indice_background + "); }")

        indice_intro = str(np.random.randint(0, 4))
        self.intro_sound = QSound("sounds/intro/intro_" + indice_intro +
                                  ".wav")
        self.background_sound.stop()

    def init_background_sound(self):
        # choix des sons au hasard dans la playlist (extrait de Zelda Windwaker)
        indice_theme = str(np.random.randint(0, 5))
        self.background_sound = QSound("sounds/main_theme/theme_" +
                                       indice_theme + ".wav")
        self.background_sound.setLoops(-1)

        self.intro_sound.stop()
        sleep(0.2)
        self.background_sound.play()
        print("back_sound")

    def sound_fx(self, adress_sound):
        self.background_sound.stop()
        sleep(0.4)
        self.fx_sound = QSound(adress_sound)
        self.fx_sound.play()

    def resize(self):
        self.ui.setFixedSize(self.ui.centralWidget.size())

    def go(self):

        Nb_ligne = self.thread.game.plateau.Nb_ligne
        Nb_colonne = self.thread.game.plateau.Nb_colonne

        self.init_grid_void(
            Nb_ligne, Nb_colonne
        )  # on s'assure que la grille ne contient des cases totalement tranparantes

        pixmap = QtGui.QPixmap("images/manette.png")
        label = ClickableLabel(message="human")
        label.clicked.connect(self.envoyer)
        label.setPixmap(pixmap)
        label.setFixedSize(99, 99)
        self.ui.gridlayout.addWidget(label, Nb_ligne // 2, (Nb_colonne // 2))

        self.init_intro_sound()
        self.intro_sound.play()
Exemple #12
0
class MainWindow_EXEC():
    def __init__(self):

        #-------------------Init QT Setup---------------------------

        app = QtWidgets.QApplication(sys.argv)

        self.MainWindow = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow()

        self.ui.setupUi(self.MainWindow)
        app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())

        #------------------Exporting Setup------------------------------

        self.ui.export_midi.clicked.connect(self.openDirectory_midi)
        self.ui.export_midi.setFocusPolicy(QtCore.Qt.NoFocus)
        self.ui.export_audio.clicked.connect(self.openDirectory_audio)
        self.ui.export_audio.setFocusPolicy(QtCore.Qt.NoFocus)

        #------------------Metronome Setup------------------------------

        self.ui.metronome_button.clicked.connect(self.metro_thread)

        #------------------Recording Setup------------------------------

        self.ui.start_stop_rec.clicked.connect(self.start_stop_recording)
        self.ui.play_gui.clicked.connect(self.play)

        # QAudio setup
        self.settings = QAudioEncoderSettings()
        self.settings.setBitRate(16)
        self.settings.setChannelCount(1)
        self.audioRecorder = QAudioRecorder()
        self.audioRecorder.setEncodingSettings(self.settings)
        self.file_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         resource_path("resources/output.wav")))

        self.url = QUrl.fromLocalFile(self.file_path)
        self.audioRecorder.setOutputLocation(self.url)

        #------------------Audio Terrain Gui Setup------------------------------

        self.terrain = Terrain()
        self.terrain.update()
        self.terrain_widget = self.terrain.getwidget()
        self.layout = QtGui.QGridLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.ui.t_widget.setLayout(self.layout)
        self.layout.addWidget(self.terrain_widget, 0, 0, 1, 1)

        #------------------Audio Trimmer Setup------------------------------

        self.ui.audio_trimmer.clicked.connect(self.trim_audio)

        if os.path.isfile("resources/output.wav"):
            self.y, self.sr = librosa.load(
                resource_path("resources/output.wav"), sr=44100)
        else:
            new_wav = AudioSegment.empty()
            new_wav.export("resources/output.wav", format="wav")
            self.y, self.sr = librosa.load(
                resource_path("resources/output.wav"), sr=44100)

        self.duration = round(
            librosa.core.get_duration(y=self.y, sr=self.sr) * self.sr)
        self.maxv = np.iinfo(np.int16).max

        self.win = pg.GraphicsLayoutWidget()
        self.p = self.win.addPlot()

        #removes X & Y Axis and disables mouse movement
        self.p.showAxis('bottom', show=False)
        self.p.showAxis('left', show=False)
        self.p.setMouseEnabled(x=False, y=False)

        self.region = pg.LinearRegionItem(brush=(100, 100, 100, 60),
                                          bounds=(0, self.duration))
        self.region.setRegion([0, self.duration])

        self.p.addItem(self.region, ignoreBounds=True)
        self.p.plot(self.y, pen="w")

        self.layout.addWidget(self.win)
        self.win.hide()

        #------------------Midi Setup------------------------------

        self.ui.convert_midi.clicked.connect(self.convertMidi)
        self.ui.midi_play.clicked.connect(self.midiplayer_thread)
        self.ui.tempo_slider.valueChanged[int].connect(self.tempo_value)
        self.ui.midi_loop.toggle()

        # default bpm is 120
        self.current_tempo = 120
        self.detected_tempo = 120

        #------------------Drum Kit Selector Setup----------------------

        self.ui.drum_kits.clicked.connect(self.select_drumkit)
        self.drum_number = 0
        self.drum_folders = [
            'Drum_Kit_1', 'Drum_Kit_2', 'Drum_Kit_3', 'Drum_Kit_4'
        ]
        self.drum_current = self.drum_folders[self.drum_number]

        #------------------EXEC Window---------------------------------
        self.MainWindow.show()
        sys.exit(app.exec_())
#---------------------------------------------------------------

#------------------Functions----------------------------------

#------------------Drum Kit Selector------------------------------

    def select_drumkit(self):
        if self.drum_number < 3:
            self.drum_number += 1
            self.drum_current = self.drum_folders[self.drum_number]
            self.ui.drum_kits.setText(self.drum_current.replace("_", " "))
        else:
            self.drum_number = 0
            self.drum_current = self.drum_folders[self.drum_number]
            self.ui.drum_kits.setText(self.drum_current.replace("_", " "))

        #------------------Audio Trimmer------------------------------

    def trim_audio(self):
        # Switch to Trimmer widget
        self.layout.removeWidget(self.terrain_widget)
        self.terrain_widget.hide()
        self.win.show()
        self.trim_values = self.region.getRegion()
        self.updateaudio()
        # Trims signal array with region values
        self.y = self.y[round(self.trim_values[0]):round(self.trim_values[1])]

        # save the new signal values to wav
        librosa.output.write_wav(resource_path("resources/output.wav"),
                                 (self.y * self.maxv).astype(np.int16),
                                 self.sr)
        self.updateplot()

    def updateplot(self):
        # Replot the trimmed wav and update region bounds
        self.duration = round(
            librosa.core.get_duration(y=self.y, sr=self.sr) * self.sr)
        self.p.plot(clear=True)
        self.p.plot(self.y, pen="w")
        self.region = pg.LinearRegionItem(brush=(100, 100, 100, 50),
                                          bounds=(0, self.duration))
        self.p.addItem(self.region, ignoreBounds=True)
        self.region.setRegion([0, self.duration])

    def updateaudio(self):
        self.y, self.sr = librosa.load(resource_path("resources/output.wav"),
                                       sr=44100)

        #------------------Metronome Threading------------------------------

    def metro_thread(self):

        if self.ui.metronome_button.isChecked():
            print('metronome is On')
            self.thread = QThread(
            )  # a new thread to run our background tasks in
            self.worker = Worker(
                self.current_tempo)  # a new worker to perform those tasks
            self.worker.moveToThread(
                self.thread
            )  # move the worker into the thread, do this first before connecting the signals
            self.thread.started.connect(
                self.worker.work
            )  # begin our worker object's loop when the thread starts running
            self.thread.start()

        else:
            print('metronome is Off')
            self.stop_loop()
            self.worker.finished.connect(
                self.loop_finished
            )  # do something in the gui when the worker loop ends
            self.worker.finished.connect(
                self.thread.quit)  # tell the thread it's time to stop running
            self.worker.finished.connect(self.thread.wait)
            self.worker.finished.connect(
                self.worker.deleteLater
            )  # have worker mark itself for deletion
            self.thread.finished.connect(self.thread.deleteLater)

    def stop_loop(self):
        self.worker.working = False

    def loop_finished(self):
        # print('Worker Finished')
        pass

    #---------------------------------------------------------

    #------------------ MIDI ------------------------------

    def tempo_value(self, value):
        self.current_tempo = value

    def convertMidi(self):
        self.ui.convert_midi.setEnabled(False)
        self.thread2 = QThread()
        self.worker2 = ConvertMidi_Worker()
        self.worker2.moveToThread(self.thread2)
        self.thread2.started.connect(self.worker2.work)
        self.thread2.start()
        self.worker2.finished.connect(self.convert_finished)
        self.worker2.finished.connect(self.thread2.quit)
        self.worker2.finished.connect(self.thread2.wait)
        self.worker2.finished.connect(self.worker2.deleteLater)
        self.thread2.finished.connect(self.thread2.deleteLater)

    def convert_finished(self, tempo):
        self.detected_tempo = tempo
        self.ui.tempo_slider.setValue(self.detected_tempo)
        self.ui.convert_midi.clearFocus()
        self.ui.convert_midi.setEnabled(True)
        print('Midi Conversion finished')

    def midiplayer_thread(self):

        if self.ui.midi_play.isChecked() and self.ui.midi_loop.isChecked(
        ) == False:

            self.ui.midi_play.setEnabled(False)
            self.win.hide()
            self.terrain_widget.show()
            self.terrain.animate()
            self.thread3 = QThread()
            self.worker3 = MidiPlayer_Worker(self.current_tempo,
                                             self.drum_current)
            self.worker3.moveToThread(self.thread3)
            self.thread3.started.connect(self.worker3.workonce)

            self.thread3.start()
            self.worker3.finished2.connect(self.midi_loop_finished2)
            self.worker3.finished2.connect(self.thread3.quit)
            self.worker3.finished2.connect(self.thread3.wait)
            self.worker3.finished2.connect(self.worker3.deleteLater)
            self.thread3.finished.connect(self.thread3.deleteLater)

        elif self.ui.midi_play.isChecked() and self.ui.midi_loop.isChecked(
        ) == True:
            self.win.hide()
            self.terrain_widget.show()
            self.start_Midi_Thread()
            self.terrain.animate()

        elif self.ui.midi_play.isChecked() == False:
            self.terrain.stop_animate()
            self.stop_Midi_Thread()

    def start_Midi_Thread(self):
        self.thread3 = QThread()
        self.worker3 = MidiPlayer_Worker(self.current_tempo, self.drum_current)
        self.worker3.moveToThread(self.thread3)
        self.thread3.started.connect(self.worker3.work)
        self.thread3.start()

    def stop_Midi_Thread(self):
        self.worker3.working = False

        self.worker3.stop()
        self.worker3.finished.connect(self.midi_loop_finished)
        self.worker3.finished.connect(self.thread3.quit)
        self.worker3.finished.connect(self.thread3.wait)
        self.worker3.finished.connect(self.worker3.deleteLater)
        self.thread3.finished.connect(self.thread3.deleteLater)
        print('done')

    def midi_loop_finished(self):
        print('Midi loop Finished')

    def midi_loop_finished2(self):
        print('Midi Player Finished')
        self.ui.midi_play.toggle()
        self.ui.midi_play.setEnabled(True)
        self.terrain.stop_animate()

    #---------------------------------------------------------

    #------------------ Recorder & Player ------------------------------

    def start_stop_recording(self):
        if self.ui.start_stop_rec.isChecked():
            self.ui.play_gui.setEnabled(False)
            self.ui.audio_trimmer.setEnabled(False)

            self.win.hide()
            self.terrain_widget.show()

            self.layout.addWidget(self.terrain_widget)
            self.audioRecorder.record()
            self.terrain.update()

            self.terrain.animate()
            print('Recording...')

        else:
            self.ui.play_gui.setEnabled(True)
            self.ui.audio_trimmer.setEnabled(True)

            self.terrain.stop_animate()
            self.audioRecorder.stop()
            self.layout.removeWidget(self.terrain_widget)
            self.terrain_widget.hide()

            self.updateaudio()
            self.win.show()
            self.updateplot()
            print('Stop Recording')

    def play(self):
        if self.ui.play_gui.isChecked():
            self.win.hide()
            self.terrain_widget.show()

            self.player = QSound(resource_path("resources/output.wav"))
            self.terrain.animate()
            self.player.play()
            # if self.player.isFinished():
            # 	self.ui.play_gui.toggle()
            # 	print('done')

        else:
            self.terrain.stop_animate()
            self.player.stop()
            self.player.deleteLater()

    #------------------ Exporting ------------------------------

    def openDirectory_midi(self):
        self.openDirectoryDialog = QtGui.QFileDialog.getExistingDirectory(
            self.MainWindow, "Save Midi File")
        if self.openDirectoryDialog:
            self.saveMidi(self.openDirectoryDialog)
        else:
            pass

    def openDirectory_audio(self):
        self.openDirectoryDialog = QtGui.QFileDialog.getExistingDirectory(
            self.MainWindow, "Save Audio File")
        if self.openDirectoryDialog:
            self.saveAudio(self.openDirectoryDialog)
        else:
            pass

    def saveMidi(self, directory):
        shutil.copy("resources/beatbox.mid", directory)

    def saveAudio(self, directory):
        shutil.copy("resources/output.wav", directory)
class Window(QMainWindow):
    """Defines main window of the game."""
    def __init__(self):
        super().__init__()
        self.__init_ui()

        # Show new window
        self.show()

        # Play background music
        self.music = QSound("res/sound/setting_field2.wav")
        self.music.play()

        # Prevent from resizing
        self.setFixedSize(self.size())

        # Variable determinates if all things are done to be rady to play
        self.canStart = False

        # Set up random generator
        seed()

    def __init_ui(self):
        """Sets an ui for a game.

        size = 800x600
        position = 200, 200
        background = backgroundPE.png
        music while setting field: setting_field1.wav
        music while playing: gameplay.wav
        """

        self.setGeometry(200, 200, 800, 600)
        self.setWindowTitle("Battleships")
        self.setWindowIcon(QIcon("res/pictures/icon.png"))

        # Setting background
        background = QPalette()
        background.setBrush(QPalette.Background,
                            QBrush(QPixmap("res/pictures/backgroundPE.png")))
        self.setPalette(background)

        # Setting player's field
        self.playerFieldLabel = label.Label(self, "Player")
        self.playerFieldLabel.setGeometry(50, 50, 295, 295)

        # Set player's target field
        self.targetFieldLabel = label.Label(self, "Enemy")
        self.targetFieldLabel.setGeometry(455, 50, 295, 295)

        # Add a label which shows information to player
        self.informativeLabel = QLabel(self)
        self.informativeLabel.setFont(QFont("MutantAcademyBB", 30))  # 54
        self.informativeLabel.setStyleSheet('color: white')
        self.informativeLabel.setText("Click on your field to place the ship")
        self.informativeLabel.setGeometry(20, 500, 800, 90)

        # Add a label which tells in-game informations
        self.inGameLabel = QLabel(self)
        self.inGameLabel.setFont(QFont("Capture It", 25))
        self.inGameLabel.setStyleSheet('color: pink')
        self.inGameLabel.setText("Ships to be placed: 10")
        self.inGameLabel.setGeometry(37, 400, 600, 90)

        # Add 'ready' button - it starts the game with ToolTip
        self.readyButton = QPushButton("Ready", self)
        self.readyButton.setToolTip(
            "Click this button once you set up the ships")
        self.readyButton.resize(self.readyButton.sizeHint())
        self.readyButton.move(360, 2)
        self.readyButton.clicked.connect(self.startGame)

        # Add which ship is being placed
        self.whichShipLabel = QLabel(self)
        self.whichShipLabel.setFont(QFont("Tahoma", 25))
        self.whichShipLabel.setGeometry(520, 400, 300, 90)
        self.whichShipLabel.setStyleSheet('color: red')
        self.whichShipLabel.setText("%d-mast ship" % self.playerFieldLabel.hp)

    def startGame(self):
        if len(self.playerFieldLabel.gameField.ships) == 10:
            self.playerFieldLabel.isGame = True
            self.playerFieldLabel.canUserClick = False
            self.targetFieldLabel.isGame = True
            self.informativeLabel.setText(
                "Shoot to opponent's field\nShips left: %d" %
                len(self.playerFieldLabel.gameField.ships))
            self.music.stop()
            self.music = QSound("res/sound/gameplay_lel.wav")
            self.music.setLoops(100)
            self.music.play()
            self.readyButton.setText("Playing...")
            self.readyButton.setToolTip("The game is in progress.")
            self.readyButton.setDisabled(True)
            self.inGameLabel.setText("")

    def ai_shoot(self):
        """Method defined for automatic shooting for ai - uses self.playerFieldLabel"""

        self.shoot_x = randint(0, 9)
        self.shoot_y = randint(0, 9)
        self.isHit = False

        result = self.playerFieldLabel.shoot_to_field(self.shoot_x,
                                                      self.shoot_y)
        # if ai hits - shoot around that place
        if result == True:
            self.isHit = True
            direction = randint(0, 3)

            if direction == 0:
                while self.isHit != False:
                    self.shoot_x += 1
                    self.isHit = self.playerFieldLabel.shoot_to_field(
                        self.shoot_x, self.shoot_y)

            elif direction == 1:
                while self.isHit != False:
                    self.shoot_x -= 1
                    self.isHit = self.playerFieldLabel.shoot_to_field(
                        self.shoot_x, self.shoot_y)

            elif direction == 2:
                while self.isHit != False:
                    self.shoot_y += 1
                    self.isHit = self.playerFieldLabel.shoot_to_field(
                        self.shoot_x, self.shoot_y)

            elif direction == 3:
                while self.isHit != False:
                    self.shoot_y -= 1
                    self.isHit = self.playerFieldLabel.shoot_to_field(
                        self.shoot_x, self.shoot_y)

            del direction

        elif result == None:
            self.ai_shoot()

    def end_game(self, winner):
        if winner == "Player":
            self.music.stop()
            self.music = QSound("res/sound/victory.wav")
            self.music.play()

            self.informativeLabel.setStyleSheet("color: yellow")
            self.informativeLabel.setFont(QFont("MutantAcademyBB", 41))
            self.informativeLabel.setText("Congratulations! Victory!")
            self.informativeLabel.setDisabled(True)
            self.targetFieldLabel.canUserClick = False
            self.targetFieldLabel.setDisabled(True)

        elif winner == "Enemy":
            self.music.stop()
            self.music = QSound("res/sound/loss.wav")
            self.music.play()

            self.targetFieldLabel.canUserClick = False
            self.informativeLabel.setStyleSheet('color: red')
            self.informativeLabel.setFont(QFont("MutantAcademyBB", 53))
            self.informativeLabel.setText("You lose. Game over.")
            self.informativeLabel.setDisabled(True)
            self.playerFieldLabel.setDisabled(True)

        self.readyButton.setText("Exit")
        self.readyButton.setToolTip("Click this button to exit the game.")
        self.readyButton.clicked.connect(self.close)
        self.readyButton.setDisabled(False)
        self.targetFieldLabel.canTextEdit = False
        self.playerFieldLabel.canTextEdit = False
Exemple #14
0
class MainApp(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainApp, self).__init__(parent)
        QMainWindow.__init__(self)
        self.setupUi(self)
        self.make_dirs()
        self.random_id()
        self.conf_ui()
        self.conf_buttons()
        self.conf_sliders()
        # connect to mqtt broker
        self.t = Thread(target=self.connect)
        self.t.start()
        self.quit = False
        # initialize camera
        self.cam = Camera()
        self.cam.signal.connect(self.conf_labels)
        # initialize stream thread
        self.st = Stream()
        self.st.signal.connect(self.conf_labels)
        self.st.changePixmap.connect(self.cam.viewImage)
        # initialize record thread
        self.rec = Record()
        self.rec.signal.connect(self.conf_labels)
        # start message thread
        self.thread = GetMessage()
        self.thread.start()
        self.thread.signal.connect(self.conf_labels)
        # start FireAlarm
        self.falarm = FireAlarm()
        self.falarm.start()
        self.falarm.signal.connect(self.conf_labels)
        # start WaterAlarm
        self.walarm = WaterAlarm()
        self.walarm.start()
        self.walarm.signal.connect(self.conf_labels)
        # start GasAlarm
        self.galarm = GasAlarm()
        self.galarm.start()
        self.galarm.signal.connect(self.conf_labels)
        # start MotionAlarm
        self.malarm = MotionAlarm()
        self.malarm.start()
        self.malarm.signal.connect(self.conf_labels)
        # start LaserAlarm
        self.lalarm = LaserAlarm()
        self.lalarm.start()
        self.lalarm.signal.connect(self.conf_labels)
        self.alarm_status = 'off'

    def keyPressEvent(self, event):
        modifiers = QApplication.keyboardModifiers()
        if event.key() == Qt.Key_Space:
            self.button_fire()
            self.button_water()
            self.button_gas()
            self.button_motion()
            self.button_laser()
        if modifiers == Qt.AltModifier:
            if event.key() == Qt.Key_1:
                self.tabWidget.setCurrentIndex(0)
            elif event.key() == Qt.Key_2:
                self.tabWidget.setCurrentIndex(1)
            elif event.key() == Qt.Key_3:
                self.tabWidget.setCurrentIndex(2)
            elif event.key() == Qt.Key_4:
                self.tabWidget.setCurrentIndex(3)
            elif event.key() == Qt.Key_5:
                self.tabWidget.setCurrentIndex(4)

    def closeEvent(self, event):
        self.button_stop_camera()
        self.falarm.quit()
        self.walarm.quit()
        self.galarm.quit()
        self.malarm.quit()
        self.lalarm.quit()
        self.quit = True
        event.accept()

    def make_dirs(self):
        if not os.path.exists(messages_dir):
            os.makedirs(messages_dir)
        if not os.path.exists(videos_dir):
            os.makedirs(videos_dir)
        open(messages_path, 'w')
        open(alarms_path, 'w')

    def random_id(self):
        s = string.ascii_letters + string.digits
        self.client_id = ''.join(random.sample(s, 7))

    def connect(self):
        self.mqttc = mqtt.Client(self.client_id)
        while not self.quit:
            try:
                self.mqttc.connect('192.168.1.10')
            except Exception:
                print('[MQTT]: Connection failed')
                print('[MQTT]: Reconnecting ...')
                time.sleep(5)
            else:
                self.mqttc.on_message = on_message
                self.mqttc.loop_start()
                self.mqttc.subscribe([('indoor_light_cb', 1),
                                      ('indoor_fan_cb', 1),
                                      ('indoor_air_cb', 1),
                                      ('indoor_curtain_cb', 1),
                                      ('indoor_door_cb', 1),
                                      ('indoor_alarm_cb', 1),
                                      ('indoor_temp_cb', 1),
                                      ('outdoor_light_cb', 1),
                                      ('irrigation_cb', 1), ('alarm_cb', 1),
                                      ('outdoor_temp_cb', 1),
                                      ('outdoor_hum_cb', 1),
                                      ('outdoor_alarm_cb', 1)])
                break

    def conf_ui(self):
        self.setFixedSize(911, 547)

    def conf_buttons(self):
        # indoor
        self.in_light_on_button.clicked.connect(self.button_in_light_on)
        self.in_light_off_button.clicked.connect(self.button_in_light_off)
        self.in_light_auto_button.clicked.connect(self.button_in_light_auto)
        self.in_fan_on_button.clicked.connect(self.button_in_fan_on)
        self.in_fan_off_button.clicked.connect(self.button_in_fan_off)
        self.in_fan_auto_button.clicked.connect(self.button_in_fan_auto)
        self.in_air_on_button.clicked.connect(self.button_in_air_on)
        self.in_air_off_button.clicked.connect(self.button_in_air_off)
        self.in_air_auto_button.clicked.connect(self.button_in_air_auto)
        self.in_curtain_on_button.clicked.connect(self.button_in_curtain_on)
        self.in_curtain_off_button.clicked.connect(self.button_in_curtain_off)
        self.in_curtain_auto_button.clicked.connect(
            self.button_in_curtain_auto)
        self.in_door_open_button.clicked.connect(self.button_in_door_open)
        self.in_door_close_button.clicked.connect(self.button_in_door_close)
        self.in_open_button.clicked.connect(self.button_in_open)
        self.in_close_button.clicked.connect(self.button_in_close)
        self.in_alarm_button.clicked.connect(self.button_in_alarm)

        # outdoor
        self.out_light_on_button.clicked.connect(self.button_out_light_on)
        self.out_light_off_button.clicked.connect(self.button_out_light_off)
        self.out_light_auto_button.clicked.connect(self.button_out_light_auto)
        self.out_irri_on_button.clicked.connect(self.button_out_irri_on)
        self.out_irri_off_button.clicked.connect(self.button_out_irri_off)
        self.out_irri_auto_button.clicked.connect(self.button_out_irri_auto)
        self.out_open_button.clicked.connect(self.button_out_open)
        self.out_close_button.clicked.connect(self.button_out_close)
        self.out_alarm_button.clicked.connect(self.button_out_alarm)

        # message
        self.message_send_button.clicked.connect(self.button_message_send)
        self.message_clear_button.clicked.connect(self.button_message_clear)

        # database
        self.refresh_button.clicked.connect(self.button_refresh)

        # camera
        self.stream_button.clicked.connect(self.button_stream)
        self.record_button.clicked.connect(self.button_record)
        self.stream_record_button.clicked.connect(self.button_stream_record)
        self.stop_camera_button.clicked.connect(self.button_stop_camera)

        # alarms
        self.fire_button.clicked.connect(self.button_fire)
        self.water_button.clicked.connect(self.button_water)
        self.gas_button.clicked.connect(self.button_gas)
        self.motion_button.clicked.connect(self.button_motion)
        self.laser_button.clicked.connect(self.button_laser)

    # camera
    def button_stream(self):
        self.st.start()

    def button_record(self):
        self.rec.start()

    def button_stream_record(self):
        self.button_stream()
        self.button_record()

    def button_stop_camera(self):
        self.st.stop()
        self.rec.stop()
        self.cam.close()

    # alarms
    def button_fire(self):
        self.falarm.stop()
        self.alarm('stop')

    def button_water(self):
        self.walarm.stop()
        self.alarm('stop')

    def button_gas(self):
        self.galarm.stop()
        self.alarm('stop')

    def button_motion(self):
        self.malarm.stop()
        self.alarm('stop')

    def button_laser(self):
        self.lalarm.stop()
        self.alarm('stop')

    # database
    def button_refresh(self):
        t = Thread(target=self.database)
        t.start()

    # indoor
    def button_in_light_on(self):
        self.mqttc.publish('indoor_light', '01')

    def button_in_light_off(self):
        self.mqttc.publish('indoor_light', '0')
        self.in_light_slider.setValue(0)

    def button_in_light_auto(self):
        self.mqttc.publish('indoor_light', '02')

    def button_in_fan_on(self):
        self.mqttc.publish('indoor_fan', '01')

    def button_in_fan_off(self):
        self.mqttc.publish('indoor_fan', '0')
        self.in_fan_slider.setValue(0)

    def button_in_fan_auto(self):
        self.mqttc.publish('indoor_fan', '02')

    def button_in_air_on(self):
        self.mqttc.publish('indoor_air', '01')

    def button_in_air_off(self):
        self.mqttc.publish('indoor_air', '0')

    def button_in_air_auto(self):
        self.mqttc.publish('indoor_air', '02')

    def button_in_curtain_on(self):
        self.mqttc.publish('indoor_curtain', '01')

    def button_in_curtain_off(self):
        self.mqttc.publish('indoor_curtain', '0')

    def button_in_curtain_auto(self):
        self.mqttc.publish('indoor_curtain', '02')

    def button_in_door_open(self):
        self.mqttc.publish('indoor_door', '01')

    def button_in_door_close(self):
        self.mqttc.publish('indoor_door', '0')

    def button_in_open(self):
        self.button_in_light_on()
        self.button_in_fan_on()
        self.button_in_curtain_on()
        self.button_in_air_on()

    def button_in_close(self):
        self.button_in_light_off()
        self.button_in_fan_off()
        self.button_in_curtain_off()
        self.button_in_air_off()

    def button_in_alarm(self):
        doc = QTextDocument()
        doc.setHtml(self.in_alarm_label.text())
        if doc.toPlainText() == 'Active':
            self.mqttc.publish('indoor_alarm', '0')
        else:
            self.mqttc.publish('indoor_alarm', '01')

    # Outdoor
    def button_out_light_on(self):
        self.mqttc.publish('outdoor_light', '01')

    def button_out_light_off(self):
        self.mqttc.publish('outdoor_light', '0')
        self.out_light_slider.setValue(0)

    def button_out_light_auto(self):
        self.mqttc.publish('outdoor_light', '02')

    def button_out_irri_on(self):
        self.mqttc.publish('irrigation', '01')

    def button_out_irri_off(self):
        self.mqttc.publish('irrigation', '0')
        self.out_irri_slider.setValue(0)

    def button_out_irri_auto(self):
        self.mqttc.publish('irrigation', '02')

    def button_message_send(self):
        self.mqttc.publish('message', self.message_text.toPlainText())

    def button_message_clear(self):
        self.message_text.setText('')

    def button_out_open(self):
        self.button_out_light_on()
        self.button_out_irri_on()

    def button_out_close(self):
        self.button_out_light_off()
        self.button_out_irri_off()

    def button_out_alarm(self):
        doc = QTextDocument()
        doc.setHtml(self.out_alarm_label.text())
        if doc.toPlainText() == 'Active':
            self.mqttc.publish('outdoor_alarm', '0')
        else:
            self.mqttc.publish('outdoor_alarm', '01')

    def conf_sliders(self):
        self.in_light_slider.sliderReleased.connect(self.slider_in_light)
        self.in_fan_slider.sliderReleased.connect(self.slider_in_fan)
        self.out_light_slider.sliderReleased.connect(self.slider_out_light)
        self.out_irri_slider.sliderReleased.connect(self.slider_out_irri)
        self.in_light_slider.valueChanged.connect(self.slider_in_light_)
        self.in_fan_slider.valueChanged.connect(self.slider_in_fan_)
        self.out_light_slider.valueChanged.connect(self.slider_out_light_)
        self.out_irri_slider.valueChanged.connect(self.slider_out_irri_)
        self.in_air_spinbox.valueChanged.connect(self.spin_ra)

    def slider_in_light(self):
        self.mqttc.publish('indoor_light', int(self.in_light_slider.value()))

    def slider_in_light_(self):
        self.in_light_percentage.setText(
            str(self.in_light_slider.value()) + '%')

    def slider_in_fan(self):
        self.mqttc.publish('indoor_fan', int(self.in_fan_slider.value()))

    def slider_in_fan_(self):
        self.in_fan_percentage.setText(str(self.in_fan_slider.value()) + '%')

    def slider_out_light(self):
        self.mqttc.publish('outdoor_light', int(self.out_light_slider.value()))

    def slider_out_light_(self):
        self.out_light_percentage.setText(
            str(self.out_light_slider.value()) + '%')

    def slider_out_irri(self):
        self.mqttc.publish('irrigation', int(self.out_irri_slider.value()))

    def slider_out_irri_(self):
        self.out_irri_percentage.setText(
            str(self.out_irri_slider.value()) + '%')

    def spin_ra(self):
        self.mqttc.publish('indoor_air', self.in_air_spinbox.value())

    def alarm(self, msg):
        self.audio = QSound(audio_path)
        self.audio.setLoops(-1)
        if msg == 'start':
            self.audio.play()
            self.alarm_status = 'on'
        else:
            self.audio.stop()
            self.alarm_status = 'off'

    def conf_labels(self, msg, topic):

        red_style = 'QPushButton {background-color: #C62828;}'
        blue_style = 'QPushButton {background-color: #1565C0;}'
        green_style = 'QPushButton {background-color: #2E7D32;}'

        if topic == 'indoor_light_cb':

            if msg == 'ON':
                self.in_light_label.setText('<p style="color:#2E7D32">ON</p>')
                self.in_light_level_label.setText(
                    '<p style="color:#2E7D32">100%</p>')
            elif msg == 'OFF':
                self.in_light_label.setText('<p style="color:#C62828">OFF</p>')
                self.in_light_level_label.setText('-')
            elif msg == 'AUTO':
                self.in_light_label.setText(
                    '<p style="color:#1565C0">AUTO</p>')
                self.in_light_level_label.setText('-')
            else:
                self.in_light_label.setText('<p style="color:#2E7D32">ON</p>')
                self.in_light_level_label.setText(
                    '<p style="color:#2E7D32">{}%</p>'.format(msg))

        elif topic == 'indoor_fan_cb':

            if msg == 'ON':
                self.in_fan_label.setText('<p style="color:#2E7D32">ON</p>')
                self.in_fan_level_label.setText(
                    '<p style="color:#2E7D32">100%</p>')
            elif msg == 'OFF':
                self.in_fan_label.setText('<p style="color:#C62828">OFF</p>')
                self.in_fan_level_label.setText('-')
            elif msg == 'AUTO':
                self.in_fan_label.setText('<p style="color:#1565C0">AUTO</p>')
                self.in_fan_level_label.setText('-')
            else:
                self.in_fan_label.setText('<p style="color:#2E7D32">ON</p>')
                self.in_fan_level_label.setText(
                    '<p style="color:#2E7D32">{}%</p>'.format(msg))

        elif topic == 'indoor_air_cb':

            if msg == 'ON':
                self.in_air_label.setText('<p style="color:#2E7D32">ON</p>')
                self.in_air_level_label.setText(
                    '<p style="color:#2E7D32">21°</p>')
            elif msg == 'OFF':
                self.in_air_label.setText('<p style="color:#C62828">OFF</p>')
                self.in_air_level_label.setText('-')
            elif msg == 'AUTO':
                self.in_air_label.setText('<p style="color:#1565C0">AUTO</p>')
                self.in_air_level_label.setText('-')
            else:
                self.in_air_label.setText('<p style="color:#2E7D32">ON</p>')
                self.in_air_level_label.setText(
                    '<p style="color:#2E7D32">{}%</p>'.format(msg))

        elif topic == 'indoor_curtain_cb':

            if msg == 'ON':
                self.in_curtain_label.setText(
                    '<p style="color:#2E7D32">ON</p>')
            elif msg == 'OFF':
                self.in_curtain_label.setText(
                    '<p style="color:#C62828">OFF</p>')
            elif msg == 'AUTO':
                self.in_curtain_label.setText(
                    '<p style="color:#1565C0">AUTO</p>')

        elif topic == 'indoor_door_cb':

            if msg == 'ON':
                self.in_door_label.setText('<p style="color:#2E7D32">OPEN</p>')
            elif msg == 'OFF':
                self.in_door_label.setText(
                    '<p style="color:#C62828">CLOSED</p>')

        elif topic == 'indoor_temp_cb':

            msg = int(float(msg))
            if msg > 22 and msg < 28:
                self.in_temp_label.setText(
                    '<p style="color:#2E7D32">{}°</p>'.format(msg))
            elif msg <= 22:
                self.in_temp_label.setText(
                    '<p style="color:#1565C0">{}°</p>'.format(msg))
            elif msg >= 28:
                self.in_temp_label.setText(
                    '<p style="color:#C62828">{}°</p>'.format(msg))

        elif topic == 'indoor_alarm_cb':

            if msg == 'ON':
                self.in_alarm_label.setText(
                    '<p style="color:#2E7D32">Active</p>')
            elif msg == 'OFF':
                self.in_alarm_label.setText(
                    '<p style="color:#C62828">Inactive</p>')

        elif topic == 'outdoor_light_cb':

            if msg == 'ON':
                self.out_light_label.setText('<p style="color:#2E7D32">ON</p>')
                self.out_light_level_label.setText(
                    '<p style="color:#2E7D32">100%</p>')
            elif msg == 'OFF':
                self.out_light_label.setText(
                    '<p style="color:#C62828">OFF</p>')
                self.out_light_level_label.setText('-')
            elif msg == 'AUTO':
                self.out_light_label.setText(
                    '<p style="color:#1565C0">AUTO</p>')
                self.out_light_level_label.setText('-')
            else:
                self.out_light_label_setText('<p style="color:#2E7D32">ON</p>')
                self.out_light_level_label.setText(
                    '<p style="color:#2E7D32">{}%</p>'.format(msg))

        elif topic == 'irrigation_cb':

            if msg == 'ON':
                self.out_irri_label.setText('<p style="color:#2E7D32">ON</p>')
                self.out_irri_level_label.setText(
                    '<p style="color:#2E7D32">100%</p>')
            elif msg == 'OFF':
                self.out_irri_label.setText('<p style="color:#C62828">OFF</p>')
                self.out_irri_level_label.setText('-')
            elif msg == 'AUTO':
                self.out_irri_label.setText(
                    '<p style="color:#1565C0">AUTO</p>')
                self.out_irri_level_label.setText('-')
            else:
                self.out_irri_label.setText('<p style="color:#2E7D32">ON</p>')
                self.out_irri_level_label.setText(
                    '<p style="color:#2E7D32">{}%</p>'.format(msg))

        elif topic == 'outdoor_temp_cb':

            msg = int(float(msg))
            if msg >= 23 and msg <= 27:
                self.out_temp_label.setText(
                    '<p style="color:#2E7D32">{}°</p>'.format(msg))
            elif msg <= 22:
                self.out_temp_label.setText(
                    '<p style="color:#1565C0">{}°</p>'.format(msg))
            elif msg >= 28:
                self.out_temp_label.setText(
                    '<p style="color:#C62828">{}°</p>'.format(msg))

        elif topic == 'outdoor_hum_cb':

            msg = int(float(msg))
            if msg >= 45 and msg <= 55:
                self.out_hum_label.setText(
                    '<p style="color:#2E7D32">{}</p>'.format(msg))
            else:
                self.out_hum_label.setText(
                    '<p style="color:#C62828">{}</p>'.format(msg))

        elif topic == 'outdoor_alarm_cb':

            if msg == 'ON':
                self.out_alarm_label.setText(
                    '<p style="color:#2E7D32">Active</p>')
            elif msg == 'OFF':
                self.out_alarm_label.setText(
                    '<p style="color:#C62828">Inactive</p>')

        elif topic == 'alarm_anime':
            if msg == 'alarm':
                if self.alarm_status == 'off':
                    self.alarm('start')
            elif msg == 'fire_red':
                self.fire_button.setStyleSheet(red_style)
            elif msg == 'fire_blue':
                self.fire_button.setStyleSheet(blue_style)
            elif msg == 'fire_green':
                self.fire_button.setStyleSheet(green_style)
            elif msg == 'water_red':
                self.water_button.setStyleSheet(red_style)
            elif msg == 'water_blue':
                self.water_button.setStyleSheet(blue_style)
            elif msg == 'water_green':
                self.water_button.setStyleSheet(green_style)
            elif msg == 'gas_red':
                self.gas_button.setStyleSheet(red_style)
            elif msg == 'gas_blue':
                self.gas_button.setStyleSheet(blue_style)
            elif msg == 'gas_green':
                self.gas_button.setStyleSheet(green_style)
            elif msg == 'motion_red':
                self.motion_button.setStyleSheet(red_style)
            elif msg == 'motion_blue':
                self.motion_button.setStyleSheet(blue_style)
            elif msg == 'motion_green':
                self.motion_button.setStyleSheet(green_style)
            elif msg == 'laser_red':
                self.laser_button.setStyleSheet(red_style)
            elif msg == 'laser_blue':
                self.laser_button.setStyleSheet(blue_style)
            elif msg == 'laser_green':
                self.laser_button.setStyleSheet(green_style)

        elif topic == 'camera':

            if msg == 'record':
                self.out_camera_label.setText(
                    '<p style="color:#2E7D32">Recording</p>')
            elif msg == 'stream':
                self.out_camera_label.setText(
                    '<p style="color:#2E7D32">Recording</p>')
                self.cam.show()
            elif msg == 'sleep':
                self.out_camera_label.setText(
                    '<p style="color:#C62828">Sleeping</p>')
            elif msg == 'nocam':
                self.out_camera_label.setText(
                    '<p style="color:#C62828">Not Available</p>')
            elif msg == 'close':
                self.st.stop()
                self.cam.close()
            elif msg == 'restart':
                self.rec.stop()
                self.rec.start()

    def database(self):
        row = 0
        col_name = 0
        col_code = 1
        col_year = 2
        col_uid = 3
        col_s1 = 4
        col_s2 = 5
        col_s3 = 6
        col_s4 = 7
        col_s5 = 8

        try:
            cnx = mysql.connector.connect(user='******',
                                          password='******',
                                          host='192.168.1.10',
                                          database='assc')
        except Exception:
            print('[MySQL]: Connection Failed')
        else:
            cursor = cnx.cursor()
            get_code = ("""SELECT aname, uid, code, year, s1, s2, s3,
                        s4, s5 FROM students""")
            cursor.execute(get_code)
            for (aname, uid, code, year, s1, s2, s3, s4, s5) in cursor:
                self.table.setItem(row, col_code, QTableWidgetItem(str(code)))
                self.table.setItem(row, col_year, QTableWidgetItem(str(year)))
                self.table.setItem(row, col_uid, QTableWidgetItem(uid))
                self.table.setItem(row, col_name, QTableWidgetItem(aname))
                self.table.setItem(row, col_s1, QTableWidgetItem(s1))
                self.table.setItem(row, col_s2, QTableWidgetItem(s2))
                self.table.setItem(row, col_s3, QTableWidgetItem(s3))
                self.table.setItem(row, col_s4, QTableWidgetItem(s4))
                self.table.setItem(row, col_s5, QTableWidgetItem(s5))
                row = row + 1
            cnx.commit()
            cursor.close()
            cnx.close()
Exemple #15
0
class MainWindow(DATA[0], DATA[1]):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.scrollArea.hide()
        self.label_6.hide()
        self.pushButton.clicked.connect(self.iniciar_sesion)
        self.setWindowTitle("PrograPop")
        self.scrollArea_2.hide()
        self.label_tiempo = QLabel("20", self)
        self.label_tiempo.move(500, 300)
        self.label_tiempo.resize(100, 100)
        self.label_tiempo.setFont(QFont("SansSerif", 20))
        self.label_tiempo.hide()
        self.song_name = None
        self.song = None
        self.salas = [{"name": "hola", "usuarios": [], "artistas": "None"}]
        self.a = 0
        self.chat = QListWidget(self)
        self.chat.resize(1000, 300)
        self.chat.move(30, 370)
        self.chat.hide()

    def iniciar_sesion(self):
        self.name = self.lineEdit.text()
        self.usuario_back = BE_Client.Client_Back(self)
        time.sleep(2)
        self.usuario_back.get_salas()
        time.sleep(2)
        self.lineEdit.hide()
        self.label_2.hide()
        self.pushButton.hide()
        self.titulo.setText("Elige una Sala")

        self.lista_items = QListWidget(self)

        for item in self.salas:
            self.lista_items.addItem(
                "Sala : {}, Usuarios: {}, artistas: {}".format(
                    item["name"], len(item["usuarios"]), item["artistas"]))

        self.lista_items.show()
        self.lista_items.resize(500, 200)
        self.lista_items.move(300, 200)

        self.lista_items.itemClicked.connect(self.conectarse_sala)
        self.actualizar = QPushButton("Actualizar", self)
        self.actualizar.move(1000, 100)
        self.actualizar.show()
        self.actualizar.clicked.connect(self.actualizar_salas)

    def conectarse_sala(self, item):
        self.lista_items.hide()
        name = item.text().split(",")[0].split(":")[1].replace(" ", "")

        self.sala_actual = name
        self.usuario_back.connect_sala(name)

        self.usuario_back.get_info()
        self.scrollArea.hide()
        self.titulo.setText(name)
        self.label_6.hide()
        self.actualizar.hide()
        self.volver = QPushButton("Salir", self)
        self.volver.move(30, 30)
        self.volver.clicked.connect(self.volver_menu)
        self.volver.show()

        # CHAT

        self.chat.show()
        self.chat.addItem("Chat")
        self.line_chat = QLineEdit(self)
        self.line_chat.move(40, 690)
        self.line_chat.resize(1000, 30)
        self.chatButton = QPushButton("Enviar", self)
        self.chatButton.move(1050, 690)
        self.chatButton.show()
        self.line_chat.show()
        self.chatButton.clicked.connect(self.enviar_mensaje)

        # Juego
        self.opcion1 = QPushButton("opcion1", self)
        self.opcion2 = QPushButton("opcion2", self)
        self.opcion3 = QPushButton("opcion3 ", self)

        self.opcion1.move(30, 200)
        self.opcion2.move(400, 200)
        self.opcion3.move(700, 200)

        self.opcion1.resize(200, 30)
        self.opcion2.resize(200, 30)
        self.opcion3.resize(200, 30)

        self.opcion1.show()
        self.opcion2.show()
        self.opcion3.show()

        self.opcion1.clicked.connect(self.opcion_selecta)
        self.opcion2.clicked.connect(self.opcion_selecta)
        self.opcion3.clicked.connect(self.opcion_selecta)

        while self.sala_actual != None:
            while not self.song_name:
                pass
            self.song = QSound(self.song_name)
            self.song_name = None
            self.song.play()
            self.label_tiempo.show()
            self.opcion1.show()
            self.opcion2.show()
            self.opcion3.show()
            QTest.qWait(1000)
            QTest.qWait(1000)
            self.label_tiempo.setText("19")
            QTest.qWait(1000)
            self.label_tiempo.setText("19")
            QTest.qWait(1000)
            self.label_tiempo.setText("17")
            QTest.qWait(1000)
            self.label_tiempo.setText("16")
            QTest.qWait(1000)
            self.label_tiempo.setText("15")
            QTest.qWait(1000)
            self.label_tiempo.setText("14")
            QTest.qWait(1000)
            self.label_tiempo.setText("13")
            QTest.qWait(1000)
            self.label_tiempo.setText("12")
            QTest.qWait(1000)
            self.label_tiempo.setText("11")
            QTest.qWait(1000)
            self.label_tiempo.setText("10")
            QTest.qWait(1000)
            self.label_tiempo.setText("9")
            QTest.qWait(1000)
            self.label_tiempo.setText("8")
            QTest.qWait(1000)
            self.label_tiempo.setText("7")
            QTest.qWait(1000)
            self.label_tiempo.setText("6")
            QTest.qWait(1000)
            self.label_tiempo.setText("5")
            QTest.qWait(1000)
            self.label_tiempo.setText("4")
            QTest.qWait(1000)
            self.label_tiempo.setText("3")
            QTest.qWait(1000)
            self.label_tiempo.setText("2")
            QTest.qWait(1000)
            self.label_tiempo.setText("1")
            QTest.qWait(1000)
            self.opcion1.hide()
            self.opcion2.hide()
            self.opcion3.hide()
            self.label_tiempo.hide()
            self.label_tiempo.setText("20")
            self.chat.addItem("Server: Preparate para la siguiente ronda")
            self.song.stop()
            QTest.qWait(1000)

    def actualizar_salas(self):
        self.lista_items.clear()
        self.usuario_back.get_salas()
        for item in self.salas:
            self.lista_items.addItem(
                "Sala : {}, Usuarios: {}, artistas: {}".format(
                    item["name"], len(item["usuarios"]), item["artistas"]))

    def volver_menu(self):
        self.chat.clear()
        self.chat.hide()
        self.usuario_back.get_salas()
        time.sleep(0.2)
        self.usuario_back.disconnect_sala(self.sala_actual)
        time.sleep(0.2)
        self.usuario_back.get_info()
        time.sleep(0.2)
        self.sala_actual = None
        self.song.stop()
        self.titulo.setText("Elige una Sala")
        self.label_6.setText("Bienvenido {}\nTienes {} puntos".format(
            self.name, self.usuario_back.puntos))
        self.label_6.show()
        self.label.setText("Nombre: {} - Usuarios : {} - Artistas : {}".format(
            self.salas[0]["name"], len(self.salas[0]["usuarios"]),
            self.salas[0]["artistas"]))
        self.lista_items.show()
        self.actualizar.show()
        self.volver.hide()
        self.line_chat.hide()
        self.chatButton.hide()
        self.scrollArea_2.hide()

        self.opcion1.hide()
        self.opcion2.hide()
        self.opcion3.hide()

    def enviar_mensaje(self):
        mensaje = self.line_chat.text()
        self.line_chat.setText("")
        self.usuario_back.chat(mensaje, self.sala_actual)

    def opcion_selecta(self):
        boton = self.sender()
        self.opcion1.hide()
        self.opcion2.hide()
        self.opcion3.hide()
        self.usuario_back.desicion(boton.text())
Exemple #16
0
class main(QtWidgets.QOpenGLWidget):
    def __init__(self, parent):
        QtWidgets.QOpenGLWidget.__init__(self, parent)
        self.started = False
        self.imageID_back = None
        self.in_scene = []
        self.ornaments = []
        self.elapsed_time_shoot = 0
        self.elapsed_time_asteroide = 0
        self.elapsed_time_inimigo = 0
        self.elapsed_time_planet = 920000000000 / 3
        self.elapsed_time_stars = 0
        self.elapsed_time_powers = 0
        self.elapsed_time_power_shoot = 0
        self.elapsed_time_power_speed = 0
        self.hack = False
        self.speed = False
        self.sound_laser = QSound("sound/laser.wav", self)
        self.sound_laser_enemy = QSound("sound/laserenemy.wav", self)
        self.sound_explosion = QSound("sound/explos.wav", self)
        self.sound_1000pts = QSound("sound/1000pts.wav", self)
        self.sound_inGame = QSound("sound/startScene.wav", self)
        self.sound_death = QSound("sound/nooo.wav", self)
        self.sound_power = QSound("sound/powerUp.wav", self)
        self.enemy_queue = Queue_rotative()
        self.asteroid_queue = Queue_rotative()
        self.bullets_queue = Queue_rotative()
        self.planets_queue = Queue_rotative()
        self.explosion_queue = Queue_rotative()
        self.propellant_queue = Queue_rotative()
        self.power_queue = Queue_rotative()
        self.animation_explosion = [None for i in range(EXPLOSION_FRAMES)]
        self.animation_propellant_enemy = [
            None for i in range(PROPELLANT_FRAMES)
        ]
        self.img_planets = [None for i in range(10)]
        self.img_nave_azul = None
        self.img_nave_amarela = None
        self.img_nave_preta = None
        self.img_tiro_azul = None
        self.img_tiro_preto = None
        self.img_tiro_amarelo = None
        self.img_tiro = None
        self.logo_init = None
        self.logo_end = None
        self.power_up_vida = None
        self.power_up_shoot = None
        self.power_up_speed = None
        self.myLogo_i = Logo()
        self.myLogo_e = Logo()
        self.myNave = None

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

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

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

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

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

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

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

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

    # Prepara a cena e carrega as texturas
    def initializeGL(self):
        glClearColor(0.0, 0.0, 0.0, 0.0)
        glShadeModel(GL_SMOOTH)
        glEnable(GL_DEPTH_TEST)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        glEnable(GL_ALPHA_TEST)
        glAlphaFunc(GL_NOTEQUAL, 0.0)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        gluPerspective(45, 1.65, 0.1, 500)
        gluLookAt(0, -100, 50, 0, 0, 0, 0, 1, 0)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

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

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

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

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

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

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

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

        self.init_queue()

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

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

        tx = 0
        ambiente = [0.2, 0.2, 0.2, 1.0]
        difusa = [0.7, 0.7, 0.7, 1.0]
        especular = [1.0, 1.0, 1.0, 1.0]
        posicao = [0.0, 3.0, 2.0, 0.0]
        lmodelo_ambiente = [0.2, 0.2, 0.2, 1.0]

        glLightfv(GL_LIGHT0, GL_AMBIENT, ambiente)
        glLightfv(GL_LIGHT0, GL_DIFFUSE, difusa)
        glLightfv(GL_LIGHT0, GL_POSITION, posicao)
        glLightfv(GL_LIGHT0, GL_SPECULAR, especular)
        glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodelo_ambiente)
        glEnable(GL_LIGHTING)
        glEnable(GL_LIGHT0)
        glEnable(GL_COLOR_MATERIAL)

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

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

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

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

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

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

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

        if event.key() == QtCore.Qt.Key_Down:
            self.myNave.moving_down = True
        if event.key() == QtCore.Qt.Key_S:
            self.myNave.moving_down = True

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

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

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

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

        if event.key() == QtCore.Qt.Key_Down:
            self.myNave.moving_down = False
        if event.key() == QtCore.Qt.Key_S:
            self.myNave.moving_down = False

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

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

        glClear(GL_COLOR_BUFFER_BIT)
        glLoadIdentity()

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

        glDisable(GL_DEPTH_TEST)

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

        # Verifica se o jogo foi iniciado
        if not self.started:
            return

        glEnable(GL_DEPTH_TEST)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        A_colliding_B_in_z = (A.get_z()[1] >= B.get_z()[0]
                              and A.get_z()[1] <= B.get_z()[1])
        # or
        B_colliding_A_in_z = (B.get_z()[1] >= A.get_z()[0]
                              and B.get_z()[1] <= A.get_z()[1])

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

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

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

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

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

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

    #  Quando o jogador morre
    def dead(self):
        self.reloc()
        self.myNave.dead = True
        self.sound_inGame.stop()
        self.sound_inGame = QSound("sound/gameOver.wav", self)
        self.sound_death.play()
        if self.sound_death.isFinished():
            self.sound_inGame.play()
        self.ornaments.append(self.myLogo_e)
        self.myLogo_e.inited = True
Exemple #17
0
class Lobby(ventana_principal, QtClass):

    send_msg = core.pyqtSignal(dict)
    give_inputs = core.pyqtSignal(list)
    give_users = core.pyqtSignal(dict)
    close_window = core.pyqtSignal(bool)

    def __init__(self, cliente):
        super().__init__()
        self.setupUi(self)
        self.cliente = cliente
        self.player = None
        self.setFixedSize(890, 700)
        self.init_widgets()
        self.host_widgets_set = False
        self.send_msg.connect(self.cliente.send)
        self.give_inputs.connect(self.cliente.set_inputs)
        self.give_users.connect(self.cliente.set_users)
        self.close_window.connect(self.cliente.close_lobby)
        self.users = {}
        self.chat_str = ""
        self.soundtrack = QSound('adrenaline.wav')
        self.soundtrack.play()

        self.player_list_items = []
        self.color_list = ['red', 'green', 'blue', 'yellow', 'cyan', 'purple']
        self.players_error_labels = [   self.Player1ErrorDisplayer, \
                                        self.Player2ErrorDisplayer, \
                                        self.Player3ErrorDisplayer, \
                                        self.Player4ErrorDisplayer  ]
        self.labels = [  self.Player1Label, \
                        self.Player2Label, \
                        self.Player3Label, \
                        self.Player4Label   ]
        self.color_lists = [ self.Player1ColorList, \
                            self.Player2ColorList, \
                            self.Player3ColorList, \
                            self.Player4ColorList   ]
        self.color_lists_previous_indexes = [   self.Player1ColorList_pi, \
                                                self.Player2ColorList_pi, \
                                                self.Player3ColorList_pi, \
                                                self.Player4ColorList_pi   ]
        self.english_to_spanish = {  "red" : "Rojo", \
                                    "green" : "Verde", \
                                    "blue" : "Azul", \
                                    "yellow" : "Amarillo", \
                                    "cyan" : "Cyan", \
                                    "purple" : "Morado"}
        self.allListsDisabled = False
        self.color_checker = core.QTimer(self)
        self.msg_color_update = False
        self.color_checker.timeout.connect(self.change_color_checker)
        self.color_checker.start(250)

        self.lft_key = None
        self.rgt_key = None
        self.key_inputs = [ [self.InputPlayer1Izq, \
                                self.InputPlayer1Drc], \
                            [self.InputPlayer2Izq, \
                                self.InputPlayer2Drc], \
                            [self.InputPlayer3Izq, \
                                self.InputPlayer3Drc], \
                            [self.InputPlayer4Izq, \
                                self.InputPlayer4Drc]   ]
        self.str_to_key = { 'q' : core.Qt.Key_Q, \
                            'w' : core.Qt.Key_W, \
                            'e' : core.Qt.Key_E, \
                            'r' : core.Qt.Key_R, \
                            't' : core.Qt.Key_T, \
                            'y' : core.Qt.Key_Y, \
                            'u' : core.Qt.Key_U, \
                            'i' : core.Qt.Key_I, \
                            'o' : core.Qt.Key_O, \
                            'p' : core.Qt.Key_P, \
                            'a' : core.Qt.Key_A, \
                            's' : core.Qt.Key_S, \
                            'd' : core.Qt.Key_D, \
                            'f' : core.Qt.Key_F, \
                            'g' : core.Qt.Key_G, \
                            'h' : core.Qt.Key_H, \
                            'j' : core.Qt.Key_J, \
                            'k' : core.Qt.Key_K, \
                            'l' : core.Qt.Key_L, \
                            'ñ' : 209, \
                            'z' : core.Qt.Key_Z, \
                            'x' : core.Qt.Key_X, \
                            'c' : core.Qt.Key_C, \
                            'v' : core.Qt.Key_V, \
                            'b' : core.Qt.Key_B, \
                            'n' : core.Qt.Key_N, \
                            'm' : core.Qt.Key_M     }
        self.input_error_labels = [ [self.Player1IzqKeyErrorLabel, \
                                        self.Player1DrcKeyErrorLabel], \
                                    [self.Player2IzqKeyErrorLabel, \
                                        self.Player2DrcKeyErrorLabel], \
                                    [self.Player3IzqKeyErrorLabel, \
                                        self.Player3DrcKeyErrorLabel], \
                                    [self.Player4IzqKeyErrorLabel, \
                                        self.Player4DrcKeyErrorLabel]   ]
        self.poderes = [False for i in range(6)]
        self.fps = 1
        self.win_score = 0
        self.radio = 0
        self.tick_corte = 0
        self.tiempo_corte = 0
        self.show()

    def init_widgets(self):
        self.Player1ColorList_pi = -1
        self.Player2ColorList_pi = -1
        self.Player3ColorList_pi = -1
        self.Player4ColorList_pi = -1
        self.AllDisplayer.setAutoFillBackground(True)
        pallete = self.palette()
        pallete.setColor(self.backgroundRole(), core.Qt.black)
        self.AllDisplayer.setPalette(pallete)
        self.EnviarButton.clicked.connect(self.get_msg)

    def init_Host_widgets(self):
        self.JugarButton.clicked.connect(self.start_countdown)

        self.FPSInput.setReadOnly(False)
        self.FPSButton.clicked.connect(self.set_fps)
        self.WinScoreInput.setReadOnly(False)
        self.WinScoreButton.clicked.connect(self.set_win_score)
        self.RadioInput.setReadOnly(False)
        self.RadioButton.clicked.connect(self.set_radio)
        self.TickCorteInput.setReadOnly(False)
        self.TickCorteButton.clicked.connect(self.set_tick_corte)
        self.TiempoCorteInput.setReadOnly(False)
        self.TiempoCorteButton.clicked.connect(self.set_tiempo_corte)

        self.UsainInput.setCheckable(True)
        self.UsainButton.clicked.connect(self.set_usain)
        self.LimpiessaInput.setCheckable(True)
        self.LimpiessaButton.clicked.connect(self.set_limpiessa)
        self.JaimeInput.setCheckable(True)
        self.JaimeButton.clicked.connect(self.set_jaime)
        self.CervessaInput.setCheckable(True)
        self.CervessaButton.clicked.connect(self.set_cervessa)
        self.FelipeInput.setCheckable(True)
        self.FelipeButton.clicked.connect(self.set_felipe)
        self.NebcoinsInput.setCheckable(True)
        self.NebcoinsButton.clicked.connect(self.set_nebcoins)

    def update_host_widgets(self, event):
        if self.cliente.isHost is not True:
            print('NO HOST')
            if event["parameter"] == "fps":
                self.FPSInput.setText(str(event["info"]))
            elif event["parameter"] == "win_score":
                self.WinScoreInput.setText(str(event["info"]))
            elif event["parameter"] == "radio":
                self.RadioInput.setText(str(event["info"]))
            elif event["parameter"] == "tick_corte":
                self.TickCorteInput.setText(str(event["info"]))
            elif event["parameter"] == "tiempo_corte":
                self.TiempoCorteInput.setText(str(event["info"]))
            elif event["parameter"] == "usain":
                self.UsainInput.setCheckState(event["info"])
            elif event["parameter"] == "limpiessa":
                self.LimpiessaInput.setCheckState(event["info"])
            elif event["parameter"] == "jaime":
                self.JaimeInput.setCheckState(event["info"])
            elif event["parameter"] == "cervessa":
                self.CervessaInput.setCheckState(event["info"])
            elif event["parameter"] == "felipe":
                self.FelipeInput.setCheckState(event["info"])
            elif event["parameter"] == "nebcoins":
                self.NebcoinsInput.setCheckState(event["info"])

    #Justificado porque esta seguido
    def set_fps(self):
        self.fps = int(self.FPSInput.text())
        msg_to_send = { "type" : "parameters_update", \
                        "parameter" : "fps", \
                        "info" : self.fps}
        self.send_msg.emit(msg_to_send)

    def set_win_score(self):
        self.win_score = int(self.WinScoreInput.text())
        msg_to_send = { "type" : "parameters_update", \
                        "parameter" : "win_score", \
                        "info" : self.win_score}
        self.send_msg.emit(msg_to_send)

    def set_radio(self):
        self.radio = int(self.RadioInput.text())
        msg_to_send = { "type" : "parameters_update", \
                        "parameter" : "radio", \
                        "info" : self.radio}
        self.send_msg.emit(msg_to_send)

    def set_tick_corte(self):
        self.tick_corte = int(self.TickCorteInput.text())
        msg_to_send = { "type" : "parameters_update", \
                        "parameter" : "tick_corte", \
                        "info" : self.tick_corte}
        self.send_msg.emit(msg_to_send)

    def set_tiempo_corte(self):
        self.tiempo_corte = int(self.TiempoCorteInput.text())
        msg_to_send = { "type" : "parameters_update", \
                        "parameter" : "tiempo_corte", \
                        "info" : self.tiempo_corte}
        self.send_msg.emit(msg_to_send)

    def set_usain(self):
        self.poderes[0] = int(self.UsainInput.isChecked())
        msg_to_send = { "type" : "parameters_update", \
                        "parameter" : "usain", \
                        "info" : self.poderes[0]}
        self.send_msg.emit(msg_to_send)

    def set_limpiessa(self):
        self.poderes[1] = int(self.LimpiessaInput.isChecked())
        msg_to_send = { "type" : "parameters_update", \
                        "parameter" : "limpiessa", \
                        "info" : self.poderes[1]}
        self.send_msg.emit(msg_to_send)

    def set_jaime(self):
        self.poderes[2] = int(self.JaimeInput.isChecked())
        msg_to_send = { "type" : "parameters_update", \
                        "parameter" : "jaime", \
                        "info" : self.poderes[2]}
        self.send_msg.emit(msg_to_send)

    def set_cervessa(self):
        self.poderes[3] = int(self.CervessaInput.isChecked())
        msg_to_send = { "type" : "parameters_update", \
                        "parameter" : "cervessa", \
                        "info" : self.poderes[3]}
        self.send_msg.emit(msg_to_send)

    def set_felipe(self):
        self.poderes[4] = int(self.FelipeInput.isChecked())
        msg_to_send = { "type" : "parameters_update", \
                        "parameter" : "felipe", \
                        "info" : self.poderes[4]}
        self.send_msg.emit(msg_to_send)

    def set_nebcoins(self):
        self.poderes[5] = int(self.NebcoinsInput.isChecked())
        msg_to_send = { "type" : "parameters_update", \
                        "parameter" : "nebcoins", \
                        "info" : self.poderes[5]}
        self.send_msg.emit(msg_to_send)

    def keyPressEvent(self, event):
        izq_key = self.key_inputs[self.player - 1][0]
        izq_label = self.input_error_labels[self.player - 1][0]
        drc_key = self.key_inputs[self.player - 1][1]
        drc_label = self.input_error_labels[self.player - 1][1]
        if izq_key.text() != '':
            if len(izq_key.text()) == 1:
                try:
                    self.lft_key = self.str_to_key[izq_key.text().lower()]
                except KeyError:
                    izq_label.setText( \
                                    'Ingrese\n' + \
                                    'una\n' + \
                                    'letra\n'   )
                    izq_label.setStyleSheet( \
                        f'font-weight: bolder; color: grey')
                    return
                if self.lft_key == self.rgt_key:
                    izq_label.setText( \
                                    'Tecla\n' + \
                                    'ya esta\n' + \
                                    'usada')
                    izq_label.setStyleSheet( \
                        f'font-weight: bolder; color: grey')
                    self.lft_key = None
                else:
                    izq_label.setText('')
            else:
                izq_label.setText( \
                                'Ingrese\n' + \
                                'una\n' + \
                                'letra\n' + \
                                'no una\n' + \
                                'palabra')
                izq_label.setStyleSheet( \
                    f'font-weight: bolder; color: grey')
        if drc_key.text() != '':
            if len(drc_key.text()) == 1:
                try:
                    self.rgt_key = self.str_to_key[drc_key.text().lower()]
                except KeyError:
                    drc_label.setText( \
                                    'Ingrese\n' + \
                                    'una\n' + \
                                    'letra\n'   )
                    drc_label.setStyleSheet( \
                        f'font-weight: bolder; color: grey')
                    return
                if self.rgt_key == self.lft_key:
                    drc_label.setText( \
                                    'Tecla\n' + \
                                    'ya esta\n' + \
                                    'usada')
                    drc_label.setStyleSheet( \
                        f'font-weight: bolder; color: grey')
                    self.rgt_key = None
                else:
                    drc_label.setText('')
            else:
                drc_label.setText( \
                                'Ingrese\n' + \
                                'una\n' + \
                                'letra\n' + \
                                'no una\n' + \
                                'palabra')
                drc_label.setStyleSheet( \
                    f'font-weight: bolder; color: grey')
        print(self.lft_key, self.rgt_key)

        if event.key() == core.Qt.Key_Return:
            if self.ChatInput.text() != '':
                self.get_msg()

    def get_msg(self):
        if self.ChatInput.text() != '':
            msg = { "type" : "chat", \
                    "username" : self.cliente.user, \
                    "data" : self.ChatInput.text()}
            self.ChatInput.setText('')
            self.send_msg.emit(msg)

    def start_countdown(self):
        msg = { "type" : "display_update", \
                "place" : "lobby", \
                "info" : "start_countdown"}
        self.send_msg.emit(msg)

    def update_playerlist(self, users):
        if self.player is None:
            self.player = len(users)
            self.block_keys_inputs()
            self.update_color_lists()
        for user in users.keys():
            if user not in self.users.keys():
                self.users[user] = users[user]
                item = widgets.QListWidgetItem()
                label_user = widgets.QLabel(user)
                widget = widgets.QWidget()
                layout = widgets.QHBoxLayout()
                layout.addWidget(label_user)
                color = f'font-weight: bolder; color: {users[user]}'
                label_user.setStyleSheet(color)
                self.update_player_widgets_color(user, \
                                        list(self.users.keys()).index(user), \
                                        users[user])
                if user == list(self.users.keys())[0]:
                    label_host = widgets.QLabel()
                    pixmap = gui.QPixmap('sprites/crown.png')
                    pixmap = pixmap.scaled(pixmap.width()* \
                                            (16*1.5/pixmap.width()), \
                                            pixmap.height()*\
                                            (16*1.5/pixmap.height()))
                    label_host.setPixmap(pixmap)
                    layout.addWidget(label_host)
                widget.setLayout(layout)
                # print(widget.layout().itemAt(0).widget().setText('Hola'))
                item.setSizeHint(widget.sizeHint())
                self.player_list_items.append(item)
                self.PlayerList.addItem(item)
                # self.PlayerList.addItem(f'{user}')
                self.PlayerList.setItemWidget(item, widget)
            else:
                self.users[user] = users[user]
                self.update_playerlist_networking(user)
        if self.host_widgets_set is False:
            if self.cliente.isHost:
                self.init_Host_widgets()
                self.host_widgets_set = True
        self.color_list = ['red', 'green', 'blue', 'yellow', 'cyan', 'purple']

    def update_playerlist_networking(self, user):
        player_index = list(self.users.keys()).index(user)
        color = f'font-weight: bolder; color: {self.users[user]}'
        print(player_index)
        self.PlayerList.itemWidget( \
            self.PlayerList.item(player_index)).layout().itemAt( \
                0).widget().setStyleSheet(color)
        self.update_player_widgets_color(user, \
                                list(self.users.keys()).index(user), \
                                self.users[user])

    def update_chatbox(self, msg):
        self.chat_str += f'{msg["username"]}: {msg["data"]}\n'
        self.ChatDisplayer.setText(self.chat_str)

    def init_countdown(self, event):
        if event is True:
            self.gridLayout_9.removeWidget(self.JugarButton)
            self.JugarButton.deleteLater()
            self.JugarButton = None
            self.CountDown = widgets.QLCDNumber(self)
            self.gridLayout_9.addWidget(self.CountDown)
            self.CountDown.display(5)
            self.CountDown.setDigitCount(len("5"))

    def update_countdown(self, event):
        self.CountDown.display(event)
        self.CountDown.setDigitCount(len(str(event)))
        if event == 0:
            self.give_inputs.emit([self.lft_key, self.rgt_key])
            self.give_users.emit(self.users)
            self.close_window.emit(True)
            self.hide()
            self.soundtrack.stop()

    def update_msg_color(self, event):
        self.msg_color_update = event

    def change_color_checker(self):
        if self.player is not None and self.msg_color_update is False:
            player_widget = { \
                        1 : [self.Player1ColorList, self.Player1ColorList_pi], \
                        2 : [self.Player2ColorList, self.Player2ColorList_pi], \
                        3 : [self.Player3ColorList, self.Player3ColorList_pi], \
                        4 : [self.Player4ColorList, self.Player4ColorList_pi]   }
            widget = player_widget[self.player][0]
            last_index = player_widget[self.player][1]
            if widget.currentIndex() != last_index:
                if self.color_list[widget.currentIndex()] not in \
                                                        self.users.values():
                    msg = { "type" : "color_update", \
                            "username" : self.cliente.user, \
                            "info" : self.color_list[widget.currentIndex()]}
                    self.send_msg.emit(msg)
                    self.msg_color_update = True
                else:
                    color_usado = self.color_list[widget.currentIndex()]
                    self.update_error_label(color_usado)

    def update_color_lists(self):
        for i in range(4):
            if i != self.player - 1:
                self.color_lists[i].setEnabled(False)

    def update_error_label(self, color):
        self.players_error_labels[self.player-1].setText( \
                                    'El color:\n' + \
                                    f'{self.english_to_spanish[color]}\n' + \
                                    'ya esta ocupado')
        self.players_error_labels[self.player-1].setStyleSheet( \
                                f'font-weight: bolder; color: grey')
        self.color_lists[self.player-1].setCurrentIndex( \
                        self.color_lists_previous_indexes[self.player-1])

    def update_player_widgets_color(self, player, player_index, color):
        self.labels[player_index].setText(player)
        self.labels[player_index].setStyleSheet( \
                                        f'font-weight: bolder; color: {color}')
        self.color_lists[player_index].setCurrentIndex( \
                                            self.color_list.index(color))
        self.color_lists_previous_indexes[player_index] = \
                                    self.color_lists[player_index].currentIndex()
        self.Player1ColorList_pi = self.color_lists_previous_indexes[0]
        self.Player2ColorList_pi = self.color_lists_previous_indexes[1]
        self.Player3ColorList_pi = self.color_lists_previous_indexes[2]
        self.Player4ColorList_pi = self.color_lists_previous_indexes[3]
        self.players_error_labels[self.player - 1].setText('')

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

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

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

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

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

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

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

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

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

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

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

        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        glEnable(GL_ALPHA_TEST)
        glAlphaFunc(GL_NOTEQUAL, 0.0)

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

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

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

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

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

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

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

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

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

        self.init_queue()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        glClear(GL_COLOR_BUFFER_BIT)
        glLoadIdentity()

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

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

        glBindTexture(GL_TEXTURE_2D, self.imageID_back)

        glPushMatrix()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    #  Quando o jogador morre
    def dead(self):
        self.reloc()
        self.myNave.dead = True
        self.sound_inGame.stop()
        self.sound_inGame = QSound("sound/gameOver.wav", self)
        self.sound_death.play()
        if self.sound_death.isFinished():
            self.sound_inGame.play()
        self.ornaments.append(self.myLogo_e)
        self.myLogo_e.inited = True
Exemple #19
0
class App(QMainWindow):
    file = None
    wave = None

    def __init__(self):
        super().__init__()
        self.title = 'Projekt MN - 18723'
        self.left = 200
        self.top = 200
        self.width = 640
        self.height = 480
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.setWindowIcon(QIcon('./fav.png'))
        self.statusBar().showMessage(self.wave)

        qtRectangle = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qtRectangle.moveCenter(centerPoint)
        self.move(qtRectangle.topLeft())

        boldFont = QFont()
        boldFont.setBold(True)

        labelFileName = QLabel(self)
        labelFileName.setFont(boldFont)
        labelFileName.setGeometry(10, 40, 100, 50)
        labelFileName.setText("Nazwa:")

        self.labelFileNameValue = QLabel(self)
        self.labelFileNameValue.setGeometry(100, 40, 400, 50)
        self.labelFileNameValue.setText("None")

        labelChannel = QLabel(self)
        labelChannel.setFont(boldFont)
        labelChannel.setGeometry(10, 80, 150, 50)
        labelChannel.setText("Kanał(y):")

        self.labelChannelValue = QLabel(self)
        self.labelChannelValue.setGeometry(120, 80, 120, 50)
        self.labelChannelValue.setText("None")

        labelSampleWidth = QLabel(self)
        labelSampleWidth.setGeometry(10, 120, 220, 50)
        labelSampleWidth.setFont(boldFont)
        labelSampleWidth.setText("Długość Próbki [bit]: ")

        self.labelSampleWidthValue = QLabel(self)
        self.labelSampleWidthValue.setGeometry(240, 120, 150, 50)
        self.labelSampleWidthValue.setText("None")

        labelSampleFreq = QLabel(self)
        labelSampleFreq.setGeometry(10, 160, 300, 50)
        labelSampleFreq.setFont(boldFont)
        labelSampleFreq.setText("Częstotliwość Próbkowania: ")

        self.labelSampleFreqValue = QLabel(self)
        self.labelSampleFreqValue.setGeometry(320, 160, 100, 50)
        self.labelSampleFreqValue.setText("None")

        labelDuration = QLabel(self)
        labelDuration.setFont(boldFont)
        labelDuration.setGeometry(10, 200, 150, 50)
        labelDuration.setText("Czas trwania:")

        self.labelDurationValue = QLabel(self)
        self.labelDurationValue.setGeometry(170, 200, 120, 50)
        self.labelDurationValue.setText("None")

        #Menu
        menuBar =  self.menuBar()

        fileOpenAction = QAction("&Otworz", self)
        fileOpenAction.setShortcut("Ctrl+O")
        fileOpenAction.setStatusTip('Otworz plik audio')
        fileOpenAction.triggered.connect(self.file_open)

        inputSignalAction = QAction("&Sygnał wejściowy", self)
        inputSignalAction.setStatusTip('Wykres sygnału wejściowego')
        inputSignalAction.triggered.connect(self.input_signal)

        spectrogramAction = QAction("&Spectrogram", self)
        spectrogramAction.setStatusTip('Wykres Spektograficzny')
        spectrogramAction.triggered.connect(self.spectrogram)

        specrumAmplitudeAction = QAction("&Widmo amplitudowe", self)
        specrumAmplitudeAction.setStatusTip('Wykres widma aplitudowego')
        specrumAmplitudeAction.triggered.connect(self.spectrum_amplitude)

        specrumAmplitudeDBAction = QAction("&Widmo amplituowe [dB]", self)
        specrumAmplitudeDBAction.setStatusTip('Wykres widma aplitudowego w skali decybelowej')
        specrumAmplitudeDBAction.triggered.connect(self.spectrum_amplitude_db)

        periodogramAction = QAction("&Periodogram", self)
        periodogramAction.setStatusTip('Wykres widmowej gęstości mocy')
        periodogramAction.triggered.connect(self.periodogram)

        quitAction = QAction("&Zamknij", self)
        quitAction.setShortcut("Ctrl+Q")
        quitAction.setStatusTip('Wylacz applikacje')
        quitAction.triggered.connect(self.close_app)

        fileMenu = menuBar.addMenu('&Plik')
        fileMenu.addAction(fileOpenAction)
        fileMenu.addAction(quitAction)

        self.plotMenu = menuBar.addMenu('&Wykresy')
        self.plotMenu.addAction(inputSignalAction)
        self.plotMenu.addAction(spectrogramAction)
        self.plotMenu.addAction(periodogramAction)
        self.plotMenu.addAction(specrumAmplitudeAction)
        self.plotMenu.addAction(specrumAmplitudeDBAction)
        self.plotMenu.setEnabled(False)

        self.btn_play = QPushButton("Play", self)
        self.btn_play.setGeometry(0, 0, 80, 80)
        self.btn_play.move(240, 300)
        self.btn_play.setVisible(False)
        self.btn_play.clicked.connect(self.play_sound)

        self.btn_stop = QPushButton("Pause", self)
        self.btn_stop.setGeometry(0, 0, 80, 80)
        self.btn_stop.move(315, 300)
        self.btn_stop.setVisible(False)
        self.btn_stop.clicked.connect(self.stop_sound)

        self.show()

    def close_app(self):
        print('Close')
        sys.exit()

    def prints(self):
        print(self.wave)

    def file_open(self):
        try:
            self.file = QFileDialog.getOpenFileName(self,"Open File", os.getcwd(), 'WAV(*.wav)')
            self.wave = wave.openfp(self.file[0], 'rb')
            self.show_info()

            with self.wave:
                self.plotMenu.setEnabled(True)
                self.statusBar().showMessage("Wczytano plik!")
                self.show_info
                self.sound = QSound(self.file[0])
                self.show_player()

        except FileNotFoundError:
            print('Nie udało się otworzyć pliku!')

    def show_info(self):
        self.labelFileNameValue.setText(os.path.basename(self.file[0]))
        self.labelChannelValue.setText(str(self.wave.getnchannels()))
        self.labelSampleFreqValue.setText(str(self.wave.getframerate()) + ' Hz')
        self.labelSampleWidthValue.setText(str(self.wave.getsampwidth()))

        self.wav_duration = self.wave.getnframes() / float(self.wave.getframerate())
        self.labelDurationValue.setText(str(round(self.wav_duration, 2)) + 's')

    def show_player(self):
        self.btn_play.setVisible(True)
        self.btn_stop.setVisible(True)

    def play_sound(self):
        self.sound.play()

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

    def spectrogram(self):
        try:
            i = 0
            numberOfChannels = self.wave.getnchannels()
            sample_rate, samples = wavfile.read(self.file[0])

            if numberOfChannels > 1:
                fig, axarr = plt.subplots(2,1,True, num="Spectrogram")

                while i < numberOfChannels:
                    axarr[i].plot(i)
                    axarr[i].set_title('Kanał ' + str(i+1))
                    frequencies, times, spectrogram = signal.spectrogram(samples[:,i], sample_rate)
                    axarr[i].pcolormesh(times, frequencies, np.log(np.abs(spectrogram)))
                    axarr[i].set_xlabel('Czas [s]')
                    axarr[i].set_ylabel('Częstotliwość [Hz]')
                    i += 1
            else:
                plt.figure("Spectrogram")
                frequencies, times, spectrogram = signal.spectrogram(samples, sample_rate)

                plt.pcolormesh(times, frequencies, np.log(spectrogram))
                plt.title('Kanał 1')
                plt.xlabel('Czas [s]')
                plt.ylabel('Częstotliwość [Hz]')

            plt.subplots_adjust(hspace = .3)
            plt.show()
        except:
            QMessageBox.about(self, 'Bład!', 'Nie udało się utworzyć wykresu!')
            print(sys.exc_info()[0])

    def spectrum_amplitude(self):
        try:
            rate, spectrum = wavfile.read(self.file[0])

            fig, axarr = plt.subplots(2,1, num="Amplituda Widma")
            fig.suptitle("Widma Sygnału")

            axarr[0].plot(0)
            axarr[0].set_title("Pełne widmo sygnału [FFT]")
            spectrum_with_coupling = fft(spectrum)
            axarr[0].plot(spectrum_with_coupling)
            axarr[0].set_xlabel('Indeks widma')
            axarr[0].set_ylabel('Amplituda widma')

            axarr[1].plot(1)
            axarr[1].set_title("Widmo \"rzeczywiste\" sygnału [RFFT]")
            spectrum_without_coupling = rfft(spectrum)
            axarr[1].plot(spectrum_without_coupling)
            axarr[1].set_xlabel('Indeks widma')
            axarr[1].set_ylabel('Amplituda widma')

            plt.subplots_adjust(hspace = .5)
            plt.show()
        except:
            QMessageBox.about(self, 'Bład!', 'Nie udało się utworzyć wykresu!')

    def input_signal(self):
        try:
            rate, spectrum = wavfile.read(self.file[0])

            plt.figure('Sygnal Wejsciowy')
            plt.plot(spectrum)
            plt.title('Sygnał Wejsciowy')
            plt.xlabel('Indeks')
            plt.show()
        except:
            QMessageBox.about(self, 'Bład!', 'Nie udało się utworzyć wykresu!')

    def spectrum_amplitude_db(self):
        try:
            rate, spectrum = wavfile.read(self.file[0])
            numberOfChannels = self.wave.getnchannels()

            if numberOfChannels > 1:
                frequencies, times, spectrogram = signal.spectrogram(spectrum[:,0], rate)
            else:
                frequencies, times, spectrogram = signal.spectrogram(spectrum, rate)

            fig, axarr = plt.subplots(2,1, num="Amplituda Widma - Skala Decybelowa")

            axarr[0].plot(0)
            axarr[0].set_title("Skala liniowa")
            axarr[0].plot(frequencies, np.abs(rfft(spectrogram)), 'r-')
            axarr[0].set_xlabel('Czestotliwosc [Hz]')

            axarr[1].plot(1)
            axarr[1].set_title("Skala logarytmiczna")
            axarr[1].plot(frequencies, 20*np.log10(np.abs(spectrogram)), 'r-')
            axarr[1].set_xlabel('Czestotliwosc [Hz]')
            axarr[1].set_ylabel('Aplituda widma [dB]')

            plt.subplots_adjust(hspace = .5)
            plt.show()
        except:
            QMessageBox.about(self, 'Bład!', 'Nie udało się utworzyć wykresu!')

    def periodogram(self):
        try:
            rate, spectrum = wavfile.read(self.file[0])
            numberOfChannels = self.wave.getnchannels()

            if numberOfChannels > 1:
                freq, Pxx = signal.periodogram(spectrum[:,0], rate, 'hamming', self.wave.getnframes(), scaling='density')
            else:
                freq, Pxx = signal.periodogram(spectrum, rate, 'hamming', self.wave.getnframes(), scaling='density')

            plt.figure("Periodogram")
            plt.semilogy(freq, Pxx)
            plt.xlim(0, 10000)
            plt.xlabel('Częstotliwość [Hz]')
            plt.ylabel('Widmowa gęstość mocy')
            plt.show()
        except:
            QMessageBox.about(self, 'Bład!', 'Nie udało się utworzyć wykresu!')
Exemple #20
0
class MainWidget(QWidget):
    def __init__(self, parent = None):
        super().__init__(parent)
        self.main_window: QMainWindow = parent
        self.left = 10
        self.top = 10
        self.width = 600
        self.height = 800
        self.leftPanelWidth = 250
        self.initUI()
        self.initMplWidget()
        self.sample = QSound(ConfigControl.get_disorderPath())

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

    def playSample(self):
        self.sample.play()
Exemple #21
0
class InputTab(VoicelabTab):
    def __init__(self, data_controller, signals, tabs, *args, **kwargs):
        """
        Args:
            data_controller:
            signals:
            tabs:
            *args:
            **kwargs:
        """
        super().__init__(data_controller, signals, tabs, *args, **kwargs)
        self.signals = signals
        self.signals["on_files_changed"].connect(self.on_files_changed)
        self.initUI()

    def initUI(self):  # initUI() creates the gui

        # FilesTab
        self.layout = QVBoxLayout()

        # List of loaded voice files
        self.list_loaded_voices = QListWidget()
        # Allows user to select and rearrange multiple voices
        self.list_loaded_voices.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        # if an item changes, connect the signal
        self.list_loaded_voices.itemSelectionChanged.connect(
            self.onselection_change)

        # Create and connect add button
        btn_add_voices = QPushButton("Load Sound File(s)")
        btn_add_voices.clicked.connect(self.onclick_add)

        # Create and connect remove button
        btn_remove_voices = QPushButton("Remove Sound File(s)")
        btn_remove_voices.clicked.connect(self.onclick_remove)

        # Create and connect start button
        self.btn_start = QPushButton("Start Queue")
        self.btn_start.clicked.connect(self.onclick_start)
        self.btn_start.setDisabled(True)

        # Create and connect help button
        btn_help = QPushButton("Help")
        btn_help.clicked.connect(self.onclick_help)

        # Create and connect play button
        btn_play = QPushButton("Play Sound File(s)")
        btn_play.clicked.connect(self.onclick_play)

        # Create and connect stop button
        btn_stop = QPushButton("Stop Playing Sound File(s)")
        btn_stop.clicked.connect(self.onclick_stop)

        # Create the progress bar
        self.progress = QProgressBar()

        # Display the widgets in the correct order
        self.layout.addWidget(btn_add_voices)
        self.layout.addWidget(btn_remove_voices)
        self.layout.addWidget(btn_play)
        self.layout.addWidget(btn_stop)
        self.layout.addWidget(btn_help)
        self.layout.addWidget(self.list_loaded_voices)
        self.layout.addWidget(self.btn_start)
        self.layout.addWidget(self.progress)

        # Set the layout
        self.setLayout(self.layout)

    # onclick_help
    def onclick_help(self):
        """Displays help files"""
        try:
            # todo this breaks in compiled version, check pyinstaller or have it load from github pages
            url = 'Voicelab/help/index.html'
            webbrowser.open(url, new=2)  # open in new tab
        except:
            pass

    # onclick_play
    def onclick_play(self):
        """Plays sounds"""
        try:
            for self.soundfile in self.playlist:
                self.sound = QSound(self.soundfile)
                self.sound.play()
        except:
            pass

    # onclick_stop
    def onclick_stop(self):
        """Stops playing sounds"""
        try:
            self.sound.stop()
        except:
            pass

    ###############################################################################################
    # on_selection_change: callback for when the selection of files has changed.
    ###############################################################################################
    def onselection_change(self):
        """on_selection_change: callback for when the selection of files has changed."""
        active_widgets = self.list_loaded_voices.selectedItems()
        active_files = [i.text() for i in active_widgets
                        ]  # text method gets the filenames

        # simply pass the selected files on to the controller
        self.data_controller.activate_voices(active_files)
        # activate_voices: from a list of file paths, set the associated voice files for processing
        self.signals["on_files_changed"].emit(
            self.data_controller.active_voices)
        self.playlist = active_files  # create playlist to play sounds -currently only plays selected sound

    ###############################################################################################
    # onclick_add: callback for when the add file button is pressed. adds a list of files to the model
    ###############################################################################################
    def onclick_add(self):
        """onclick_add: This button opens a dialog to select sounds"""
        # Select a collection of voice files using the systems default dialog
        options = QFileDialog.Options()  # clear any file dialog options
        # get a list of file locations using the PyQt5 QFileDialog.getOpenFileNames function
        file_locations = QFileDialog.getOpenFileNames(
            self,
            "QFileDialog.getOpenFileNames()",
            "",
            "Sound Files (*.wav *.mp3 *.aiff *.ogg *.aifc *.au *.nist *.flac)",  # set what file types we'll read
            options=options,
        )[0]

        # Display the loaded files in a list. Only add if the file is not already loaded
        # drf You can add multiple copies of the same file to the list, but only one Parselmouth Sound object
        # drf ever goes into the self.data_controller.loaded_voices dictionary
        for file_location in file_locations:
            print(
                f"self.data_controller.loaded_voices {self.data_controller.loaded_voices}"
            )
            if file_location is not self.data_controller.loaded_voices:
                widget = QListWidgetItem(parent=self.list_loaded_voices)
                widget.setText(file_location)
                widget.setSelected(True)

            # This creates a Parselmouth Sound Object for each filename and puts it into the loaded_voices dictionary
            # The key is the filename and the value is the parselmouth sound object
            self.data_controller.load_voices([file_location])

        # Send the signal that the active voices list has changed
        if len(file_locations) > 0:
            self.signals["on_files_changed"].emit(
                self.data_controller.active_voices)

    ###############################################################################################
    # on_files_changed: callback for when the list of files are changes to update the displayed list.
    ###############################################################################################
    def on_files_changed(self, file_locations):
        """
        Args:
            file_locations:
        """
        # If there are no voices loaded, disable the start button, otherwise enable it
        if len(file_locations) > 0:
            self.btn_start.setDisabled(False)
        else:
            self.btn_start.setDisabled(True)

    ###############################################################################################
    # onclick_remove()
    # Remove all of the selected voice files from the list gui and the data model
    ###############################################################################################
    def onclick_remove(self):
        try:
            active_files = self.list_loaded_voices.selectedItems(
            )  # get list of selected files

            for list_item in active_files:  # go through list of select files
                file_path = list_item.text(
                )  # get the file path from the list of files
                self.data_controller.unload_voices(
                    [file_path])  # unload the voices from the datta controller
                self.list_loaded_voices.takeItem(
                    self.list_loaded_voices.row(
                        list_item))  # take the items of the gui list

            self.signals["on_files_changed"].emit(
                self.data_controller.active_voices
            )  # send a signal that the list of voices changed
        except:
            pass

    ###############################################################################################
    # onclick_start()
    # Constructs and starts a WARIO pipeline to process loaded voices according to the settings
    ###############################################################################################
    def onclick_start(self):

        self.data_controller.reset_figures()  # reset the figures

        n_voices = len(self.data_controller.active_voices
                       )  # count how many files to process
        n_functions = len(
            self.data_controller.active_functions
        ) + 1  # count how many functions to run + 1 (why +1?)
        self.progress.setMinimum(0)  # start progress bar at 0
        self.progress.setMaximum(n_voices *
                                 n_functions)  # end of the progress bar
        self.signals["on_progress_update"].connect(
            self.on_progress_updated)  # connect signal to update progress bar

        self.start_process(
        )  # start the pipeline - code in VoiceLabTab.VoiceLabTab

        self.tabs.setCurrentIndex(2)

    ###############################################################################################
    # on_progress_updated: callback function for when progress is made during pipeline processing
    # + node: the name of the node that finished running
    # + start: the progress number this started with (most often 0)
    # + current: the current progress as an integer of how many nodes have finished processing
    # + end: the total number of nodes that will be processed as reported at the start of processing
    ###############################################################################################
    def on_progress_updated(self, node, start, current, end):
        """
        Args:
            node:
            start:
            current:
            end:
        """
        self.progress.setValue(current)
        print(node, start, current, end)
Exemple #22
0
class main(QtWidgets.QOpenGLWidget):
    ########### INITIALIZE AND CREATE VAR ##################
    def __init__(self, parent):
        QtWidgets.QOpenGLWidget.__init__(self, parent)
        self.started = False
        self.imageID_back = None
        self.in_scene = []
        self.ornaments = []
        self.moveSettings()
        self.player_x = 0
        self.player2_x = 20

        self.elapsed_time_shoot = 0
        self.elapsed_time_asteroide = 0
        self.elapsed_time_inimigo = 0
        self.elapsed_time_flower = 500000000000 / 2
        self.elapsed_time_planet = 920000000000 / 3
        self.elapsed_time_stars = 0
        self.hack = False
        ########## SOUNDS ##################
        self.sound_laser = QSound("sound/laser.wav", self)
        self.sound_laser_enemy = QSound("sound/laserenemy.wav", self)
        self.sound_explosion = QSound("sound/explos.wav", self)
        self.sound_1000pts = QSound("sound/1000pts.wav", self)
        self.sound_inGame = QSound("sound/startScene.wav", self)
        self.sound_death = QSound("sound/nooo.wav", self)
        ########### LISTS OBJECTS ##################
        self.enemy_queue = Queue_rotative()
        self.asteroid_queue = Queue_rotative()
        self.bullets_queue = Queue_rotative()
        self.flowers_queue = Queue_rotative()
        self.planets_queue = Queue_rotative()
        # self.stars_queue = Queue_rotative()
        self.explosion_queue = Queue_rotative()
        self.propellant_queue = Queue_rotative()

        self.animation_explosion = [None for i in range(EXPLOSION_FRAMES)]
        self.animation_propellant_enemy = [
            None for i in range(PROPELLANT_FRAMES)
        ]
        self.img_nave_azul = None
        self.img_nave_amarela = None
        self.img_nave_preta = None
        self.img_tiro_azul = None
        self.img_tiro_preto = None
        self.img_tiro_amarelo = None
        self.img_tiro = None
        self.logo_init = None
        self.logo_end = None

        self.myLogo_i = Logo()
        self.myLogo_e = Logo()

        self.myNave = None
        self.myNave2 = None

    def init_queue(self):

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

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

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

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

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

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

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

    ########### KEYBOARD PLAYER FUNC ##################
    def moveSettings(self):
        self.shortcut_left = QShortcut(QtCore.Qt.Key_A, self)
        self.shortcut_left.activated.connect(self.move_left)

        self.shortcut_right = QShortcut(QtCore.Qt.Key_D, self)
        self.shortcut_right.activated.connect(self.move_right)

        self.shortcut_left_shoot = QShortcut(QtCore.Qt.Key_Q, self)
        self.shortcut_left_shoot.activated.connect(self.move_left_and_shoot)

        self.shortcut_right_shoot = QShortcut(QtCore.Qt.Key_E, self)
        self.shortcut_right_shoot.activated.connect(self.move_right_and_shoot)

        self.shortcut_up = QShortcut(QtCore.Qt.Key_W, self)
        self.shortcut_up.activated.connect(self.player_shoot)

        self.shortcut_hack = QShortcut(QtCore.Qt.Key_T, self)
        self.shortcut_hack.activated.connect(self.active_hack)

        self.shortcut_left = QShortcut(QtCore.Qt.Key_J, self)
        self.shortcut_left.activated.connect(self.move2_left)

        self.shortcut_right = QShortcut(QtCore.Qt.Key_L, self)
        self.shortcut_right.activated.connect(self.move2_right)

        self.shortcut_up = QShortcut(QtCore.Qt.Key_I, self)
        self.shortcut_up.activated.connect(self.player2_shoot)

    ########### PREPARING THE SCENE ##################
    def initializeGL(self):
        glClearColor(0.0, 0.0, 0.0, 0.0)
        glShadeModel(GL_SMOOTH)

        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        glEnable(GL_ALPHA_TEST)
        glAlphaFunc(GL_NOTEQUAL, 0.0)

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

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

        self.myNave2 = Nave(self.animation_propellant_enemy, self.player2_x)
        self.in_scene.append(self.myNave2)

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

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

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

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

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

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

        self.init_queue()

    def loadImage(self, path):
        im = Image.open(path)

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

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

    ########### PAINT FUNC ##################
    def paintGL(self):
        self.check_end_backm()
        self.update()
        if self.myNave.dead:
            self.started = False

        glClear(GL_COLOR_BUFFER_BIT)
        glLoadIdentity()

        ########### DRAW BACKGROUND ##################
        glColor3f(1.0, 1.0, 1.0)
        glDisable(GL_LIGHTING)
        glEnable(GL_TEXTURE_2D)

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

        glBindTexture(GL_TEXTURE_2D, self.imageID_back)

        glPushMatrix()

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

        glPopMatrix()
        glDisable(GL_TEXTURE_2D)

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

        ########### DRAW ORNAMENTS ##################
        for obj in self.ornaments:
            if not obj == None:
                if obj.dead:
                    if isinstance(obj, Flor):
                        self.flowers_queue.push(obj)
                        self.ornaments.remove(obj)
                    elif isinstance(obj, Planeta):
                        self.planets_queue.push(obj)
                        self.ornaments.remove(obj)
                    elif isinstance(obj, Star):
                        self.ornaments.remove(obj)
                obj.draw()
                obj.act()
                obj.check_dead()

        # print(self.bullets_queue.tam())
        ########### VERIFY IF THE GAME HAS STARTED ##################
        if (not self.started):
            return

        ########### DRAW SCENE ##################
        for obj in self.in_scene:
            if not obj == None:
                if obj.dead:
                    if isinstance(obj, Enemy):
                        new_explosion = self.explosion_queue.pop()
                        new_explosion.load(self.animation_explosion,
                                           obj.move_x + obj.position_x,
                                           obj.move_y + 6, "enemy")
                        self.in_scene.append(new_explosion)
                        self.enemy_queue.push(obj)
                        self.in_scene.remove(obj)
                    elif isinstance(obj, Asteroide):
                        new_explosion = self.explosion_queue.pop()
                        new_explosion.load(self.animation_explosion,
                                           obj.move_x + obj.position_x,
                                           obj.move_y + 5, "enemy")
                        self.in_scene.append(new_explosion)
                        self.asteroid_queue.push(obj)
                        self.in_scene.remove(obj)
                    elif isinstance(obj, Shoot):
                        self.bullets_queue.push(obj)
                        self.in_scene.remove(obj)
                    elif isinstance(obj, Explode):
                        obj.dead = False
                        self.explosion_queue.push(obj)
                        self.in_scene.remove(obj)
                obj.draw()
                obj.act()
                obj.check_dead()

        ########### COLLISION CHECK ##################
        for obj_A in self.in_scene:
            if isinstance(obj_A, Asteroide):
                for obj_B in self.in_scene:
                    if not (obj_A == obj_B):
                        if isinstance(obj_B, Nave) and self.collide(
                                obj_B, obj_A):
                            # obj_B.dead = True
                            ui.down_life()
                            obj_A.dead = True
                        elif isinstance(obj_B, Shoot) and self.collide(
                                obj_B, obj_A):
                            if not obj_B.is_enemy:
                                obj_A.dead = True
                                if not self.hack:
                                    obj_B.dead = True
                                self.sound_explosion.play()
                                ui.up_point(10)
                                if ui.score % 1000 == 0:
                                    self.sound_1000pts.play()
            elif isinstance(obj_A, Enemy):
                obj_A.elapsed_shoot_time += time()
                if obj_A.elapsed_shoot_time >= SHOOT_TIME_ENEMY:
                    if obj_A.nave_type == 0:
                        self.create_shoot(obj_A.move_x + obj_A.position_x,
                                          obj_A.move_y, obj_A.move_y + 6, True,
                                          obj_A.nave_type, obj_A.shoot_type,
                                          self.img_tiro_azul)
                    elif obj_A.nave_type == 1:
                        self.create_shoot(obj_A.move_x + obj_A.position_x,
                                          obj_A.move_y, obj_A.move_y + 6, True,
                                          obj_A.nave_type, obj_A.shoot_type,
                                          self.img_tiro_amarelo)
                    elif obj_A.nave_type == 2:
                        self.create_shoot(obj_A.move_x + obj_A.position_x,
                                          obj_A.move_y, obj_A.move_y + 6, True,
                                          obj_A.nave_type, obj_A.shoot_type,
                                          self.img_tiro_preto)

                    obj_A.elapsed_shoot_time = 0
                for obj_B in self.in_scene:
                    if not (obj_A == obj_B):
                        if isinstance(obj_B, Nave) and self.collide(
                                obj_B, obj_A):
                            # obj_B.dead = True
                            ui.down_life()
                            obj_A.dead = True
                        elif isinstance(obj_B, Shoot) and self.collide(
                                obj_B, obj_A):
                            if not obj_B.is_enemy:
                                obj_A.dead = True
                                if self.hack:
                                    obj_B.dead = False
                                else:
                                    obj_B.dead = True
                                self.sound_explosion.play()
                                ui.up_point(10)
                                if ui.score % 1000 == 0:
                                    self.sound_1000pts.play()
            elif isinstance(obj_A, Shoot):
                if obj_A.is_enemy:
                    for obj_B in self.in_scene:
                        if not (obj_A == obj_B):
                            if isinstance(obj_B, Nave) and self.collide(
                                    obj_B, obj_A):
                                # obj_B.dead = True
                                ui.down_life()
                                obj_A.dead = True

        self.spawn_asteroide()
        self.spawn_inimigos()

        self.update()

    def check_end_backm(self):
        if self.sound_inGame.isFinished():
            self.sound_inGame.play()

    def update_time(self):
        self.elapsed_time_shoot += time()
        self.elapsed_time_asteroide += time()
        self.elapsed_time_inimigo += time()
        self.elapsed_time_flower += time()
        self.elapsed_time_planet += time()
        self.elapsed_time_stars += time()

    def spawn_stars(self):
        if self.elapsed_time_stars >= SPANW_TIME_STARS:
            position = randint(-49, 49)
            scale = self.rand_tam_star()
            new_star = Star(position, scale)
            self.ornaments.append(new_star)
            self.elapsed_time_stars = 0

    def spawn_planets(self):
        if self.elapsed_time_planet >= SPANW_TIME_PLANET:
            position = randint(-50, 50)
            scale = self.rand_tam()
            new_planet = self.planets_queue.pop()
            new_planet.load(position, scale)
            self.ornaments.append(new_planet)
            self.elapsed_time_planet = 0

    def rand_tam(self):
        return float(str(randint(0, 2)) + "." + str(randint(1, 5)))

    def rand_tam_star(self):
        return float("0." + str(randint(1, 3)))

    def spawn_flowers(self):
        if self.elapsed_time_flower >= SPANW_TIME_FLOWER:
            position = randint(-50, 50)

            new_flower = self.flowers_queue.pop()
            new_flower.load(position)
            self.ornaments.append(new_flower)
            self.elapsed_time_flower = 0

    ########### SPAWNING ASTEROIDE FUNCS #################
    def spawn_asteroide(self):
        if self.elapsed_time_asteroide >= SPANW_TIME:
            new_aste = self.asteroid_queue.pop()
            new_aste.load(randint(-49, 43))
            self.in_scene.append(new_aste)
            self.elapsed_time_asteroide = 0

    ########### SPAWNING ASTEROIDE FUNCS #################
    def spawn_inimigos(self):
        if self.elapsed_time_inimigo >= SPANW_TIME_ENEMY:
            self.create_inimigos()

    def create_inimigos(self):
        new_inimigo = self.enemy_queue.pop()
        new_inimigo.load(randint(-49, 43), self.animation_propellant_enemy,
                         self.img_nave_azul, self.img_nave_amarela,
                         self.img_nave_preta)
        self.in_scene.append(new_inimigo)
        self.elapsed_time_inimigo = 0

    ########### MOVING PLAYER FUNCS #################
    def move_left(self):
        if self.myNave.move_x + self.myNave.position_x - 4.0 >= -47:
            self.myNave.move_left()
            self.player_x -= 3

    def move_left_and_shoot(self):
        if self.myNave.move_x + self.myNave.position_x - 4.0 >= -47:
            self.myNave.move_left()
            self.player_x -= 3
            self.create_shoot(self.player_x)

    def move_right(self):
        if self.myNave.move_x + self.myNave.position_x + 4.0 <= 47:
            self.myNave.move_right()
            self.player_x += 3

    def move_right_and_shoot(self):
        if self.myNave.move_x + self.myNave.position_x + 4.0 <= 47:
            self.myNave.move_right()
            self.player_x += 3
            self.create_shoot(self.player_x)

    #############NEWS##############################

    def move2_left(self):
        if self.myNave2.move_x + self.myNave2.position_x - 4.0 >= -47:
            self.myNave2.move_left()
            self.player2_x -= 3

    def move2_right(self):
        if self.myNave2.move_x + self.myNave2.position_x + 4.0 <= 47:
            self.myNave2.move_right()
            self.player2_x += 3

    ########### SHOOT PLAYER FUNC ##################
    ########### CREATE THE BULLET ##################
    def player_shoot(self):
        self.create_shoot(self.player_x)

    def player2_shoot(self):
        self.create_shoot(self.player2_x)

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

    ########### COLISION CHECK FUNC ##################
    def collide(self, A, B):
        A_colliding_B_in_x = (A.get_x()[1] >= B.get_x()[0]
                              and A.get_x()[1] <= B.get_x()[1])
        #or
        B_colliding_A_in_x = (B.get_x()[1] >= A.get_x()[0]
                              and B.get_x()[1] <= A.get_x()[1])

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

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

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

    def reestart(self):
        self.reloc()
        self.started = False
        self.in_scene = []
        self.player_x = 0
        self.player2_x = 20
        self.myNave = Nave(self.animation_propellant_enemy, self.player_x)
        self.myNave2 = Nave(self.animation_propellant_enemy,
                            self.player_x + 20)
        self.elapsed_time_shoot = 0
        self.elapsed_time_asteroide = 0
        self.elapsed_time_inimigo = 0
        self.hack = False
        self.in_scene.append(self.myNave)
        self.in_scene.append(self.myNave2)
        self.sound_inGame.stop()
        self.sound_inGame = QSound("sound/inGame.wav", self)
        self.sound_inGame.play()
        if self.myLogo_i.inited:
            self.ornaments.remove(self.myLogo_i)
            self.myLogo_i.inited = False
        if self.myLogo_e.inited:
            self.ornaments.remove(self.myLogo_e)
            self.myLogo_e.inited = False

    def reloc(self):
        for obj in self.in_scene:
            if isinstance(obj, Enemy):
                self.enemy_queue.push(obj)
                self.in_scene.remove(obj)
            elif isinstance(obj, Asteroide):
                self.asteroid_queue.push(obj)
                self.in_scene.remove(obj)
            elif isinstance(obj, Shoot):
                self.bullets_queue.push(obj)
                self.in_scene.remove(obj)
            elif isinstance(obj, Explode):
                self.explosion_queue.push(obj)
                self.in_scene.remove(obj)

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

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

        self.myLogo_i.inited = True

    def dead(self):
        self.myNave.dead = True
        self.sound_inGame.stop()
        self.sound_inGame = QSound("sound/gameOver.wav", self)
        self.sound_death.play()
        if self.sound_death.isFinished():
            self.sound_inGame.play()
        self.ornaments.append(self.myLogo_e)
        self.myLogo_e.inited = True
Exemple #23
0
class App(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle('The Seeker of fire')
        self.showFullScreen()

        self.Text = QLabel(self)
        self.book = QLabel(self)
        self.location = QLabel(self)
        self.changed = False

        self.action_targ = QLabel(self)
        self.action_targ.resize(self.width() / 12, 10)
        self.action_targ.move(0, 0)
        self.action_targ.setStyleSheet('QLabel {background-color: Red;'
                                       'border-radius: 5px }')
        self.targ_pos = [(self.width() / 2.17, self.height() / 2.5 - 20),
                         (self.width() / 2.9, self.height() / 2.5 - 20),
                         (self.width() / 1.75, self.height() / 2.5 - 20)]

        self.the_right_answer = [False, False, False]

        self.ur_damage = 10
        self.e_damage = 0
        self.HP_points = 100
        self.eHP_points = 100
        self.result = False

        self.cursor = QCursor(QPixmap('cursor_3.png'))
        self.cursor.pixmap()
        self.setCursor(self.cursor)

        self.skip = QPushButton(self)
        self.skip.resize(100, 20)
        self.skip.move(self.width() / 2 + 180,
                       self.height() / 4 + self.height() / 16 + 20)
        self.skip.setText('SKIP')
        self.skip.setStyleSheet(
            'QPushButton {background-color: rgba(10, 20, 100, 0.2)}'
            'QPushButton:hover {background-color: Red}')
        self.read = True
        self.skip.clicked.connect(self.next)

        melody = 'DS2.wav'
        self.playable = QSound(melody)
        self.playable.play()

        melody2 = 'in_battle.wav'
        self.playable2 = QSound(melody2)
        self.next_melody = False

        self.movie = QMovie("fire_3.gif")
        self.movie.setScaledSize(QSize(self.width(), self.height()))
        self.movie.frameChanged.connect(self.repaint)
        self.movie.start()

        self.NPC_enemy = QLabel(self)
        self.NPC_enemy.resize(self.height() / 5, self.height() / 5)
        self.NPC_enemy.move(self.width() / 2.3, self.height() / 16)
        self.NPC_enemy.setStyleSheet(
            "QLabel {color: rgb(0, 0, 51);"
            'background-color: rgba(10, 20, 100, 0.2);'
            'border-color: rgba(100, 100, 100, 0.5);'
            'border-style: solid;'
            'border-width: 2px;'
            '}'
            'QLabel:hover {background-color: rgba(100, 0, 0, 0.7)}')

        self.book.resize(self.width() / 3, self.height() / 16)
        self.book.move(self.width() / 3, self.height() / 4 + 40)
        self.book.setStyleSheet(
            "QLabel {background-color: rgba(100, 40, 51, 0.5);"
            "text-align: center }")
        self.book.setFont(QFont('Times New Roman', 12))

        self.attack = QPushButton(self)
        self.defend = QPushButton(self)
        self.dodge = QPushButton(self)

        self.change_size('attack_proj.png',
                         (int(self.width() / 12), int(self.height() / 4)))
        self.change_size('shield.png',
                         (int(self.width() / 12), int(self.height() / 4)))
        self.change_size('dodging.png',
                         (int(self.width() / 12), int(self.height() / 4)))

        self.attack.setStyleSheet(
            'QPushButton {background-color: rgba(10, 20, 100, 0.2);'
            'border-color: rgb(10, 20, 100,);'
            'border-style: solid;'
            'border-width: 5px;'
            'border-radius: 40px;'
            'background-image: url(attack_proj.png)'
            '}'
            'QPushButton:pressed {background-image: url(DS3.jpg)}')
        self.attack.resize(self.width() / 12, self.height() / 4)
        self.attack.move(self.width() / 2.17, self.height() / 2.5)
        self.attack.clicked.connect(self.attack_fnc)

        self.defend.setStyleSheet(
            'QPushButton {background-color: rgba(10, 20, 100, 0.2);'
            'border-color: rgb(10, 20, 100,);'
            'border-style: solid;'
            'border-width: 5px;'
            'border-radius: 40px;'
            'background-image: url(shield.png)'
            '}'
            'QPushButton:pressed {background-image: url(DS3.jpg)}')
        self.defend.resize(self.width() / 12, self.height() / 4)
        self.defend.move(self.width() / 2.9, self.height() / 2.5)
        self.defend.clicked.connect(self.defend_fnc)

        self.dodge.setStyleSheet(
            'QPushButton {background-color: rgba(10, 20, 100, 0.2);'
            'border-color: rgb(10, 20, 100,);'
            'border-style: solid;'
            'border-width: 5px;'
            'border-radius: 40px;'
            'background-image: url(dodging.png)'
            '}'
            'QPushButton:pressed {background-image: url(DS3.jpg)}')
        self.dodge.resize(self.width() / 12, self.height() / 4)
        self.dodge.move(self.width() / 1.75, self.height() / 2.5)
        self.dodge.clicked.connect(self.dodge_fnc)

        self.Text.move(self.width() / 3, 0)
        self.Text.resize(self.width() / 3, self.height())
        self.Text.move(self.width() / 3, 0)

        self.Text.setStyleSheet(
            "QLabel {color: rgb(0, 0, 51);"
            'font-family: "Times New Roman", Georgia, Serif;'
            'font-size: 25px;'
            'background-color: rgba(10, 20, 100, 0.2);'
            'border-color: rgb(10, 20, 100,);'
            'border-style: solid;'
            'border-width: 5px'
            '}')
        self.HP = QProgressBar(self)
        self.HP.resize(self.width() / 3, 30)
        self.HP.move(self.width() / 3, self.height() * 0)
        self.HP.setStyleSheet(
            "QProgressBar{border: 1px solid transparent;text-align: center;"
            "color:rgba(255,255,250,0);"
            "border-radius: 10px;"
            "border-width: 8px;"
            "border-image: 9,2,5,2; "
            "background-color: Grey;"
            "}"
            "QProgressBar::chunk {background-color: qlineargradient(x1: 0, "
            "y1: 0, x2: 0, y2: 1, stop: 0 rgba(100,80,50,1), stop: 1 rgba(255,0,0,1));"
            "border-radius: 5px}")
        self.HP.setValue(self.HP_points)

        self.eHP = QProgressBar(self)
        self.eHP.resize(self.width() / 6, 10)
        self.eHP.setStyleSheet(
            "QProgressBar{border: 1px solid transparent;text-align: center;"
            "color:rgba(255,255,250,0);"
            "border-radius: 10px;"
            "border-width: 8px;"
            "border-image: 9,2,5,2; "
            "background-color: Grey"
            "}"
            "QProgressBar::chunk {background-color: qlineargradient(x1: 0, "
            "y1: 0, x2: 0, y2: 1, stop: 0 rgba(100,80,50,100), stop: 1 rgba(255,0,0,255));"
            "border-radius: 5px}")
        self.eHP.move(self.width() / 2.45, self.width() / 6.5)

        self.close_button = QPushButton(self)
        self.close_button.resize(self.width() / 4, self.height() / 20)
        self.close_button.move(self.width() / 3 + self.width() / 24,
                               self.height() / 1.07)
        self.close_button.setStyleSheet(
            'QPushButton {border: 3px solid;'
            'border-radius: 10px;'
            'background-color: Khaki'
            '}'
            'QPushButton:pressed{border: 1px solid;'
            'border-radius: 40px;'
            'background-color: Red'
            '}'
            'QPushButton:hover{background-color: rgba(255, 0, 0, 40)}')
        self.close_button.clicked.connect(self.close_event)
        self.close_button.setFont(QFont('Times New Roman', 20))
        self.close_button.setText('Выход')

        self.location.resize(self.width() / 3, self.height() / 8)
        self.location.move(self.width() / 3, self.height() / 4)
        self.location.setFont(QFont('Times New Roman', 20))
        self.location.setText('ЗАБРОШЕННЫЕ МОГИЛЫ')
        self.location.setStyleSheet(
            "QLabel {background-color: rgba(250, 40, 51, 0.5);"
            "}")
        self.location.setAlignment(Qt.AlignCenter)

        self.game()

    def next(self):
        self.read = False

    def paintEvent(self, event):
        currentframe = self.movie.currentPixmap()
        framerect = currentframe.rect()
        framerect.moveCenter(self.rect().center())
        if framerect.intersects(event.rect()):
            painter = QPainter(self)
            painter.drawPixmap(framerect.left(), framerect.top(), currentframe)

    def close_event(self):
        self.close()

    def game(self):
        dont_stop = threading.Thread(target=self.always_on)
        screen = threading.Thread(target=self.on_screen)
        screen.start()
        dont_stop.start()

    def on_screen(self):
        self.HP.show()
        self.close_button.show()
        self.Text.show()
        self.book.show()
        self.NPC_enemy.show()
        self.skip.show()
        self.attack.show()
        self.defend.show()
        self.dodge.show()
        self.eHP.show()

        self.write('И в самом деле. Замок, что зовётся Лотриком, ')
        self.write('стоит там, где сходятся земли Повелителей пепла. ')
        self.write(
            'Покоряя север, пилигримы убеждаются, что старые сказания не лгут')
        self.write('Огонь затухает, и повелители пепла покидают свои троны')
        self.write('Когда огонь под угрозой, когда звонит колокол,')
        self.write(' Повелители пепла поднимаются из своих могил.')
        self.write('Олдрик, святой покровитель глубин.')
        self.write('Легион нежити Фаррона, Хранители Бездны')
        self.write(
            'И мрачный правитель из осквернённой столицы - гигант Йорм.')
        self.write(
            'Но в действительности... Повелители оставят свои троны, и негорящие восстанут.'
        )
        self.write('Безымянная, проклятая нежить, недостойная стать пеплом.')
        self.write('И стало так. Негорящие всегда ищут угли.')

        self.location.show()
        time.sleep(2)
        self.location.close()

        self.write('Вы поднимаетесь из могилы. В руках у вас ваш меч. ')
        self.write('Вы чётко знате, что будуте делать дальше')
        self.write('Вам предстоит вернуть повелителей на свои троны и спасти ')
        self.write('угасающий мир от погружения во тьму')
        self.write('Перед вами тропа')
        self.write('Пути назад больше нет')
        self.write('...')
        self.write('Вы идете по тропе')

        self.write(
            'Перед вами Полый, нежить, потерявшая рассудок и навеки лишившаяся '
        )
        self.write('возможности прикоснуться к Огню')
        self.write('Полый достает меч')
        self.write('Приготовьтесь к битве')
        self.write(' ')

        self.NPC_enemy.close()
        self.NPC_enemy.setStyleSheet(
            'QLabel { background-image: url(hollow.jpg)}')
        time.sleep(0.3)
        self.NPC_enemy.show()
        self.next_melody = True
        self.playable.stop()
        # self.eHP.setValue(100)

        self.book.setStyleSheet('QLabel {color: Red }')

        self.the_right_answer = [False, False, True]
        self.write_in_battle('Усиленная атака сверху')
        time.sleep(2)

        if self.result is not True:
            self.write_in_battle('Вы погибли')
            time.sleep(2)
            self.close()
        else:
            self.eHP_points -= 10
            self.eHP.close()
            self.eHP.setValue(self.eHP_points)
            self.eHP.show()
            self.write_in_battle('Вы успешно уклонились')
            self.result = False

        self.the_right_answer = [False, True, False]
        self.write_in_battle('Противник потерял равновесие')
        time.sleep(2)

        if self.result is not True:
            self.write_in_battle('Вы погибли')
            time.sleep(2)
            self.close()
        else:
            self.eHP_points -= 10
            self.eHP.close()
            self.eHP.setValue(self.eHP_points)
            self.eHP.show()
            self.write_in_battle('Вы успешно атаковали')
            self.result = False

        self.the_right_answer = [False, False, True]
        self.write_in_battle('Выпад вперед!')
        time.sleep(1)

        if self.result is not True:
            self.write_in_battle('Вы погибли')
            time.sleep(2)
            self.close()
        else:
            self.eHP_points -= 10
            self.eHP.close()
            self.eHP.setValue(self.eHP_points)
            self.eHP.show()
            self.write_in_battle('Ваш противник в ярости!')
            self.result = False

        self.the_right_answer = [True, False, False]
        self.write_in_battle('Полый нансосит слабый удар')
        time.sleep(1.5)

        if self.result is not True:
            self.write_in_battle('Вы погибли')
            time.sleep(2)
            self.close()
        else:
            self.eHP_points -= 10
            self.eHP.close()
            self.eHP.setValue(self.eHP_points)
            self.eHP.show()
            self.write_in_battle('Щит сломан')
            self.result = False

        self.the_right_answer = [False, True, False]
        self.write_in_battle('Полый выронил меч. Это ваш шанс!')
        victory = False
        time.sleep(0.8)

        if self.result is not True:
            self.write_in_battle('Полый увернулся')
            self.write_in_battle('Вы подбираете его щит')
        else:
            self.eHP_points -= 60
            self.eHP.close()
            self.eHP.setValue(self.eHP_points)
            self.eHP.show()
            self.write_in_battle('Полый побежден!')
            self.result = False
            victory = True

        if victory is False:
            self.the_right_answer = [False, False, True]
            self.write_in_battle('Полый нансосит слабый удар')
            time.sleep(1.5)

            if self.result is not True:
                self.write_in_battle('Вы погибли')
                time.sleep(2)
                self.close()
            else:
                self.eHP_points -= 30
                self.eHP.close()
                self.eHP.setValue(self.eHP_points)
                self.eHP.show()
                self.write_in_battle('Парирование')
                self.result = False

            self.the_right_answer = [False, True, False]
            self.write_in_battle('Полый медленно замахнулся')
            time.sleep(1.5)

            if self.result is not True:
                self.write_in_battle('Вы погибли')
                time.sleep(2)
                self.close()
            else:
                self.eHP_points -= 30
                self.eHP.close()
                self.eHP.setValue(self.eHP_points)
                self.eHP.show()
                self.write_in_battle('Полый сделал шаг назад')
                self.result = False

            self.the_right_answer = [False, True, False]
            self.write_in_battle('Полый поднимает меч')
            time.sleep(1.5)

            if self.result is not True:
                self.write_in_battle('Вы погибли')
                time.sleep(2)
                self.close()
            else:
                self.eHP_points -= 10
                self.eHP.close()
                self.eHP.setValue(self.eHP_points)
                self.eHP.show()
                self.write_in_battle('Полый падает')
                self.result = False

        self.next_melody = False
        self.NPC_enemy.close()
        self.NPC_enemy.setStyleSheet(
            "QLabel {color: rgb(0, 0, 51);"
            'background-color: rgba(10, 20, 100, 0.2);'
            'border-color: rgba(100, 100, 100, 0.5);'
            'border-style: solid;'
            'border-width: 2px;'
            '}'
            'QLabel:hover {background-color: rgba(100, 0, 0, 0.7)}')
        time.sleep(0.3)
        self.NPC_enemy.show()
        self.write('Полый побежден')
        if victory is True:
            self.NPC_enemy.close()
            self.NPC_enemy.setStyleSheet(
                'QLabel { background-image: url(letter.jpg)}')
            time.sleep(0.3)
            self.NPC_enemy.show()
            self.write('Вы получили новый щит: урон противников снижен')
            self.write('Ваш щит сломан: урон противников повышен')
            self.write('Вы продолжаете идти по тропе')
            self.write('Справа от вас труп')
            self.write('В его карамане что-то есть')
            self.write('Найдена записка')
            self.write('С тех времен, как Гвин впервые ')
            self.write(
                'разжег <не разобрать>, минуло много веков и много циклов <не разобрать>'
            )
            self.write('пламени. После того, как он разжег огонь,')
            self.write('этот путь повторили многие великие герои, ')
            self.write('известные как <не разобрать>')

    def always_on(self):
        while True:
            time.sleep(0.5)
            if self.playable.isFinished() is True:
                if self.next_melody is False:
                    self.playable2.stop()
                    self.playable.play()
            if self.playable2.isFinished() is True:
                if self.next_melody is True:
                    self.playable2.play()

    def change_size(self, input_image_path, size=(0, 0)):
        original_image = Image.open(input_image_path)
        resized_image = original_image.resize(size)
        resized_image.save(input_image_path)
        self.changed = True

    def write(self, text):
        your_text = ' '

        for letter in text:
            if self.read is True:
                time.sleep(0.1)
                your_text += letter
                self.book.setText(your_text)
            else:
                self.read = True
                break
        time.sleep(0.2)

    def write_in_battle(self, text):
        your_text = ' '

        for letter in text:
            time.sleep(0.05)
            your_text += letter
            self.book.setText(your_text)

    def defend_fnc(self):
        if self.the_right_answer[0] is True:
            self.result = True
        else:
            self.result = False

        self.action_targ.close()
        self.action_targ.move(self.targ_pos[1][0], self.targ_pos[1][1])
        self.action_targ.show()

    def attack_fnc(self):
        if self.the_right_answer[1] is True:
            self.result = True
        else:
            self.result = False
        self.action_targ.close()
        self.action_targ.move(self.targ_pos[0][0], self.targ_pos[0][1])
        self.action_targ.show()

    def dodge_fnc(self):
        if self.the_right_answer[2] is True:
            self.result = True
        else:
            self.result = False
        self.action_targ.close()
        self.action_targ.move(self.targ_pos[2][0], self.targ_pos[2][1])
        self.action_targ.show()
Exemple #24
0
class Schedule(QWidget):
    def __init__(self, *args):
        super().__init__(*args)
        loadUi('ui.ui', self)
        self.setWindowState(self.windowState() and ~QtCore.Qt.WindowMinimized
                            or QtCore.Qt.WindowActive)
        self.move(QDesktopWidget().availableGeometry().center() -
                  self.frameGeometry().center())
        self.button_relax.clicked.connect(lambda action: self.start('relax'))
        self.button_work.clicked.connect(lambda action: self.start('work'))
        self.button_pause_continue.clicked.connect(self.pause_continue)
        self.button_pause_continue.hide()
        self.button_settings.clicked.connect(
            lambda action: self.change_timeout())
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.event_second_passed)
        self.sound_timer = QSound('alarm.wav', self)
        self.epoch = datetime(1970, 1, 1, 0, 0, 0)
        self.prev_minute = 0
        default_session = {
            'timeout': 45,
            'countdown': datetime(1970, 1, 1, 0, 45, 0),
            'prev_action': '',
            'action': '',
            'header': 'Ready',
            'progress': 0,
            'current_ratio': '0:0',
            'button_pause_continue': 'Pause',
            'title': 'Schedule',
            'day': datetime.now().day,
            'current_work': self.epoch,
            'current_relax': self.epoch,
            'today_work': self.epoch,
            'today_relax': self.epoch,
        }

        try:
            with open('session.pickle', 'rb') as file:
                temp_session = pickle.load(file)
            if temp_session['day'] == datetime.now().day:
                self.session = temp_session
            else:
                self.session = default_session
        except FileNotFoundError:
            self.session = default_session

        if self.session['countdown'].minute != self.session['timeout']:
            self.session['button_pause_continue'] = 'Continue'
            self.button_pause_continue.show()

        self.set_display()
        self.add_bg()

    def change_timeout(self):
        user_input, confirmed = QInputDialog.getText(
            self,
            'Change timeout...',
            'Please insert new timeout',
            text=str(self.session['timeout']),
            flags=QtCore.Qt.WindowTitleHint)
        if confirmed:
            try:
                int_user_input = int(user_input)
            except TypeError:
                return
            else:
                if 1 <= int_user_input <= 60:
                    self.session['timeout'] = int_user_input
                    self.session['countdown'] = datetime(
                        1970, 1, 1, 0, self.session['timeout'], 0)
                    self.session['progress'] = 0
                    self.session['header'] = 'Ready'
                    self.session['title'] = 'Schedule'
                    self.button_pause_continue.hide()
                    self.set_display()

    def set_display(self):
        self.ui_header.setText(self.session['header'])
        self.button_pause_continue.setText(
            self.session['button_pause_continue'])
        self.ui_timer.setText(self.session['countdown'].strftime('%H:%M:%S'))
        self.ui_progress_bar.setValue(self.session['progress'])
        self.ui_today_work.setText(
            self.session['today_work'].strftime('%H:%M:%S'))
        self.ui_current_work.setText(
            self.session['current_work'].strftime('%H:%M:%S'))
        self.ui_today_relax.setText(
            self.session['today_relax'].strftime('%H:%M:%S'))
        self.ui_current_relax.setText(
            self.session['current_relax'].strftime('%H:%M:%S'))
        self.ui_current_ratio.setText(self.session['current_ratio'])
        self.setWindowTitle(self.session['title'])

    def add_bg(self):
        palette = QPalette()
        palette.setBrush(QPalette.Background, QBrush(QPixmap("bg.jpg")))
        self.setPalette(palette)

    def event_action(self):
        self.session['today_{}'.format(
            self.session['action'])] += timedelta(seconds=1)
        if self.session['prev_action'] == self.session[
                'action'] or not self.session['prev_action']:
            self.session['current_{}'.format(
                self.session['action'])] += timedelta(seconds=1)
        else:
            self.session['prev_action'] = self.session['action']
            self.session['current_{}'.format(
                self.session['action'])] = datetime(1970, 1, 1, 0, 0, 1)
        if self.session['action'] == 'work':
            self.session['current_relax'] = self.epoch
        else:
            self.session['current_work'] = self.epoch
        self.set_display()

    def get_ratio(self):
        minutes_work = self.session['today_work'].minute
        minutes_relax = self.session['today_relax'].minute
        divisor = gcd(minutes_work, minutes_relax)
        ratio_work = int(minutes_work / divisor) if minutes_work else 0
        ratio_relax = int(minutes_relax / divisor) if minutes_relax else 0
        return ratio_work, ratio_relax

    def event_second_passed(self):
        self.session['countdown'] -= timedelta(seconds=1)
        time_elapsed = self.session['countdown'].minute * 60 + self.session[
            'countdown'].second
        self.session['progress'] = (self.session['timeout'] * 60 - time_elapsed
                                    ) / (self.session['timeout'] * 60) * 100
        self.event_action()
        if self.session['countdown'].minute != self.prev_minute:
            pass
        self.prev_minute = self.session['countdown'].minute
        self.session['current_ratio'] = '{}:{}'.format(*self.get_ratio())
        self.session['title'] = self.session['countdown'].strftime('%H:%M:%S')
        if not self.session['countdown'].hour \
                and not self.session['countdown'].minute \
                and not self.session['countdown'].second:
            self.session['countdown'] = datetime(1970, 1, 1, 0,
                                                 self.session['timeout'], 0)
            self.session['progress'] = 0
            self.session['title'] = 'Schedule'
            self.session['header'] = 'Ready'
            self.session['button_pause_continue'] = 'OK'
            self.timer.stop()
            self.sound_timer.play()
            self.button_relax.show()
            self.button_work.show()
            self.button_pause_continue.clicked.disconnect(self.pause_continue)
            self.button_pause_continue.clicked.connect(self.stop_sound)
        self.set_display()

        with open('session.pickle', 'wb') as file:
            pickle.dump(self.session, file)

    def start(self, action):
        self.session['header'] = '{}...'.format(action.capitalize())
        self.session['button_pause_continue'] = 'Pause'
        self.session['prev_action'] = self.session['action'].lower()
        self.session['action'] = action
        self.session['countdown'] = datetime(1970, 1, 1, 0,
                                             self.session['timeout'], 0)
        self.session['progress'] = 0
        self.sound_timer.stop()
        try:
            self.button_pause_continue.clicked.disconnect(self.stop_sound)
            self.button_pause_continue.clicked.connect(self.pause_continue)
        except TypeError:
            pass
        self.button_pause_continue.show()
        self.button_settings.hide()
        self.set_display()
        self.timer.start(1000)

    def stop_sound(self):
        self.session['header'] = 'Ready'
        self.sound_timer.stop()
        self.button_settings.show()
        self.button_pause_continue.hide()
        self.button_pause_continue.clicked.disconnect(self.stop_sound)
        self.button_pause_continue.clicked.connect(self.pause_continue)
        self.set_display()

    def pause_continue(self):
        if self.timer.isActive():
            self.session['header'] = 'Pause'.format(
                self.session['action'].capitalize())
            self.session['button_pause_continue'] = 'Continue'
            self.button_settings.show()
            self.timer.stop()
        else:
            self.session['header'] = '{}...'.format(
                self.session['action'].capitalize())
            self.session['button_pause_continue'] = 'Pause'
            self.button_settings.hide()
            self.timer.start(1000)
        self.set_display()