def about(self, widget): about = About() about.show()
def on_about_clicked(self): my_about = About() my_about.show() my_about.exec_()
class ElmoCut(QMainWindow, Ui_MainWindow): def __init__(self): super().__init__() self.version = 1.1 self.icon = self.processIcon(app_icon) # Add window icon self.setWindowIcon(self.icon) self.setupUi(self) self.setStyleSheet(load_stylesheet()) # Main Props self.scanner = Scanner() self.killer = Killer() # Settings props self.minimize = True self.remember = False self.from_tray = False # We send elmocut to the settings window self.settings_window = Settings(self, self.icon) self.about_window = About(self, self.icon) self.applySettings() # Threading self.scan_thread = ScanThread() self.scan_thread.thread_finished.connect(self.ScanThread_Reciever) self.scan_thread.progress.connect(self.pgbar.setValue) # Connect buttons self.buttons = [ (self.btnScanEasy, self.scanEasy, scan_easy_icon, 'Arping Scan'), (self.btnScanHard, self.scanHard, scan_hard_icon, 'Pinging Scan'), (self.btnKill, self.kill, kill_icon, 'Kill selected device'), (self.btnUnkill, self.unkill, unkill_icon, 'Un-kill selected device'), (self.btnKillAll, self.killAll, killall_icon, 'Kill all devices'), (self.btnUnkillAll, self.unkillAll, unkillall_icon, 'Un-kill all devices'), (self.btnSettings, self.openSettings, settings_icon, 'View elmoCut settings'), (self.btnAbout, self.openAbout, about_icon, 'About elmoCut') ] for btn, btn_func, btn_icon, btn_tip in self.buttons: btn.setToolTip(btn_tip) btn.clicked.connect(btn_func) btn.setIcon(self.processIcon(btn_icon)) self.pgbar.setVisible(False) # Table Widget self.tableScan.itemClicked.connect(self.deviceClicked) self.tableScan.cellClicked.connect(self.cellClicked) self.tableScan.setColumnCount(4) self.tableScan.verticalHeader().setVisible(False) self.tableScan.setHorizontalHeaderLabels( ['IP Address', 'MAC Address', 'Vendor', 'Type']) ''' System tray icon and it's tray menu ''' show_option = QAction('Show', self) hide_option = QAction('Hide', self) quit_option = QAction('Quit', self) kill_option = QAction(self.processIcon(kill_icon), '&Kill All', self) unkill_option = QAction(self.processIcon(unkill_icon), '&Unkill All', self) show_option.triggered.connect(self.show) hide_option.triggered.connect(self.hide_all) quit_option.triggered.connect(self.quit_all) kill_option.triggered.connect(self.killAll) unkill_option.triggered.connect(self.unkillAll) tray_menu = QMenu() tray_menu.addAction(show_option) tray_menu.addAction(hide_option) tray_menu.addSeparator() tray_menu.addAction(kill_option) tray_menu.addAction(unkill_option) tray_menu.addSeparator() tray_menu.addAction(quit_option) self.tray_icon = QSystemTrayIcon(self) self.tray_icon.setIcon(self.icon) self.tray_icon.setToolTip('elmoCut') self.tray_icon.setContextMenu(tray_menu) self.tray_icon.show() self.tray_icon.activated.connect(self.tray_clicked) @staticmethod def processIcon(icon_data): """ Create icon pixmap object from raw data """ pix = QPixmap() icon = QIcon() pix.loadFromData(icon_data) icon.addPixmap(pix) return icon def connected(self): """ Prompt when disconnected """ if is_connected(): return True self.log('Connection lost!', 'red') QMessageBox.critical(self, 'elmoCut', 'Connection Lost!') return False def log(self, text, color='white'): """ Print log info at left label """ self.lblleft.setText(f"<font color='{color}'>{text}</font>") def openSettings(self): """ Open settings window """ self.settings_window.hide() self.settings_window.currentSettings() self.settings_window.show() def openAbout(self): """ Open about window """ self.about_window.hide() self.about_window.show() def applySettings(self): """ Apply saved settings """ self.settings_window.updateElmocutSettings() def tray_clicked(self, event): """ Show elmoCut when tray icon is left-clicked """ if event == QSystemTrayIcon.Trigger: self.show() def hide_all(self): """ Hide option for tray (Hides window and settings) """ self.hide() self.settings_window.hide() self.about_window.hide() def quit_all(self): """ Unkill any killed device on exit from tray icon """ self.killer.unkill_all() self.settings_window.close() self.about_window.close() self.from_tray = True self.close() def resizeEvent(self, event=True): """ Auto resize table widget columns dynamically """ for i in range(4): self.tableScan.setColumnWidth(i, self.tableScan.width() // 4) def closeEvent(self, event): """ Run in background if self.minimize is True else exit """ # If event recieved from tray icon if self.from_tray: event.accept() return # If event is recieved from close X button ## If minimize is true if self.minimize: event.ignore() self.hide_all() return ## If not kill all and shutdown self.killer.unkill_all() self.settings_window.close() self.about_window.close() self.hide() QMessageBox.information( self, 'Shutdown', 'elmoCut will exit completely.\n\n' 'Enable minimized from settings\n' 'to be able to run in background.') event.accept() def current_index(self): return self.scanner.devices[self.tableScan.currentRow()] def cellClicked(self, row, column): """ Copy selected cell data to clipboard """ # Get current row device = self.current_index() # Get cell text using dict.values instead of .itemAt() cell = list(device.values())[column] self.lblcenter.setText(cell) copy(cell) def deviceClicked(self): """ Disable kill, unkill buttons when admins are selected """ not_enabled = not self.current_index()['admin'] self.btnKill.setEnabled(not_enabled) self.btnUnkill.setEnabled(not_enabled) def showDevices(self): """ View scanlist devices with correct colors processed """ self.tableScan.clearSelection() self.tableScan.clearContents() self.tableScan.setRowCount(len(self.scanner.devices)) for row, device in enumerate(self.scanner.devices): for column, item in enumerate(device.values()): # Skip 'admin' key if type(item) == bool: continue # Center text in eah cell ql = QTableWidgetItem() ql.setText(item) ql.setTextAlignment(Qt.AlignCenter) # Highlight Admins and killed devices if device['admin']: colored_item(ql, '#00ff00', '#000000') if device['mac'] in self.killer.killed: colored_item(ql, '#ff0000', '#ffffff') # Add cell to the row self.tableScan.setItem(row, column, ql) status = f'{len(self.scanner.devices) - 2} devices' \ f' ({len(self.killer.killed)} killed)' self.lblright.setText(status) self.tray_icon.setToolTip(status) # Show selected cell data self.lblcenter.setText('Nothing Selected') def processDevices(self): """ Rekill any paused device after scan """ self.tableScan.clearSelection() # first device in list is the router self.killer.router = self.scanner.router # re-kill paused and update to current devices self.killer.rekill_stored(self.scanner.devices) for rem_device in self.scanner.devices: if rem_device['mac'] in get_settings('killed') * self.remember: self.killer.kill(rem_device) # clear old database self.killer.release() self.log(f'Found {len(self.scanner.devices) - 1} devices.', 'orange') self.showDevices() @check_connection def kill(self): """ Apply ARP spoofing to selected device """ if not self.tableScan.selectedItems(): self.log('No device selected.', 'red') return device = self.current_index() if device['mac'] in self.killer.killed: self.log('Device is already killed.', 'red') return # Killing process self.killer.kill(device) set_settings('killed', list(self.killer.killed) * self.remember) self.log('Killed ' + device['ip'], 'fuchsia') self.showDevices() @check_connection def unkill(self): """ Disable ARP spoofing on previously spoofed devices """ if not self.tableScan.selectedItems(): self.log('No device selected.', 'red') return device = self.current_index() if device['mac'] not in self.killer.killed: self.log('Device is already unkilled.', 'red') return # Unkilling process self.killer.unkill(device) set_settings('killed', list(self.killer.killed) * self.remember) self.log('Unkilled ' + device['ip'], 'lime') self.showDevices() @check_connection def killAll(self): """ Kill all scanned devices except admins """ self.killer.kill_all(self.scanner.devices) set_settings('killed', list(self.killer.killed) * self.remember) self.log('Killed All devices.', 'fuchsia') self.showDevices() @check_connection def unkillAll(self): """ Unkill all killed devices except admins """ self.killer.unkill_all() set_settings('killed', list(self.killer.killed) * self.remember) self.log('Unkilled All devices.', 'lime') self.showDevices() def scanEasy(self): """ Easy Scan button connector """ self.ScanThread_Starter() def scanHard(self): """ Hard Scan button connector """ # Set correct max for progress bar self.ScanThread_Starter(scan_type=1) def ScanThread_Starter(self, scan_type=0): """ self.scan_thread QThread Starter """ if not self.connected(): return self.centralwidget.setEnabled(False) # Save copy of killed devices self.killer.store() self.killer.unkill_all() self.log(['Arping', 'Pinging'][scan_type] + ' your network...', ['aqua', 'fuchsia'][scan_type]) self.pgbar.setVisible(True) self.pgbar.setMaximum(self.scanner.device_count) self.pgbar.setValue(self.scanner.device_count * (not scan_type)) self.scan_thread.scanner = self.scanner self.scan_thread.scan_type = scan_type self.scan_thread.start() def ScanThread_Reciever(self): """ self.scan_thread QThread results reciever """ self.centralwidget.setEnabled(True) self.pgbar.setVisible(False) self.processDevices()
class Main(Ui_MainWindow, QtWidgets.QMainWindow): def __init__(self): super().__init__() self.about: About = None self.norm_table: Dict[int:float] = None self.btc_table: Dict[int:float] = None self.num_from_c = None self.norm_rates() self.init_ui() self.signals() self.separator(1) self.cc_show() def init_ui(self): self.setupUi(self) self.setFixedSize(290, 200) self.menuSeparator.setToolTipsVisible(True) self.actiontext.setToolTip('By default it\'s Dot') self.show() def signals(self): self.btc.triggered.connect(self.cc_show) self.exchange.clicked.connect(self.change_rates) self.btc_rates_btn.clicked.connect(self.btc_rates) self.firstC.currentIndexChanged.connect(self.norm_operations) self.secondC.currentIndexChanged.connect(self.norm_operations) self.secondC_2.currentIndexChanged.connect(self.btc_operations) self.firstCINP.textChanged.connect(self.norm_operations) self.firstCINP_2.textChanged.connect(self.btc_operations) self.actionRates.triggered.connect(self.norm_rates) self.actionDot.triggered.connect(lambda: self.separator(1)) self.actionComma.triggered.connect(lambda: self.separator(22)) self.actionAbout.triggered.connect(self.initiate_about) @property def index_first_c(self) -> int: return self.firstC.currentIndex() @property def index_second_c(self) -> int: return self.secondC.currentIndex() @property def index_second_c_btc(self) -> int: return self.secondC_2.currentIndex() def change_rates(self): index_one, index_two = self.index_first_c, self.index_second_c self.secondC.setCurrentIndex(index_one) self.firstC.setCurrentIndex(index_two) def norm_rates(self): try: params_for_var = 'USD,BGN,RUB,HRK,INR,NOK,PLN,TRY' request_api = requests.get( f'https://api.exchangeratesapi.io/latest?symbols={params_for_var}', timeout=2) norm_value = request_api.json() except requests.ConnectionError: QtWidgets.QMessageBox.critical( self, 'Connection Error', 'There was a network error.' '\nTry to download the rates manually' '\nby pressing <Rates> button in <Help> menu') return None except: return None self.norm_table = { 0: 1, 1: norm_value['rates']['USD'], 2: norm_value['rates']['BGN'], 3: norm_value['rates']['RUB'], 4: norm_value['rates']['HRK'], 5: norm_value['rates']['INR'], 6: norm_value['rates']['NOK'], 7: norm_value['rates']['PLN'], 8: norm_value['rates']['TRY'], } def btc_rates(self): try: request_api = requests.get('https://blockchain.info/ticker') btc_value = request_api.json() except requests.ConnectionError: QtWidgets.QMessageBox.critical( self, 'Connection Error', 'There was a network error.' '\nTry to download the rates manually' '\nby pressing <Rates> button in <Help> menu') return None except: return None self.btc_table = { 0: btc_value['EUR']['last'], 1: btc_value['USD']['last'], 2: btc_value['USD']['last'], 3: btc_value['RUB']['last'], 4: btc_value['INR']['last'], } def norm_operations(self): if len(self.firstCINP.text()) == 0: self.secondCOUT.clear() return None try: str_inp = self.firstCINP.text() self.num_from_c = float(str_inp.replace(',', '.')) out = self.rates_return() format_and_round = format(round(out, 3), ',') self.secondCOUT.setText(format_and_round) except: return None def btc_operations(self): if len(self.firstCINP_2.text()) == 0: self.secondCOUT_2.clear() return None try: str_inp = self.firstCINP_2.text() self.num_from_c = float(str_inp.replace(',', '.')) out = self.btc_return() format_and_round = format(round(out, 3), ',') self.secondCOUT_2.setText(format_and_round) except: return None def rates_return(self) -> float: return (self.num_from_c * self.norm_table[self.index_second_c] ) / self.norm_table[self.index_first_c] def btc_return(self) -> float: if self.secondC_2.currentIndex() == 2: return (self.num_from_c * self.btc_table[0]) * self.norm_table[2] return self.num_from_c * self.btc_table[self.index_second_c_btc] def separator(self, sep: int): var = QtGui.QDoubleValidator( QtCore.QLocale.setDefault(QtCore.QLocale(sep))) self.firstCINP.clear() self.secondCOUT.clear() self.firstCINP_2.clear() self.secondCOUT_2.clear() self.firstCINP.setValidator(var) self.firstCINP_2.setValidator(var) def cc_show(self): if self.btc.isChecked(): self.frame_8.show() self.line.show() self.setFixedSize(290, 370) self.btc_rates() else: self.frame_8.close() self.line.close() self.firstCINP_2.clear() self.secondCOUT_2.clear() self.setFixedSize(290, 200) def initiate_about(self): self.about = About() self.about.setFixedSize(398, 280) self.about.show()
class QdvGrab(QMainWindow): def __init__(self, parent=None): super(QdvGrab, self).__init__(parent) self.setupUi() self.connectActions() self.updateUi() QTimer.singleShot(0, self.loadSettings) self.ui.statusbar = QStatusBar() message = str("Welcome to DvGrab {}".format(app_version)) self.ui.statusbar.showMessage(message) print(message) def centerScreen(self): """ We keep the windows geometry modified by the user either this one by default :param self: :return: """ geometry_window = "" #we catch variables (width/height) if geometry_window: self.resize(geometry_window[0], geometry_window[1]) else: geometry_window = (self.geometry().width(), self.geometry().height()) #we catch the window size on the screen size_screen = QDesktopWidget().screenGeometry() self.move(((size_screen.width() - geometry_window.width())/2), ((size_screen.height() - geometry_window.height()))/2) #=================================================================================================================== def loadSettings(self): settings = QSettings() new_output_path = settings.value("output_default_path") name_camcorder = settings.value("name_camcorder") formats_choose = settings.value("formats_choose") automatic_conversion = settings.value("automatic_conversion") detection_scene = settings.value("detection_scene") automatic_record = settings.value("automatic_record") if new_output_path: self.ui.lneoutputfile.setText(new_output_path) if name_camcorder: self.ui.lnenamecamecorder.setText(name_camcorder) if formats_choose: self.ui.cmbformatcapture.setCurrentIndex(formats_choose) if automatic_conversion: self.ui.chknone.setChecked(True) if detection_scene: self.ui.chkdetection.setChecked(True) if automatic_record: self.ui.chkautomaticrecord.setChecked(True) # ================================================================================================================== def setupUi(self): self.ui = Ui_MainWindow() self.ui.setupUi(self) #Set Tooltips for the main gui self.ui.btnacquisitiondv.setToolTip(self.tr(" Choose the Dv Acquisition mode ")) self.ui.lblcamcorder.setToolTip(self.tr(" Set the Camcorder Name ")) self.ui.lblfree.setToolTip(self.tr(" Set the free space disk available ")) self.ui.lblused.setToolTip(self.tr(" Set the used space disk ")) self.ui.lbltotal.setToolTip(self.tr(" Set the total space disk not and available ")) self.ui.btnrecordmpeg.setToolTip(self.tr(" Choose the HDV Acquisition mode ")) self.ui.btnstartrecord.setToolTip(self.tr(" Run the film acquisition ")) self.ui.btnpreferences.setToolTip(self.tr(" Set the Preferences Screen ")) self.ui.btnhelp.setToolTip(self.tr(" ")) self.ui.btnquit.setToolTip(self.tr(" Exit the application ")) #Set Status Tips for the main gui in the statusBar() self.ui.lblcamcorder.setStatusTip(self.tr('The camcorder name is ')) self.ui.lblfree.setStatusTip(self.tr('The free space disk available is of ')) self.ui.lblused.setStatusTip(self.tr('The space disk used is of ')) self.ui.lbltotal.setStatusTip(self.tr('The total space disk is of ')) self.ui.btnacquisitiondv.setStatusTip(self.tr('Dv Acquisition mode is used')) self.ui.btnrecordmpeg.setStatusTip(self.tr('HDV Acquisition mode is used')) self.ui.btnstartrecord.setStatusTip(self.tr('The process is run')) self.ui.btnpreferences.setStatusTip(self.tr('Preferences Screen has been called')) self.ui.btnhelp.setStatusTip(self.tr('The web help oneline is opened')) self.ui.btnquit.setStatusTip(self.tr('Exit')) # ================================================================================================================== def connectActions(self): """ Function making connections not done by Qt Designer """ self.ui.btnacquisitiondv.clicked.connect(self.Recording) self.ui.btnrecordmpeg.clicked.connect(self.Recording) self.ui.btnstartrecord.clicked.connect(self.Acquisition) self.ui.btnpreferences.clicked.connect(self.run_preferences_screen) self.ui.btnhelp.clicked.connect(self.Help) self.ui.btnquit.clicked.connect(self.Quit) self.ui.actionOpen_Directory.triggered.connect(self.openDirectory) self.ui.actionQuit.triggered.connect(self.Quit) self.ui.actionPreferences.triggered.connect(self.run_preferences_screen) self.ui.actionAbout_Qt.triggered.connect(self.AboutQt) self.ui.actionAbout_QdvGrab.triggered.connect(self.AboutQdvgrab) self.ui.actionHelp.triggered.connect(self.Help) # ================================================================================================================== def updateUi(self): self.ui.lnecapturename.setText("My Awesome Movie") self.ui.lnecapturename.setFocus() self.ui.lnecapturename.selectAll() # ================================================================================================================== def Recording(self): """ Run the type of acquisition asked """ pass # ================================================================================================================== def Acquisition(self): """ Run the acquisition process i.e run dvgrab """ pass # ================================================================================================================== def Help(self): """ Call the help webpage on Github """ try: webbrowser.open("https://github.com/olielvewen/QDvGrab/wiki") print("Website wiki project is opened") except: QMessageBox.information(self, self.tr("QdvGrab - Error"), self.tr("Unable to open the Wiki page")) print("Impossible to open the wiki page") # ================================================================================================================== def Quit(self): """ Close properly the application """ application.quit() # ================================================================================================================== def run_preferences_screen(self): """ Run the Preferences Dialog """ self.windo = PreFerences() self.windo.show() # ================================================================================================================== def closeEvent(self, event): """ function run just before the mainwindow is closed and stop all work in progress and save settings """ #stop work in progress if there are one #Save all settings if they have done modified PreFerences.saveSettings() event.accept() #=================================================================================================================== def openDirectory(self,new_output_path): """ Open the directory choose by the user either open this one by default :param new_output_path: :return: """ if new_output_path: preferences.PreFerences.outputPath() else: new_output = QFileDialog.getExistingDirectory(self, self.tr("QDvGrab - Choose a Directory"), os.path.join(QDir.homePath() + "/Videos/")) #=================================================================================================================== def AboutQt(self): """ Method helping you to know which version of Qt you are using displaying an nice window """ QMessageBox.aboutQt(QdvGrab) #=================================================================================================================== def AboutQdvgrab(self): """ Run the About Dialog """ self.windo = About() self.windo.show() #=================================================================================================================== def logInfo(self): """ method for getting info about what user have done in the configfile - necessary for debugging - probably will be replace in the future by logging function """ pass #=================================================================================================================== def onCaptureProgress(self): """ update the progression of the progressbar """ pass #=================================================================================================================== def checkSizeDisk(self): """ method for getting the size (free or not) of the hard drive """ pass #=================================================================================================================== def getDevice(self): """ method for getting the mounting point and the name (?) of the camcorder """ pass #=================================================================================================================== def creationProcess(self): """ method for create the command line """ pass
class Main(QtGui.QMainWindow): def __init__(self): QObject.__init__(self) self.cuadros = [] self.casillas = [] QtGui.QMainWindow.__init__(self) QtGui.QMessageBox.information(self, "Bienvenido a sudoku", "Bienvenido a QSudoku. Version 0.2.05") self.ui=Ui_MainTable() self.ui.setupUi(self) self.initGuiCelda() self.initMenuBar() self.initTeclado() #formulario de niveles self.level = Nivel() QObject.connect(self.level, SIGNAL("nivel"), self.iniciarJuego) self.ui.crono.display("00:00") self.bandera = True def initGuiCelda(self): self.ui.cmdVerificar.setEnabled(False) self.ui.cmdHint.setEnabled(False) self.ui.tablero.setHorizontalSpacing(8) self.ui.tablero.setVerticalSpacing(8) self.casillas = [] z=0 fil = 0 col = 0 for i in range(0,3): fil = i*3 for j in range(0,3): col = j*3 cuadro = QtGui.QGridLayout() cuadro.setHorizontalSpacing(1) cuadro.setVerticalSpacing(1) for l in range(0,3): for m in range(0,3): cas = Celda(fil, col, 0) self.casillas.append(cas) cuadro.addWidget(cas,l,m) z = z+1 col = col +1 fil = fil +1 col = j*3 self.ui.tablero.addLayout(cuadro, i, j) fil = i*3 self.celdaRuntime = Celda(0,0,0) self.tm = QTime(0,0,0,0) def initCrono(self): self.tiempo = QTimer(self) QObject.connect(self.tiempo, SIGNAL("timeout()"), self.timeRefresh) self.tiempo.start(1000) self.tiempoIni = QTime.currentTime() QTimer.singleShot(1000, self.timeRefresh) def timeRefresh(self): actual = QTime.currentTime() m_ini = self.tiempoIni.minute() s_ini = self.tiempoIni.second() ms_ini = self.tiempoIni.msec() m_act = actual.minute() s_act = actual.second() ms_act = actual.msec() if ms_act < ms_ini: ms_act = 1000 + ms_act s_act = s_act +1 if s_act < s_ini: s_act = 60 + s_act m_act = m_act - 1 m = m_act - m_ini s = s_act - s_ini ms = ms_act - ms_ini #actualizo el tiempo self.tm.setHMS(0, m, s, ms) self.ui.crono.display(self.tm.toString("mm:ss")) def initMenuBar(self): QObject.connect(self.ui.actionAcerca_de, SIGNAL("triggered()"), self.acercaDe) QObject.connect(self.ui.actionNueva, SIGNAL("triggered()"), self.nuevaPartida) QObject.connect(self.ui.actionGuardar, SIGNAL("triggered()"), self.guardarPartida) QObject.connect(self.ui.actionCargar, SIGNAL("triggered()"), self.cargarPartida) QObject.connect(self.ui.actionSalir, SIGNAL("triggered()"), self.salirJuego) QObject.connect(self.ui.actionRanking, SIGNAL("triggered()"), self.verRanking) def verRanking(self): self.ranking = Ranking() self.ranking.setWindowModality(Qt.ApplicationModal) self.ranking.show() def salirJuego(self): puntaje = self.calcularPuntaje() QtGui.QMessageBox.about(self, "Salir", "Su puntaje fue de : "+ str(puntaje)) self.close() self.destroy() def acercaDe(self): print "entra a acerca de :)" self.ab = About() self.ab.setWindowModality(Qt.ApplicationModal) self.ab.show() def nuevaPartida(self): self.level.show() def iniciarJuego(self, nivel): self.level.hide() self.activarTeclado() self.setCeldasBlanco() self.setTableroInicio() self.setTableroInicialSegunNivel(nivel) self.setTableroEnPantalla() while True: self.nombre, valor = QtGui.QInputDialog.getText(self, "Sudoku", "Ingrese su nombre") if self.nombre == "" or valor==False: QtGui.QMessageBox.warning(self, "Mensaje", "No se ha ingresado texto") else: break self.ui.lbl_jugador.setText(self.nombre) if nivel==0: self.ui.lbl_level.setText("Novato") self.hints = 12 self.dificultad = 0 elif nivel==1: self.ui.lbl_level.setText("Intermedio") self.hints = 8 self.dificultad = 1 elif nivel==2: self.ui.lbl_level.setText("Profesional") self.hints = 4 self.dificultad = 2 elif nivel==3: self.ui.lbl_level.setText("Leyenda") self.hints = 2 self.dificultad = 3 self.initCrono() self.ui.cmdHint.setText("Hints "+str(self.hints)) def setTableroEnPantalla(self): for i in range(0,9): for j in range(0,9): tmp = self.tableroActual[i][j] if tmp!= 0: self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setValue(tmp) else: self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setValue(0) def setTableroInicialSegunNivel(self, nivel): if nivel==0: for i in range(0,50): fila = randint(0,8) col = randint(0,8) self.tableroActual[fila][col] = self.matriz[fila][col] if nivel==1: for i in range(0,40): fila = randint(0,8) col = randint(0,8) self.tableroActual[fila][col] = self.matriz[fila][col] if nivel==2: for i in range(0,30): fila = randint(0,8) col = randint(0,8) self.tableroActual[fila][col] = self.matriz[fila][col] if nivel==3: for i in range(0,25): fila = randint(0,8) col = randint(0,8) self.tableroActual[fila][col] = self.matriz[fila][col] print self.tableroActual def setTableroInicio(self): matrizSolucion = GenMatriz() self.matriz = [ [ 0 for i in range(9) ] for j in range(9) ] self.tableroActual = [ [ 0 for i in range(9) ] for j in range(9) ] self.matriz = matrizSolucion.matriz print "imprimiendo matriz de juego main: \n" print self.matriz def setCeldasBlanco(self): for i in range(0,9): for j in range(0,9): self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBackColor("white") def activarTeclado(self): for i in range(0,10): self.teclado[i].setEnabled(True) self.ui.cmdHint.setEnabled(True) self.ui.cmdVerificar.setEnabled(True) QObject.connect(self.ui.cmdHint, SIGNAL("clicked()"), self.cmdHint_clicked) QObject.connect(self.ui.cmdVerificar, SIGNAL("clicked()"), self.cmdVerificar_clicked) for i in range(0,81): cas = self.casillas[i] QObject.connect(cas, SIGNAL("clicked()"), cas.setEmpty) QObject.connect(cas, SIGNAL("clicked()"), self.getCeldaRuntime) def initTeclado(self): z=0 self.teclado = [] for i in range(0,3): for j in range(0,3): cmd = QtGui.QPushButton(str(z+1)) cmd.setEnabled(False) self.teclado.append(cmd) QObject.connect(self.teclado[z], SIGNAL("clicked()"), self.numPressed) print "entra "+str(z) self.ui.tecladoNum.addWidget(self.teclado[z],i,j) z = z+1 cmd = QtGui.QPushButton("0") cmd.setEnabled(False) self.teclado.append(cmd) QObject.connect(self.teclado[z], SIGNAL("clicked()"), self.numPressed) self.ui.tecladoNum.addWidget(self.teclado[z], 4, 1) def numPressed(self): numeroASetear = int(self.sender().text()) self.celdaRuntime.setValue(numeroASetear) def getCeldaRuntime(self): if self.celdaRuntime: print "entra a resetear y colocar borde" self.celdaRuntime.reset() self.celdaRuntime.setBlackBorder() if self.bandera == False: self.volverTableroNormal() self.bandera = True self.celdaRuntime = self.sender() self.setTableroActual() self.setPistas() def setTableroActual(self): print "dentro de setTableroActual" try: print self.tableroActual for i in range(0,9): for j in range(0,9): tmp = self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().getValue() self.tableroActual[i][j] = tmp except AttributeError: print "Aun no se inicializado tableroActual... :(" def setPistas(self): pistas = [1,2,3,4,5,6,7,8,9] fila = self.celdaRuntime.fila columna = self.celdaRuntime.columna print "fila: " +str(fila) + "columna: " +str(columna) print "pista en fila" try: for i in range(0,9): tmp = self.tableroActual[fila][i] print tmp if tmp!=0: pistas[tmp-1]=0 print "pista en columna" for j in range(0,9): tmp = self.tableroActual[j][columna] print tmp if tmp!= 0: pistas[tmp-1]=0 l = (((columna/3)+1)+(fila/3)*3) for i in range((((l-1)/3)*3),((((l-1)/3)*3)+3)): for j in range((((l-1)%3)*3),((((l-1)%3)*3)+3)): tmp = self.tableroActual[i][j] if tmp != 0: pistas[tmp-1]=0 except AttributeError: print "Aun no se inicializado tableroActual... :(" k = 0 print "pistas: " print pistas for j in range(0,9): tmp = pistas[j] if tmp!=0 & k<5: self.celdaRuntime.addHints(tmp) k = k+1 def guardarPartida(self): g = Guardar() try: self.setTableroActual() g.guardarValores(self.matriz, self.tableroActual, self.nombre, self.ui.lbl_level.text(), self.tm.toString()) if g.crearArchivo() == True: print "se creo archivo" else: print "cancelo o ocurrio algun error :(" except AttributeError: print "no ha empezado a jugar..." QtGui.QMessageBox.about(self, "Mensaje", "Aun no has empezado a jugar... intentalo :)") def cargarPartida(self): g = Guardar() if g.leerArchivo() == True: self.tableroActual = g.matriz self.matriz = g.matriz self.nombre = g.nombre self.ui.lbl_jugador.setText(g.nombre) self.ui.lbl_level.setText(g.nivel) self.setTableroEnPantalla() self.activarTeclado() self.setCeldasBlanco() self.initCrono() else: return def checkFila(self, fila, col): for i in range(0,9): if i!=col: if self.tableroActual[fila][i] == self.tableroActual[fila][col]: print "Error en fila "+str(fila+1) return False return True def checkColumna(self, fila, col): for i in range(0,9): if i!=fila: if self.tableroActual[i][col] == self.tableroActual[fila][col]: print "Error en la columna " + str(col+1) return False return True def chechCuadro(self, fila, col): v_cuadro = int(fila/3) h_cuadro = int(col/3) for i in range(v_cuadro*3,v_cuadro*3+3): for j in range(h_cuadro*3,h_cuadro*3+3): if i != fila or j != col: if self.tableroActual[fila][col] == self.tableroActual[i][j]: print "Error en el cuadro: "+str(fila)+","+str(col) return False return True def cmdVerificar_clicked(self): t = True self.setTableroActual() for i in range(0,9): for j in range(0,9): self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBackColor("white") if self.checkFila(i, j)==False: #pintar las celdas de Rojo self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBackColor("red") self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBlackBorder() t = False if self.checkColumna(i, j)==False: #pintar las celdas de rojo self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBackColor("red") self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBlackBorder() t = False if self.chechCuadro(i, j)==False: #pintar las celdas de rojo self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBackColor("red") self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBlackBorder() t = False if t==True: QtGui.QMessageBox.about(self, "Felicitaciones", "Sudoku Resuleto Correctamente") else: QtGui.QMessageBox.about(self, "Mensaje", "Sudoku resuleto incorrectamente") self.bandera = False def volverTableroNormal(self): for i in range(0,9): for j in range(0,9): self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBackColor("white") def cmdHint_clicked(self): print "proximamente lo implementaremos" if self.hints > 0: self.hints = self.hints-1 self.sender().setText("Hints "+str(self.hints)) self.setTableroActual() while True: irnd = randint(1,8) jrnd = randint(1,8) if self.tableroActual[irnd][jrnd] == 0: break self.tableroActual[irnd][jrnd] = self.matriz[irnd][jrnd] self.ui.tablero.itemAtPosition(irnd/3, jrnd/3).itemAtPosition(irnd%3, jrnd%3).widget().setValue(self.tableroActual[irnd][jrnd]) self.setTableroEnPantalla() else: QtGui.QMessageBox.about(self, "Mensaje", "No le quedan mas ayudas :(") self.ui.cmdHint.setEnabled(False) def calcularPuntaje(self): b=0 for i in range(0,9): for j in range(0,9): try: a = self.tableroActual[i][j] except AttributeError: print "aun no ha empezado a jugar" return 0 if a!=0: b = b+1 if self.dificultad == 0: return (b-30)*10-self.tm.minute() if self.dificultad == 1: return (b-30)*10-self.tm.minute() if self.dificultad == 2: return (b-30)*10-self.tm.minute() if self.dificultad == 3: return (b-30)*10-self.tm.minute() return 0