class Tower(QObject): mover = pyqtSignal(Move) attack = pyqtSignal() mouse_arriba_senal = pyqtSignal(SendLabel) mouse_fuera_senal = pyqtSignal(SendLabel) muerto = pyqtSignal(str) def __init__(self, parent, team, pos): super().__init__() self.tower_building = Buildings.Tower(pos, team, constantes) self.nombre = 'tower' self.team = team self.tower_label = FLabel.FLabel(parent, self) self.tower_label.setGeometry(80, 80, 80, 80) self.pixmap = QPixmap(os.getcwd() + '/uis/Sprites/buildings/tower.png') self.pixmap = self.pixmap.scaled(80, 80) self.tower_label.setPixmap(self.pixmap) self.tower_label.setStyleSheet('background:transparent') self.position = pos self.tower_label.setVisible(True) self.tower_label.show() self.mover.connect(parent.actualizar_imagen) self.mover.emit( Move(self.tower_label, self.position[0], self.position[1])) self.muerto.connect(parent.sumar_puntos) self.pbar = QProgressBar(parent) self.pbar.setGeometry(pos[0] + 9, pos[1] - 5, 70, 9) self.pbar.setValue(self.tower_building.health) self.timer = QTimer(self) self.timer.timeout.connect(self.run) self.timer.start(100) def run(self): self.pbar.setValue(self.tower_building.health_bar) if self.tower_building.health <= 0: self.tower_label.close() self.pbar.close() self.muerto.emit('tower') # Ahora la torre ataca a la unidad mas cercana # No alcanze a hacerlo.... def mouse_arriba(self): self.mouse_arriba_senal.emit( SendLabel(self.tower_label, self.tower_building)) def mouse_fuera(self): self.mouse_fuera_senal.emit(SendLabel(False, False)) def atacar(self): pass
class Nexo(QObject): mover = pyqtSignal(Move) attack = pyqtSignal() mouse_arriba_senal = pyqtSignal(SendLabel) mouse_fuera_senal = pyqtSignal(SendLabel) muerto = pyqtSignal(str) def __init__(self, parent, team, pos): super().__init__() self.nexo_building = Buildings.Nexo(team, constantes) self.nombre = 'nexo' self.team = team self.nexo_label = FLabel.FLabel(parent, self) self.nexo_label.setGeometry(80, 80, 80, 80) self.pixmap = QPixmap(os.getcwd() + '/uis/Sprites/buildings/nexo.png') self.pixmap = self.pixmap.scaled(80, 80) self.nexo_label.setPixmap(self.pixmap) self.nexo_label.setStyleSheet('background:transparent') self.position = pos self.nexo_label.setVisible(True) self.nexo_label.show() self.mover.connect(parent.actualizar_imagen) self.mover.emit( Move(self.nexo_label, self.position[0], self.position[1])) self.muerto.connect(parent.sumar_puntos) self.pbar = QProgressBar(parent) self.pbar.setGeometry(pos[0] + 4, pos[1] - 5, 75, 9) self.pbar.setValue(self.nexo_building.health_bar) self.lifetimer = QTimer(self) self.lifetimer.timeout.connect(self.actualizar_vida) self.lifetimer.start(100) def actualizar_vida(self): self.pbar.setValue(self.nexo_building.health_bar) if self.nexo_building.health <= 0: self.nexo_label.close() self.pbar.close() self.muerto.emit('nexo') def mouse_arriba(self): self.mouse_arriba_senal.emit( SendLabel(self.nexo_label, self.nexo_building)) def mouse_fuera(self): self.mouse_fuera_senal.emit(SendLabel(False, False))
def savePhoto(self): if self.size_select == -1 or self.color_select == -1: QMessageBox.warning(self, "警告", "请选择尺寸和颜色!", QMessageBox.Close) return file_path, file_p = QFileDialog.getSaveFileName( self, "保存照片", "./save/save.jpg", "*.jpg;;*.png;;*.jpeg;;*.bmp;;All Files (*)") if file_path == '': return if not self.batch: t_img = Controller.changeSize(self.image, self.size_select) cv2.imwrite(file_path, t_img, None) else: file_path = file_path[:len(file_path)-4] file_p = file_p[1:] bar = QProgressBar(self) bar.setGeometry(390, 530, 281, 31) step = 100 / len(self.image_paths) bar.show() bar.setValue(0) i = 1 for path in self.image_paths: self.image = cv2.imread(path) self.toFit() self.getRect() self.getOutline() self.getDilate() if self.beautify_select: self.beautify() if self.color_select == 0: self.toRed() elif self.color_select == 1: self.toBlue() else: self.toWhite() t_img = Controller.changeSize(self.image, self.size_select) f_path = file_path + str(i) + file_p cv2.imwrite(f_path, t_img, None) bar.setValue(step * i) i = i + 1 bar.close() QMessageBox.information(self, "信息", "保存成功!", QMessageBox.Close)
class ChampionEnemigo(QObject): mover = pyqtSignal(Move) att_image = pyqtSignal(Move) look_mouse = pyqtSignal() mouse_arriba_senal = pyqtSignal(SendLabel) mouse_fuera_senal = pyqtSignal(SendLabel) muerto = pyqtSignal(str) def __init__(self, parent, champion): super().__init__() self.nombre = champion if champion == 'arthas': self.champion = Champions.Arthas(2, constantes) elif champion == 'chau': self.champion = Champions.Chau(2, constantes) elif champion == 'hernan': self.champion = Champions.Hernan(2, constantes) self.jugador_label = QLabel(parent) self.jugador_label.setGeometry(40, 40, 40, 40) self.pixmap = QPixmap('uis/Sprites/' + str(self.nombre) + '/1.png') self.pixmap = self.pixmap.scaled(40, 40) self.jugador_label.setPixmap(self.pixmap) self.pbar = QProgressBar(parent) self.pbar.setGeometry(40, 37, 40, 9) self.pbar.setValue(self.champion.health_bar) self.jugador_label.setStyleSheet('background:transparent') self.jugador_label.setVisible(True) self.jugador_label.show() self.mover.connect(parent.actualizar_imagen) self.muerto.connect(parent.sumar_puntos) self.att_image.connect(parent.actualizar_imagen) self.look_mouse.connect(parent.actualizar_imagen) self.position = [40, 40] self.mover.emit( Move(self.jugador_label, self.jugador_label.x(), self.jugador_label.y())) self.estado_caminar = 1 self.estado_atacar = 1 self.target = SendLabel(False, False) self.lifetimer = QTimer(self) self.lifetimer.timeout.connect(self.actualizar_vida) self.lifetimer.start(50) self.angulo = 0 def actualizar_vida(self): self.pbar.setValue(self.champion.health_bar) if self.champion.health <= 0: self.jugador_label.close() self.pbar.close() self.muerto.emit('champion') def set_target(self, targ): self.target = targ def mouse_arriba(self): pass def mouse_fuera(self): pass @staticmethod def distance(x1, y1, x2, y2): dist = sqrt(((x2 - x1)**2) + ((y2 - y1)**2)) return dist def attack(self): if self.target.objeto: if self.target.objeto.nombre == 'shop': self.mostrar_tienda.emit() else: if self.target.label and self.target.objeto.team != 2: # Ahora tengo que ver si alguna de las esquinas entre ambos objetos estan en rango de ataquedd # (hipotenusa de un triangulo) # Ademas tome en cuenta la distancia de los puntos medios de los lados de cada uno d1 = self.distance( self.jugador_label.x() + self.jugador_label.width(), self.jugador_label.y() + self.jugador_label.height(), self.target.label.x(), self.target.label.y()) d2 = self.distance( self.jugador_label.x(), self.jugador_label.y() + self.jugador_label.height(), self.target.label.x() + self.target.label.width(), self.target.label.y()) d3 = self.distance( self.jugador_label.x() + self.jugador_label.width(), self.jugador_label.y(), self.target.label.x(), self.target.label.y() + self.target.label.height()) d4 = self.distance( self.jugador_label.x(), self.jugador_label.y(), self.target.label.x() + self.target.label.width(), self.target.label.y() + self.target.label.height()) d5 = self.distance( self.jugador_label.x() + (self.jugador_label.width() / 2), self.jugador_label.y() + self.jugador_label.height(), self.target.label.x() + (self.target.label.width() / 2), self.target.label.y()) d6 = self.distance( self.jugador_label.x() + self.jugador_label.width(), self.jugador_label.y() + (self.jugador_label.height() / 2), self.target.label.x(), self.target.label.y() + (self.target.label.height() / 2)) d7 = self.distance( self.jugador_label.x() + (self.jugador_label.width() / 2), self.jugador_label.y(), self.target.label.x() + (self.target.label.width() / 2), self.target.label.y() + self.target.label.height()) d8 = self.distance( self.jugador_label.x(), self.jugador_label.y() + (self.jugador_label.height() / 2), self.target.label.x() + self.target.label.width(), self.target.label.y() + (self.target.label.height()) / 2) if d1 <= self.champion.att_range or d2 <= self.champion.att_range or d3 <= self.champion.att_range \ or d4 <= self.champion.att_range or d5 <= self.champion.att_range or d6 <= self.champion. \ att_range or d7 <= self.champion.att_range or d8 <= self.champion.att_range: self.target.objeto.health -= self.champion.strengh string = '/uis/Sprites/' + str( self.nombre) + '/att' + str(self.estado_atacar) pixmap = QPixmap(os.getcwd() + string) pixmap = pixmap.scaled(40, 40) pixmap = pixmap.transformed(QtGui.QTransform().rotate( self.angulo)) self.jugador_label.setPixmap(pixmap) self.estado_atacar += 1 if self.estado_atacar == 4: self.estado_atacar = 1 self.att_image.emit( Move(self.jugador_label, self.jugador_label.x(), self.jugador_label.y())) def caminar(self): string = '/uis/Sprites/' + str(self.nombre) + '/' + str( self.estado_caminar) pixmap = QPixmap(os.getcwd() + string) pixmap = pixmap.scaled(40, 40) pixmap = pixmap.transformed(QtGui.QTransform().rotate(self.angulo)) self.jugador_label.setPixmap(pixmap) self.estado_caminar += 1 if self.estado_caminar == 4: self.estado_caminar = 1 self.pbar.move(self.jugador_label.x(), self.jugador_label.y() - 7) def move_left(self): self.position[0] = self.jugador_label.x() self.position[1] = self.jugador_label.y() self.position[0] -= self.champion.speed self.mover.emit( Move(self.jugador_label, self.position[0], self.position[1])) def move_right(self): self.position[0] = self.jugador_label.x() self.position[1] = self.jugador_label.y() self.position[0] += self.champion.speed self.mover.emit( Move(self.jugador_label, self.position[0], self.position[1])) def move_front(self): self.position[0] = self.jugador_label.x() self.position[1] = self.jugador_label.y() self.position[1] -= self.champion.speed self.mover.emit( Move(self.jugador_label, self.position[0], self.position[1])) def move_back(self): self.position[0] = self.jugador_label.x() self.position[1] = self.jugador_label.y() self.position[1] += self.champion.speed self.mover.emit( Move(self.jugador_label, self.position[0], self.position[1]))
class WeakSubdito(QObject): mover = pyqtSignal(Move) mouse_arriba_senal = pyqtSignal(SendLabel) mouse_fuera_senal = pyqtSignal(SendLabel) muerto = pyqtSignal(str) def __init__(self, parent, team, posx, posy): super().__init__() self.team = team self.subdito = Subdito.WeakSubdito(team, constantes) self.subdito_label = FLabel.FLabel(parent, self) self.subdito_label.setGeometry(30, 30, 30, 30) self.pixmap = QPixmap(os.getcwd() + '/uis/Sprites/subditos/1') self.pixmap = self.pixmap.scaled(30, 30) self.subdito_label.setPixmap(self.pixmap) self.subdito_label.setStyleSheet('background:transparent') self.subdito_label.show() self.mover.connect(parent.actualizar_imagen) self.muerto.connect(parent.sumar_puntos) self.position = [posx, posy] self.timer = QTimer(self) self.timer.timeout.connect(self.run) self.timer.start(1000) self.estado_caminar = 1 self.lifetimer = QTimer(self) self.lifetimer.timeout.connect(self.actualizar_vida) self.lifetimer.start(50) self.pbar = QProgressBar(parent) self.pbar.setGeometry(posx, posy - 7, 40, 9) self.pbar.setValue(self.subdito.health_bar) self.pbar.show() self.mover.emit( Move(self.subdito_label, self.position[0], self.position[1])) def actualizar_vida(self): self.pbar.setValue(self.subdito.health_bar) if self.subdito.health <= 0: self.subdito_label.close() self.pbar.close() self.muerto.emit('weak') def run(self): if self.team == 1: self.position[0] = self.subdito_label.x() + self.subdito.speed self.position[1] = self.subdito_label.y() + self.subdito.speed self.caminar() self.mover.emit( Move(self.subdito_label, self.position[0], self.position[1])) else: self.position[0] = self.subdito_label.x() - self.subdito.speed self.position[1] = self.subdito_label.y() - self.subdito.speed self.caminar() self.mover.emit( Move(self.subdito_label, self.position[0], self.position[1])) self.pbar.move(self.subdito_label.x(), self.subdito_label.y() - 7) def caminar(self): string = '/uis/Sprites/subditos/' + str(self.estado_caminar) pixmap = QPixmap(os.getcwd() + string) pixmap = pixmap.scaled(40, 40) self.subdito_label.setPixmap(pixmap) self.estado_caminar += 1 if self.estado_caminar == 4: self.estado_caminar = 1 self.pbar.move(self.subdito_label.x(), self.subdito_label.y() - 7) def mouse_arriba(self): self.mouse_arriba_senal.emit( SendLabel(self.subdito_label, self.subdito_label)) def mouse_fuera(self): self.mouse_fuera_senal.emit(SendLabel(False, False))
class Character(QObject): mover = pyqtSignal(Move) att_image = pyqtSignal(Move) look_mouse = pyqtSignal() mouse_arriba_senal = pyqtSignal(SendLabel) mouse_fuera_senal = pyqtSignal(SendLabel) mostrar_tienda = pyqtSignal() def __init__(self, parent, champion): super().__init__() self.nombre = champion if champion == 'arthas': self.champion = Champions.Arthas(2, constantes) elif champion == 'chau': self.champion = Champions.Chau(2, constantes) elif champion == 'hernan': self.champion = Champions.Hernan(2, constantes) self.jugador_label = QLabel(parent) self.jugador_label.setGeometry(40, 40, 40, 40) self.pixmap = QPixmap('uis/Sprites/' + str(self.nombre) + '/1.png') self.pixmap = self.pixmap.scaled(40, 40) self.jugador_label.setPixmap(self.pixmap) self.pbar = QProgressBar(parent) self.pbar.setGeometry(900, 600, 40, 9) self.pbar.setValue(self.champion.health_bar) self.jugador_label.setStyleSheet('background:transparent') self.jugador_label.setVisible(True) self.jugador_label.show() self.mover.connect(parent.actualizar_imagen) self.att_image.connect(parent.actualizar_imagen) self.look_mouse.connect(parent.actualizar_imagen) self.position = [900, 600] self.timer = QTimer(self) self.timer.timeout.connect(self.run) self.timer.start(10) self.mover.emit( Move(self.jugador_label, self.position[0], self.position[1])) self.estado_caminar = 1 self.estado_atacar = 1 self.target = SendLabel(False, False) self.lifetimer = QTimer(self) self.lifetimer.timeout.connect(self.actualizar_vida) self.lifetimer.start(50) self.angulo = 0 def actualizar_vida(self): self.pbar.setValue(self.champion.health_bar) if self.champion.health <= 0: self.jugador_label.close() self.pbar.close() def set_target(self, targ): self.target = targ def mouse_arriba(self): pass def mouse_fuera(self): pass @staticmethod def distance(x1, y1, x2, y2): dist = sqrt(((x2 - x1)**2) + ((y2 - y1)**2)) return dist def attack(self): if self.target.objeto: if self.target.objeto.nombre == 'shop': self.mostrar_tienda.emit() else: if self.target.label and self.target.objeto.team != 2: # Ahora tengo que ver si alguna de las esquinas entre ambos objetos estan en rango de ataquedd # (hipotenusa de un triangulo) # Ademas tome en cuenta la distancia de los puntos medios de los lados de cada uno d1 = self.distance( self.jugador_label.x() + self.jugador_label.width(), self.jugador_label.y() + self.jugador_label.height(), self.target.label.x(), self.target.label.y()) d2 = self.distance( self.jugador_label.x(), self.jugador_label.y() + self.jugador_label.height(), self.target.label.x() + self.target.label.width(), self.target.label.y()) d3 = self.distance( self.jugador_label.x() + self.jugador_label.width(), self.jugador_label.y(), self.target.label.x(), self.target.label.y() + self.target.label.height()) d4 = self.distance( self.jugador_label.x(), self.jugador_label.y(), self.target.label.x() + self.target.label.width(), self.target.label.y() + self.target.label.height()) d5 = self.distance( self.jugador_label.x() + (self.jugador_label.width() / 2), self.jugador_label.y() + self.jugador_label.height(), self.target.label.x() + (self.target.label.width() / 2), self.target.label.y()) d6 = self.distance( self.jugador_label.x() + self.jugador_label.width(), self.jugador_label.y() + (self.jugador_label.height() / 2), self.target.label.x(), self.target.label.y() + (self.target.label.height() / 2)) d7 = self.distance( self.jugador_label.x() + (self.jugador_label.width() / 2), self.jugador_label.y(), self.target.label.x() + (self.target.label.width() / 2), self.target.label.y() + self.target.label.height()) d8 = self.distance( self.jugador_label.x(), self.jugador_label.y() + (self.jugador_label.height() / 2), self.target.label.x() + self.target.label.width(), self.target.label.y() + (self.target.label.height()) / 2) if d1 <= self.champion.att_range or d2 <= self.champion.att_range or d3 <= self.champion.att_range \ or d4 <= self.champion.att_range or d5 <= self.champion.att_range or d6 <= self.champion. \ att_range or d7 <= self.champion.att_range or d8 <= self.champion.att_range: self.target.objeto.health -= self.champion.strengh string = '/uis/Sprites/' + str( self.nombre) + '/att' + str(self.estado_atacar) pixmap = QPixmap(os.getcwd() + string) pixmap = pixmap.scaled(40, 40) pixmap = pixmap.transformed(QtGui.QTransform().rotate( self.angulo)) self.jugador_label.setPixmap(pixmap) self.estado_atacar += 1 if self.estado_atacar == 4: self.estado_atacar = 1 self.att_image.emit( Move(self.jugador_label, self.jugador_label.x(), self.jugador_label.y())) def upgrade(self, compra): if compra.habilidad == 'frostmourne': self.champion.strengh += compra.valor if compra.habilidad == 'ballesta': self.champion.att_range += compra.valor if compra.habilidad == 'boots': self.champion.speed += compra.valor if compra.habilidad == 'objeto': self.champion.poder += compra.valor if compra.habilidad == 'armadura': self.champion.att_speed += compra.valor if compra.habilidad == 'carta': habilidad = random.choice( ['frostmourne', 'ballesta', 'boots', 'objeto', 'armadura']) self.upgrade(Compra(habilidad, compra.valor)) def run(self): pass def caminar(self): string = '/uis/Sprites/' + str(self.nombre) + '/' + str( self.estado_caminar) pixmap = QPixmap(os.getcwd() + string) pixmap = pixmap.scaled(40, 40) pixmap = pixmap.transformed(QtGui.QTransform().rotate(self.angulo)) self.jugador_label.setPixmap(pixmap) self.estado_caminar += 1 if self.estado_caminar == 4: self.estado_caminar = 1 self.pbar.move(self.jugador_label.x(), self.jugador_label.y() - 7) def move_left(self): self.mover.emit( Move( self.jugador_label, self.jugador_label.x() - (self.champion.speed * cos(self.angulo)), self.jugador_label.y() + (self.champion.speed * sin(self.angulo)))) self.caminar() def move_right(self): self.mover.emit( Move( self.jugador_label, self.jugador_label.x() + (self.champion.speed * cos(self.angulo)), self.jugador_label.y() - (self.champion.speed * sin(self.angulo)))) self.caminar() def move_front(self): self.mover.emit( Move( self.jugador_label, self.jugador_label.x() + (self.champion.speed * cos(self.angulo)), self.jugador_label.y() + (self.champion.speed * sin(self.angulo)))) self.caminar() def move_back(self): self.mover.emit( Move( self.jugador_label, self.jugador_label.x() - (self.champion.speed * cos(self.angulo)), self.jugador_label.y() - (self.champion.speed * sin(self.angulo)))) self.caminar() def look(self, mouse): distx = mouse.x - self.jugador_label.x() disty = mouse.y - self.jugador_label.y() try: self.angulo = degrees(atan(disty / distx)) except: pass if distx < 0: self.angulo += 180 if distx > 0 > disty: self.angulo += 360 self.rota() def rota(self): string = '/uis/Sprites/' + str(self.nombre) + '/' + str( self.estado_caminar) pixmap = QPixmap(os.getcwd() + string) pixmap = pixmap.scaled(40, 40) pixmap = pixmap.transformed(QtGui.QTransform().rotate(self.angulo)) self.jugador_label.setPixmap(pixmap) self.mover.emit( Move(self.jugador_label, self.jugador_label.x(), self.jugador_label.y()))
class Tag(QMainWindow): bool_ = True # for player (play/unpause) def __init__(self): super().__init__() self.ui = uic.loadUi('tag_editor.ui') self.ui.setWindowTitle('Music Tag Viewer') self.ui.setWindowIcon(QIcon(':/icons/icons/window_icon.png')) self.statusBar = self.ui.statusBar() self.tracksTable = self.ui.tableWidgetItems self.tagsTable = self.ui.tableWidget self.progressBar = QProgressBar() # -- all imported tracks_information self.files = [] self.current_file_index = 0 self.tags_str_keys = [ 'artist', 'title', 'album', 'genre', 'tracknumber', 'date', 'quality' ] stylesheet = "::section{Background-color:rgb(204,204,204);}" self.tracksTable.horizontalHeader().setStyleSheet(stylesheet) self.tagsTable.horizontalHeader().setStyleSheet(stylesheet) self.searchDialog = SearchDialog() # for web search self.initUI() def initUI(self): # -- resize column self.tracksTable.resizeColumnToContents(1) # -- activate cell self.tracksTable.cellClicked.connect(self.cell_clicked) # coord # -- actions # add folder action add_folder_action = self.ui.actionAdd_Folder add_folder_action.triggered.connect(self.show_folder_dialog) # add file action add_file_action = self.ui.actionAdd_File add_file_action.triggered.connect(self.show_file_dialog) # close app action exit_action = self.ui.actionExit exit_action.triggered.connect(self.show_quit_message) # search on web actioon search_on_web_action = self.ui.actionSearch_on_Web search_on_web_action.triggered.connect(self.show_web_search_dialog) self.ui.show() def cell_clicked(self, r, c): """When cell clicked slot. :param r: row :param c: count """ item = self.tracksTable.item(r, 2) # title for file in self.files: if item.text() == file.track_info['title']: self.statusBar.showMessage( 'Track size: {} mb File path: {}'.format( file.track_info['track_size'], file.file_path)) self.current_file_index = self.files.index(file) self.update_tag_table(file) # -- player actions # play action if Tag.bool_: play_action = self.ui.actionPlay # create instance of Player object self.player = Player(file.file_path) Tag.bool_ = True play_action.triggered.connect(self.play) # pause action pause_action = self.ui.actionPause pause_action.triggered.connect(self.pause) # stop action stop_action = self.ui.actionStop stop_action.triggered.connect(self.stop) # -- slots for player def play(self): # use for start playing if Tag.bool_: self.player.play() Tag.bool_ = False self.player.unpause() def pause(self): # use for pause playing self.player.pause() def stop(self): # stop playing self.player.stop() Tag.bool_ = True def show_quit_message(self): reply = QMessageBox.question( self, 'Quit message', 'Are you sure you w' 'ant to exit Music T' 'ag Editor?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: self.ui.close() self.searchDialog.ui.close() def show_file_dialog(self): self.files.clear() if not Tag.bool_: self.stop() file_name = QFileDialog.getOpenFileName(self, 'Open file', '/home', '*.mp3')[0] if file_name: self.files.append(TagExtractor(file_name)) # update trackTable widget self.update_tracks_table() def show_folder_dialog(self): self.files.clear() if not Tag.bool_: self.stop() folder_items = QFileDialog \ .getExistingDirectory(self, 'Open folder', '/home', QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks) completed = 0 self.progressBar.setMaximumSize(180, 20) self.statusBar.addPermanentWidget(self.progressBar) self.statusBar.showMessage('Load songs...') if folder_items: for item in os.listdir(folder_items): path = folder_items + '/' + item if os.path.isfile(path): if path.endswith('.mp3'): self.files.append( TagExtractor(folder_items + '/' + item)) else: continue self.progressBar.setValue(completed) completed += 100 / len(os.listdir(folder_items)) + 0.1 self.progressBar.close() self.statusBar.showMessage('Added ' + str(len(self.files)) + ' tracks') # -- update trackTable widget self.update_tracks_table() def update_tag_table(self, file): for count in range(1, 2): for row, tag in enumerate(self.tags_str_keys): new_item = QTableWidgetItem(file.track_info[tag]) self.tagsTable.setItem(row, count, new_item) if count < 2: t_item = self.tagsTable.item(row, count) t_item.setFlags(Qt.ItemIsDragEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) def update_tracks_table(self): self.tracksTable.setRowCount(len(self.files)) keys = ['artist', 'length', 'title'] for r, item in enumerate(self.files): for c, key in enumerate(keys): new_item = QTableWidgetItem(item.track_info[key]) self.tracksTable.setItem(r, c, new_item) t_item = self.tracksTable.item(r, c) # get item t_item.setFlags(Qt.ItemIsDragEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) item_for_icon = self.tracksTable.item(r, 0) item_for_icon.setIcon(QIcon(':/icons/icons/song_icon.png')) def show_web_search_dialog(self): self.searchDialog.ui.show()
class principal(entidad): mover = pyqtSignal(Move) muerte = pyqtSignal() crea = pyqtSignal(Crear) revisa = pyqtSignal() actualiza = pyqtSignal() pedir = pyqtSignal() def __init__(self, parent, posx, posy): super().__init__() self.nivel = 1 self.tamano = 3 self.velocidad = 1.1 - self.tamano / 10 self.label = labels.FLabel(parent, self) self.label.setGeometry(30, 30, (self.tamano + 1) * 10, (self.tamano + 1) * 10) self.rec = QRect(posx, posy, (self.tamano + 1) * 10, (self.tamano + 1) * 10) self.experiencia = 200 self.parent = parent self.puntaje = 0 self.position = [posx, posy] self.pixmap = QPixmap(os.getcwd() + '/images/p1.png') self.pixmap = self.pixmap.scaled(self.tamano * 10, self.tamano * 10) self.angulo = radians(90) self.degrees = 90 self.pixmap = self.pixmap.transformed(QtGui.QTransform().rotate( self.degrees)) self.label.setPixmap(self.pixmap) self.label.move(posx, posy) self.pbar = QProgressBar(parent) self.pbar.setGeometry(posx, posy - 8, self.tamano * 10, 9) self.vida = self.vida_maxima self.pbar.setValue(self.vida / self.vida_maxima * 100) self.subio_nivel = False self.terminado = False self.imagen = 1 # usar esto para ver si se puede!! hacer un self.path que sea un # path.Path que vaya cambiando cada vez que se cambia posicion o # geometria del label para asi comparar mas facil :) """p = path.Path([(30, 30), (50, 30), (50, 50), (30, 50)]) print(p.contains_point((49, 32))) print(p.contains_point((49, 29)))""" # aqui cambiar esto def run(self): self.label.show() self.pbar.show() self.timer = QTimer(self) self.timer.timeout.connect(self.generador_enemigos) self.timer.start(self.cantidad() * 1000) #self.timer.start(7000) self.lifetimer = QTimer(self) self.lifetimer.timeout.connect(self.actualizar_vida) self.lifetimer.start(50) self.ataquetimer = QTimer(self) self.ataquetimer.timeout.connect(self.ataque) self.ataquetimer.start(10) self.atacandotimer = QTimer(self) self.atacandotimer.timeout.connect(self.pelea) self.ataquetimer.start(50) self.mover.connect(self.parent.actualizar_imagen) self.crea.connect(self.parent.crea_enemigos) self.muerte.connect(self.parent.salir) self.timer = QTimer(self) self.mover.emit( Move(self.label, self.position[0], self.position[1])) self.rec = QRect(self.position[0], self.position[1], (self.tamano + 1) * 10, (self.tamano + 1) * 10) self.actualiza.connect(self.parent.actualiza_datos) # self.pedir.connect(parent.retorna_enemigos) def revisar_tiempo(self): self.timer.start(self.cantidad() * 1000) pass def cantidad(self): if self.nivel == 1: lamda = 1 / 10 elif self.nivel == 2: lamda = 1 / 8 elif self.nivel == 3: lamda = 1 / 6 elif self.nivel == 4: lamda = 1 / 4 elif self.nivel == 5: lamda = 1 / 2 a = expovariate(lamda) return a def generador_enemigos(self): tamano = self.generador_tamanos() posicion = (150,150) self.crea.emit(Crear(tamano, posicion)) def compravida(self): if self.puntaje < 700: pass else: self.puntaje -= 700 self.vida = self.vida * 1.2 def generador_tamanos(self): if self.nivel == 1: a = 1 b = 5 c = 1 elif self.nivel == 2: a = 1 b = 6 c = 3 elif self.nivel == 3: a = 3 b = 7 c = 5 elif self.nivel == 4: a = 5 b = 9 c = 7 elif self.nivel == 5: a = 7 b = 10 c = 9 tamano = floor(triangular(a, b, c)) if tamano > 10: tamano = 10 return tamano def compravelocidad(self): if self.puntaje < 250: pass else: self.puntaje -= 250 self.velocidad = self.velocidad * 1.1 def compraataque(self): if self.puntaje < 500: pass else: self.puntaje -= 500 # sube vel ataque def pelea(self, objeto): enemigo = objeto.persona enemigo.vida -= self.cap_ataque if enemigo.vida <= 0: self.sumar_puntos(enemigo) def ataque(self): self.revisar() def move_right(self): self.degrees += 15 self.angulo = radians(self.degrees) string = '/images/p' + str(self.imagen) + '.png' self.act_label(string) def move_left(self): self.degrees -= 15 self.angulo = radians(self.degrees) string = '/images/p' + str(self.imagen) + '.png' self.act_label(string) def move_front(self): if self.imagen == 8: self.imagen = 1 else: self.imagen += 1 string = '/images/p' + str(self.imagen) + '.png' self.act_label(string) self.mover.emit(Move(self.label, self.label.x() + sin(self.angulo) * 10 * self.velocidad, self.label.y() - cos( self.angulo) * 10 * self.velocidad)) self.rec = QRect(self.label.x(), self.label.y(), (self.tamano + 1) * 10, (self.tamano + 1) * 10) self.pbar.move(self.label.x(), self.label.y() - 8) def move_back(self): if self.imagen == 1: self.imagen = 8 else: self.imagen -= 1 string = '/images/p' + str(self.imagen) + '.png' self.act_label(string) self.mover.emit(Move(self.label, self.label.x() - sin(self.angulo) * 10 * self.velocidad, self.label.y() + cos( self.angulo) * 10 * self.velocidad)) self.rec = QRect(self.label.x(), self.label.y(), (self.tamano + 1) * 10, (self.tamano +1) *10) self.pbar.move(self.label.x(), self.label.y() - 8) def act_label(self, string): self.label.setGeometry(self.label.x(), self.label.y(), (self.tamano + 1) * 10, (self.tamano + 1) * 10) self.pixmap = QPixmap(os.getcwd() + string) self.pixmap = self.pixmap.scaled(self.tamano * 10, self.tamano * 10) self.pixmap = self.pixmap.transformed(QtGui.QTransform().rotate( self.degrees)) self.label.setPixmap(self.pixmap) self.pbar.setGeometry(self.label.x(), self.label.y() - 8, self.tamano * 10, 9) def actualizar_vida(self): # cambiar TODOS los labels del front self.actualiza.emit() self.pbar.setValue(self.vida / self.vida_maxima * 100) if self.vida <= 0: self.label.close() self.terminado = True self.pbar.close() self.muerte.emit() def sumar_puntos(self, mato): peg = 100 * max(self.tamano - mato.tamano + 3, 1) self.experiencia += peg # esta es clave!! def revisar(self): if self.experiencia >= 1000: if self.nivel == 5: self.muerte.emit() return self.nivel += 1 self.subio_nivel = False if self.tamano < 10: self.tamano += 1 self.puntaje += self.experiencia self.experiencia = 0 string = '/images/p' + str(self.imagen) + '.png' self.act_label(string) # cambiar tamaño if self.experiencia >= 500 and not self.subio_nivel: self.subio_nivel = True if self.tamano < 10: self.tamano += 1 string = '/images/p' + str(self.imagen) + '.png' self.act_label(string) self.velocidad = 1.1 - self.tamano / 10 @staticmethod def distance(x1, y1, x2, y2): dist = sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2)) return dist
class MainGui(QWidget): def __init__(self, parent): super(MainGui, self).__init__(parent) # The height of each thumbnail self.thumb_height = 200 # A list of thumbnails, no markers, each entry is a dict: # {"idx": int, "date": str, "time": str, "safety": str, "tags": list) # "idx" being the thumbnail's location in the layout self.thumb_list = [] self.layout = QVBoxLayout(self) # This is needed to keep it looking clean and centered self.layout.setContentsMargins(0, 0, 0, 0) self.layout.setAlignment(Qt.AlignCenter) # Create self.home_title self.home_title = QLabel("szurubooru_uploader") self.home_title.setObjectName("homeTitle") self.home_title.setFont(Fonts.NotoSansDisplay("ExtraLight", 40)) self.home_title.setAlignment(Qt.AlignCenter) # Create self.home_desc self.home_desc = QLabel("Uploading and Tagging helper for szurubooru") self.home_desc.setObjectName("homeDesc") self.home_desc.setFont(Fonts.NotoSansDisplay("Light Italic", 15)) self.home_desc.setAlignment(Qt.AlignCenter) # Create open_folder self.open_folder = QPushButton(" Import folder") self.open_folder.clicked.connect(self.pick_folder) self.open_folder.setObjectName("openFolder") self.open_folder.setFont(Fonts.NotoSansDisplay("Italic", 12)) self.open_folder.setIcon(QIcon(QPixmap(FILE_IMPORT_ICON))) self.open_folder.setIconSize(QSize(14, 14)) # Create main thumbnail layout, wrapper, and scroll area (but don't insert) # The QScrollArea is the parent of a QWidget which is the wrapper and parent of a QLayout # Why? I have no idea self.thumb_layout_scroll_area = QScrollArea() self.thumb_layout_wrapper = QWidget(self.thumb_layout_scroll_area) self.thumb_layout = FlowLayout(self.thumb_layout_wrapper, -1, 5, 5) self.thumb_layout.update_wrapper_height.connect(self.update_thumb_layout_wrapper_height) self.thumb_layout_wrapper.setVisible(False) # Create progressbar (but don't insert!) self.loading_progressbar = QProgressBar() self.loading_progressbar.setFont(Fonts.NotoSansDisplay("Regular", 6)) self.loading_progressbar.setAlignment(Qt.AlignLeft) self.loading_progressbar.setFixedHeight(12) # Assemble initial UI self.layout.addStretch(1) self.layout.addWidget(self.home_title) self.layout.addWidget(self.home_desc) self.layout.addStretch(1) self.layout.addWidget(self.open_folder) self.layout.addStretch(1) self.setLayout(self.layout) def resizeEvent(self, event): # Override the resizeEvent of the main window to to automatically update the wrapper's width # to what is needed, since it doesn't update by itself. self.thumb_layout_wrapper.setFixedWidth(self.thumb_layout_scroll_area.size().width()) def count_files(self, folder_path): self.file_count = 0 for root, dirs, files in os.walk(folder_path): for name in files: ext = name.split('.')[-1] if ext in FileExts.image_exts or ext in FileExts.video_exts or ext in FileExts.misc_exts: self.file_count += 1 def pick_folder(self): print("Picking folder...") # Launch file picker if debug is diabled if dbg.ENABLED: folder_path = dbg.PATH else: folder_path = QFileDialog.getExistingDirectory(self, "Select folder", "./", QFileDialog.ShowDirsOnly) # If we get a file then move on if folder_path != '': self.count_files(folder_path) print(f"Selected \"{folder_path}\", contains {self.file_count} files.") self.layout.removeWidget(self.open_folder) self.open_folder.close() self.start_import_files_thread(folder_path) def reorganize_ui(self): # Remove widgets in preperation for repositioning self.layout.removeWidget(self.home_title) self.layout.removeWidget(self.home_desc) self.layout.removeWidget(self.open_folder) self.home_desc.close() # Renovate home_title self.home_title.setFont(Fonts.NotoSansDisplay("Light Italic", 14)) self.home_title.setAlignment(Qt.AlignLeft) self.home_title.setContentsMargins(15, 5, 0, 0) # Re-add widgets and layouts self.layout.addWidget(self.thumb_layout_scroll_area) self.layout.addWidget(self.loading_progressbar) self.layout.insertWidget(0, self.home_title) # Re-adjust stretches self.layout.setStretch(2, 0) self.layout.setStretchFactor(self.thumb_layout_scroll_area, 150) def start_import_files_thread(self, folder_path): print("Starting thread...") self.reorganize_ui() self.loading_progressbar.setVisible(True) # Begin thread self.import_files_thread = ImportFiles(folder_path, self.thumb_height) self.import_files_thread.send_thumbnails_signal.connect(self.add_thumbnails_to_grid) self.import_files_thread.format_progressbar.connect(self.format_progressbar) self.import_files_thread.max_progressbar.connect(self.max_progressbar) self.import_files_thread.increment_progressbar.connect(self.increment_progressbar) # Start timing loading process self.load_start = time.time() self.import_files_thread.start() # SIGNALS def format_progressbar(self, fmt): # Allows the loading thread to change the format of the progressbar # Reset the progressbar first because we only call this at the start of a new operation self.loading_progressbar.reset() # We add a space before the text because setContentsMargins doesn't work on QProgressbars fsr self.loading_progressbar.setFormat(f" {fmt}") def max_progressbar(self, val): # Allows the loading thread to set the maximum value of the progressbar self.loading_progressbar.setMaximum(val) def increment_progressbar(self): # Allows the loading thread to increment the progressbar self.loading_progressbar.setValue(self.loading_progressbar.value() + 1) def show_thumb_layout(self): # Allows the loading thread to show the thumb layout only right before the thumbnail insertion self.thumb_layout_wrapper.setVisible(True) def add_thumbnails_to_grid(self, thumbs_list): # Adds each thumbnail from the given list to the thumb layout print(f"Adding {len(thumbs_list)} total elements to the layout...") for idx, (data, path, creation_date, creation_time) in enumerate(thumbs_list): # If the previous date isn't the current date or if we are at the start, add a datesection if not thumbs_list[idx - 1] or thumbs_list[idx - 1][1] != creation_date: # Initialize custom Datesection item datesection = DatesectionItem() # Set text of Datesection item to "Unknown Date" if no date found if creation_date[0] == "0000": datesection.setText("Unknown Date") else: # Otherwise make it the date datesection.setDate(creation_date[0], creation_date[1], creation_date[2]) self.thumb_layout.addWidget(datesection) # Create item to add to our layout, and load the bytearray into it item = ThumbnailItem() item.loadFromData(data) # Add the item to the layout self.thumb_layout.addWidget(item) self.thumb_layout_scroll_area.setWidget(self.thumb_layout_wrapper) # Add an entry to our thumbs list current_thumb_dict = { "path": path, "ext": path.split('.')[-1] "date": creation_date, "time": creation_time, "widget": item, "tags": [] "selected": False, "safety": ''} self.thumb_list.append(current_thumb_dict.copy()) # Increment progressbar self.increment_progressbar() # Finally, cleanup and perform post-load actions thumbs_list = None self.post_load() def update_thumb_layout_wrapper_height(self, height): # Allows the FlowLayout to set the height it needs *when it's ready* # Before, the height was set after all the thumbnail-adding was complete, leading to a race # condition problem. To sovle that, this is run everytime the layout is updated to avoid that. self.thumb_layout_wrapper.setFixedHeight(height) def post_load(self): # Remove progressbar self.loading_progressbar.setVisible(False) self.layout.removeWidget(self.loading_progressbar) self.loading_progressbar.close() # Set the size of the wrapper for thumb_layout to the size of the QScrollArea it's in self.thumb_layout_wrapper.setFixedWidth(self.thumb_layout_scroll_area.size().width()) print(f"Loading finished in {(time.time() - self.load_start) * 1000}ms.")
class DownloadImage(QWidget): def __init__(self, c): super().__init__() self.c = c # basic layout for download widget self.grid = QGridLayout() self.init_UI() self.threadpool = QThreadPool() # variables to add to tree widget self.words = [] self.keywords = [] self.search_num = 0 # initialize download numbers self.picture_on = False # size of the images self.scale_num = MainWindow.y // 10 self.text_image = False # shows the progress of image download self.pr_bar = QProgressBar() def init_UI(self): # get the data from Enterwords self.c.set_keyword.connect(self.search_setting) # tree widget to show word, keyword, search_num and downloaded images self.tree = QTreeWidget() # edit is made more easier self.tree.setEditTriggers(QAbstractItemView.SelectedClicked | QAbstractItemView.DoubleClicked) # to make UX make add keyboard events self.tree.installEventFilter(self) # add tree widget to layout self.grid.addWidget(self.tree, 1, 0) # settings for tree widget header = QTreeWidgetItem(["단어", "검색 키워드", '검색 개수', "이미지", '']) self.tree.setHeaderItem(header) self.tree.itemPressed.connect(self.changePic) # label, button widget to set the number of search_num, update from the image folder and download the images depending on the tree widget label_search = QLabel('전체 검색 개수') self.every_search_num = QSpinBox() self.every_search_num.setMinimum(1) self.every_search_num.setValue(5) self.every_search_num.valueChanged.connect(self.change_every_search) self.download_bt = QPushButton("이미지\n다운로드") self.download_bt.setShortcut('Ctrl+F') self.download_bt.setToolTip('단축키 : Ctrl + F') self.download_bt.clicked.connect(self.start_download) # add label, update, download button widget to the vertical layout box(vbox) self.vbox = QVBoxLayout() self.vbox.addWidget(label_search) self.vbox.addWidget(self.every_search_num) self.vbox.addWidget(self.download_bt) # stretch is needed to make gui better self.vbox.addStretch(1) # add vbox to the layout self.grid.addLayout(self.vbox, 1, 1) # adjust the size of the column layout self.grid.setColumnStretch(0, 13) self.grid.setColumnStretch(1, 2) self.setLayout(self.grid) # self.eventFilter, self.changePic is for the basic behavior of Tree widget # it uses the keypress event to make UX better def eventFilter(self, source, event): if event.type() == QEvent.KeyPress: if event.key() == Qt.Key_Return: item = self.tree.selectedItems()[0] if item.parent(): file = item.data(3, 1) item.parent().setData( 3, 1, file.scaled(self.scale_num, self.scale_num)) item.parent().path = item.path item.parent().setExpanded(False) self.tree.setCurrentItem(item.parent()) elif item.childCount() > 0: if item.isExpanded() == True: item.setExpanded(False) else: item.setExpanded(True) if event.key() == Qt.Key_Delete or event.key() == Qt.Key_Backspace: item = self.tree.selectedItems()[0] if item.parent(): if item.parent().childCount() > 1: path = item.path item.parent().removeChild(item) del item if os.path.exists(path): send2trash(path) return super(DownloadImage, self).eventFilter(source, event) # When you press a tree item(mouse click) the main image changes @pyqtSlot(QTreeWidgetItem) def changePic(self, item): if item.parent(): file = QPixmap(item.path) item.parent().setData(3, 1, file.scaled(self.scale_num, self.scale_num)) # top item's path variable contains the image path item.parent().path = item.path # add items to top level of tree widget @pyqtSlot(list) def search_setting(self, search_list): # clears all the items from tree widget to add new items self.tree.clear() # initialize download numbers self.picture_on = False # get the data from enterword widget self.search_list = search_list for word, keyword in zip(search_list[0], search_list[1]): # make item item = QTreeWidgetItem([word, keyword]) # Tooltip for keyboard item.setToolTip(1, '더블 클릭하여 변경하세요.') item.setToolTip(3, '사진을 선택할 때 화살표, 엔터, 백스페이스 키보드를 누를 수 있습니다.') # 2 is the index column, 0 is the type of data, and the last parameter is the data item.setData(2, 0, self.every_search_num.value()) # add the items to top level within tree widget self.tree.addTopLevelItem(item) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable) # when you change the spin box you change all of the search_num @pyqtSlot(int) def change_every_search(self, value): for it_idx in range(self.tree.topLevelItemCount()): self.tree.topLevelItem(it_idx).setData(2, 0, value) def enable_buttons(self): self.download_bt.setEnabled(True) self.c.enable_set_keyword_bt.emit() def disable_buttons(self): self.download_bt.setEnabled(False) self.c.disable_set_keyword_bt.emit() @pyqtSlot() def start_download(self): # disable the buttons self.disable_buttons() # if no keywords exist enable buttons and press Set Keyword Button if self.tree.topLevelItemCount() == 0: self.enable_buttons() self.c.press_set_keyword_bt.emit() q = QMessageBox(self) q.information(self, 'information', '검색어 키워드가 존재하지 않아요. 그래서 검색어 키워드 버튼을 대신 눌렀습니다~.', QMessageBox.Ok) return # the data to be passed to downloader words = [] keywords = [] search_num = [] for it_idx in range(self.tree.topLevelItemCount()): words.append(self.tree.topLevelItem(it_idx).text(0)) keywords.append(self.tree.topLevelItem(it_idx).text(1)) search_num.append(self.tree.topLevelItem(it_idx).text(2)) self.dir_path = self.get_save_dir() if self.dir_path: # add progressbar to layout self.grid.addWidget(self.pr_bar, 2, 0, 1, 2) self.pr_bar.show() # initiate progress bar self.pr_bar.setValue(0) download_worker = DownloadWorker(download_images.download_image, words, keywords, search_num, self.pr_bar, self.dir_path, text_image=self.text_image) download_worker.signal.download_complete.connect( self.finish_download) # Execute self.threadpool.start(download_worker) q = QMessageBox(self) q.information(self, 'information', '다운로드 및 이미지를 불러오는 중입니다. 조금만 기다려주세요~^^', QMessageBox.Ok) else: self.enable_buttons() def get_save_dir(self): save_path = os.path.join(os.getcwd(), 'dir_path.json') is_dir_path = os.path.exists(save_path) if is_dir_path: with open(save_path) as f: data = json.load(f) if 'default_dir' in data.keys(): dir_path = data['default_dir'] return dir_path else: q = QMessageBox(self) q.information(self, 'information', '다운로드 받은 이미지를 저장할 폴더를 선택하세요.', QMessageBox.Ok) fname = str( QFileDialog.getExistingDirectory(self, "이미지를 저장할 폴더")) if fname: data['default_dir'] = fname with open(save_path, 'w') as f: json.dump(data, f) dir_path = fname return dir_path else: return else: q = QMessageBox(self) q.information(self, 'information', '다운로드 받은 이미지를 저장할 폴더를 선택하세요.', QMessageBox.Ok) fname = str(QFileDialog.getExistingDirectory(self, "이미지를 저장할 폴더")) if fname: with open(save_path, 'w') as f: json.dump({'default_dir': fname}, f) dir_path = fname return dir_path else: return # execute when download is finished @pyqtSlot(list) def finish_download(self, word_imagePath): # word_imagePath is for new downloaded words and old_word_imagePath is for updating already downloaded words self.word_imagePath = word_imagePath[0] self.old_word_imagePath = word_imagePath[1] # combine word_imagePath and old_word_imagePath to update the images only on first download if self.picture_on == False: self.word_imagePath.update(self.old_word_imagePath) # go through top level items for it_idx in range(self.tree.topLevelItemCount()): item = self.tree.topLevelItem(it_idx) try: pic_path = self.word_imagePath[self.tree.topLevelItem( it_idx).text(0)] # if the word exists in the given image path clear the children to update new children for i in reversed(range(item.childCount())): item.removeChild(item.child(i)) # update new children for path in pic_path: picture = QPixmap(path) if not picture.isNull(): pic_item = QTreeWidgetItem(item) # set path variable so the image can be used pic_item.path = path pic_item.setData( 3, 1, picture.scaled(self.scale_num, self.scale_num)) else: # if picture is not valid and it exists delete it if os.path.exists(path): send2trash(path) # because the children are updated the main image changes if item.childCount() > 0: # set main image and add image button only if child exists init_pic = QPixmap(item.child(0).path) item.setData( 3, 1, init_pic.scaled(self.scale_num, self.scale_num)) # set path variable so the image can be used item.path = item.child(0).path # make a button that can add additional pictures add_image_bt = QPushButton("이미지 변경") # open file dialog, pass the image dir path as parameter add_image_bt.clicked.connect( lambda _, item=item, path=os.path.dirname(item.path): self.add_image(item=item, dir_path=path)) # layout setting for the button button_widget = QWidget() vbox = QVBoxLayout() vbox.addWidget(add_image_bt) button_widget.setLayout(vbox) # add button widget to tree widget self.tree.setItemWidget(item, 4, button_widget) except KeyError: # if word doesn't exist in the given image path leave it be pass # hide progress bar self.pr_bar.close() # this variable is set to True to indicate that now it's not the first time you click the 'Download Button' self.picture_on = True # after downloding the pictures 'Download Button', 'Update Button' and 'Set Keyword Button' is set back to enabled self.enable_buttons() @pyqtSlot(QTreeWidgetItem, str) def add_image(self, item, dir_path): fname = QFileDialog.getOpenFileName( self, 'Open file', dir_path, "Image files (*.jpg *.gif *.png *bmp)") img_path = fname[0] if img_path: if os.path.basename(img_path) not in os.listdir(dir_path): # copy image file to dir_path copy(img_path, dir_path) # add child to item pic_item = QTreeWidgetItem(item) # add picture data picture = QPixmap(img_path) pic_item.setData( 3, 1, picture.scaled(self.scale_num, self.scale_num)) # set path variable so the image can be used pic_item.path = img_path # change main image init_pic = QPixmap(img_path) item.setData(3, 1, init_pic.scaled(self.scale_num, self.scale_num)) # set path variable so the image can be used item.path = img_path
class Traveltimedialog(rcspy_Taupdialog.Ui_Dialog, QtWidgets.QDialog): def __init__(self, parent): super(Traveltimedialog, self).__init__(parent) self.setupUi(self) self.Rcs = parent self.initList() self.source = None self.btn_input_source.setEnabled(False) #self.File_list.setSelectionMode(QAbstractItemView.ExtendedSelection) self.connectevent() def setInv(self): for file in self.Files.files: file.setInv() def initList(self): self.Files = self.Rcs.Files for file in self.Files.files: listitem = QListWidgetItem(file) listitem.setText(file.name) self.File_list.addItem(listitem) def connectevent(self): self.File_list.itemSelectionChanged.connect( self.OnFilelist_selectionchange) self.channel_list.itemSelectionChanged.connect( self.Onchannellist_selectionchange) self.btnOK.clicked.connect(self.Onbtnok) self.btn_Cancel.clicked.connect(self.Onbtnback) self.btn_Inv.clicked.connect(self.OnbtnattachInv) self.btn_Event.clicked.connect(self.OnbtnattachEvent) self.btn_input_source.clicked.connect(self.Oninputsouceinfo) pass def OnFilelist_selectionchange(self): self.btn_input_source.setEnabled(True) self.channel_list.clear() if len(self.File_list.selectedItems()) == 1: file = self.File_list.selectedItems()[0].parent for station in file.stations: listitem = QListWidgetItem(station) listitem.setText(station.name) self.channel_list.addItem(listitem) if file.Invpath != None: self.invdisplayer.setText(str(file.Invpath)) self.source = file.source if self.source != None: self.soulongti.setText(str(self.source.longitude)) self.soulati.setText(str(self.source.latitude)) self.soudepth.setText(str(self.source.depth)) self.sourcetime.setText(str(self.source.time)) else: self.soulongti.setText('') self.soulati.setText('') self.soudepth.setText('') self.sourcetime.setText('') def Onchannellist_selectionchange(self): if len(self.channel_list.selectedItems()) > 0: station = self.channel_list.selectedItems()[0].parent if station.depth != -1: self.stadepth.setText(str(station.depth)) if station.longitude != -1: self.stalongti.setText(str(station.longitude)) if station.latitude != -1: self.stalati.setText(str(station.latitude)) def Oninputsouceinfo(self): if len(self.File_list.selectedItems()) == 1: self.inputdialog = Sourceinputdialog( self, self.File_list.selectedItems()[0].parent) self.inputdialog.show() def Onbtnok(self): if len(self.File_list.selectedItems()) == 1: file = self.File_list.selectedItems()[0].parent source = file.source if source != None: list = [] if self.Pgchenkbox.isChecked(): list.append('P') if self.Sgchenkbox.isChecked(): list.append('S') if self.Pnchenkbox.isChecked(): list.append('Pn') if self.Snchenkbox.isChecked(): list.append('Sn') self.pgb = QProgressBar(self) self.pgb.setWindowTitle("Working") self.pgb.setGeometry(10, 465, 520, 30) self.pgb.show() allnum = len(file.stations) currnum = 0 try: for station in file.stations: self.pgb.setValue(float(currnum * 100) / float(allnum)) station.get_travel_time(list, source) currnum = currnum + 1 self.pgb.close() self.Rcs.draw() QMessageBox.about(self, 'tips', 'finished') except Exception, e: QMessageBox.about(self, "tips", "ErrorSourceinfo") self.pgb.close() else: QMessageBox.about(self, 'tips', 'No source information')
class Autopickdialog(rcspy_Autopickdialog.Ui_Dialog, QtWidgets.QDialog): def __init__(self, parent): super(Autopickdialog, self).__init__(parent) self.setupUi(self) self.Rcs = parent self.initList() self.channel_list.setSelectionMode(QAbstractItemView.ExtendedSelection) self.connectevent() def initList(self): self.Files = self.Rcs.Files for file in self.Files.files: listitem = QListWidgetItem(file) listitem.setText(file.name) self.File_list.addItem(listitem) def connectevent(self): self.File_list.itemSelectionChanged.connect( self.OnFilelist_selectionchange) self.channel_list.itemSelectionChanged.connect( self.Onchannellist_selectionchange) self.allchannel_checkbox.stateChanged.connect(self.Onallchannel_change) self.btnOK.clicked.connect(self.Onbtnok) self.btn_Cancel.clicked.connect(self.Onbtnback) pass def OnFilelist_selectionchange(self): self.channel_list.clear() if len(self.File_list.selectedItems()) == 1: self.channel_list.setEnabled(True) self.allchannel_checkbox.setEnabled(True) file = self.File_list.selectedItems()[0].parent for station in file.stations: listitem = QListWidgetItem(station) listitem.setText(station.name) self.channel_list.addItem(listitem) if len(self.File_list.selectedItems()) > 1: for item in self.File_list.selectedItems(): file = item.parent for station in file.stations: listitem = QListWidgetItem(station) listitem.setText(station.name) self.channel_list.addItem(listitem) self.channel_list.setEnabled(False) self.allchannel_checkbox.setChecked(True) self.allchannel_checkbox.setEnabled(False) def Onchannellist_selectionchange(self): count = self.channel_list.count() if len(self.channel_list.selectedItems()) == count: self.allchannel_checkbox.setChecked(True) else: self.allchannel_checkbox.setChecked(False) def Onallchannel_change(self): if self.allchannel_checkbox.isChecked() == True: self.channel_list.selectAll() else: self.channel_list.clearSelection() def Onbtnok(self): if len(self.channel_list.selectedItems()) == 0: pass else: allnum = 0 self.pgb = QProgressBar(self) self.pgb.setWindowTitle("Working") self.pgb.setGeometry(10, 5, 550, 28) self.pgb.show() for item in self.channel_list.selectedItems(): station = item.parent if isinstance(station, Station): allnum = allnum + 1 currnum = 0 for item in self.channel_list.selectedItems(): station = item.parent if isinstance(station, Station): f1 = self.low_frq.value() f2 = self.upp_frq.value() lta_p = self.lta_p.value() sta_p = self.sta_p.value() lta_s = self.lta_s.value() sta_s = self.sta_s.value() m_p = int(self.m_p.value()) m_s = int(self.m_s.value()) l_p = self.l_p.value() l_s = self.l_s.value() station.Ar_pick(f1, f2, lta_p, sta_p, lta_s, sta_s, m_p, m_s, l_p, l_s) self.pgb.setValue(int(float(currnum) * 100 / allnum)) currnum = currnum + 1 # except Exception,e: # print e self.pgb.close() QMessageBox.about(self, "tip", "finished!") self.Rcs.draw() pass def Onbtnback(self): self.close() pass
class Preprocessdialog(rcspy_Preprocessdialog.Ui_Dialog, QtWidgets.QDialog): def __init__(self, parent): super(Preprocessdialog, self).__init__(parent) self.setupUi(self) self.Rcs = parent self.initList() self.Inv_test() self.File_list.setSelectionMode(QAbstractItemView.ExtendedSelection) self.channel_list.setSelectionMode(QAbstractItemView.ExtendedSelection) self.connectevent() def Inv_test(self): current = 0 for file in self.Files.files: if file.format != 'SEED': current = current + 1 else: if not isinstance(file.Inv, Inventory): current = current - 1 if current != 0: QMessageBox.about(self, "warning", str(current) + "File(s) not set Inventory") def initList(self): self.Files = self.Rcs.Files for file in self.Files.files: listitem = QListWidgetItem(file) listitem.setText(file.name) self.File_list.addItem(listitem) def connectevent(self): self.File_list.itemSelectionChanged.connect( self.OnFilelist_selectionchange) self.channel_list.itemSelectionChanged.connect( self.Onchannellist_selectionchange) self.allchannel_checkbox.stateChanged.connect(self.Onallchannel_change) self.fminSlider.valueChanged.connect(self.OnfminSlider_valueChanged) self.fmaxSlider.valueChanged.connect(self.OnfmaxSlider_valueChanged) self.fminspin.valueChanged.connect(self.Onfminspin_valueChange) self.fmaxspin.valueChanged.connect(self.Onfmaxspin_valueChange) self.btnOK.clicked.connect(self.Onbtnok) self.btn_Cancel.clicked.connect(self.Onbtnback) def OnFilelist_selectionchange(self): self.channel_list.clear() if len(self.File_list.selectedItems()) == 1: self.channel_list.setEnabled(True) self.allchannel_checkbox.setEnabled(True) file = self.File_list.selectedItems()[0].parent for station in file.stations: listitem = QListWidgetItem(station) listitem.setText(station.name) self.channel_list.addItem(listitem) if len(self.File_list.selectedItems()) > 1: for item in self.File_list.selectedItems(): file = item.parent for station in file.stations: listitem = QListWidgetItem(station) listitem.setText(station.name) self.channel_list.addItem(listitem) self.channel_list.setEnabled(False) self.allchannel_checkbox.setChecked(True) self.allchannel_checkbox.setEnabled(False) def Onchannellist_selectionchange(self): count = self.channel_list.count() if len(self.channel_list.selectedItems()) == count: self.allchannel_checkbox.setChecked(True) else: self.allchannel_checkbox.setChecked(False) def Onallchannel_change(self): if self.allchannel_checkbox.isChecked() == True: self.channel_list.selectAll() else: self.channel_list.clearSelection() def OnfminSlider_valueChanged(self): self.fminspin.setValue(float(self.fminSlider.value()) / 10.0) if self.fminSlider.value() > self.fmaxSlider.value(): self.fmaxSlider.setValue(self.fminSlider.value()) def OnfmaxSlider_valueChanged(self): self.fmaxspin.setValue(float(self.fmaxSlider.value()) / 10.0) if self.fminSlider.value() > self.fmaxSlider.value(): self.fminSlider.setValue(self.fmaxSlider.value()) def Onfminspin_valueChange(self): self.fminSlider.setValue(self.fminspin.value() * 10) def Onfmaxspin_valueChange(self): self.fmaxSlider.setValue(self.fmaxspin.value() * 10) def Onbtnok(self): self.errorcontrol = True if len(self.File_list.selectedItems()) == 0: QMessageBox.about(self, "tips", "please set export files") else: self.pgb = QProgressBar(self) self.pgb.setWindowTitle("Working") self.pgb.setGeometry(10, 5, 540, 20) self.pgb.show() if self.detrend_switch.isChecked(): self.current_process.setText("detrend") self.detrend() if self.bandpass_switch.isChecked(): self.current_process.setText("bp_filter") self.bandpass_Filter() if self.lowpass_switch.isChecked(): self.current_process.setText("lp_filter") self.lowpass_Filter() if self.remove_response_switch.isChecked(): self.current_process.setText("rm_response") self.remove_response() self.pgb.close() self.current_process.setText(" ") if self.errorcontrol == True: QMessageBox.about(self, "tips", "finished") self.Rcs.update_ondraw_stations() self.Rcs.draw() def Onbtnback(self): self.close() pass def detrend(self): currnum = 0 if len(self.File_list.selectedItems()) == 1: for item in self.channel_list.selectedItems(): allnum = len(self.channel_list.selectedItems()) station = item.parent if self.radioConstant.isChecked(): station.detrend(type='constant') if self.radioLinear.isChecked(): station.detrend(type='linear') self.pgb.setValue(float(currnum * 100) / float(allnum)) currnum = currnum + 1 pass else: for item in self.File_list.selectedItems(): allnum = len(self.File_list.selectedItems()) file = item.parent if self.radioConstant.isChecked(): file.detrend(type='constant') if self.radioLinear.isChecked(): file.detrend(type='linear') self.pgb.setValue(float(currnum * 100) / float(allnum)) currnum = currnum + 1 def bandpass_Filter(self): currnum = 0 try: if len(self.File_list.selectedItems()) == 1: for item in self.channel_list.selectedItems(): allnum = len(self.channel_list.selectedItems()) station = item.parent station.Filter( 'bandpass', freqmin=float(self.fminspin.text()[0:-2]), freqmax=float(self.fmaxspin.text()[0:-2]), ) self.pgb.setValue(float(currnum * 100) / float(allnum)) currnum = currnum + 1 pass else: '''calculate allnum''' for item in self.File_list.selectedItems(): allnum = len(item.parent.stations) for item in self.File_list.selectedItems(): file = item.parent for station in file.stations: station.Filter( 'bandpass', freqmin=float(self.fminspin.text()[0:-2]), freqmax=float(self.fmaxspin.text()[0:-2]), ) self.pgb.setValue(float(currnum * 100) / float(allnum)) currnum = currnum + 1 except Exception, e: self.errorcontrol = False QMessageBox.about(self, "Error", str(e)) pass
class Exportdialog(rcspy_Exportdialog.Ui_Dialog, QtWidgets.QDialog): def __init__(self, parent): super(Exportdialog, self).__init__(parent) self.setupUi(self) self.File_list.setSelectionMode(QAbstractItemView.ExtendedSelection) self.channel_list.setSelectionMode(QAbstractItemView.ExtendedSelection) self.connectevent() self.expath = "" self.radioMSEED.setChecked(True) self.radioSEED.setEnabled(False) def getFiles(self, Files): self.Files = Files for file in self.Files.files: listitem = QListWidgetItem(file) listitem.setText(file.name) self.File_list.addItem(listitem) def connectevent(self): self.btnOK.clicked.connect(self.Onbtnok) self.btn_Cancel.clicked.connect(self.Onbtncancel) self.File_list.itemSelectionChanged.connect( self.OnFilelist_selectionchange) self.channel_list.itemSelectionChanged.connect( self.Onchannellist_selectionchange) self.allchannel_checkbox.stateChanged.connect(self.Onallchannel_change) self.btn_set_folder.clicked.connect(self.set_exfolder) def set_exfolder(self): foldername = QFileDialog.getExistingDirectory(self, 'save folder') if foldername != "": self.expath = foldername self.Exfolder_edit.setText(foldername) def Onallchannel_change(self): if self.allchannel_checkbox.isChecked() == True: self.channel_list.selectAll() else: self.channel_list.clearSelection() self.single_channel_checkbox.setEnabled(True) def OnFilelist_selectionchange(self): self.channel_list.clear() if len(self.File_list.selectedItems()) == 1: self.channel_list.setEnabled(True) self.allchannel_checkbox.setEnabled(True) file = self.File_list.selectedItems()[0].parent for station in file.stations: listitem = QListWidgetItem(station) listitem.setText(station.name) self.channel_list.addItem(listitem) if len(self.File_list.selectedItems()) > 1: for item in self.File_list.selectedItems(): file = item.parent for station in file.stations: listitem = QListWidgetItem(station) listitem.setText(station.name) self.channel_list.addItem(listitem) self.channel_list.setEnabled(False) self.allchannel_checkbox.setChecked(True) self.allchannel_checkbox.setEnabled(False) self.radioMSEED.setChecked(True) def Onchannellist_selectionchange(self): count = self.channel_list.count() if len(self.channel_list.selectedItems()) == count: self.allchannel_checkbox.setChecked(True) else: self.allchannel_checkbox.setChecked(False) def Onbtncancel(self): self.close() def Onbtnok(self): if self.expath == "": QMessageBox.about(self, "tips", "please set export folder") elif len(self.File_list.selectedItems()) == 0: QMessageBox.about(self, "tips", "please set export files") else: self.dir = QDir() self.dir.cd(self.expath) self.pgb = QProgressBar(self) self.pgb.setWindowTitle("Exporting") self.pgb.setGeometry(140, 380, 260, 25) self.pgb.show() if self.radioMSEED.isChecked(): self.Export2mseed() if self.radioASCII.isChecked(): self.Export2Ascii() if self.radioSAC.isChecked(): self.Export2sac() self.pgb.close() QMessageBox.about(self, "tips", "finished") def Export2mseed(self): self.allnum = len(self.File_list.selectedItems()) self.currnum = 0 if self.allnum == 1: self.allnum = len(self.channel_list.selectedItems()) * 3 exstream = obspy.core.Stream() append = exstream.append for item in self.channel_list.selectedItems(): for channel in item.parent.channels: append(channel.tr) step = self.currnum * 100 / self.allnum self.pgb.setValue(int(step)) self.currnum = self.currnum + 1 file = self.File_list.selectedItems()[0].parent filesave = self.expath + "/" + str(file.ename) + ".mseed" ''' single channel ''' if self.single_channel_checkbox.isChecked() == True: self.currnum = 0 if self.dir.exists(file.ename) == False: self.dir.mkdir(file.ename) filesave = self.expath + "/" + file.ename + "/" for tr in exstream: tr.write(filesave + str(tr.id) + ".mseed", format='MSEED') step = self.currnum * 100 / self.allnum self.pgb.setValue(int(step)) self.currnum = self.currnum + 1 else: exstream.write(filesave, format='MSEED') else: ''' single channel ''' if self.single_channel_checkbox.isChecked() == True: for item in self.File_list.selectedItems(): self.allnum = self.allnum + len(item.parent.stations) * 3 for item in self.File_list.selectedItems(): file = item.parent if self.dir.exists(file.ename) == False: self.dir.mkdir(file.ename) filesave = self.expath + "/" + str(file.ename) + "/" for tr in file.stream: tr.write(filesave + str(tr.id) + ".mseed", format='MSEED') self.currnum = self.currnum + 1 step = self.currnum * 100 / self.allnum self.pgb.setValue(int(step)) else: for item in self.File_list.selectedItems(): file = item.parent filesave = self.expath + "/" + str(file.ename) + ".mseed" file.stream.write(filesave, format='MSEED') self.currnum = self.currnum + 1 step = self.currnum * 100 / self.allnum self.pgb.setValue(int(step)) def Export2Ascii(self): self.allnum = len(self.File_list.selectedItems()) self.currnum = 0 if self.allnum == 1: self.allnum = len(self.channel_list.selectedItems()) * 3 exstream = obspy.core.Stream() append = exstream.append for item in self.channel_list.selectedItems(): for channel in item.parent.channels: append(channel.tr) self.currnum = self.currnum + 1 step = self.currnum * 100 / self.allnum self.pgb.setValue(int(step)) file = self.File_list.selectedItems()[0].parent filesave = self.expath + "/" + str(file.ename) + ".ascii" ''' single channel ''' if self.single_channel_checkbox.isChecked() == True: if self.dir.exists(file.ename) == False: self.dir.mkdir(file.ename) filesave = self.expath + "/" + file.ename + "/" for tr in exstream: tr.write(filesave + str(tr.id) + ".ascii", format='SLIST') else: exstream.write(filesave, format='SLIST') else: ''' single channel ''' if self.single_channel_checkbox.isChecked() == True: for item in self.File_list.selectedItems(): self.allnum = self.allnum + len(item.parent.stations) * 3 for item in self.File_list.selectedItems(): file = item.parent if self.dir.exists(file.ename) == False: self.dir.mkdir(file.ename) filesave = self.expath + "/" + str(file.ename) + "/" for tr in file.stream: tr.write(filesave + str(tr.id) + ".ascii", format='SLIST') self.currnum = self.currnum + 1 step = self.currnum * 100 / self.allnum self.pgb.setValue(int(step)) else: for item in self.File_list.selectedItems(): file = item.parent filesave = self.expath + "/" + str(file.ename) + ".ascii" file.stream.write(filesave, format='SLIST') self.currnum = self.currnum + 1 step = self.currnum * 100 / self.allnum self.pgb.setValue(int(step)) def Export2sac(self): self.allnum = len(self.File_list.selectedItems()) self.currnum = 0 if self.allnum == 1: self.allnum = len(self.channel_list.selectedItems()) * 3 exstream = obspy.core.Stream() append = exstream.append for item in self.channel_list.selectedItems(): for channel in item.parent.channels: append(channel.tr) self.currnum = self.currnum + 1 step = self.currnum * 100 / self.allnum self.pgb.setValue(int(step)) file = self.File_list.selectedItems()[0].parent if self.dir.exists(file.ename) == False: self.dir.mkdir(file.ename) for tr in exstream: filesave = self.expath + "/" + file.ename + "/" + str( tr.id) + ".SAC" tr.write(filesave, format='SAC') else: self.allnum = 0 for item in self.File_list.selectedItems(): self.allnum = self.allnum + len(item.parent.stations) * 3 for item in self.File_list.selectedItems(): if self.dir.exists(item.parent.ename) == False: self.dir.mkdir(item.parent.ename) filedir = self.expath + "/" + item.parent.ename + "/" for tr in item.parent.stream: filesave = filedir + tr.id + ".SAC" tr.write(filesave, format='SAC') self.currnum = self.currnum + 1 step = self.currnum * 100 / self.allnum self.pgb.setValue(int(step))
def processAllLinks(linkList, parent): email = [] phone = [] institute = [] gender = [] gender_result = "" linkListLen = len(linkList) progress= QProgressBar(parent) progress.move(250,200) step = 0 if linkListLen != 0: step = 100 / linkListLen else: print ("no page link") return {} progress.show() pValue = 0 for link in linkList: pValue = pValue + step print (pValue,"%") progress.setValue(pValue) linkContent = getLinkContent(link) if linkContent == None: continue tmp = searchPhone(linkContent) if tmp != None: for p in tmp: phone.append(p) tmp = searchEmail(linkContent) if tmp != None: for e in tmp: email.append(e) tmp = searchInstiute(linkContent) if tmp != None: for i in tmp: institute.append(i) gender.append(searchGender(linkContent)) if gender.count("男") > gender.count("女"): gender_result = "男" elif gender.count("男") < gender.count("女"): gender_result = "女" else: gender_result = "未知" progress.close() map_result = {} if (gender_result.count("男") == 0 and gender_result.count("女") == 0): map_result["gender"] = "未知" elif (gender_result.count("男") >= gender_result.count("女")): map_result["gender"] = "男" else: map_result["gender"] = "女" #由于第一页的内容最相关,第一页的邮箱被确定,然后后面的根据出现次数来选 emailResultList = [] if (len(email) == 0): emailResultList.append("未知") else: emailResultList.append(email[0]) #选择剩余出现次数最多的 if (len(email) > 1): most_email = Counter(email).most_common(1)[0][0] if most_email != emailResultList[0]: emailResultList.append(most_email) map_result["email"] = emailResultList #由于第一页的内容最相关,第一页的手机被确定,然后后面的根据出现次数来选 phoneResultList = [] if (len(phone) == 0): phoneResultList.append("未知") #选择剩余出现次数最多的 else: phoneResultList.append(phone[0]) if (len(phone) > 1): most_phone = Counter(phone).most_common(1)[0][0] if most_phone != phoneResultList[0]: phoneResultList.append(most_phone) map_result["phone"] = phoneResultList #学院,选择出现次数最多的 if (len(institute) >= 1): most_institute = Counter(institute).most_common(1)[0][0] else: most_institute = "未知" map_result["institute"] = most_institute return map_result
class InstallWindow(QWidget): def __init__(self, parent=None, *args): super(InstallWindow, self).__init__(parent) self.parent = parent # layout config self.resize(self.parent.frameSize()) self.setStyleSheet('color:#fff') # handle click on start and init ui self.parent.start_app.install.clicked.connect(self.start_download) self.initUI() def initUI(self): # Alternative Background image config self.background = QLabel(self) self.background.resize(self.frameSize()) self.background.setPixmap(QPixmap(PATH + '/images/bg.png')) self.background.setScaledContents(True) # Text Box self.vertical_layout = QWidget(self) self.vertical_layout.setGeometry(40, 150, 281, 131) #self.vertical_layout.setStyleSheet('background:transparent') self.box_layout = QVBoxLayout(self.vertical_layout) self.box_layout.setContentsMargins(0, 0, 0, 0) # Title self.install_status = QLabel('Descargando...', self.vertical_layout) self.install_status.setFont(self.parent.set_font("WorkSans Bold", 20)) self.install_status.setAlignment(Qt.AlignLeading | Qt.AlignLeft | Qt.AlignVCenter) # Subtitle self.install_info = QLabel( 'Gracias por descargar Alice, pronto podrás disfrutar de todas sus caracteristicas solo usando tu voz.', self.vertical_layout) self.install_info.setFont(self.parent.set_font("Roboto Medium", 8)) self.install_info.setWordWrap(True) self.install_info.setAlignment(Qt.AlignLeading | Qt.AlignLeft) # Add labels to QVBoxLayout self.box_layout.addWidget(self.install_status) self.box_layout.addWidget(self.install_info) # Add StatusBar self.status_bar = QProgressBar(self) self.status_bar.setGeometry(40, 350, 720, 23) self.status_bar.setTextVisible(False) def start_download(self): # Detect Arch platforms = { 'linux1': 'Linux', 'linux2': 'Linux', 'darwin': 'OS X', 'win32': 'Windows' } if sys.platform in platforms: self.download = Downloader(platforms[sys.platform]) else: self.install_status.setText("Error :(") self.install_info.setText( "Tu sistema operativo no es compatible con Alice pero no te preocupes pronto lo será, mientras tanto puedes usarla en otros dispositivos." ) self.status_bar.close()
class App(QWidget): def __init__(self): super().__init__() self.setWindowTitle('The Seeker of fire') self.showFullScreen() self.Text = QLabel(self) self.book = QLabel(self) self.location = QLabel(self) self.changed = False self.action_targ = QLabel(self) self.action_targ.resize(self.width() / 12, 10) self.action_targ.move(0, 0) self.action_targ.setStyleSheet('QLabel {background-color: Red;' 'border-radius: 5px }') self.targ_pos = [(self.width() / 2.17, self.height() / 2.5 - 20), (self.width() / 2.9, self.height() / 2.5 - 20), (self.width() / 1.75, self.height() / 2.5 - 20)] self.the_right_answer = [False, False, False] self.ur_damage = 10 self.e_damage = 0 self.HP_points = 100 self.eHP_points = 100 self.result = False self.cursor = QCursor(QPixmap('cursor_3.png')) self.cursor.pixmap() self.setCursor(self.cursor) self.skip = QPushButton(self) self.skip.resize(100, 20) self.skip.move(self.width() / 2 + 180, self.height() / 4 + self.height() / 16 + 20) self.skip.setText('SKIP') self.skip.setStyleSheet( 'QPushButton {background-color: rgba(10, 20, 100, 0.2)}' 'QPushButton:hover {background-color: Red}') self.read = True self.skip.clicked.connect(self.next) melody = 'DS2.wav' self.playable = QSound(melody) self.playable.play() melody2 = 'in_battle.wav' self.playable2 = QSound(melody2) self.next_melody = False self.movie = QMovie("fire_3.gif") self.movie.setScaledSize(QSize(self.width(), self.height())) self.movie.frameChanged.connect(self.repaint) self.movie.start() self.NPC_enemy = QLabel(self) self.NPC_enemy.resize(self.height() / 5, self.height() / 5) self.NPC_enemy.move(self.width() / 2.3, self.height() / 16) self.NPC_enemy.setStyleSheet( "QLabel {color: rgb(0, 0, 51);" 'background-color: rgba(10, 20, 100, 0.2);' 'border-color: rgba(100, 100, 100, 0.5);' 'border-style: solid;' 'border-width: 2px;' '}' 'QLabel:hover {background-color: rgba(100, 0, 0, 0.7)}') self.book.resize(self.width() / 3, self.height() / 16) self.book.move(self.width() / 3, self.height() / 4 + 40) self.book.setStyleSheet( "QLabel {background-color: rgba(100, 40, 51, 0.5);" "text-align: center }") self.book.setFont(QFont('Times New Roman', 12)) self.attack = QPushButton(self) self.defend = QPushButton(self) self.dodge = QPushButton(self) self.change_size('attack_proj.png', (int(self.width() / 12), int(self.height() / 4))) self.change_size('shield.png', (int(self.width() / 12), int(self.height() / 4))) self.change_size('dodging.png', (int(self.width() / 12), int(self.height() / 4))) self.attack.setStyleSheet( 'QPushButton {background-color: rgba(10, 20, 100, 0.2);' 'border-color: rgb(10, 20, 100,);' 'border-style: solid;' 'border-width: 5px;' 'border-radius: 40px;' 'background-image: url(attack_proj.png)' '}' 'QPushButton:pressed {background-image: url(DS3.jpg)}') self.attack.resize(self.width() / 12, self.height() / 4) self.attack.move(self.width() / 2.17, self.height() / 2.5) self.attack.clicked.connect(self.attack_fnc) self.defend.setStyleSheet( 'QPushButton {background-color: rgba(10, 20, 100, 0.2);' 'border-color: rgb(10, 20, 100,);' 'border-style: solid;' 'border-width: 5px;' 'border-radius: 40px;' 'background-image: url(shield.png)' '}' 'QPushButton:pressed {background-image: url(DS3.jpg)}') self.defend.resize(self.width() / 12, self.height() / 4) self.defend.move(self.width() / 2.9, self.height() / 2.5) self.defend.clicked.connect(self.defend_fnc) self.dodge.setStyleSheet( 'QPushButton {background-color: rgba(10, 20, 100, 0.2);' 'border-color: rgb(10, 20, 100,);' 'border-style: solid;' 'border-width: 5px;' 'border-radius: 40px;' 'background-image: url(dodging.png)' '}' 'QPushButton:pressed {background-image: url(DS3.jpg)}') self.dodge.resize(self.width() / 12, self.height() / 4) self.dodge.move(self.width() / 1.75, self.height() / 2.5) self.dodge.clicked.connect(self.dodge_fnc) self.Text.move(self.width() / 3, 0) self.Text.resize(self.width() / 3, self.height()) self.Text.move(self.width() / 3, 0) self.Text.setStyleSheet( "QLabel {color: rgb(0, 0, 51);" 'font-family: "Times New Roman", Georgia, Serif;' 'font-size: 25px;' 'background-color: rgba(10, 20, 100, 0.2);' 'border-color: rgb(10, 20, 100,);' 'border-style: solid;' 'border-width: 5px' '}') self.HP = QProgressBar(self) self.HP.resize(self.width() / 3, 30) self.HP.move(self.width() / 3, self.height() * 0) self.HP.setStyleSheet( "QProgressBar{border: 1px solid transparent;text-align: center;" "color:rgba(255,255,250,0);" "border-radius: 10px;" "border-width: 8px;" "border-image: 9,2,5,2; " "background-color: Grey;" "}" "QProgressBar::chunk {background-color: qlineargradient(x1: 0, " "y1: 0, x2: 0, y2: 1, stop: 0 rgba(100,80,50,1), stop: 1 rgba(255,0,0,1));" "border-radius: 5px}") self.HP.setValue(self.HP_points) self.eHP = QProgressBar(self) self.eHP.resize(self.width() / 6, 10) self.eHP.setStyleSheet( "QProgressBar{border: 1px solid transparent;text-align: center;" "color:rgba(255,255,250,0);" "border-radius: 10px;" "border-width: 8px;" "border-image: 9,2,5,2; " "background-color: Grey" "}" "QProgressBar::chunk {background-color: qlineargradient(x1: 0, " "y1: 0, x2: 0, y2: 1, stop: 0 rgba(100,80,50,100), stop: 1 rgba(255,0,0,255));" "border-radius: 5px}") self.eHP.move(self.width() / 2.45, self.width() / 6.5) self.close_button = QPushButton(self) self.close_button.resize(self.width() / 4, self.height() / 20) self.close_button.move(self.width() / 3 + self.width() / 24, self.height() / 1.07) self.close_button.setStyleSheet( 'QPushButton {border: 3px solid;' 'border-radius: 10px;' 'background-color: Khaki' '}' 'QPushButton:pressed{border: 1px solid;' 'border-radius: 40px;' 'background-color: Red' '}' 'QPushButton:hover{background-color: rgba(255, 0, 0, 40)}') self.close_button.clicked.connect(self.close_event) self.close_button.setFont(QFont('Times New Roman', 20)) self.close_button.setText('Выход') self.location.resize(self.width() / 3, self.height() / 8) self.location.move(self.width() / 3, self.height() / 4) self.location.setFont(QFont('Times New Roman', 20)) self.location.setText('ЗАБРОШЕННЫЕ МОГИЛЫ') self.location.setStyleSheet( "QLabel {background-color: rgba(250, 40, 51, 0.5);" "}") self.location.setAlignment(Qt.AlignCenter) self.game() def next(self): self.read = False def paintEvent(self, event): currentframe = self.movie.currentPixmap() framerect = currentframe.rect() framerect.moveCenter(self.rect().center()) if framerect.intersects(event.rect()): painter = QPainter(self) painter.drawPixmap(framerect.left(), framerect.top(), currentframe) def close_event(self): self.close() def game(self): dont_stop = threading.Thread(target=self.always_on) screen = threading.Thread(target=self.on_screen) screen.start() dont_stop.start() def on_screen(self): self.HP.show() self.close_button.show() self.Text.show() self.book.show() self.NPC_enemy.show() self.skip.show() self.attack.show() self.defend.show() self.dodge.show() self.eHP.show() self.write('И в самом деле. Замок, что зовётся Лотриком, ') self.write('стоит там, где сходятся земли Повелителей пепла. ') self.write( 'Покоряя север, пилигримы убеждаются, что старые сказания не лгут') self.write('Огонь затухает, и повелители пепла покидают свои троны') self.write('Когда огонь под угрозой, когда звонит колокол,') self.write(' Повелители пепла поднимаются из своих могил.') self.write('Олдрик, святой покровитель глубин.') self.write('Легион нежити Фаррона, Хранители Бездны') self.write( 'И мрачный правитель из осквернённой столицы - гигант Йорм.') self.write( 'Но в действительности... Повелители оставят свои троны, и негорящие восстанут.' ) self.write('Безымянная, проклятая нежить, недостойная стать пеплом.') self.write('И стало так. Негорящие всегда ищут угли.') self.location.show() time.sleep(2) self.location.close() self.write('Вы поднимаетесь из могилы. В руках у вас ваш меч. ') self.write('Вы чётко знате, что будуте делать дальше') self.write('Вам предстоит вернуть повелителей на свои троны и спасти ') self.write('угасающий мир от погружения во тьму') self.write('Перед вами тропа') self.write('Пути назад больше нет') self.write('...') self.write('Вы идете по тропе') self.write( 'Перед вами Полый, нежить, потерявшая рассудок и навеки лишившаяся ' ) self.write('возможности прикоснуться к Огню') self.write('Полый достает меч') self.write('Приготовьтесь к битве') self.write(' ') self.NPC_enemy.close() self.NPC_enemy.setStyleSheet( 'QLabel { background-image: url(hollow.jpg)}') time.sleep(0.3) self.NPC_enemy.show() self.next_melody = True self.playable.stop() # self.eHP.setValue(100) self.book.setStyleSheet('QLabel {color: Red }') self.the_right_answer = [False, False, True] self.write_in_battle('Усиленная атака сверху') time.sleep(2) if self.result is not True: self.write_in_battle('Вы погибли') time.sleep(2) self.close() else: self.eHP_points -= 10 self.eHP.close() self.eHP.setValue(self.eHP_points) self.eHP.show() self.write_in_battle('Вы успешно уклонились') self.result = False self.the_right_answer = [False, True, False] self.write_in_battle('Противник потерял равновесие') time.sleep(2) if self.result is not True: self.write_in_battle('Вы погибли') time.sleep(2) self.close() else: self.eHP_points -= 10 self.eHP.close() self.eHP.setValue(self.eHP_points) self.eHP.show() self.write_in_battle('Вы успешно атаковали') self.result = False self.the_right_answer = [False, False, True] self.write_in_battle('Выпад вперед!') time.sleep(1) if self.result is not True: self.write_in_battle('Вы погибли') time.sleep(2) self.close() else: self.eHP_points -= 10 self.eHP.close() self.eHP.setValue(self.eHP_points) self.eHP.show() self.write_in_battle('Ваш противник в ярости!') self.result = False self.the_right_answer = [True, False, False] self.write_in_battle('Полый нансосит слабый удар') time.sleep(1.5) if self.result is not True: self.write_in_battle('Вы погибли') time.sleep(2) self.close() else: self.eHP_points -= 10 self.eHP.close() self.eHP.setValue(self.eHP_points) self.eHP.show() self.write_in_battle('Щит сломан') self.result = False self.the_right_answer = [False, True, False] self.write_in_battle('Полый выронил меч. Это ваш шанс!') victory = False time.sleep(0.8) if self.result is not True: self.write_in_battle('Полый увернулся') self.write_in_battle('Вы подбираете его щит') else: self.eHP_points -= 60 self.eHP.close() self.eHP.setValue(self.eHP_points) self.eHP.show() self.write_in_battle('Полый побежден!') self.result = False victory = True if victory is False: self.the_right_answer = [False, False, True] self.write_in_battle('Полый нансосит слабый удар') time.sleep(1.5) if self.result is not True: self.write_in_battle('Вы погибли') time.sleep(2) self.close() else: self.eHP_points -= 30 self.eHP.close() self.eHP.setValue(self.eHP_points) self.eHP.show() self.write_in_battle('Парирование') self.result = False self.the_right_answer = [False, True, False] self.write_in_battle('Полый медленно замахнулся') time.sleep(1.5) if self.result is not True: self.write_in_battle('Вы погибли') time.sleep(2) self.close() else: self.eHP_points -= 30 self.eHP.close() self.eHP.setValue(self.eHP_points) self.eHP.show() self.write_in_battle('Полый сделал шаг назад') self.result = False self.the_right_answer = [False, True, False] self.write_in_battle('Полый поднимает меч') time.sleep(1.5) if self.result is not True: self.write_in_battle('Вы погибли') time.sleep(2) self.close() else: self.eHP_points -= 10 self.eHP.close() self.eHP.setValue(self.eHP_points) self.eHP.show() self.write_in_battle('Полый падает') self.result = False self.next_melody = False self.NPC_enemy.close() self.NPC_enemy.setStyleSheet( "QLabel {color: rgb(0, 0, 51);" 'background-color: rgba(10, 20, 100, 0.2);' 'border-color: rgba(100, 100, 100, 0.5);' 'border-style: solid;' 'border-width: 2px;' '}' 'QLabel:hover {background-color: rgba(100, 0, 0, 0.7)}') time.sleep(0.3) self.NPC_enemy.show() self.write('Полый побежден') if victory is True: self.NPC_enemy.close() self.NPC_enemy.setStyleSheet( 'QLabel { background-image: url(letter.jpg)}') time.sleep(0.3) self.NPC_enemy.show() self.write('Вы получили новый щит: урон противников снижен') self.write('Ваш щит сломан: урон противников повышен') self.write('Вы продолжаете идти по тропе') self.write('Справа от вас труп') self.write('В его карамане что-то есть') self.write('Найдена записка') self.write('С тех времен, как Гвин впервые ') self.write( 'разжег <не разобрать>, минуло много веков и много циклов <не разобрать>' ) self.write('пламени. После того, как он разжег огонь,') self.write('этот путь повторили многие великие герои, ') self.write('известные как <не разобрать>') def always_on(self): while True: time.sleep(0.5) if self.playable.isFinished() is True: if self.next_melody is False: self.playable2.stop() self.playable.play() if self.playable2.isFinished() is True: if self.next_melody is True: self.playable2.play() def change_size(self, input_image_path, size=(0, 0)): original_image = Image.open(input_image_path) resized_image = original_image.resize(size) resized_image.save(input_image_path) self.changed = True def write(self, text): your_text = ' ' for letter in text: if self.read is True: time.sleep(0.1) your_text += letter self.book.setText(your_text) else: self.read = True break time.sleep(0.2) def write_in_battle(self, text): your_text = ' ' for letter in text: time.sleep(0.05) your_text += letter self.book.setText(your_text) def defend_fnc(self): if self.the_right_answer[0] is True: self.result = True else: self.result = False self.action_targ.close() self.action_targ.move(self.targ_pos[1][0], self.targ_pos[1][1]) self.action_targ.show() def attack_fnc(self): if self.the_right_answer[1] is True: self.result = True else: self.result = False self.action_targ.close() self.action_targ.move(self.targ_pos[0][0], self.targ_pos[0][1]) self.action_targ.show() def dodge_fnc(self): if self.the_right_answer[2] is True: self.result = True else: self.result = False self.action_targ.close() self.action_targ.move(self.targ_pos[2][0], self.targ_pos[2][1]) self.action_targ.show()
class enemigo(entidad): mover = pyqtSignal(Move) muerto = pyqtSignal(str) revisar = pyqtSignal(Revisa) def __init__(self, parent, posx, posy, tamano): super().__init__() self.label = labels.FLabel(parent, self) self.tamano = tamano self.vida = self.vida_maxima self.label.setGeometry(30, 30, (self.tamano + 1) * 10, (self.tamano + 1) * 10) self.rec = QRect(posx, posy, (self.tamano + 1) * 10, (self.tamano + 1) * 10) self.position = [posx, posy] self.pixmap = QPixmap(os.getcwd() + '/images/e1.png') self.pixmap = self.pixmap.scaled(self.tamano * 10, self.tamano * 10) self.label.setPixmap(self.pixmap) self.label.move(posx, posy) self.label.show() self.pbar = QProgressBar(parent) self.pbar.setGeometry(posx, posy - 8, self.tamano * 10, 9) self.pbar.setValue(self.vida / self.vida_maxima * 100) self.pbar.show() self.angulo = radians(0) self.degrees = 0 self.vivo = True self.velocidad = 1.1 - self.tamano / 10 self.imagen = 1 self.en_guardia = False # esto es que el principal es mayor self.mayor = 'mayor' # esto cambiarlo self.lifetimer = QTimer(self) self.lifetimer.timeout.connect(self.actualizar_vida) self.lifetimer.start(10) self.revisatimer = QTimer(self) self.revisatimer.timeout.connect(self.revisa_alrededores) self.revisatimer.start(1000) # aca tambien atacar self.mover.connect(parent.actualizar_imagen) self.revisar.connect(parent.revisa) self.mover.emit( Move(self.label, self.position[0], self.position[1])) self.rec = QRect(self.position[0], self.position[1], (self.tamano + 1) * 10, (self.tamano + 1) * 10) def actualizar_vida(self): self.pbar.setValue(self.vida) if self.vida <= 0: self.label.close() self.pbar.close() self.vivo = False def revisa_alrededores(self): self.revisar.emit(Revisa(self, self.rango_vision)) if self.en_guardia: self.caminatimer = QTimer(self) if self.mayor == 'mayor': pass elif self.mayor == 'igual': pass else: pass else: self.caminar() def caminar(self): # aca se laggea con el time.sleep, por lo que hare otro thread que # se ejecute cuando tenga que caminar, pero en teoria este deberia # ser el que funciona #time.sleep(1) probabilidad = self.probabilidad if probabilidad < 0.25: self.mover_arriba() elif probabilidad < 0.5: self.mover_abajo() elif probabilidad < 0.75: self.mover_derecha() else: self.mover_izquierda() @property def rango_vision(self): return self.tamano * 30 @property def rango_escape(self): return self.rango_vision * 1.5 @property def tiempo_reaccion(self): return uniform(0, 1) def personaje_vision(self, principal): distancia = principal.distance(self.position[0], self.position[1], principal.position[0], principal.position[1]) if distancia <= self.rango_vision: return True return False def act_label(self, string): self.label.setGeometry(self.label.x(), self.label.y(), (self.tamano + 1) * 10, (self.tamano + 1) * 10) self.rec = QRect(self.label.x(), self.label.y(), (self.tamano + 1) * 10, (self.tamano +1) * 10) self.pixmap = QPixmap(os.getcwd() + string) self.pixmap = self.pixmap.scaled(self.tamano * 10, self.tamano * 10) self.pixmap = self.pixmap.transformed(QtGui.QTransform().rotate( self.degrees)) self.label.setPixmap(self.pixmap) self.pbar.setGeometry(self.label.x(), self.label.y() - 8, self.tamano * 10, 9) def run(self): pass def pelea(self, objeto): jugador = objeto.persona jugador.vida -= self.cap_ataque def mover_arriba(self): if self.imagen == 8: self.imagen = 1 else: self.imagen += 1 string = '/images/e' + str(self.imagen) + '.png' self.act_label(string) self.mover.emit(Move(self.label, self.position[0], self.position[1] - 20 * self.velocidad)) self.position = (self.label.x(), self.label.y()) self.rec = QRect(self.position[0], self.position[1], (self.tamano + 1) * 10, (self.tamano + 1) * 10) self.pbar.move(self.position[0], self.position[1] - 8) def mover_abajo(self): if self.imagen == 8: self.imagen = 1 else: self.imagen += 1 string = '/images/e' + str(self.imagen) + '.png' self.act_label(string) self.mover.emit(Move(self.label, self.position[0], self.position[1] + 20 * self.velocidad)) self.position = (self.label.x(), self.label.y()) self.rec = QRect(self.position[0], self.position[1], (self.tamano + 1) * 10, (self.tamano + 1) * 10) self.pbar.move(self.position[0], self.position[1] - 8) def mover_izquierda(self): if self.imagen == 8: self.imagen = 1 else: self.imagen += 1 string = '/images/e' + str(self.imagen) + '.png' self.act_label(string) self.mover.emit(Move(self.label, self.position[1] - 20 * self.velocidad, self.position[1])) self.position = (self.label.x(), self.label.y()) self.rec = QRect(self.position[0], self.position[1], (self.tamano + 1) * 10, (self.tamano + 1) * 10) self.pbar.move(self.position[0], self.position[1] - 8) def mover_derecha(self): if self.imagen == 8: self.imagen = 1 else: self.imagen += 1 string = '/images/e' + str(self.imagen) + '.png' self.act_label(string) self.mover.emit(Move(self.label, self.position[1] + 20 * self.velocidad, self.position[1])) self.position = (self.label.x(), self.label.y()) self.rec = QRect(self.position[0], self.position[1], (self.tamano + 1) * 10, (self.tamano + 1) * 10) self.pbar.move(self.position[0], self.position[1] - 8) def ataque(self, objeto): if isinstance(objeto, principal): # aca no hace nada pass # aca hacer como un while objeto.rangovision < diferencia pass