class PriceAlertDialog(QDialog): def __init__(self, price=0, symbol="btcusdt", typ="below", parent=None): super().__init__(parent=parent) self.setWindowTitle("PRICE ALERT!") btn = QDialogButtonBox.Ok self.buttonBox = QDialogButtonBox(btn) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.layout = QVBoxLayout() self.msg = QLabel( f"An alert was triggered for {symbol.upper()}, because the price was {typ.lower()} {price}." ) self.layout.addWidget(self.msg) self.layout.addWidget(self.buttonBox) self.setLayout(self.layout) def set_ticker(self, symbol, price, typ): self.msg.setText( f"An alert was triggered for {symbol.upper()}, because the price was {typ.lower()} {price}." ) def play_sound(self): self.alert_sound = QSound( "C:/Users/nikar/Desktop/Day Trading/BinanceFutures/alert.wav") self.alert_sound.setLoops(3) self.alert_sound.play()
def initSounds(): global ping, anim01, musicA, musicB ping = QSound("ritual/Ping.wav") anim01 = QSound("ritual/anim01.wav") musicA = QSound("ritual/track1.wav") musicA.setLoops(QSound.Infinite) musicB = QSound("ritual/track2.wav") musicB.setLoops(QSound.Infinite)
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()
def __init__(self, parent=None): super(RetroCar, self).__init__(parent) self.rows, self.cols = [25, 10] self.factor = 25 self.resize(self.factor * QSize(self.cols, self.rows)) self.isObs = 0 self.isBorder = 0 self.car_pos = QPoint(self.cols / 2, self.rows - 4) self.size = QSize(self.factor, self.factor) self._poss = [ QPoint(0, -1), QPoint(0, 0), QPoint(1, 0), QPoint(-1, 0), QPoint(0, 1), QPoint(-1, 2), QPoint(1, 2) ] self.color = QColor(0, 0, 0) final = 3 self.border = [] while final < self.rows: self.border += list(range(final - 3, final)) final += 5 self.obs_pos = None self.create_obs() self.rect_text = QRect(self.cols * self.factor / 2, self.rows * self.factor / 2, 5 * self.factor, 2 * self.factor) self.rect_text.moveCenter( QPoint(self.cols / 2, self.rows / 2) * self.factor) self.isDrawMenu = True self.text_Menu = 'Iniciar' self.setMinimumSize(self.factor * QSize(self.cols, self.rows)) self.setMaximumSize(self.factor * QSize(self.cols, self.rows)) self.move(QDesktopWidget().screen().rect().center() - self.rect().center()) self.score = 0 sound = QSound("Tetris.wav", self) sound.setLoops(QSound.Infinite) sound.play() self.level = 1 self.scores = [5000 * (x + 1) for x in list(range(8))]
class Troubleshooter(QWizard, Ui_Wizard): def __init__(self, ctx: ApplicationContext): super(self.__class__, self).__init__() self.setupUi(self) song_path = ctx.get_resource('sounds\good.wav') self.song = QSound(song_path) self.song.play() self.song.setLoops(99999999) def closeEvent(self, event): reply = QMessageBox.question(self, 'Message', "LET ME FINISH.", QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.No: event.accept() else: event.ignore() def reject(self): self.close()
class Entity(QGraphicsPixmapItem): trigger = pyqtSignal(Entity_Dies) nivel = 0 enemy_apparition_stats = [(1 / 10, 1, 5, 1), (1 / 8, 1, 6, 3), (1 / 6, 3, 7, 5), (1 / 4, 5, 9, 7), (1 / 2, 7, 10, 9)] def __init__(self, type, level, parent): # type puede ser enemigo o jugador super().__init__() self.orientation = 0 self.angular_velocity = 0 self.velocity = 0 self.setTransformOriginPoint(50, 50) self.aux_signal_object = aux_signal_emiter(parent) self.type = type self.level = level self.set_atrributes() self.set_health() self.wall = QSound("sounds/effects/wall.wav", parent=None) self.wall.setLoops(1) def set_atrributes(self): if self.type == "Enemy": self.datos = Entity.enemy_apparition_stats[self.level] self.tamaño = floor( triangular(self.datos[1], self.datos[2], self.datos[3])) self.ponderador = self.tamaño / 10 pass else: self.tamaño = 2 self.ponderador = 0.2 def set_health(self): self.max_health = 20 * self.tamaño + 100 self.health = 20 * self.tamaño + 100
class Config(object): def load_config(self): # 读取配置文件 self.setting = QSettings('./setting.ini', QSettings.IniFormat) # self.setting.setIniCodec("UTF8") # 加载落子音效 self.sound_piece = QSound("sound/move.wav") self.background_music = QSound("sound/bgm.wav") self.background_music.setLoops(-1) # 加载配置 self.config = {} self.setting.beginGroup("setting") ck = self.setting.childKeys() for k in ck: self.config[k] = self.setting.value(k) self.setting.endGroup() # print('配置字典', self.config) # 读取样式文件 # print('qss/', type(self.config['qss'])) style_file = self.setting.value('qss/' + self.config['qss']) # print("common:49", style_file) self.QSS = self.read_qss(style_file) # 设置程序图标 icon = QIcon('img/logo.png') self.setWindowIcon(icon) @staticmethod def read_qss(style_file): with open(style_file, 'r') as f: return f.read() @staticmethod def get_time(): tm = "{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}"\ .format(*localtime()[:6]) return tm pass
class VentanaFinal(QWidget): def __init__(self, *args): super().__init__(*args) def crear_pantalla(self, resultado): if resultado == "victoria": self.ruta = ruta_victoria self.ruta_sonido = ruta_sonido_victoria titulo = '¡Victoria!' else: self.ruta = ruta_derrota self.ruta_sonido = ruta_sonido_derrota titulo = 'Derrota :(' self.setWindowTitle(titulo) self.label_usuario = QLabel() self.movie = QMovie(self.ruta) self.movie.frameChanged.connect(self.repaint) self.movie.start() self.sonido() self.show() def sonido(self): self.soundtrack = QSound(self.ruta_sonido) self.soundtrack.play() self.soundtrack.setLoops(1000) def paintEvent(self, event): frame_actual = self.movie.currentPixmap() frameRect = frame_actual.rect() frameRect.moveCenter(self.rect().center()) if frameRect.intersects(event.rect()): painter = QPainter(self) painter.drawPixmap(frameRect.left(), frameRect.top(), frame_actual)
class Window(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.sound() self.initUI() self.loopMenu() def keyPressEvent(self, event): if type(event) == QKeyEvent: if event.key( ) == Qt.Key_Space and self.demarre and not self.Gameover and not self.inMenu: self.animation() elif event.key( ) == Qt.Key_Space and not self.demarre and not self.Gameover and not self.inMenu: self.initUI() self.update() self.loopMenu() elif event.key( ) == Qt.Key_Space and not self.demarre and not self.Gameover and self.inMenu: self.wave() def initUI(self): self.setFixedSize(800, 1000) self.setWindowTitle('Flappy 2048') self.setWindowIcon(QIcon('./ressources/images/icon.png')) self.inMenu = True #Etat dans le menu self.setCenter() self.Etat = "Press Space to jump" self.Gameover = False #Etat game over self.score = 1 self.copie_score = 1 self.gravity = 0.006 self.vitesse = 0 self.pts = [[150, 300]] self.angle = 360.0 self.demarre = False self.tubeposhaut = [1500, -500] self.tubeposbas = [1500, 450] self.bare = 0 self.barre = QImage("./ressources/images/barre.png") self.listetube = [[-200, 750], [-300, 650], [-400, 550], [-500, 450], [-600, 350], [-700, 250]] self.show() self.cond_passage = False self.couleur = { 2: QColor(238, 228, 218), 4: QColor(192, 57, 43), 8: QColor(231, 76, 60), 16: QColor(155, 89, 182), 32: QColor(142, 68, 173), 64: QColor(41, 128, 185), 128: QColor(52, 152, 219), 256: QColor(26, 188, 156), 512: QColor(22, 160, 133), 1024: QColor(39, 174, 96), 2048: QColor(46, 204, 113), 4096: QColor(241, 196, 15), 8192: QColor(243, 156, 18), 16384: QColor(230, 126, 34), 32768: QColor(211, 84, 0), 65536: QColor(52, 73, 94), 131072: QColor(44, 62, 80) } self.tubscore = [] for i in range(0, 10): condition = True while condition: nbr_aleatoire = random.randint(1, 12) if nbr_aleatoire not in self.tubscore and nbr_aleatoire != 1: self.tubscore.append(nbr_aleatoire) condition = False def paintEvent(self, event): painter = QPainter(self) pts = self.pts[:] painter.setRenderHint(QPainter.Antialiasing) self.rect = QRect(pts[0][0], pts[0][1], 100, 100) self.goal = QRect(self.tubeposhaut[0], self.tubeposhaut[1] + 800, 150, 150) self.tub1 = QRect(self.tubeposhaut[0], self.tubeposhaut[1] + 500, 150, 150) self.tub2 = QRect(self.tubeposhaut[0], self.tubeposhaut[1] + 650, 150, 150) self.tub3 = QRect(self.tubeposhaut[0], self.tubeposhaut[1] + 950, 150, 150) self.tub4 = QRect(self.tubeposhaut[0], self.tubeposhaut[1] + 350, 150, 150) self.tub5 = QRect(self.tubeposhaut[0], self.tubeposhaut[1] + 1100, 150, 150) self.tub6 = QRect(self.tubeposhaut[0], self.tubeposhaut[1] + 1250, 150, 150) self.tub7 = QRect(self.tubeposhaut[0], self.tubeposhaut[1] + 1400, 150, 150) self.tub8 = QRect(self.tubeposhaut[0], self.tubeposhaut[1] + 1550, 150, 150) self.tub9 = QRect(self.tubeposhaut[0], self.tubeposhaut[1] + 350, 150, 150) self.tub10 = QRect(self.tubeposhaut[0], self.tubeposhaut[1] + 200, 150, 150) self.tub = [ self.tub1, self.tub2, self.tub3, self.tub4, self.tub5, self.tub6, self.tub7, self.tub8, self.tub9, self.tub10 ] self.goaladapter = QRect(self.tubeposhaut[0] - 35, self.tubeposhaut[1] + 825, 30, 110) self.tube1 = QRect(self.tubeposhaut[0], self.tubeposhaut[1], 150, 800) self.tube = QRect(self.tubeposbas[0], self.tubeposbas[1], 150, 800) center = self.rect.center() pen = QPen() pen.setBrush(QColor(100, 100, 100)) pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin) pen.setWidth(8) painter.setPen(pen) font = QFont("Arial", 23, QFont.Bold) painter.setFont(font) ###Dessin des cubes autour de l'objectif for i in range(0, 10): self.taillepen = 23 if len(str(2**self.tubscore[i])) > 5: self.taillepen = 20 if len(str(2**self.tubscore[i])) > 7: self.taillepen = 17 painter.setFont(QFont("Arial", self.taillepen, QFont.Bold)) if 2**self.tubscore[i] <= 131072: for j in self.couleur: if 2**self.tubscore[i] == j: pickcouleur = self.couleur[j] else: pickcouleur = QColor(59, 59, 51) painter.setBrush(QBrush(pickcouleur)) painter.drawRects(self.tub[i]) if 2**self.tubscore[i] > 2: painter.setPen(QPen(QColor(255, 250, 250))) painter.drawText(self.tub[i], Qt.AlignCenter, str(2**self.tubscore[i])) painter.setPen(pen) painter.setFont(font) painter.setPen(pen) ###Dessin du cube objectif self.taillepen = 23 if len(str(2**self.copie_score)) > 6: self.taillepen = 20 if len(str(2**self.copie_score)) > 9: self.taillepen = 15 painter.setFont(QFont("Arial", self.taillepen, QFont.Bold)) if 2**self.copie_score <= 131072: for i in self.couleur: if 2**self.copie_score == i: pickcouleur = self.couleur[i] else: pickcouleur = QColor(59, 59, 51) painter.setBrush(QBrush(pickcouleur)) if not self.cond_passage: painter.drawRect(self.goal) if 2**self.copie_score > 2: pen.setBrush(QColor(255, 250, 250)) painter.setPen(pen) painter.drawText(self.goal, Qt.AlignCenter, str(2**self.copie_score)) font = QFont("Arial", 30, QFont.Bold) painter.setFont(font) ### Reglages taille police du score self.taillepen = 20 if len(str(2**self.score)) >= 5: self.taillepen = 18 if len(str(2**self.score)) >= 8: self.taillepen = 15 if len(str(2**self.score)) >= 9: self.taillepen = 13 font = QFont("Arial", self.taillepen, QFont.Bold) painter.setFont(font) ###Dessin du cube volant painter.translate(center.x(), center.y()) painter.rotate(self.angle) painter.translate(-center.x(), -center.y()) pen.setBrush(QColor(100, 100, 100)) painter.setPen(pen) if 2**self.score <= 131072: for i in self.couleur: if 2**self.score == i: pickcouleur = self.couleur[i] else: pickcouleur = QColor(59, 59, 51) painter.setBrush(QBrush(pickcouleur)) painter.drawRect(self.rect) if 2**self.score > 2: painter.setPen(QPen(QColor(255, 250, 250))) painter.drawText(self.rect, Qt.AlignCenter, str(2**self.score)) painter.end() ### Dessin menu peinteur = QPainter(self) if not self.demarre: peinteur.setBrush(QBrush(QColor(250, 250, 250, 170))) stylo = QPen() stylo.setBrush(QColor(100, 100, 100)) peinteur.setPen(stylo) font = QFont("Arial", 35, QFont.Bold) peinteur.setFont(font) self.getBestScore() if self.Etat == "Game Over": peinteur.drawImage(0, 960, self.barre) peinteur.drawRect(0, 0, 800, 1080) peinteur.drawText(250, 500, self.Etat) self.setBestScore() if self.Etat == "Press Space to jump": peinteur.setFont(QFont("Arial", 20, QFont.Bold)) peinteur.drawText( 10, 950, "Best score : " + str(("{:,}".format( 2**self.score_recup).replace(",", " ")))) peinteur.setFont(QFont("Arial", 35, QFont.Bold)) peinteur.drawText(150, 730, self.Etat) peinteur.drawImage(0, 960, self.barre) else: peinteur.drawImage(self.bare, 960, self.barre) peinteur.drawImage(self.bare + 1004, 960, self.barre) peinteur.end() self.show() def loopMenu(self): i = 0 while self.inMenu: self.pts[0][1] += math.cos(i) * 4 self.update() QApplication.processEvents() sleep(0.01) i += 0.03 def closeEvent(self, event): sys.exit() def sound(self): self.luft = QSound("./ressources/sons/99_Luftballons.wav") self.flap = QSound("./ressources/sons/flap.wav") self.coin = QSound("./ressources/sons/coin.wav") self.punch = QSound("./ressources/sons/punch.wav") self.luft.play() self.luft.setLoops(QSound.Infinite) def wave(self): self.demarre = True self.Etat = " " self.inMenu = False for point in self.pts: while point[1] < 860 and not (self.rect).intersects( self.tube1) and not (self.rect).intersects( self.tube) and point[1] > -200: if (self.rect).intersects(self.goaladapter): a, yp1, b, c = QRect.getCoords(self.goaladapter) point[1] = yp1 if (self.rect).intersects(self.goal): self.vitesse = 0 self.angle = 360.0 self.tubeposhaut[0] -= 1.3 self.tubeposbas[0] -= 1.3 self.bare -= 1.3 sleep(0.004) collision = (self.rect).intersected(self.goal) x, a, b, c = QRect.getCoords(collision) if b == 216: self.score += 1 self.cond_passage = True self.coin.play() self.vitesse += self.gravity point[1] += self.vitesse self.looptube() self.loopbarre() self.tubeposhaut[0] -= 1 self.tubeposbas[0] -= 1 self.bare -= 1 if self.angle < 400.0: self.angle += 0.15 self.update() QApplication.processEvents() sleep(0.00001) self.demarre = False self.colisiontube() self.punch.play() self.Etat = "Game Over" self.update() QApplication.processEvents() def loopbarre(self): if self.bare < -1004: self.bare = 0 def looptube(self): if self.tubeposhaut[0] < -205: self.cond_passage = False self.listetube self.r = random.randint(0, 5) self.tubeposbas[1] = self.listetube[self.r][1] self.tubeposhaut[1] = self.listetube[self.r][0] self.tubeposbas[0] = 800 self.tubeposhaut[0] = 800 self.copie_score = self.score if self.score < 6: for i in range(0, 10): condition = True while condition: nbrandom = random.randint(1, 12) if nbrandom not in self.tubscore and nbrandom != self.score: self.tubscore[i] = nbrandom condition = False else: for i in range(0, 10): condition = True while condition: nbrandom = random.randint(self.score - 5, self.score + 6) if nbrandom not in self.tubscore and nbrandom != self.score: self.tubscore[i] = nbrandom condition = False def colisiontube(self): self.Gameover = True self.Etat = "Game Over" if (self.rect).intersects(self.tube1) or (self.rect).intersects( self.tube): self.pts[0][0] -= 5 while self.pts[0][1] < 860: self.vitesse += self.gravity self.pts[0][1] += self.vitesse * 3 self.update() QApplication.processEvents() sleep(0.00002) self.Gameover = False def animation(self): self.vitesse = -1.3 while self.angle > 325: self.angle -= 0.35 self.update() self.flap.play() def getBestScore(self): try: with open("./ressources/score", "rb") as fichier: self.score_recup = pickle.load(fichier) except: with open("./ressources/score", "wb") as fichier: pickle.dump(0, fichier) with open("./ressources/score", "rb") as fichier: self.score_recup = pickle.load(fichier) def setBestScore(self): if 2**self.score > 2**self.score_recup: with open("./ressources/score", "wb") as fichier: pickle.dump(self.score, fichier) def setCenter(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft())
class AppController(QObject): """The main controller of this application.""" def __init__(self): super(AppController, self).__init__() ServiceAdaptor(self) self.contexts = [] self._osdVisible = False self._initQuitTimer() def _initQuitTimer(self): self._quitTimer = QTimer() self._quitTimer.setInterval(10 * 1000) self._quitTimer.setSingleShot(True) self._quitTimer.timeout.connect(self._checkContexts) def _checkContexts(self): if (self.contexts) or self._osdVisible: self._quitTimer.start() else: qApp.quit() def _contextNeedSound(self): self._sound.play() def _contextFinished(self): sender = self.sender() if sender in self.contexts: # TODO: the remove _doesn't_ get the sender object # garbage collected, there must be some reference cycles. self.contexts.remove(sender) self._checkContexts() def _contextNeedOSD(self, area): def _osdClosed(): self._osdVisible = False self._osdVisible = True self._qmlEngine = QQmlApplicationEngine() self._qmlEngine.load(QUrl(OSD_QML)) osd = self._qmlEngine.rootObjects()[0] osd.setX(area.x() + (area.width() - osd.width()) / 2) osd.setY(area.y() + (area.height() - osd.height()) / 2) osd.showTips() osd.closed.connect(_osdClosed) def _createContextSettings(self): settings = ScreenshotSettings() settings.tmpImageFile = "%s.png" % tempfile.mktemp() settings.tmpBlurFile = "%s-blur.png" % tempfile.mktemp() settings.tmpMosaiceFile = "%s-mosaic.png" % tempfile.mktemp() settings.tmpSaveFile = "%s-save.png" % tempfile.mktemp() return settings def runWithArguments(self, arguments): for _context in self.contexts: if _context.isActive(): return argValues = processArguments(arguments) delay = argValues["delay"] self._sound = QSound(SOUND_FILE) self._sound.setLoops(1) context = AppContext(argValues) context.settings = self._createContextSettings() context.finished.connect(self._contextFinished) context.needSound.connect(self._contextNeedSound) context.needOSD.connect(self._contextNeedOSD) self.contexts.append(context) if delay > 0: notificationsInterface.notify(_("Deepin Screenshot"), _("Deepin Screenshot will start after %s seconds.") % delay) QTimer.singleShot(max(0, delay * 1000), context.main)
# else: # self.timer.start() # self.gameWindow.dto.isPaused = 0 ##典型开关型代码优化 if self.gameWindow.gameDto.isPaused: self.timer.start() else: self.timer.stop() self.gameWindow.gameDto.isPaused = not self.gameWindow.gameDto.isPaused def keyTest(self): self.gameWindow.gameDto.nowRemoveLine += 2 self.gameService.updateSpeed( self.gameService.updateLevel(self.gameService.updatePoint(2))) self.gameWindow.update() def keySetup(self): ##TODO 设置按钮功能 pass if __name__ == '__main__': app = QApplication(sys.argv) # 播放背景音乐 backmusic = QSound(r"music\backmusic01.wav") backmusic.setLoops(-1) backmusic.play() # 创建游戏控制器 GameControl() sys.exit(app.exec_())
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()
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
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()
class Strategy2MainWindow(QMainWindow, Ui_MainWindow): def __init__(self): super(Strategy2MainWindow, self).__init__() self.setupUi(self) # QMessageBox.information(self,'app_path',frozen_dir.app_path()) # QMessageBox.information(self,'resource_path',frozen_dir.resource_path()) self.app_path = frozen_dir.resource_path() self.prevAt = 161 # default:161 self.prevLimit = 9 # default:9 self.txtPrevAt.setText(str(self.prevAt)) self.txtPrevLimit.setText(str(self.prevLimit)) self.txtNx = [ self.txtN1, self.txtN2, self.txtN3, self.txtN4, self.txtN5, self.txtN6, self.txtN7, self.txtN8, self.txtN9, self.txtN10 ] self.pixNum = [] for n in range(11): # print("n = %d" % n) if n > 0: self.txtNx[n - 1].setScaledContents(True) self.txtNx[n - 1].setPixmap(self.pixNum[0]) pix = QPixmap(self.app_path + r'\client\resource\images\Num_%d.png' % n) self.pixNum.append(pix) self.currentOptionInfo = None # 当前期数信息 self.currentOptionIssue = 0 # 当前最新期号 self.__initSounds() self.__initBusiness() def __initBusiness(self): ''' 初始化业务处理 :return: ''' # UI界面的一些初始化 self.tableTodayRecords.horizontalHeader().setStyleSheet( 'QHeaderView::section{background:#f0f0f0}') self.tableTodayRecords.setColumnWidth(0, 120) self.tableTips.horizontalHeader().setStyleSheet( 'QHeaderView::section{background:#f0f0f0}') self.tableTips.verticalHeader().setStyleSheet( 'QHeaderView::section{background:#f0f0f0}') self.showOptionInfo() self.updateTableViewToday(None) # # 历史数据 self.datasUpdateThread = DatasUpdateThread() self.datasUpdateThread.updated.connect(self.datasTopUpdateShow) self.datasUpdateThread.updated.connect(self.datasUpdatedCall) self.datasUpdateThread.updated.connect(self.updateTableViewToday) self.datasUpdateThread.start() # 全局定时器 self.gIntervalTimer = QTimer() self.gIntervalTimer.timeout.connect(self.gIntervalTimerCall) self.gIntervalTimer.start(1000) # 启动定时器 self.currentCounter = [] # 当计分析计数器 def __initSounds(self): ''' 加载提示音效 :return: ''' self.soundLightMusic = QSound( self.app_path + r'\client\resource\sounds\00_ligth_music.wav', self) # 轻音乐 self.soundWin = QSound(self.app_path + r'\client\resource\sounds\01_win.wav', self) # 中奖提示 self.soundLoss = QSound(self.app_path + r'\client\resource\sounds\01_loss.wav', self) # 全输提示 self.soundAooo = QSound(self.app_path + r'\client\resource\sounds\02_aooo.wav', self) # 断网提示 self.soundNewMessage = QSound( self.app_path + r'\client\resource\sounds\03_new_message.wav', self) # 提注提示 self.soundIOSShort = QSound( self.app_path + r'\client\resource\sounds\04_ios_short.wav', self) # 提注提示 self.soundZhoJi = QSound( self.app_path + r'\client\resource\sounds\06_qibinghao_shengli.wav', self) # 开始召集 # # # self.soundZhoJi.setLoops(5) # # self.soundZhoJi.play() # self.soundLightMusic.play() # # self.soundWin.play() # # self.soundAooo.play() # # self.soundNewMessage.play() # # self.soundIOSShort.play() # 提示音相关状态位 self.tipsCounter = 0 # 当预测目标有变化时发出提示音 self.winIssue = 0 # 中奖提示音,防止行情更新重复播放 self.trigger = 2 # 当达到触发条件是,最多播入提示声次数 self.currentTestIssue = 0 # 当前测算期数 def showOptionInfo(self): ''' 显示期数数据 :return: ''' currentOptionInfo = DatasHandleHub.currentOptionInfo() # 期数 self.txtNextOption.setText(str(currentOptionInfo['nextOption'])) # self.txtLastOption.setText(str(currentOptionInfo['lastOption'])) self.txtTodaySurplus.setText(str(currentOptionInfo['todaySurplus'])) # 时间倒计时 self.txtNextOpenTime.setText( self.countDown(currentOptionInfo['nextOpenTime'])) self.txtNextStopTime.setText( self.countDown(currentOptionInfo['nextStopTime'])) self.currentOptionInfo = currentOptionInfo def countDown(self, target, now=None): ''' 显示倒计时 :param target: :param now: :return: ''' if now is None: now = datetime.datetime.now() else: now = parse(now) target = parse(target) total_seconds = int((target - now).total_seconds()) _s = 0 _m = 0 _h = 0 if total_seconds > 0: # 时:分:秒 计时器 _s = total_seconds % 60 _m = (total_seconds // 60) % 60 _h = (total_seconds // 3600) % 24 _s = str(_s).zfill(2) _m = str(_m).zfill(2) _h = str(_h).zfill(2) return ":".join([_h, _m, _s]) def gIntervalTimerCall(self): ''' 全局定时器刷新 :param mainWin: :return: ''' # print("全局定时器刷新:{}".format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) # 刷新期数、开奖结果、倒计时 self.showOptionInfo() # 第隔3秒更新行情(开奖)记录数据 now = datetime.datetime.now() now_minute = int(now.strftime("%M")) now_second = int(now.strftime("%S")) # if now_minute % 5 == 0 and now_second in [1,5,10]: # self.datasUpdateProcess.start() self.datasUpdateThread.start() def datasTopUpdateShow(self, datas): ''' 更新显示当前最新结果 :param records: :return: ''' # print("更新显示当前最新结果") # print(datas) df = datas.sort_values(by='issue', ascending=False) newLastOptionIssue = df.iloc[0][0] if newLastOptionIssue > self.currentOptionIssue: self.currentOptionIssue = newLastOptionIssue # TODO: 新的开奖记录 ,发开提示声音 print("TODO: 新的开奖记录 ,发开提示声音") self.soundIOSShort.play() # 更新开奖记录显示 self.txtLastOption.setText(str(newLastOptionIssue)) for i in range(10): col = "r" + str(i + 1) # self.txtNx[i].setText(str(df.iloc[0][i + 2])) self.txtNx[i].setPixmap(self.pixNum[df.iloc[0][i + 2]]) def datasUpdatedCall(self, datas): ''' 根据行情分析提示结果 :param datas: :return: ''' if datas is None or len(datas) == 0: self.soundAooo.play() return # 根据行情分析提示结果 print("根据行情分析提示结果") # 过滤当前记录 df = pd.DataFrame(datas) currentDate = DatasUtils.todayDate() df['date'] = df['open_at'].map( lambda x: datetime.datetime.strftime(x, '%Y-%m-%d')) df = df[df['date'] == currentDate] df.sort_values(by="issue", ascending=True, inplace=True) issue = df['issue'].max() index = int(str(issue)[-3:]) # 统计 subDf = df.copy() if len(subDf) > self.prevAt: subDf = subDf.iloc[0:self.prevAt] counter = [] for r in range(1, 11): col = "r" + str(r) grouped = subDf.groupby(by=col) for num, group in grouped: if len(group) <= self.prevLimit: count = len(group) # 计算目标是否确认? status = "待确认" if self.prevAt - index < self.prevLimit: if count + self.prevAt - index <= self.prevLimit: status = "已确认" counter.append({ "r": r, "n": num, "count": count, 'status': status # True 已确认,False 待确认 }) self.currentCounter = copy.deepcopy(counter) tips = "" if index < self.prevAt: # 未达到目标遇测 tips = "距离:%d 期,预测目标:%d" % (self.prevAt - index, len(counter)) # 统计有变动即提示 if len(counter) != self.tipsCounter: # 提示变动 self.soundNewMessage.play() # pass # 记录新的计数 self.tipsCounter = len(counter) self.updateTableViewTips(counter) elif index == self.prevAt: if len(counter) > 0: tips = "触发:%d期,符合结果:共 %d 目标" % (self.prevAt, len(counter)) if self.trigger > 0: # self.soundWin.play() self.soundZhoJi.setLoops(3) self.soundZhoJi.play() # pass else: tips = "触发:%d期,符合结果:0 目标" % self.prevAt if self.trigger > 0: self.soundAooo.play() # pass self.trigger -= 1 self.updateTableViewTips(counter) else: tips = "触发:%d期,符合结果:共 %d 目标" % (self.prevAt, len(counter)) # 计算中奖记录,变形counter if index > self.prevAt and self.currentTestIssue < df['issue'].max(): self.currentTestIssue = df['issue'].max() # 提取已开奖记录 tops = df.iloc[self.prevAt:] # tops = pd.DataFrame(tops) # print(tops) # 构造记录分板 bets = [] lastRoundHasWin = False for topIndex, row in tops.iterrows(): # print(row) lastRoundHasWin = False issueIndex = int(str(row['issue'])[-3:]) for cc in counter: col = "r" + str(cc['r']) # print(col) bet = { 'groupK': "x".join( [str(v) for v in [cc['r'], cc['n'], cc['count']]]), 'index': issueIndex, 'issue': row['issue'], 'open_at': row['open_at'], 'r': cc['r'], 'n': cc['n'], 'count': cc['count'], 'open': row[col], 'win': "胜" if row[col] == cc['n'] else "负" } if row[col] == cc['n']: lastRoundHasWin = True bets.append(bet) bets = pd.DataFrame(bets) # print(bets) haftA = (180 - self.prevAt) // 2 haftB = haftA if haftA * 2 < (180 - self.prevAt): haftA += 1 newCounter = [] grouped = bets.groupby(by="groupK") for groupK, group in grouped: r, n, c = tuple(str(groupK).split("x")) haftBGroup = group.iloc[haftB:] row = { 'r': r, 'n': n, 'count': c, 'allWin': len(group[group['win'] == '胜']), 'allLoss': len(group[group['win'] == '负']), 'haftBWin': len(haftBGroup[haftBGroup['win'] == '胜']), 'haftBLoss': len(haftBGroup[haftBGroup['win'] == '负']), } newCounter.append(row) # 更新TableViews self.updateTableViewTips(newCounter) if lastRoundHasWin: # 本轮有赢 self.soundWin.play() # pass else: # 本轮全输 self.soundLoss.play() # pass if tips != "": self.txtTips.setText(tips) if index != len(df): # 期数引索与开奖记录数不一到致,开奖期数可能不完整 QMessageBox.critical(self, "警告", "注意!注意!注意!开奖期数可能不完整!") def updateTableViewToday(self, datas): ''' 更新今天开奖记录显示 :param datas: :return: ''' columns = [ 'issue', 'open_at', 'r1', 'r2', 'r3', 'r4', 'r5', 'r6', 'r7', 'r8', 'r9', 'r10' ] df = None if datas is not None and len(datas) > 0: df = pd.DataFrame(datas) del datas['date'] df['open_at'] = df['open_at'].map( lambda x: datetime.datetime.strftime(x, '%Y-%m-%d %H:%M')) else: df = pd.DataFrame(columns=columns) df.rename(columns={ 'issue': '期号', 'open_at': '开奖时间', 'r1': '1道', 'r2': '2道', 'r3': '3道', 'r4': '4道', 'r5': '5道', 'r6': '6道', 'r7': '7道', 'r8': '8道', 'r9': '9道', 'r10': '10道' }, inplace=True) model = MyPandasModel(df) self.tableTodayRecords.setModel(model) self.tableTodayRecords.setColumnWidth(0, 120) self.tableTodayRecords.setColumnWidth(1, 160) def updateTableViewTips(self, records): ''' 更新提示统计记录列表 :param records: :return: ''' columns = ['r', 'n', 'count', 'status'] df = None self.tableTips.setRowCount(0) if records is not None and len(records) > 0: df = pd.DataFrame(records) df.sort_values(by="count", ascending=True, inplace=True) self.tableTips.setRowCount(len(df)) # 检查是否带有已开奖记录 if len(records[0]) > 4: self.tableTips.setColumnHidden(3, True) self.tableTips.setColumnHidden(4, False) self.tableTips.setColumnHidden(5, False) self.tableTips.setColumnHidden(6, False) self.tableTips.setColumnHidden(7, False) rowIndex = 0 for index, row in df.iterrows(): # print(row) itemR = QTableWidgetItem(str(row['r'])) itemR.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter) self.tableTips.setItem(rowIndex, 0, itemR) itemN = QTableWidgetItem(str(row['n'])) itemN.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter) self.tableTips.setItem(rowIndex, 1, itemN) itemC = QTableWidgetItem(str(row['count'])) itemC.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter) self.tableTips.setItem(rowIndex, 2, itemC) itemAllWin = QTableWidgetItem(str(row['allWin'])) itemAllWin.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter) self.tableTips.setItem(rowIndex, 4, itemAllWin) itemAllLoss = QTableWidgetItem(str(row['allLoss'])) itemAllLoss.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter) self.tableTips.setItem(rowIndex, 5, itemAllLoss) itemHaftBWin = QTableWidgetItem(str(row['haftBWin'])) itemHaftBWin.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter) self.tableTips.setItem(rowIndex, 6, itemHaftBWin) itemHaftBLoss = QTableWidgetItem(str(row['haftBLoss'])) itemHaftBLoss.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter) self.tableTips.setItem(rowIndex, 7, itemHaftBLoss) rowIndex += 1 else: self.tableTips.setColumnHidden(3, False) self.tableTips.setColumnHidden(4, True) self.tableTips.setColumnHidden(5, True) self.tableTips.setColumnHidden(6, True) self.tableTips.setColumnHidden(7, True) rowIndex = 0 for index, row in df.iterrows(): # print(row) itemR = QTableWidgetItem(str(row['r'])) itemR.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter) self.tableTips.setItem(rowIndex, 0, itemR) itemN = QTableWidgetItem(str(row['n'])) itemN.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter) self.tableTips.setItem(rowIndex, 1, itemN) itemC = QTableWidgetItem(str(row['count'])) itemC.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter) self.tableTips.setItem(rowIndex, 2, itemC) itemS = QTableWidgetItem(row['status']) if row['status'] != "已确认": itemS.setForeground(QBrush(QColor(255, 0, 0))) itemS.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight) self.tableTips.setItem(rowIndex, 3, itemS) rowIndex += 1 else: self.tableTips.setColumnHidden(3, False) self.tableTips.setColumnHidden(4, True) self.tableTips.setColumnHidden(5, True) self.tableTips.setColumnHidden(6, True) self.tableTips.setColumnHidden(7, True) df = pd.DataFrame(columns=columns) self.tableTips.setRowCount(0) def closeEvent(self, QCloseEvent): ''' 退出程序窗口事件 :param QCloseEvent: :return: ''' # 使用QMessageBox提示 reply = QMessageBox.warning(self, "温馨提示", "即将退出, 确定?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if (reply == QMessageBox.Yes): QCloseEvent.accept() if (reply == QMessageBox.No): QCloseEvent.ignore()
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_()
class MainGame(QWidget): move_character_signal = pyqtSignal(str) part_adder_lock = Lock() def __init__(self): super().__init__() self.directions = { Qt.Key_D: 'R', Qt.Key_A: 'L', Qt.Key_W: 'U', Qt.Key_S: 'D' } self.libraries = dict() self.front_entities = [] self.setGeometry(100, 100, 512, 512) self.background = QLabel(self) self.background.setPixmap( QPixmap(join('sprites_game', 'background.bmp')).scaledToHeight(512)) front_character = QLabel(self) front_character.setGeometry(QRect(300, 300, 30, 30)) front_character.setPixmap( QPixmap(join('sprites_game', 'snake_head.png'))) self.front_entities.append(front_character) self.backend_character = Character(self, 300, 300) self.move_character_signal.connect(self.backend_character.update_dir) self.music = QSound(join("sounds", "snake_audio.wav")) self.audio_eat = QSound(join("sounds", "snake_eat.wav")) self.music.setLoops(-1) self.music.play() def keyPressEvent(self, e): key = e.key() if key in self.directions: self.move_character_signal.emit(self.directions[key]) @pyqtSlot(dict) def update_from_backend(self, event): status = event['status'] if status == 'move': self.move_snake_part(event) elif status == 'new_library': self.create_library(event) elif status == 'ate': self.eat_library(event) def move_snake_part(self, event): part = event['part'] if part == len(self.front_entities): # Si la parte no existe, agregamos una with self.part_adder_lock: body_part = QLabel('', self) body_part.setGeometry(QRect(event['x'], event['y'], 30, 30)) body_part.setPixmap( QPixmap(join('sprites_game', 'snake_body.png'))) body_part.show() self.front_entities.append(body_part) elif part > len(self.front_entities): # si es que se agregaron dos partes instantáneamente, # retornamos para que después se agregue la otra return part_to_move = self.front_entities[part] part_to_move.move(event['x'], event['y']) def create_library(self, event): library = QLabel('', self) library.setGeometry(event['location']) library.setPixmap(QPixmap(join('sprites_game', 'library.png'))) self.libraries[event['coordenates']] = library library.show() def eat_library(self, event): self.audio_eat.play() library = self.libraries[event['coordenates']] library.hide() library.deleteLater() del self.libraries[event['coordenates']]
self.viderLayout_main() self.changeJoueurnom() main = self.jeux.listeJoueur[self.jeux.joueurActuel].mainj for i in range(len(main)): d = main[i] for j in range(2): l1 = MyQLabel(self, d) p = QtGui.QPixmap('img/dice' + str(d[j]) + str(d.color) + '.png') l1.setPixmap(p) l1.clicked.connect(self.jeuxjoueur) self.ui.gridLayout_main.addWidget(l1, j, i) def boiteVictoire(self): """une boite de dialogue qui dit qui est le gagnant""" a = QtWidgets.QMessageBox(self) a.setText("victoire du joueur: " + self.jeux.listeJoueur[self.jeux.gagnant].nomjoueur + str(self.jeux.nbpointgagnant)) a.show() a.exec_() if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) s = QSound('gnagna.wav') s.setLoops(-1) s.play() window = jeuxUI() window.show() sys.exit(app.exec_())
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()