def result(self): ch = 0 w = 0 for i in self.wordslist: if ch >= self.countlength: break ch += len(i) w += 1 print(w) print(self.countlength) print(ch) clearLayout(self.lay) tosend = [] self.time = time() - self.firtime h = round(self.time) self.time = self.time / 60 self.time = round(w / self.time) tosend.append(self.time) tosend.append(self.name) h = str(h) + ' seconds' tosend.append(h) self.errorcount = str(self.errorcount) + ' errors' tosend.append(self.errorcount) QSound.play(self.success) self.socket.sendall(pickle.dumps(tosend)) ss = [] for i in tosend: i = str(i) label = QLabel(' '.join(ss)) label2 = QLabel('Wait for others, it may take maximum 30 sec') self.lay.addWidget(label) self.lay.addWidget(label2) self.typing = []
def sec(self): text1 = self.editline.text() if len(self.before) < len(text1): if text1[-1] == self.mainlist[0]: self.counter += 1 typed = self.typing[:self.counter] future = self.typing[self.counter:] text = '''<font color='blue' size=8>{}</font> <font size=8>{}</font>'''.format(typed, future) self.textline.setText(text) if self.mainlist[0] == ' ': self.editline.setText('') self.before = '' else: self.countlength += 1 self.before = text1 self.mainlist = self.mainlist[1:] if not len(self.mainlist): self.result() else: self.errorcount += 1 self.before = text1 QSound.play(self.success) else: self.before = text1
def keyPressEvent(self, e): upperText = e.text().upper() if QApplication.focusWidget().accessibleName() == 'citationCodeEdit': if upperText in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": QSound.play("sounds/" + upperText + ".wav") newEvent = QKeyEvent(QEvent.KeyPress, e.key(), e.modifiers(), text=upperText) return super(CodeLineEdit, self).keyPressEvent(newEvent)
class FingersProtocol(Protocol): def __init__(self, signals, name='Fingers', update_statistics_in_the_end=True, **kwargs): kwargs['name'] = name kwargs['update_statistics_in_the_end'] = update_statistics_in_the_end super().__init__(signals, **kwargs) self.widget_painter = FingersProtocolWidgetPainter() self.is_half_time = False self.beep = SingleBeep() self.elapsed = 0 self.is_first_update = True self.cur_state = 100 self.istrials = 1 self.soundpath_end = co_sound_dir_path + '/end.wav' self.sound_end = QSound(self.soundpath_end) self.sound_end_on = False # Construct events sequence with corresponding times all_events_seq = np.array([0], dtype=np.int) all_events_times = np.array([0], dtype=np.int) # start after 5 seconds cur_ev_time = 3 # # # # # # # # # # # # # # # # # SET-UP # # # # # # # # # # # # # # # # # # time_rest = 2 time_prepare = 1 time_move_signal = 1 time_move = 3 time_stop_signal = 1 # 2 + 2 + 1 + 3 + 1 = 8 sec - duration of one trial fingers_set = np.arange(1, 11) # fingers_set = np.arange(1,5) # left hand only # fingers_set = np.arange(6, 11) # right hand only # number of repetitions of each finger numreps = 5 # EXPERIMENT DURATION WILL BE: numreps * duration of one trial; 400s # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # fingers_list = np.tile(fingers_set, numreps) fingers_list_in_order = np.random.permutation(fingers_list) for j in np.arange(len(fingers_list_in_order)): i = fingers_list_in_order[j] finger_events = np.array([i, i + 10, 0, 21, 0], dtype=np.int) finger_event_times = cur_ev_time + np.cumsum([ time_rest, time_prepare, time_move_signal, time_move, time_stop_signal ]) # time_stop, time_stop+time_rest, time_stop+time_rest+time_prepare, time_stop+time_rest+time_prepare+time_move]); all_events_seq = np.concatenate((all_events_seq, finger_events)) all_events_times = np.concatenate( (all_events_times, finger_event_times)) cur_ev_time = all_events_times[-1] all_events_seq = np.concatenate( (all_events_seq, [50])) # 50 = protocol finished all_events_times = np.concatenate( (all_events_times, [cur_ev_time + time_rest * 2])) print(all_events_seq) print(all_events_times) self.pos_in_events_times = 0 self.events_seq = all_events_seq self.events_times = all_events_times with open("backup_fingers_events_seq.pkl", "wb") as f: pkl.dump(all_events_seq, f) with open("backup_fingers_all_events_times.pkl", "wb") as f: pkl.dump(all_events_times, f) def update_state(self, samples, reward, chunk_size=1, is_half_time=False, samples_counter=None): # if(samples_counter is not None): if (self.is_first_update): self.is_first_update = False self.protocol_start_time = time.time() self.elapsed = 0 self.widget_painter.goFullScreen() self.elapsed = time.time() - self.protocol_start_time self.check_times() return None, self.cur_state def check_times(self): if (self.pos_in_events_times < len(self.events_times) - 1): if (self.elapsed > self.events_times[self.pos_in_events_times + 1]): self.pos_in_events_times = self.pos_in_events_times + 1 if (self.pos_in_events_times < len(self.events_times)): self.cur_state = self.events_seq[self.pos_in_events_times] if self.cur_state == 50: print('will try to close protocol') # self.close_protocol() self.experiment.next_protocol() print('tried to close protocol') else: self.widget_painter.change_pic(self.cur_state) self.check_times() def close_protocol(self, **kwargs): self.is_half_time = False self.beep = SingleBeep() self.widget_painter.set_message('') if self.sound_end_on == False: # winsound.PlaySound(base64.b64decode(self.sound_correct), winsound.SND_MEMORY) self.sound_end.play() self.sound_end_on = True super(FingersProtocol, self).close_protocol(**kwargs) # self.widget_painter.set_message(self.text) def construct_dir_epoch(self, num_trials_in_dir_epoch, num_states, stim_on_t, stim_off_t): num_arrow_flashes = num_states * num_trials_in_dir_epoch fullseq = np.zeros([num_arrow_flashes]) for i in np.arange(num_trials_in_dir_epoch): this_trial = np.random.permutation(np.array([1, 2, 3, 4])).astype(int) # this_trial = np.array([1, 2, 3, 4]).astype(int) if (i > 0): last_num_prev_trial = fullseq[(4 * i - 1)] first_num_this_trial = this_trial[0] if (last_num_prev_trial == first_num_this_trial): pos_to_switch_with = random.randint(1, 3) new_first = this_trial[pos_to_switch_with] this_trial[pos_to_switch_with] = this_trial[0] this_trial[0] = new_first fullseq[4 * i:(4 * i + 4)] = this_trial num_events = num_arrow_flashes * 2 event_seq_dir_epoch = np.zeros([num_events], dtype=np.int) event_times_dir_epoch = np.zeros([num_events]) event_times_dir_epoch = np.arange(0, num_events * stim_on_t, stim_on_t) / float(1000) event_seq_dir_epoch[::2] = fullseq return event_seq_dir_epoch, event_times_dir_epoch def construct_finger_trial(self, num_trials_in_dir_epoch, num_states, stim_on_t, stim_off_t): num_arrow_flashes = num_states * num_trials_in_dir_epoch fullseq = np.zeros([num_arrow_flashes]) for i in np.arange(num_trials_in_dir_epoch): this_trial = np.random.permutation(np.array([1, 2, 3, 4])).astype(int) # this_trial = np.array([1, 2, 3, 4]).astype(int) if (i > 0): last_num_prev_trial = fullseq[(4 * i - 1)] first_num_this_trial = this_trial[0] if (last_num_prev_trial == first_num_this_trial): pos_to_switch_with = random.randint(1, 3) new_first = this_trial[pos_to_switch_with] this_trial[pos_to_switch_with] = this_trial[0] this_trial[0] = new_first fullseq[4 * i:(4 * i + 4)] = this_trial num_events = num_arrow_flashes * 2 event_seq_dir_epoch = np.zeros([num_events], dtype=np.int) event_times_dir_epoch = np.zeros([num_events]) event_times_dir_epoch = np.arange(0, num_events * stim_on_t, stim_on_t) / float(1000) event_seq_dir_epoch[::2] = fullseq return event_seq_dir_epoch, event_times_dir_epoch def construct_dir_epoch_2(self, num_states, stim_on_t, stim_off_t, target, rarity): num_target_flashes = 5 num_total_flashes_0 = rarity * num_target_flashes num_nontarget_flashes = (num_total_flashes_0 - num_target_flashes) // (num_states - 1) # num_total_flashes = num_nontarget_flashes*(num_states-1) + num_target_flashes seq = [] for i in np.arange(1, num_states + 1): if (i == target): seq = seq + [i] * num_target_flashes else: seq = seq + [i] * num_nontarget_flashes seq = np.random.permutation(np.array(seq)).astype(int) num_events = seq.shape[0] * 2 event_seq_dir_epoch = np.zeros([num_events], dtype=np.int) event_times_dir_epoch = np.zeros([num_events]) event_times_dir_epoch = np.arange(0, num_events * stim_on_t, stim_on_t) / float(1000) event_seq_dir_epoch[::2] = seq return event_seq_dir_epoch, event_times_dir_epoch
class TimerWidget(QWidget, ClockAssets): # widget containing the timer and all methods associated with it def __init__(self): super().__init__() self.timer_duration = QTime(0, 5, 0) self.zero_time = QTime(0, 0, 0) self.timer_is_running = False self.timer = QTimer() self.timer.timeout.connect(self.update_timer) self.init_window() def init_window(self): self.stack = QStackedLayout() self.stack.addWidget(self.create_timer_window()) self.stack.addWidget(self.create_change_time_window()) self.setLayout(self.stack) def change_window(self, index): self.stack.setCurrentIndex(index) if self.stack.currentIndex() == 0: self.display_timer_time() self.change_timer_button_logo("play") self.toggle_timer_button.setDisabled(False) elif self.stack.currentIndex() == 1: # stops timer if user goes to change_time window self.stop_timer() # WINDOW def create_timer_window(self): # shows timer window self.timer_time = self.timer_duration self.timer_time_label = QLabel() self.timer_time_label.setAlignment(Qt.AlignCenter) self.timer_time_label.setFont(QFont("Arial", 20)) self.display_timer_time() self.change_time_button = QPushButton("Change Time") self.change_time_button.setFixedWidth(200) self.change_time_button.clicked.connect(lambda: self.change_window(1)) self.reset_timer_button = QPushButton() self.reset_timer_button.setIcon(QIcon(self.reset_icon)) self.reset_timer_button.setFixedWidth(200) self.reset_timer_button.clicked.connect(self.reset_timer) self.toggle_timer_button = QPushButton() self.toggle_timer_button.setIcon(QIcon(self.play_icon)) self.toggle_timer_button.setFixedWidth(200) self.toggle_timer_button.clicked.connect(self.toggle_timer) if self.timer_time == self.zero_time: self.toggle_timer_button.setDisabled(True) else: self.toggle_timer_button.setDisabled(False) self.vbox = QVBoxLayout() self.vbox.addWidget(self.timer_time_label) self.vbox.addWidget(self.change_time_button, alignment=Qt.AlignHCenter) self.vbox.addWidget(self.reset_timer_button, alignment=Qt.AlignHCenter, stretch=1) self.vbox.addWidget(self.toggle_timer_button, alignment=Qt.AlignHCenter, stretch=2) self.timer_widget = QWidget() self.timer_widget.setLayout(self.vbox) return self.timer_widget def display_timer_time(self): self.timer_time_label.setText(self.timer_time.toString("hh:mm:ss")) # EFFECT def change_timer_button_logo(self, action): if action == "play": self.toggle_timer_button.setIcon(QIcon(self.play_icon)) elif action == "pause": self.toggle_timer_button.setIcon(QIcon(self.pause_icon)) # EFFECT def play_alarm_sound_effect(self): # plays sound effect self.sound_effect = QSound(self.alarm_sound) self.sound_effect.play() def toggle_timer(self): # starts timer if it's not running or # stops timer if it is running if self.timer_is_running: self.timer_is_running = False self.change_timer_button_logo("play") self.stop_timer() else: # resume playing timer if self.timer_time != self.zero_time: self.timer_is_running = True self.change_timer_button_logo("pause") self.start_timer() def start_timer(self): # starts timer countdown self.timer.start(1000) def stop_timer(self): self.timer.stop() def update_timer(self): # updates timer's time every 1 second # decrements one second from time self.timer_time = self.timer_time.addSecs(-1) if self.timer_time == self.zero_time: self.stop_timer() self.timer_is_running = False self.change_timer_button_logo("play") self.toggle_timer_button.setDisabled(True) self.play_alarm_sound_effect() self.display_timer_time() def reset_timer(self): # changes timer countdown back to normal self.timer_time = self.timer_duration self.display_timer_time() if self.timer_time == self.zero_time: self.toggle_timer_button.setDisabled(True) else: self.toggle_timer_button.setDisabled(False) # WINDOW def create_change_time_window(self): # shows change time window self.stop_timer() self.hour_input = QLineEdit() self.hour_input.setAlignment(Qt.AlignHCenter) self.hour_input.setValidator(QIntValidator()) self.hour_input.setText(self.timer_duration.toString("hh")) self.hour_label = QLabel("HH") self.minute_input = QLineEdit() self.minute_input.setAlignment(Qt.AlignHCenter) self.minute_input.setValidator(QIntValidator()) self.minute_input.setText(self.timer_duration.toString("mm")) self.minute_label = QLabel("MM") self.second_input = QLineEdit() self.second_input.setAlignment(Qt.AlignHCenter) self.second_input.setValidator(QIntValidator()) self.second_input.setText(self.timer_duration.toString("ss")) self.second_label = QLabel("SS") self.grid_layout = QGridLayout() self.grid_layout.addWidget(self.hour_input, 0, 0) self.grid_layout.addWidget(self.hour_label, 1, 0, alignment=Qt.AlignHCenter) self.grid_layout.addWidget(self.minute_input, 0, 1) self.grid_layout.addWidget(self.minute_label, 1, 1, alignment=Qt.AlignHCenter) self.grid_layout.addWidget(self.second_input, 0, 2) self.grid_layout.addWidget(self.second_label, 1, 2, alignment=Qt.AlignHCenter) self.set_time_button = QPushButton("Set Time") self.set_time_button.clicked.connect(self.check_time_input) self.vbox = QVBoxLayout() self.vbox.addStretch() self.vbox.addLayout(self.grid_layout) self.vbox.addStretch() self.vbox.addWidget(self.set_time_button) self.change_time_widget = QWidget() self.change_time_widget.setLayout(self.vbox) return self.change_time_widget def check_time_input(self): # checks if user's HH, MM, SS in Change Time Window # are valid inputs hours = self.hour_input.text() minutes = self.minute_input.text() seconds = self.second_input.text() if hours == "": hours = 0 if minutes == "": minutes = 0 if seconds == "": seconds = 0 hours = int(hours) minutes = int(minutes) seconds = int(seconds) if hours >= 0 and minutes >= 0 and seconds >= 0: if hours < 24 and minutes < 60 and seconds < 60: if hours == 0 and minutes == 0 and seconds == 0: self.show_button_effect() else: self.timer_duration = QTime(hours, minutes, seconds) self.change_window(0) self.timer_time = self.timer_duration self.display_timer_time() else: # button turns red to give user feedback self.show_button_effect() else: self.show_button_effect() # EFFECT def show_button_effect(self): # changes button's color to red and returns back to normal after half a second self.set_time_button.setStyleSheet("background-color: red") QTimer.singleShot(500, self.reset_button_color) # EFFECT def reset_button_color(self): # resets buttons color back to light grey self.set_time_button.setStyleSheet("background-color: light grey")
def Play4(self): QSound.play("dependencies/ahh.wav")
def Play2(self): QSound.play("dependencies/foghorn.wav")
def slot_card_set_user(self, user_name, card_id): card = self.cards[card_id] user_photo = self.known_users.get(user_name, None) card.set_user(user_name, user_photo) QSound.play('sounds/request.wav')
def buttonClicked(self, row, col): clicked = self.sender() self.updateMoveCount() print("Button was clicked!") print(row) print(col) if not self.muteFlag: sound = QSound("WindowsNavigationStart.wav") sound.play("WindowsNavigationStart.wav") # If we did not click a flag then do these commands if self.revealMode: clicked.setEnabled(False) self.buttons[row][col] = QLabel(str(self.mine.getSquare(row, col))) self.buttons[row][col].setAlignment(Qt.AlignCenter) self.buttons[row][col].setStyleSheet( "background-color : lightblue") self.board.addWidget(self.buttons[row][col], row, col) else: # If we are in flag mode and the tile is not set as a flag then make it a flag and set the icon if not self.mine.getSquareForFlag(row, col).getFlag(): self.mine.getSquareForFlag(row, col).flagToggle() button = QPushButton() button.setIcon(QIcon("error2.png")) button.setIconSize(QSize(25, 25)) button.clicked.connect(lambda _, row1=row, col1=col: self. buttonClicked(row1, col1)) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.buttons[row][col] = (button) self.buttons[row][col].setStyleSheet( "background-color : #A9A9A9") self.board.addWidget(self.buttons[row][col], row, col) # Else turn off the flag elif self.mine.getSquareForFlag(row, col).getFlag(): self.buttons[row][col].setIcon(QIcon()) self.mine.getSquareForFlag(row, col).flagToggle() # Update the puzzle if self.mine.getGameState() == 0: # We lose here print("You lost the game") self.timer.stop() self.disableAllButtons() self.mine.revealAllBombs(self.board, self.buttons) self.setFlagWinOrLoseLabel("You lose") if not self.muteFlag: sound = QSound("WindowsXPStartup.wav") sound.play("WindowsXPStartup.wav") pixmap = QPixmap("windows3.png") self.buttons[row][col].setStyleSheet("background-color : #ff1919") self.buttons[row][col].setPixmap(pixmap) self.buttons[row][col].setAlignment(Qt.AlignCenter) self.gameHappen = True elif self.mine.getGameState() == 1: # We win here print("You win the game") self.timer.stop() if not self.muteFlag: sound = QSound("tada.wav") sound.play("tada.wav") self.disableAllButtons() self.setFlagWinOrLoseLabel("You win") self.gameHappen = True
class AddEditPuzzle(QDialog): def __init__(self, collection=None, currentPuzzleIndex=-1, parent=None): print('Initializing AddEditPuzzle') super(AddEditPuzzle, self).__init__(parent) # Turn off the context help button (The ? in the title bar.) self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint) self._collection = collection self._currentPuzzleIndex = currentPuzzleIndex self._puzzles = collection.puzzles() self._puzzleWords = {} # used to compare lengths of words puzzleCode and puzzleSolution self._codeKeys = {} # used to make sure the code is consistent throughout the puzzle self._errorSound = QSound('sounds/error-01.wav') self.codeKeys = {} self.puzzleWords = {} self.setupUI() self.puzzleCodeEdit.installEventFilter(self) self.citationCodeEdit.installEventFilter(self) self.puzzleSolutionEdit.installEventFilter(self) self.citationSolutionEdit.installEventFilter(self) if self._currentPuzzleIndex >= 0: self.setPuzzleSelector(self._currentPuzzleIndex) self._mode = "Edit" else: self._mode = None # Commented out 9-22-2016 # self._puzzleEdited = False # self.updateUI() # ToDo: Eliminate code that has been commented out for a while def eventFilter(self, source, event): # ToDo: Add explanation text to eventFilter, checkPuzzle, and checkCitation. # ToDo: Include code consistency checking to the eventFilter # ToDo: change function names to lower case as you work on each one - not eventFilter if (event.type() == QEvent.FocusOut): if source is self.puzzleTitleEdit: self.set_editing_access() if source is self.puzzleCodeEdit: self.set_editing_access() if self.puzzleCodeEdit.toPlainText() and self.puzzleSolutionEdit.toPlainText(): self.checkPuzzle() if source is self.citationCodeEdit: if self.citationCodeEdit.text() and self.citationSolutionEdit.text(): self.checkCitation() if source is self.puzzleSolutionEdit: if self.puzzleSolutionEdit.toPlainText() and self.puzzleCodeEdit.toPlainText(): self.checkPuzzle() if source is self.citationSolutionEdit: if self.citationSolutionEdit.text() and self.citationCodeEdit.text(): self.checkCitation() self.blockSignals(False) return super(AddEditPuzzle, self).eventFilter(source, event) def set_editing_access(self): """ Manages the availability of the Save Puzzle button The Save Puzzle button is turned off if either puzzleTitleEdit or puzzleCodeEdit are empty. :return: None """ # ToDo: modify or remove editBoxChanged routine and the connections to it in light of the new eventFilter if self.puzzleTitleEdit.text() == "" or self.puzzleCodeEdit.toPlainText() == "": self.puzzleSolutionEdit.setEnabled(False) self.citationCodeEdit.setEnabled(False) self.citationSolutionEdit.setEnabled(False) self.hintEdit.setEnabled(False) self.storePuzzleButton.setEnabled(False) else: self.puzzleSolutionEdit.setEnabled(True) self.citationCodeEdit.setEnabled(True) self.citationSolutionEdit.setEnabled(True) self.hintEdit.setEnabled(True) self.storePuzzleButton.setEnabled(True) def checkPuzzle(self): wordLengthsEqual, text1, text2 = self.compareWordLengths(self.puzzleCodeEdit.toPlainText(), self.puzzleSolutionEdit.toPlainText()) if not wordLengthsEqual: msg = "There are problems between the puzzle code and its solution.<br>" msg += "See below." self.inputError(msg) else: self.resetErrorBox() self.puzzleCodeEdit.setText(text1) self.puzzleSolutionEdit.setText(text2) def checkCitation(self): wordLengthsEqual, text1, text2 = self.compareWordLengths(self.citationCodeEdit.text(), self.citationSolutionEdit.text()) if not wordLengthsEqual: msg = "Citation code structure does not match the solution:<br>" msg += text1 + " does not match " + text2 self.inputError(msg) else: self.resetErrorBox() def inputError(self, msg): self._errorSound.play() self.errorDisplayWindow.setStyleSheet("QLabel { background-color : white; }") self.errorDisplayWindow.setText(msg) def resetErrorBox(self): self.errorDisplayWindow.setStyleSheet("QLabel { background-color: rgb(240, 240, 240) }") self.errorDisplayWindow.setText("") def compareWordLengths(self, text1, text2): print("got to compareWordLengths with text1 =", text1, " and text2 =", text2) result = True msg = "" if len(text1) != len(text2): result = False index = 0 wordList1 = text1.split() wordList2 = text2.split() newText1 = "" newText2 = "" for word in wordList1: if index < len(wordList2): if len(word) != len(wordList2[index]): result = False newText1 += "<font color=red>" + word + "</font> " newText2 += "<font color=red>" + wordList2[index] + "</font> " else: newText1 += "<font color=black>" + word + "</font> " newText2 += "<font color=black>" + wordList2[index] + "</font> " else: result = False newText1 += "<font color=pink>" + word + "</font> " index += 1 while index < len(wordList2): result = False newText2 += "<font color=blue>" + wordList2[index] + "</font> " index += 1 return result, newText1.strip(), newText2.strip() def collection(self): return self._collection def currentPuzzleIndex(self): return self._currentPuzzleIndex def setCurrentPuzzleIndex(self, index): self._currentPuzzleIndex = index def puzzles(self): return self._puzzles def setPuzzles(self, puzzles): self._puzzles = puzzles def addPuzzle(self, puzzle): self._puzzles.append(puzzle) def insertPuzzle(self, index, puzzle): self._puzzles.insert(index, puzzle) # this function has not yet been used in the code below # ToDo: Alter the code to use insertPuzzle when needed def setupUI(self): print('in setupUI') self.setWindowIcon(QIcon("images/editpuzzleicon-2.png")) self.setWindowTitle("Add or Edit Puzzles") self.addPuzzleButton = QPushButton("Add New Puzzle") self.addPuzzleButton.clicked.connect(self.createNewPuzzle) addButtonLayout = QHBoxLayout() addButtonLayout.addSpacing(220) addButtonLayout.addWidget(self.addPuzzleButton) errorLabel = QLabel("Error Display") self.errorDisplayWindow = QLabel('') self.errorDisplayWindow.setFrameStyle(QFrame.Panel | QFrame.Sunken) self.errorDisplayWindow.setMinimumHeight(50) self.errorDisplayWindow.setAlignment(Qt.AlignTop) self.errorDisplayWindow.setTextFormat(Qt.RichText) self.errorDisplayWindow.setStyleSheet("QLabel { background-color : rgb(240, 240, 240); }") errorDisplayLayout = QVBoxLayout() errorDisplayLayout.addWidget(errorLabel) errorDisplayLayout.addWidget(self.errorDisplayWindow) puzzleSelectorLabel = QLabel("Puzzle Selector:") self.puzzleSelector = QComboBox() self.puzzleSelector.currentIndexChanged.connect(self.addEditPuzzleSelectorChanged) puzzleTitleLabel = QLabel("Puzzle Name:") self.puzzleTitleEdit = QLineEdit() # self.puzzleTitleEdit.textChanged.connect(self.editBoxChanged) puzzleCodeLabel = QLabel("Puzzle Code:") self.puzzleCodeEdit = CodeTextEdit() self.puzzleCodeEdit.setAccessibleName("puzzleCodeEdit") self.puzzleCodeEdit.setTabChangesFocus(True) self.puzzleCodeEdit.setMaximumHeight(60) # self.puzzleCodeEdit.textChanged.connect(self.editBoxChanged) citationCodeLabel = QLabel("Citation Code (if any):") self.citationCodeEdit = CodeLineEdit() self.citationCodeEdit.setAccessibleName("citationCodeEdit") # self.citationCodeEdit.textChanged.connect(self.editBoxChanged) puzzleSolutionLabel = QLabel("Puzzle Solution (if any):") self.puzzleSolutionEdit = CodeTextEdit() self.puzzleSolutionEdit.setTabChangesFocus(True) self.puzzleSolutionEdit.setMaximumHeight(60) # self.puzzleSolutionEdit.textChanged.connect(self.editBoxChanged) citationSolutionLabel = QLabel("Citation Solution (if any):") self.citationSolutionEdit = CodeLineEdit() # self.citationSolutionEdit.textChanged.connect(self.editBoxChanged) hintLabel = QLabel("Hints (if any):") self.hintEdit = HintLineEdit() # self.hintEdit.textChanged.connect(self.editBoxChanged) puzzleButtonBox = QDialogButtonBox() self.storePuzzleButton = puzzleButtonBox.addButton("Store Puzzle", QDialogButtonBox.ActionRole) self.deleteButton = puzzleButtonBox.addButton("Delete", QDialogButtonBox.DestructiveRole) self.clearButton = puzzleButtonBox.addButton("Clear", QDialogButtonBox.ActionRole) self.cancelPuzzleButton = puzzleButtonBox.addButton("Cancel New Puzzle", QDialogButtonBox.RejectRole) self.storePuzzleButton.clicked.connect(self.storePuzzle) self.deleteButton.clicked.connect(self.deletePuzzle) self.clearButton.clicked.connect(self.clearPuzzle) self.cancelPuzzleButton.clicked.connect(self.cancelPuzzle) puzzleGrid = QGridLayout() puzzleGrid.addWidget(puzzleSelectorLabel, 0, 0, Qt.AlignRight) puzzleGrid.addWidget(self.puzzleSelector, 0, 1) puzzleGrid.addWidget(puzzleTitleLabel, 1, 0, Qt.AlignRight) puzzleGrid.addWidget(self.puzzleTitleEdit, 1, 1) puzzleGrid.addWidget(puzzleCodeLabel, 2, 0, Qt.AlignRight | Qt.AlignTop) puzzleGrid.addWidget(self.puzzleCodeEdit, 2, 1) puzzleGrid.addWidget(citationCodeLabel, 3, 0, Qt.AlignRight) puzzleGrid.addWidget(self.citationCodeEdit, 3, 1) puzzleGrid.addWidget(puzzleSolutionLabel, 4, 0, Qt.AlignRight | Qt.AlignTop) puzzleGrid.addWidget(self.puzzleSolutionEdit, 4, 1) puzzleGrid.addWidget(citationSolutionLabel, 5, 0) puzzleGrid.addWidget(self.citationSolutionEdit, 5, 1) puzzleGrid.addWidget(hintLabel, 6, 0, Qt.AlignRight) puzzleGrid.addWidget(self.hintEdit, 6, 1) puzzleEditLayout = QVBoxLayout() puzzleEditLayout.addLayout(errorDisplayLayout) puzzleEditLayout.addLayout(puzzleGrid) puzzleEditLayout.addWidget(puzzleButtonBox) self.puzzleEditControls = QGroupBox("Puzzle Editor") self.puzzleEditControls.setEnabled(False) self.puzzleEditControls.setLayout(puzzleEditLayout) cancelButton = QPushButton("Cancel") cancelButton.clicked.connect(self.cancelDialog) self.acceptButton = QPushButton("Accept Changes") self.acceptButton.setEnabled(False) self.acceptButton.clicked.connect(self.accept) dialogButtonLayout = QHBoxLayout() dialogButtonLayout.addSpacing(220) dialogButtonLayout.addWidget(self.acceptButton) dialogButtonLayout.addWidget(cancelButton) dialogLayout = QVBoxLayout(self) dialogLayout.addLayout(addButtonLayout) dialogLayout.addWidget(self.puzzleEditControls) dialogLayout.addLayout(dialogButtonLayout) def setPuzzleSelector(self, index): """ Adds all the puzzles in the current collection to the puzzleSelector and sets the selector to the given index :return: None """ # ToDo: Make sure puzzleSelector is properly set upon entry under all circumstances print("In setPuzzleSelector") currentCollection = self.collection() self.puzzleEditControls.setEnabled(True) self.cancelPuzzleButton.setEnabled(False) self.storePuzzleButton.setEnabled(False) self.puzzleSelector.blockSignals(True) self.puzzleSelector.clear() for puzzle in currentCollection.puzzles(): self.puzzleSelector.addItem(puzzle.puzzleTitle()) print("self.puzzleSelector.currentIndex() = ", self.puzzleSelector.currentIndex(), " just before being set to ", index) self.puzzleSelector.blockSignals(False) self.puzzleSelector.setCurrentIndex(self.currentPuzzleIndex()) self.displayPuzzle(index) def displayPuzzle(self, index): """ When there is a current puzzle, this method is called to populate the widgets of the puzzle editor group with the values of the current puzzle :return: None """ print("Got to displayPuzzle") # index = self.currentPuzzleIndex() # self.setCurrentPuzzleIndex(index) currentPuzzle = self._puzzles[index] self.puzzleTitleEdit.blockSignals(True) self.puzzleTitleEdit.setText(currentPuzzle.puzzleTitle()) self.puzzleTitleEdit.blockSignals(False) self.puzzleCodeEdit.blockSignals(True) self.puzzleCodeEdit.setText(currentPuzzle.puzzleCode()) self.puzzleCodeEdit.blockSignals(False) self.citationCodeEdit.blockSignals(True) self.citationCodeEdit.setText(currentPuzzle.citationCode()) self.citationCodeEdit.blockSignals(False) self.puzzleSolutionEdit.blockSignals(True) self.puzzleSolutionEdit.setText(currentPuzzle.puzzleSolution()) self.puzzleSolutionEdit.blockSignals(False) self.citationSolutionEdit.blockSignals(True) self.citationSolutionEdit.setText(currentPuzzle.citationSolution()) self.citationSolutionEdit.blockSignals(False) hintText = "" for hint in currentPuzzle.hints(): hintText += hint + "; " self.hintEdit.blockSignals(True) self.hintEdit.setText(hintText) self.hintEdit.blockSignals(False) print("Got to end of displayPuzzle") # Commented Out 9-22-2016 # def updateUI(self): # """ # Sets the availability of the dialog box's controls according to its present state # :return: None # """ # if self._puzzleEdited: # self.storePuzzleButton.setEnabled(True) # else: # self.storePuzzleButton.setEnabled(False) def createNewPuzzle(self): """ If a puzzle is present (as indicated by a non-negative value of self.puzzleSelector.index) The contents of the input boxes are cleared and a suggested title, "Puzzle n", where n is an integer indicating the next available number, is placed in the puzzleTitleEdit control. :return: None """ print("Got to createNewPuzzle") self.puzzleEditControls.setEnabled(True) self.addPuzzleButton.setEnabled(False) self.puzzleSelector.setEnabled(False) self.deleteButton.setEnabled(False) self.cancelPuzzleButton.setEnabled(True) self.clearPuzzle() nextNumber = len(self._puzzles) + 1 self._oldPuzzleIndex = self._currentPuzzleIndex self._currentPuzzleIndex = nextNumber - 1 self.puzzleTitleEdit.setText("Puzzle " + str(nextNumber)) self.puzzleCodeEdit.setFocus() self._mode = "Add" def addEditPuzzleSelectorChanged(self): print("Got to addEditPuzzleSelectorChanged") self._currentPuzzleIndex = self.puzzleSelector.currentIndex() self.displayPuzzle(self._currentPuzzleIndex) self._mode = "Edit" def deletePuzzle(self): print("Got to deletePuzzle") def clearPuzzle(self): """ Clears the current puzzle out of the puzzle editor and creates the puzzleWords and codeKeys dictionaries to assist in the spontaneous checking of the puzzle entry. See the various error checking routines called by editBoxChanged to see how these are used. :return: None """ print("Got to clearPuzzle") self.puzzleTitleEdit.setText("") self.puzzleCodeEdit.setText("") self.citationCodeEdit.setText("") self.puzzleSolutionEdit.setText("") self.citationSolutionEdit.setText("") self.hintEdit.setText("") self._puzzleWords = {} self._codeKeys = {} def cancelPuzzle(self): """ If the user clicks this button he or she has decided NOT to add a new puzzle, but doesn't want to leave the dialog box entirely. Perhaps to edit an existing puzzle. :return: None """ print("Got to cancelPuzzle") self.addPuzzleButton.setEnabled(True) self.clearPuzzle() if self._oldPuzzleIndex >= 0: self.setPuzzleSelector(self._oldPuzzleIndex) self.puzzleSelector.setEnabled(True) else: self.puzzleEditControls.setEnabled(False) def storePuzzle(self): """ Checks the edited puzzle for errors and, if there are none stores the puzzle in the collection and updates the user interface according to whether the puzzle was a new one being added or an old one being edited. If there are errors, prints an error message and returns focus to its best guess as to where the problem is. :return: None """ print("Got to storePuzzle") # class LengthMismatchError(Exception):pass class InconsistentCodeError(Exception):pass class BadHintFormatError(Exception):pass class BadHintError(Exception):pass title = self.puzzleTitleEdit.text() puzzleTitle = self.puzzleTitleEdit.text() puzzleCode = self.puzzleCodeEdit.toPlainText().upper() citationCode = self.citationCodeEdit.text().upper() puzzleSolution = self.puzzleSolutionEdit.toPlainText().upper() citationSolution = self.citationSolutionEdit.text().upper() hints = self.cleanHints(self.hintEdit.text()) # ToDo: Find ways to help the user find the errors: characteer position counts, character highlighting, etc. try: # Commented out 9-22-2016 # results = self.lengthMismatchErrorTests(puzzleCode, puzzleSolution, citationCode, citationSolution) # if not results[0]: # raise LengthMismatchError(results[1]) # # InconsistentCodeError tests if puzzleSolution != "": codeDict = {} solutionDict = {} solutionIndex = 0 for codeChar in puzzleCode: solutionChar = puzzleSolution[solutionIndex] if codeChar in codeDict.keys(): if codeDict[codeChar] != solutionChar: msg = "The code letter, " + codeChar + " in the puzzle code, cannot represent both " msg += codeDict[codeChar] + " and " + solutionChar + " in the solution.\n\n" msg += "Check position " + str(solutionIndex + 1) + "." raise InconsistentCodeError(msg) else: solutionIndex += 1 elif solutionChar in solutionDict.keys(): if solutionDict[solutionChar] != codeChar: msg = "The solution letter, " + solutionChar + " in the puzzle solution," msg += " cannot be represented by both " + solutionDict[solutionChar] + " and " msg += codeChar + " in the puzzle code.\n\n" msg += "Check position " + str(solutionIndex+1) + "." raise InconsistentCodeError(msg) else: solutionIndex += 1 else: codeDict[codeChar] = solutionChar solutionDict[solutionChar] = codeChar solutionIndex += 1 solutionIndex = 0 for codeChar in citationCode: solutionChar = citationSolution[solutionIndex] if codeChar in codeDict.keys(): if codeDict[codeChar] != solutionChar: msg = "The letter, " + codeChar + " in the citation code, cannot represent both " msg += codeDict[codeChar] + " and " + solutionChar + " in the solution.\n\n" msg += "Check position " + str(solutionIndex + 1) + "." raise InconsistentCodeError(msg) else: solutionIndex += 1 elif solutionChar in solutionDict.keys(): if solutionDict[solutionChar] != codeChar: msg = "The solution letter, " + solutionChar + " in the citation solution, " msg += "cannot be represented by both " + solutionDict[solutionChar] + " and " msg += codeChar + " in the citation code.\n\n" msg += "Check position " + str(solutionIndex + 1) + "." raise InconsistentCodeError(msg) else: solutionIndex += 1 else: codeDict[codeChar] = solutionChar solutionDict[solutionChar] = codeChar solutionIndex += 1 # BadHintFormatError Tests' print("hints = ", hints) if len(hints) != 0: for hint in hints: print(hint) if (len(hint.strip()) != 3) or (hint[1] != '='): msg = "Hints must have the format '(code letter 1)=(solution letter 1); " msg += "(code letter 2) = (solution letter 2)' etc. For example: A=C; H=W" msg += "See the help files for further information." raise BadHintFormatError(msg) # BadHintError Tests print("Got to BadHintError Tests with hints = ", hints) parsedHints = self.parseHints(hints) print("parsedHints = ", parsedHints) for hintpair in parsedHints: print("codeDict: ", codeDict, " solutionDict: ", solutionDict, " hintpair: ", hintpair) if hintpair[0] not in codeDict.keys(): print("B") msg = "The hint for letter " + hintpair[0] + " does not help since it is not in the puzzle code." raise BadHintError(msg) elif hintpair[1] not in solutionDict.keys(): msg = "The hint that " + hintpair[0] + "=" + hintpair[1] + " makes no sense since " + hintpair[1] msg += " does not appear in the solution." raise BadHintError(msg) elif codeDict[hintpair[0]] != hintpair[1]: msg = "In the puzzle, " + hintpair[0] + " represents " + codeDict[hintpair[0]] + ". " msg += "The hint says it represents " + hintpair[1] + "." raise BadHintError(msg) # Commented out 9-22-2016 # except LengthMismatchError as e: # QMessageBox.warning(self, "Length Mismatch Error", str(e)) # if "puzzle" in str(e): # codeWords = puzzleCode.split() # solutionWords = puzzleSolution.split() # if len(codeWords) == len(solutionWords): # index = 0 # for word in codeWords: # if len(word) != len(solutionWords[index]): # codeWords[index] = '<font color="red">' + word + '</font>' # solutionWords[index] = '<font color="red".' + solutionWords[index] + '</font>' # index += 1 # else: # # figure out what to do if not the same number of words # pass # replacement = "" # for word in codeWords: # replacement += word + " " # self.puzzleCodeEdit.setHtml(replacement.strip()) # replacement = "" # for word in solutionWords: # replacement += word + " " # self.puzzleSolutionEdit.setHtml(replacement.strip()) # # self.puzzleCodeEdit.setFocus() # else: # self.citationCodeEdit.setFocus() # return except InconsistentCodeError as e: QMessageBox.warning(self, "Insonsistent Code Error", str(e)) if "puzzle" in str(e): self.puzzleCodeEdit.setFocus() else: self.citationCodeEdit.setFocus() return except BadHintFormatError as e: QMessageBox.warning(self, "Bad Hint Format Error", str(e)) self.hintEdit.setFocus() except BadHintError as e: QMessageBox.warning(self, "Bad Hint Error", str(e)) self.hintEdit.setFocus() return print("Got past the tests.") self.acceptButton.setEnabled(True) if self._mode == "Add": # new puzzle is added to the collection newpuzzle = data_structures.Puzzle(puzzleTitle, puzzleCode, citationCode, puzzleSolution, citationSolution, hints) self._collection.addPuzzle(newpuzzle) self.setPuzzleSelector(-1) self.createNewPuzzle() self.storePuzzleButton.setEnabled(False) self.deleteButton.setEnabled(False) else: # updated puzzle is altered in the collection correctedpuzzle = data_structures.Puzzle(puzzleTitle, puzzleCode, citationCode, puzzleSolution, citationSolution, hints) self._collection.correctPuzzle(correctedpuzzle, self._currentPuzzleIndex) self.setPuzzleSelector(self._currentPuzzleIndex) # puzzle selector is updated if the puzzle title changed self.storePuzzleButton.setEnabled(False) def accept(self): print("got to accept") QDialog.accept(self) # Commented out 9-22-2016 # def lengthMismatchErrorTests(self, puzzleCode, puzzleSolution, citationCode, citationSolution): # print("Got to lengthMismatchErrorTests") # # if puzzleSolution != "" and len(puzzleCode) != len(puzzleSolution): # return False, "The puzzle's code and its solution are not the same length." # # if citationSolution != "" and len(citationCode) != len(citationSolution): # return False, "The citation's code and its solution are not the same length." # # return True, "" def cancelDialog(self): QDialog.reject(self) # # def lengthMismatch(self, text1, text2): # """ # Checks the length of each word in text1 and text2 and alerts the user if they are not the same. # This routine is called when a space has been typed or an Edit widget has lost focus. # :return: True if error found, False otherwise # """ # # ToDo: Think the lengthMismatch routine through carefully and make it work! # print("Checking for lengthMismatch") # if len(text1) != 0: # wordList1 = text1.split() # wordList2 = text2.split() # for index in range(min(len(wordList1), len(wordList2))): # if len(wordList1[index]) != len(wordList2[index]): # self._errorSound.play() # self.errorDisplayWindow.setStyleSheet("QLabel { background-color : white; }") # msg = "The length of " + wordList1[-1] + " does not match " + wordList2[-1] + "." # self.errorDisplayWindow.setText(msg) # return True # # self.errorDisplayWindow.setText('') # self.errorDisplayWindow.setStyleSheet("QLabel { background-color : rgb(240, 240, 240); }") # return False def cleanHints(self, hintstring): """ cleans a hint string that may contain extra spaces or a trailing semicolon and converts it to a list of untested "hints" that do not contain spaces :param hintstring: string :return: list of strings """ if hintstring == "": return [] hintstring = hintstring.rstrip(";") hintlist = hintstring.split(";") newhintlist = [] for hint in hintlist: newhint = "" for char in hint: if char != " ": newhint += char newhintlist.append(newhint) return newhintlist def parseHints(self, hintlist): """ Takes a list of hints, for instance, ['A=B', 'N=H'] and parses it into a list of tuples :param hints: list :return: list of lists with the format (code letter, solution letter) """ print("Got to self.parseHints with hints = ", hintlist) parsed = [] for hint in hintlist: parsed.append(hint.split('=')) return parsed
class MainWindow(widget[0], widget[1]): nombre = pyqtSignal() pedir = pyqtSignal(str) def __init__(self): super().__init__() self.labels = {} self.botones = {} self.labels_puntajes = [] self.opciones = [] self.labels_otros = {} self.otros = {} self.mitimer = None self.cancion = None self.la_proxima1 = False self.setupUi(self) self.initGui() self.fondo = QImage("fondo.png").scaled( QSize( self.frameGeometry().width(), self.frameGeometry().height())) # resize Image to widgets size palette = QPalette() palette.setBrush(10, QBrush(self.fondo)) self.setPalette(palette) self.primera_cancion = True self.la_proxima = False self.boton_ingreso.clicked.connect(self.crear_cliente) self.boton_puntajes.clicked.connect(self.abrir_puntajes) def initGui(self): self.show() def keyPressEvent(self, key): if key.key() == 16777220: self.crear_cliente() def avanzar(self): self.label_usuario.setText("Usuario: " + self.nombre_usuario.text()) self.label_puntaje.setText("Puntaje: " + str(self.cliente.puntaje)) self.label_puntaje_2.setText("Puntaje: " + str(self.cliente.puntaje)) self.stackedWidget.setCurrentIndex(1) def crear_cliente(self): self.boton_ingreso.clicked.disconnect() nombre = self.nombre_usuario.text() self.cliente = Client(port, host, nombre, self) self.boton_ingreso.clicked.connect(self.cambiar_nombre) self.volver_puntajes.clicked.connect(self.volver_sala) def cambiar_nombre(self): self.ingrese_nombre.setText("Nombre ya usado, intente nuevamente:") for i in self.salas: self.labels[i].hide() self.labels[i + "tiempo"].hide() self.labels[i + "cancion"].hide() self.botones[i].hide() self.labels[i + "contador"].hide() self.stackedWidget.setCurrentIndex(0) self.boton_ingreso.clicked.connect(self.enviar_nombre) def enviar_nombre(self): nombre = self.nombre_usuario.text() self.cliente.nombre(nombre) def post_cambio(self): for i in self.salas: self.labels[i].show() self.labels[i + "tiempo"].show() self.labels[i + "cancion"].show() self.botones[i].show() self.labels[i + "contador"].show() def reproducir(self, tupla): if self.primera_cancion: self.primera_cancion = False else: self.cancion.stop() self.cancion = QSound("songs/" + tupla[0], self) self.cancion.play() def recibir_salas(self, salas): self.salas = salas n = 100 for i in self.salas: self.labels[i] = QLabel(self) self.labels[i].setText(i) self.labels[i].setGeometry(50, n, 100, 50) self.labels[i].show() self.labels[i + "tiempo"] = QLabel(self) self.labels[i + "tiempo"].setText("") self.labels[i + "tiempo"].setGeometry(150, n, 100, 50) self.labels[i + "tiempo"].show() self.labels[i + "cancion"] = QLabel(self) art = choice(self.salas[i]["canciones"], 2, False) self.labels[i + "cancion"].setText(art[0].split("-")[0] + ", " + art[1].split("-")[0]) self.labels[i + "cancion"].setGeometry(200, n, 250, 100) self.labels[i + "cancion"].show() self.botones[i] = QPushButton(self) self.botones[i].setText(i) self.botones[i].setGeometry(500, n, 100, 50) self.botones[i].show() self.labels[i + "contador"] = QLabel(self) self.labels[i + "contador"].setText("") self.labels[i + "contador"].setGeometry(600, n, 100, 50) self.labels[i + "contador"].show() n += 100 for i in self.botones: self.botones[i].clicked.connect(partial(self.abrir_sala, i)) def actualizar_salas(self, tupla): self.salas = tupla[0] self.otros = tupla[1] contador = 0 for sala in self.salas: self.labels[sala + "tiempo"].setText( str(self.salas[sala]["tiempo"]) + " segundos") for otro in self.otros: if self.otros[otro]["sala"] == sala: contador += 1 self.labels[sala + "contador"].setText(str(contador) + " jugadores") contador = 0 def abrir_sala(self, nombre): self.nombre_sala = nombre self.cliente.sala = nombre self.timer.setText(str(self.salas[nombre]["tiempo"])) self.nombre_sala_label.setText(nombre) for i in self.botones: self.botones[i].hide() for i in self.labels: self.labels[i].hide() self.n = 150 for otros in self.otros: if self.otros[otros]["sala"] == self.nombre_sala: self.labels_otros[otros] = QLabel(self) self.labels_otros[otros].setText( otros + "\n--> " + str(self.otros[otros]["puntos"]) + " puntos\n--> " + str(self.otros[otros]["tiempo"])) self.labels_otros[otros].setGeometry(650, self.n, 140, 50) self.labels_otros[otros].show() self.n += 60 self.stackedWidget.setCurrentIndex(2) self.opciones = [ self.opcion1, self.opcion2, self.opcion3, self.opcion4 ] pregunta = random.randint(0, 1) if pregunta == 0: self.pregunta.setText("¿Qué canción está sonando?") else: self.pregunta.setText("¿Qué artista está tocando?") ops = choice(self.salas[nombre]["canciones"], 4, False) if self.salas[nombre]["cancion_actual"] not in ops: la_buena = randint(0, 3) ops[la_buena] = self.salas[nombre]["cancion_actual"] print("correcta", self.salas[nombre]["cancion_actual"]) for i in range(4): print(ops[i]) if pregunta == 0: self.opciones[i].setText(ops[i].split("-")[1].strip(".wav")) else: self.opciones[i].setText(ops[i].split("-")[0].strip(".wav")) if ops[i] != self.salas[nombre]["cancion_actual"]: self.opciones[i].clicked.connect(partial(self.puntaje, 0)) else: self.opciones[i].clicked.connect(partial(self.puntaje, 1)) self.opciones[i].hide() self.cliente.reproducir(nombre, self.salas[nombre]["cancion_actual"]) self.boton_volver.clicked.connect(self.volver_sala) self.mitimer = QTimer(self) self.mitimer.timeout.connect(self.en_sala) self.mitimer.start(1000) def en_sala(self): if self.la_proxima and str( self.salas[self.nombre_sala]["tiempo"]) != "0": self.cliente.caracteristicas["tiempo"] = "-" self.la_proxima = False self.la_proxima1 = False self.correcto.hide() self.cliente.reproducir( self.nombre_sala, self.salas[self.nombre_sala]["cancion_actual"]) pregunta = random.randint(0, 1) if pregunta == 0: self.pregunta.setText("¿Qué canción está sonando?") else: self.pregunta.setText("¿Qué artista está tocando?") ops = choice(self.salas[self.nombre_sala]["canciones"], 4, False) if self.salas[self.nombre_sala]["cancion_actual"] not in ops: la_buena = randint(0, 3) ops[la_buena] = self.salas[self.nombre_sala]["cancion_actual"] print("correcta", self.salas[self.nombre_sala]["cancion_actual"]) for i in range(4): print(ops[i]) if pregunta == 0: self.opciones[i].setText( ops[i].split("-")[1].strip(".wav")) else: self.opciones[i].setText( ops[i].split("-")[0].strip(".wav")) if ops[i] != self.salas[self.nombre_sala]["cancion_actual"]: self.opciones[i].clicked.disconnect() self.opciones[i].clicked.connect(partial(self.puntaje, 0)) else: self.opciones[i].clicked.disconnect() self.opciones[i].clicked.connect(partial(self.puntaje, 1)) self.opciones[i].show() if str(self.salas[self.nombre_sala] ["tiempo"]) == "0" or self.la_proxima1: self.la_proxima = True if str(self.salas[self.nombre_sala]["tiempo"]) == "1": self.la_proxima1 = True for otros in self.otros: if self.otros[otros][ "sala"] == self.nombre_sala and otros not in self.labels_otros: self.labels_otros[otros] = QLabel(self) self.labels_otros[otros].setGeometry(650, self.n, 140, 50) self.labels_otros[otros].show() self.n += 60 for otros in self.labels_otros: if self.otros[otros]["sala"] != self.nombre_sala: self.labels_otros[otros].hide() self.labels_otros[otros].setText(otros + "\n--> " + str(self.otros[otros]["puntos"]) + " puntos\n--> " + str(self.otros[otros]["tiempo"])) self.timer.setText(str(self.salas[self.nombre_sala]["tiempo"])) def puntaje(self, a): if a == 1: self.correcto.setText( "Respuesta correcta!\n" + str(int(self.salas[self.nombre_sala]["tiempo"]) * 100) + " puntos") self.cliente.caracteristicas["tiempo"] = self.salas[ self.nombre_sala]["tiempo"] self.cliente.caracteristicas["record"][ self.nombre_sala]["correctas"] += 1 else: self.cliente.caracteristicas["record"][ self.nombre_sala]["incorrectas"] += 1 self.correcto.setText("Respuesta incorrecta..") print(self.cliente.caracteristicas["record"][self.nombre_sala]) self.cliente.puntaje += a * int( self.salas[self.nombre_sala]["tiempo"]) * 100 self.label_puntaje_2.setText("Puntaje: " + str(self.cliente.puntaje)) self.label_puntaje.setText("Puntaje: " + str(self.cliente.puntaje)) for i in self.opciones: i.hide() self.correcto.show() def volver_sala(self): if self.mitimer: self.mitimer.stop() self.cliente.sala = "-" self.cliente.caracteristicas["tiempo"] = "-" self.la_proxima = False if self.cancion: self.cancion.stop() self.correcto.setText("Esperando canción\nsiguiente...") self.correcto.show() self.n = 150 for i in self.labels_otros: self.labels_otros[i].hide() self.labels_otros = {} for i in self.botones: self.botones[i].show() for i in self.labels: self.labels[i].show() for i in self.opciones: i.show() for i in self.labels_puntajes: for label in self.labels_puntajes[i]: label.hide() self.stackedWidget.setCurrentIndex(1) def abrir_puntajes(self): for i in self.botones: self.botones[i].hide() for i in self.labels: self.labels[i].hide() self.y = 120 self.stackedWidget.setCurrentIndex(3) self.labels_puntajes = {} self.lista = [] puntajes = [] for i in self.otros: puntajes.append(self.otros[i]["puntos"]) puntajes.sort(reverse=True) print(self.otros) for puntaje in puntajes: print(puntaje) for cliente in self.otros: if puntaje == self.otros[cliente]["puntos"]: if cliente not in self.lista: self.lista.append(cliente) if cliente not in self.labels_puntajes: self.labels_puntajes[cliente] = [ QLabel(self), QLabel(self), QLabel(self), QLabel(self) ] self.labels_puntajes[cliente][0].setText(cliente) self.labels_puntajes[cliente][1].setText( str(self.otros[cliente]["puntos"])) mejor = [] print(self.otros[cliente]) for sala in self.otros[cliente]["record"]: mejor.append( self.otros[cliente]["record"][sala]["correctas"]) mejor.sort(reverse=True) for lasala in self.otros[cliente]["record"]: if mejor[0] == self.otros[cliente]["record"][lasala][ "correctas"]: mejorsala = lasala self.labels_puntajes[cliente][2].setText(mejorsala) peor = [] for sala in self.otros[cliente]["record"]: peor.append( self.otros[cliente]["record"][sala]["incorrectas"]) peor.sort(reverse=True) for lasala in self.otros[cliente]["record"]: if peor[0] == self.otros[cliente]["record"][lasala][ "incorrectas"]: peorsala = lasala self.labels_puntajes[cliente][3].setText(peorsala) #self.lista.append(self.labels_puntajes[cliente]) print(self.lista) for cliente in self.lista: self.labels_puntajes[cliente][0].setGeometry(10, self.y, 100, 100) self.labels_puntajes[cliente][1].setGeometry(300, self.y, 100, 100) self.labels_puntajes[cliente][2].setGeometry(500, self.y, 100, 100) self.labels_puntajes[cliente][3].setGeometry(700, self.y, 100, 100) self.labels_puntajes[cliente][0].show() self.labels_puntajes[cliente][1].show() self.labels_puntajes[cliente][2].show() self.labels_puntajes[cliente][3].show() self.y += 35
class ActionWidget(QWidget): def __init__(self, parent=None, dev=None): super(ActionWidget, self).__init__(parent) self.setStyleSheet("background-color: black;") vbox = QVBoxLayout() self.dev = dev self.action = ActionLabel(self) self.timerlabel = TimerLabel(self) vbox.addWidget(self.action) vbox.addWidget(self.timerlabel) vbox.setContentsMargins(QMargins(0, 0, 0, 0)) self.setLayout(vbox) # Workers self.threadpool = QThreadPool() self.quit_thread = False self._active_listen = True # Timer self._interval_done = True self._interval_time = 0 self._timer = QTimer() self._timer.timeout.connect(self.iterate) # Sound self.timer_sound = QSound(TIMER_FX) self.interval_sound = QSound(TIMER_FX3) # Button self._button = None # ON EXIT self.thread_done = False self.start_action_signal() def toggle_led(self): self._active_listen = False self.dev.wr_cmd("pyb.LED(1).toggle()") self.action.toggle() self._active_listen = True if self.action.value: self._timer.start(1000) else: self._timer.stop() def update_state(self, state): self.action.toggle() self._button.pushbutton(True) if state == "ON": self._timer.start(1000) else: self._timer.stop() def listen_action_state(self, progress_callback): while not self.quit_thread: if self._active_listen: if self.dev.serial.readable() and self.dev.serial.in_waiting: state = self.dev.serial.readline().decode().replace( '\r\n', '') progress_callback.emit(state) print(state) time.sleep(0.1) print('Thread Done!') self.thread_done = True def start_action_signal(self): # Pass the function to execute # Any other args, kwargs are passed to the run function worker_led = Worker(self.listen_action_state) # worker.signals.result.connect(self.print_output) # worker.signals.finished.connect(self.thread_complete) # worker.signals.progress.connect(self.progress_fn) worker_led.signals.progress.connect(self.update_state) # Execute self.threadpool.start(worker_led) def iterate(self): try: if self._interval_done: interval_type, self._interval_time = next( self.timerlabel._int_gen) self.action.setStyleSheet( self.action._type_action_style[interval_type]) self.action.setText(self.action._type_action[interval_type]) self.timerlabel.setText( str(timedelta( seconds=self._interval_time)).split('.')[0][2:]) self._interval_done = False else: self._interval_time -= 1 if self._interval_time > 0 and self._interval_time <= 3: self.timer_sound.play() elif self._interval_time == 0: self._interval_done = True self.interval_sound.play() self.timerlabel.setText( str(timedelta( seconds=self._interval_time)).split('.')[0][2:]) except StopIteration: self.toggle_led() self.finish_state() self.timerlabel.reset_intervals() self._button.pushbutton(True) def finish_state(self): self.action.setStyleSheet(self.action.finished_bg) self.action.setText("Finished") self.timerlabel.setText("00:00") def closeEvent(self, event): self._timer.stop() self.quit_thread = True try: while not self.thread_done: time.sleep(0.5) print("shutdown...") except Exception as e: print(e) print("SHUTDOWN COMPLETE") sys.exit()
def play_audio_cry(self): sound = ':/pokemon/pokemon/cries/{id}.wav'.format( id=str(self.pokemon['species_id'])) QSound.play(sound)
def keyUp(self): if self.dto.isPaused or (not self.dto.isStarted) or self.dto.isLosed: ##暂停或未开始或输了 return self.dto.gameAct.rotate(self.dto.gameMap, self.dto.gameAct.rectCode) QSound.play("music\move.wav")
class CrawlWindow(QWidget): def __init__(self): super(CrawlWindow, self).__init__() self.resize(500, 500) self.setWindowTitle('抖音个性签名采集器') self.setWindowIcon(QIcon(':reson/maoyan.ico')) # 初始化启动按钮 self.start_btn = QPushButton(self) self.start_btn_2 = QPushButton(self) self.start_btn_3 = QPushButton(self) self.start_btn_4 = QPushButton(self) # 初始化表格控件 self.table = QTableWidget(self) # 初始化输出文本框 self.log_browser = QTextBrowser(self) # 初始化水平布局 self.h_layout = QHBoxLayout() self.h1_layout = QHBoxLayout() # 初始化垂直布局 self.v_layout = QVBoxLayout() # 初始化音频播放 self.btn_sound = QSound(':reson/btn.wav', self) self.finish_sound = QSound(':reson/finish.wav', self) # 实例化线程 self.worker = MyThread() self.worker_2 = MyThread_2() self.worker_3 = MyThread_3() self.worker_4 = MyThread_4() # 实例化 self.start_btn_init() self.start_2_btn_init() self.start_3_btn_init() self.start_4_btn_init() self.table_init() self.set_log_init() self.layout_init() # 读取连接设备 self.device = None self.device_2 = None self.device_3 = None self.device_4 = None self.adb_devices() # 检查代理 self.proxy() def start_btn_init(self): """ 启动按钮按钮 配置""" self.start_btn.setText('启动_1') self.start_btn.setEnabled(False) # self.start_btn.setFixedSize(300, 30) self.start_btn.clicked.connect(self.start_btn_slot) def start_2_btn_init(self): """ 启动按钮按钮 配置""" self.start_btn_2.setText('启动_2') self.start_btn_2.setEnabled(False) # self.start_btn.setFixedSize(300, 30) self.start_btn_2.clicked.connect(self.start_2_btn_slot) def start_3_btn_init(self): """ 启动按钮按钮 配置""" self.start_btn_3.setText('启动_3') self.start_btn_3.setEnabled(False) # self.start_btn.setFixedSize(300, 30) self.start_btn_3.clicked.connect(self.start_3_btn_slot) def start_4_btn_init(self): """ 启动按钮按钮 配置""" self.start_btn_4.setText('启动_4') self.start_btn_4.setEnabled(False) # self.start_btn.setFixedSize(300, 30) self.start_btn_4.clicked.connect(self.start_4_btn_slot) def table_init(self): """表格控件 配置""" # self.table.setFixedSize(500, 250) self.table.setColumnCount(4) self.table.setHorizontalHeaderLabels(['设备', '连接状态', '运行状态', '运行时间']) self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.table.setEditTriggers( QAbstractItemView.NoEditTriggers) # 设置为文本不可编辑 # 配置默认文本 row = self.table.rowCount() self.table.insertRow(row) self.table.setItem(row, 0, QTableWidgetItem('设备一')) self.table.setItem(row, 1, QTableWidgetItem('未连接')) self.table.setItem(row, 2, QTableWidgetItem('未启动')) self.table.setItem(row, 3, QTableWidgetItem('-')) row = self.table.rowCount() self.table.insertRow(row) self.table.setItem(row, 0, QTableWidgetItem('设备二')) self.table.setItem(row, 1, QTableWidgetItem('未连接')) self.table.setItem(row, 2, QTableWidgetItem('未启动')) self.table.setItem(row, 3, QTableWidgetItem('-')) row = self.table.rowCount() self.table.insertRow(row) self.table.setItem(row, 0, QTableWidgetItem('设备三')) self.table.setItem(row, 1, QTableWidgetItem('未连接')) self.table.setItem(row, 2, QTableWidgetItem('未启动')) self.table.setItem(row, 3, QTableWidgetItem('-')) row = self.table.rowCount() self.table.insertRow(row) self.table.setItem(row, 0, QTableWidgetItem('设备四')) self.table.setItem(row, 1, QTableWidgetItem('未连接')) self.table.setItem(row, 2, QTableWidgetItem('未启动')) self.table.setItem(row, 3, QTableWidgetItem('-')) def set_log_init(self): """输出控件 配置""" # 输出至输出文本框 self.worker.log_signal.connect(self.set_log_slot) self.worker_2.log_signal.connect(self.set_log_slot) self.worker_3.log_signal.connect(self.set_log_slot) self.worker_4.log_signal.connect(self.set_log_slot) # 输出至表格控件 # self.worker.result_signal.connect(self.set_table_slot) # # 调用清屏槽 # self.worker.start_q.connect(self.set_start_slot) def layout_init(self): """页面布局""" self.h_layout.addWidget(self.start_btn) self.h_layout.addWidget(self.start_btn_2) self.h1_layout.addWidget(self.start_btn_3) self.h1_layout.addWidget(self.start_btn_4) self.v_layout.addWidget(self.table) self.v_layout.addWidget(self.log_browser) self.v_layout.addLayout(self.h_layout) self.v_layout.addLayout(self.h1_layout) self.setLayout(self.v_layout) def start_btn_slot(self): """程序启动""" self.btn_sound.play() self.log_browser.append('<font color="green">{}程序启动{}</font>'.format( '*' * 20, '*' * 20)) # 启动线程 self.worker.start() self.finish_sound.play() # 改变设置按钮状态为不可点击 self.start_btn.setEnabled(False) # 改变表格窗口文本 self.table.setItem(0, 0, QTableWidgetItem(self.device)) self.table.setItem(0, 1, QTableWidgetItem('已连接')) self.table.setItem(0, 2, QTableWidgetItem('已启动')) self.table.setItem( 0, 3, QTableWidgetItem(datetime.now().strftime('%m-%d %H:%M:%S'))) def start_2_btn_slot(self): """程序启动""" self.btn_sound.play() self.log_browser.append('<font color="green">{}程序启动{}</font>'.format( '*' * 20, '*' * 20)) # 启动线程 self.worker_2.start() self.finish_sound.play() # 改变设置按钮状态为不可点击 self.start_btn_2.setEnabled(False) # 改变表格窗口文本 self.table.setItem(1, 0, QTableWidgetItem(self.device_2)) self.table.setItem(1, 1, QTableWidgetItem('已连接')) self.table.setItem(1, 2, QTableWidgetItem('已启动')) self.table.setItem( 1, 3, QTableWidgetItem(datetime.now().strftime('%m-%d %H:%M:%S'))) def start_3_btn_slot(self): """程序启动""" self.btn_sound.play() self.log_browser.append('<font color="green">{}程序启动{}</font>'.format( '*' * 20, '*' * 20)) # 启动线程 self.worker_3.start() self.finish_sound.play() # 改变设置按钮状态为不可点击 self.start_btn_3.setEnabled(False) # 改变表格窗口文本 self.table.setItem(2, 0, QTableWidgetItem(self.device_3)) self.table.setItem(2, 1, QTableWidgetItem('已连接')) self.table.setItem(2, 2, QTableWidgetItem('已启动')) self.table.setItem( 2, 3, QTableWidgetItem(datetime.now().strftime('%m-%d %H:%M:%S'))) def start_4_btn_slot(self): """程序启动""" self.btn_sound.play() self.log_browser.append('<font color="green">{}程序启动{}</font>'.format( '*' * 20, '*' * 20)) # 启动线程 self.worker_4.start() self.finish_sound.play() # 改变设置按钮状态为不可点击 self.start_btn_4.setEnabled(False) # 改变表格窗口文本 self.table.setItem(3, 0, QTableWidgetItem(self.device_4)) self.table.setItem(3, 1, QTableWidgetItem('已连接')) self.table.setItem(3, 2, QTableWidgetItem('已启动')) self.table.setItem( 3, 3, QTableWidgetItem(datetime.now().strftime('%m-%d %H:%M:%S'))) def set_log_slot(self, log): self.log_browser.append(log) def proxy(self): tss1 = '2019-12-4 00:00:00' timeArray = time.strptime(tss1, "%Y-%m-%d %H:%M:%S") timeStamp = int(time.mktime(timeArray)) now_time = int(round(time.time())) if now_time > timeStamp: self.log_browser.append('<font color="red">代理到期请及时续费!</font>') self.start_btn.setEnabled(False) self.start_btn_2.setEnabled(False) self.start_btn_3.setEnabled(False) self.start_btn_4.setEnabled(False) os._exit(0) self.log_browser.append('<font color="green">代理效验成功!</font>') def adb_devices(self): """读取设备列表""" get_cmd = "adb devices" # 查询连接设备列表 count = 0 try: while True: # 连接设备 if count > 2: print("读取设备信息失败,请检查设备是否成功启动") self.log_browser.append('读取设备信息失败,请检查设备是否成功启动') break # 读取连接设备信息 p = subprocess.Popen(get_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=True) (output, err) = p.communicate() # 分割多条信息为列表 output = output.decode().replace('\r', '').split('\n') # 剔除列表中空字符串 output = list(filter(None, output)) if not len(output) > 1: print("读取设备信息失败,自动重启中...") self.log_browser.append('读取设备信息失败,自动重启中...') count += 1 continue # 连接设备列表 devices = [i.split('\t') for i in output[1:]] # 读取成功列表 success = [i[0] for i in devices if i[1] == 'device'] for i in success: print("设备连接成功:[{}]".format(i)) self.log_browser.append("设备连接成功:[{}]".format(i)) if len(success) == 1: self.device = success[0] self.start_btn.setEnabled(True) # 改变表格窗口文本 self.table.setItem(0, 0, QTableWidgetItem(self.device)) self.table.setItem(0, 1, QTableWidgetItem('已连接')) elif len(success) == 2: self.device = success[0] self.device_2 = success[1] self.start_btn.setEnabled(True) self.start_btn_2.setEnabled(True) # 改变表格窗口文本 self.table.setItem(0, 0, QTableWidgetItem(self.device)) self.table.setItem(0, 1, QTableWidgetItem('已连接')) self.table.setItem(1, 0, QTableWidgetItem(self.device_2)) self.table.setItem(1, 1, QTableWidgetItem('已连接')) elif len(success) == 3: self.device = success[0] self.device_2 = success[1] self.device_3 = success[2] self.start_btn.setEnabled(True) self.start_btn_2.setEnabled(True) self.start_btn_3.setEnabled(True) # 改变表格窗口文本 self.table.setItem(0, 0, QTableWidgetItem(self.device)) self.table.setItem(0, 1, QTableWidgetItem('已连接')) self.table.setItem(1, 0, QTableWidgetItem(self.device_2)) self.table.setItem(1, 1, QTableWidgetItem('已连接')) self.table.setItem(2, 0, QTableWidgetItem(self.device_3)) self.table.setItem(2, 1, QTableWidgetItem('已连接')) else: self.device = success[0] self.device_2 = success[1] self.device_3 = success[2] self.device_4 = success[3] self.start_btn.setEnabled(True) self.start_btn_2.setEnabled(True) self.start_btn_3.setEnabled(True) self.start_btn_4.setEnabled(True) self.table.setItem(0, 0, QTableWidgetItem(self.device)) self.table.setItem(0, 1, QTableWidgetItem('已连接')) self.table.setItem(1, 0, QTableWidgetItem(self.device_2)) self.table.setItem(1, 1, QTableWidgetItem('已连接')) self.table.setItem(2, 0, QTableWidgetItem(self.device_3)) self.table.setItem(2, 1, QTableWidgetItem('已连接')) self.table.setItem(3, 0, QTableWidgetItem(self.device_4)) self.table.setItem(3, 1, QTableWidgetItem('已连接')) break # return success except: print('读取设备信息失败,请检查设备是否成功启动!') self.log_browser.append('读取设备信息失败,请检查设备是否成功启动!')
def play_audio(self, path): print(path) QSound.play(path)
class Notifier(QObject): def __init__(self, parent): super().__init__(parent) self._conn = QDBusConnection("Xware Desktop").sessionBus() self._interface = QDBusInterface(_DBUS_NOTIFY_SERVICE, _DBUS_NOTIFY_PATH, _DBUS_NOTIFY_INTERFACE, self._conn) self._notified = {} # a dict of notifyId: taskDict app.taskModel.taskCompleted.connect(self.notifyTaskCompleted, Qt.DirectConnection) self._capabilities = self._getCapabilities() if "actions" in self._capabilities: successful = self._conn.connect(_DBUS_NOTIFY_SERVICE, _DBUS_NOTIFY_PATH, _DBUS_NOTIFY_INTERFACE, "ActionInvoked", self.slotActionInvoked) if not successful: logging.error("ActionInvoked connect failed.") self._qSound_complete = QSound(":/sound/download-complete.wav", self) @property def isConnected(self): return self._conn.isConnected() @pyqtSlot("QObject", result = "void") def notifyTaskCompleted(self, taskItem): if app.settings.getbool("frontend", "notifybysound"): self._qSound_complete.play() if not app.settings.getbool("frontend", "popnotifications"): return self._dbus_notifyCompleted(taskItem) def _getCapabilities(self): # get libnotify server caps and remember it. qdBusMsg = self._interface.call( "GetCapabilities" ) if qdBusMsg.errorName(): logging.error("cannot get org.freedesktop.Notifications.GetCapabilities") return [] else: return qdBusMsg.arguments()[0] def _dbus_notifyCompleted(self, task: "TaskItem"): if "actions" in self._capabilities: actions = QDBusArgument(["open", "打开", "viewOneFile", "在文件夹中显示"], QMetaType.QStringList) else: actions = QDBusArgument([], QMetaType.QStringList) qdBusMsg = self._interface.call( "Notify", QDBusArgument("Xware Desktop", QMetaType.QString), # app_name QDBusArgument(0, QMetaType.UInt), # replace_id QDBusArgument("xware-desktop", QMetaType.QString), # app_icon QDBusArgument("下载完成", QMetaType.QString), # summary QDBusArgument(task.name, QMetaType.QString), # body actions, { "category": "transfer.complete", }, # hints QDBusArgument(5000, QMetaType.Int), # timeout ) if qdBusMsg.errorName(): logging.error("DBus, notifyTask {}: {}".format(qdBusMsg.errorName(), qdBusMsg.errorMessage())) else: # add it to the dict notificationId = qdBusMsg.arguments()[0] self._notified[notificationId] = task.id @pyqtSlot(QDBusMessage) def slotActionInvoked(self, msg): notifyId, action = msg.arguments() taskId = self._notified.get(notifyId, None) if not taskId: # other applications' notifications return taskItem = app.taskModel.taskManager.get(taskId, None) if not taskItem: logging.debug("taskItem cannot be found anymore in TaskModel.") return fullpath = taskItem.fullpath # path + name if action == "open": return systemOpen(fullpath) elif action == "viewOneFile": return viewOneFile(fullpath) elif action == "default": # Unity's notify osd always have a default action. return else: raise Exception("Unknown action from slotActionInvoked: {}.".format(action))
def onHovered(self): QSound.play(str(self.root_path) + '/musics/button_hover.wav')
class CrawlWindow(QWidget): def __init__(self): super(CrawlWindow, self).__init__() self.resize(1000, 600) self.setWindowTitle('关键词新闻搜索') self.setWindowIcon(QIcon(':reson/4.jpg')) # 初始化搜索文本框 self.movie_name = QLineEdit(self) # 初始化渠道下拉框 self.source_combobox = QComboBox(self) # 初始化一键搜索按钮 self.start_btn = QPushButton(self) # 初始化开始爬取按钮 self.get_btn = QPushButton(self) # 初始化一键分析按钮 self.word_cloud = QPushButton(self) # 初始化另存下拉框 self.save_combobox = QComboBox(self) # 初始化表格控件 self.table = QTableWidget(self) # 初始化输出文本框 self.log_browser = QTextBrowser(self) # 初始化进度条 self.progressbar = QProgressBar(self) # 初始化水平布局 self.h_layout = QHBoxLayout() # 初始化垂直布局 self.v_layout = QVBoxLayout() # 实例化词云程序 self.cloud = Cloud() # 实例化启动程序 self.crawl_thread = CrawlThread() # 初始化数据库 self.db = None # 初始化音频播放 self.btn_sound = QSound(':reson/btn.wav', self) self.finish_sound = QSound(':reson/finish.wav', self) # 实例化 self.movie_init() self.source_init() self.btn_init() self.combobox_init() self.table_init() self.word_cloud_init() self.log_init() self.progressbar_init() self.layout_init() self.crawl_init() # self.db_connect() def movie_init(self): """搜索文本框默认配置""" # 设置文本框尺寸 self.movie_name.setFixedSize(200, 25) # 设置默认文本 self.movie_name.setPlaceholderText("请输入关键词,不超过十个中文") # 限制10个中文字符 self.movie_name.setMaxLength(10) def source_init(self): """搜索渠道下拉框配置""" save_list = ['搜索渠道选择', '新华网', '新浪新闻', '百度新闻'] self.source_combobox.addItems(save_list) # 设置标签状态为可用 self.source_combobox.setEnabled(True) # 当下拉索引发生改变时发射信号触发绑定的事件 # self.source_combobox.currentTextChanged.connect(self.combobox_slot) def btn_init(self): self.start_btn.setText('一键搜索') self.get_btn.setText('开始爬取') self.get_btn.setEnabled(False) self.start_btn.clicked.connect(lambda: self.btn_slot(self.start_btn)) self.get_btn.clicked.connect(lambda: self.btn_slot(self.get_btn)) # TODO def word_cloud_init(self): """一键分析配置""" self.word_cloud.setText('一键分析') self.word_cloud.setEnabled(False) self.word_cloud.clicked.connect(self.word_cloud_slot) def combobox_init(self): """另存为下拉框配置""" save_list = ['另存为', 'MySQL', 'csv', 'txt', 'json'] self.save_combobox.addItems(save_list) # 设置标签状态为不可用 self.save_combobox.setEnabled(False) # 当下拉索引发生改变时发射信号触发绑定的事件 self.save_combobox.currentTextChanged.connect(self.combobox_slot) # 1 def table_init(self): self.table.setColumnCount(5) self.table.setHorizontalHeaderLabels(['新闻链接', '新闻摘要', '评论信息', '渠道来源', '发布日期']) self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) def log_init(self): """输出文本框配置""" # 设置盒子尺寸 self.log_browser.setMaximumHeight(150) def progressbar_init(self): """进度条""" self.progressbar.setRange(0, 10) self.progressbar.setValue(0) def layout_init(self): """页面布局""" self.h_layout.addWidget(self.movie_name) self.h_layout.addWidget(self.source_combobox) self.h_layout.addWidget(self.start_btn) self.h_layout.addWidget(self.get_btn) self.h_layout.addWidget(self.word_cloud) self.h_layout.addWidget(self.save_combobox) self.v_layout.addWidget(self.table) self.v_layout.addWidget(self.log_browser) self.v_layout.addWidget(self.progressbar) self.v_layout.addLayout(self.h_layout) self.setLayout(self.v_layout) def crawl_init(self): self.crawl_thread.total_nums.connect(self.total_nums_slot) self.crawl_thread.finished_signal.connect(self.finish_slot) self.crawl_thread.log_signal.connect(self.set_log_slot) self.crawl_thread.result_signal.connect(self.set_table_slot) def btn_slot(self, btn): self.btn_sound.play() # 点击一键搜索 if btn == self.start_btn: # 判断是否输入关键词 if self.movie_name.text(): self.log_browser.clear() self.log_browser.append('<font color="red">一键搜索</font>') self.log_browser.append('<font color="red">搜索中...</font>') self.table.clearContents() self.table.setRowCount(0) self.get_btn.setEnabled(True) self.save_combobox.setEnabled(False) self.crawl_thread.render(self.movie_name, self.source_combobox) self.crawl_thread.start() else: self.log_browser.append('<font color="red">请输入搜索关键词!</font>') if btn == self.get_btn: self.log_browser.append('<font color="red">开始爬取</font>') self.get_btn.setEnabled(False) self.start_btn.setEnabled(True) self.word_cloud.setEnabled(True) self.save_combobox.setEnabled(True) self.run() def word_cloud_slot(self): self.cloud.run() def total_nums_slot(self, total_nums): """搜索到新闻数""" total_nums = '本次搜索总找到新闻:{}条'.format(total_nums) self.log_browser.append(total_nums) def finish_slot(self): self.start_btn.setEnabled(True) self.get_btn.setEnabled(False) self.save_combobox.setEnabled(True) def set_log_slot(self, new_log): self.log_browser.append(new_log) def set_table_slot(self, img, summary, name, star, time): row = self.table.rowCount() self.table.insertRow(row) self.table.setItem(row, 0, QTableWidgetItem(img)) self.table.setItem(row, 1, QTableWidgetItem(summary)) self.table.setItem(row, 2, QTableWidgetItem(name)) self.table.setItem(row, 3, QTableWidgetItem(star)) self.table.setItem(row, 4, QTableWidgetItem(time)) def combobox_slot(self, text): if text == 'MySQL': # self.save_to_MySQL() pass elif text == 'csv': self.save_to_csv() elif text == 'txt': self.save_to_txt() elif text == 'json': self.save_to_json() # def db_connect(self): # """ # SQL配置 # db = QtSql.QSqlDatabase.addDatabase('QMYSQL') # db.setHostName('主机名') # db.setDatabaseName('数据库名') # db.setUserName('用户名') # db.setPassword('密码') # db.setPort(3306) # 端口号 # db.open() # 判断是否连接数据库成功 返回布尔值 # """ # # 创建数据库连接并打开 # self.db = QSqlDatabase.addDatabase('QMYSQL') # self.db.setHostName('localhost') # self.db.setDatabaseName('news') # self.db.setUserName('root') # self.db.setPassword('raspberry') # if not self.db.open(): # QMessageBox.critical(self, 'Database Connection', self.db.lastError().text()) def closeEvent(self, QCloseEvent): self.db.close() # def save_to_MySQL(self): # query = QSqlQuery() # # # query.exec_("CREATE TABLE IF NOT EXISTS movie " # # "(img VARCHAR(100), name VARCHAR(50), star VARCHAR(100)," # # " time VARCHAR(50), score VARCHAR(5))") # # for row in range(self.table.rowCount()): # word = self.movie_name.text() # img = self.table.item(row, 0).text() # name = self.table.item(row, 1).text() # star = self.table.item(row, 2).text() # time = self.table.item(row, 3).text() # query.prepare("INSERT INTO words (keyword,new_url,new_tag,new_summary,source) " # "VALUES (?, ?, ?, ?, ?)") # # sql = 'insert into words(keyword,new_url,new_tag,new_summary,source) VALUES ' \ # # '(%(keyword)s,%(url)s,%(tag)s,%(summary)s,%(source)s)' # # query.bindValue(0, word) # # query.bindValue(1, img) # # query.bindValue(2, name) # # query.bindValue(3, star) # # query.bindValue(4, time) # query.addBindValue(word) # query.addBindValue(img) # query.addBindValue(name) # query.addBindValue(star) # query.addBindValue(time) # # query.exec_() # # QMessageBox.information(self, '保存到MySQL', '保存成功!', QMessageBox.Ok) def save_to_csv(self): """保存为scv文件""" content = [] for row in range(self.table.rowCount()): img = self.table.item(row, 0).text() summary = self.table.item(row, 1).text() name = self.table.item(row, 2).text() star = self.table.item(row, 3).text() time = self.table.item(row, 4).text() content.append([img, summary, name, star, time]) with open('./关键词搜索.csv', 'w', newline='', encoding='utf-8') as f: writer = csv.writer(f) writer.writerow(['新闻链接', '新闻摘要', '渠道来源', '发布日期', '新闻摘要']) writer.writerows(content) QMessageBox.information(self, '保存到csv', '保存成功!', QMessageBox.Ok) def save_to_txt(self): """保存为txt""" content = '' for row in range(self.table.rowCount()): img = '新闻链接:{}\n'.format(self.table.item(row, 0).text()) summary = '新闻摘要:{}\n'.format(self.table.item(row, 1).text()) name = '渠道来源:{}\n'.format(self.table.item(row, 2).text()) star = '发布日期:{}\n'.format(self.table.item(row, 3).text()) time = '新闻摘要:{}\n'.format(self.table.item(row, 4).text()) content += img + summary + name + star + time + '\n' with open('./关键词搜索新闻.txt', 'w', encoding='utf-8') as f: f.write(content) QMessageBox.information(self, '保存到txt', '保存成功!', QMessageBox.Ok) def save_to_json(self): """保存为json文件""" content = [] for row in range(self.table.rowCount()): img = self.table.item(row, 0).text() summary = self.table.item(row, 1).text() name = self.table.item(row, 2).text() star = self.table.item(row, 3).text() time = self.table.item(row, 4).text() content.append( { '新闻链接': img, '新闻摘要': summary, '渠道来源': name, '评论内容': star, '发布日期': time, } ) with open('./关键词搜索新闻.json', 'w', encoding='utf-8') as f: json.dump(content, f, ensure_ascii=False) QMessageBox.information(self, '保存到json', '保存成功!', QMessageBox.Ok) def run(self): """根据url爬取数据""" for row in range(self.table.rowCount()): new_url = self.table.item(row, 0).text() self.log_browser.append('开始爬取:{}'.format(new_url)) self.progressbar.setValue(row + 1) if self.progressbar.value() == 10: self.finish_sound.play() self.log_browser.append('<font color="red">全部爬取完毕!</font>')
class Ui_MainWindow(QWidget): def __init__(self): super().__init__() self.setupUi(MainWindow) def setupUi(self, MainWindow): MainWindow.setObjectName("") MainWindow.setGeometry(10, 10, 475, 550) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(os.getcwd() + "/download.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(120, 90, 101, 29)) self.pushButton.setObjectName("pushButton") self.lineEdit = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit.setGeometry(QtCore.QRect(140, 30, 211, 31)) self.lineEdit.setObjectName("lineEdit") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(60, 40, 67, 17)) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(60, 140, 221, 401)) self.label_2.setText("") self.pix = QPixmap(os.getcwd() + '/gg.jpeg') self.label_2.setPixmap(self.pix) self.label_2.setScaledContents(True) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(150, 160, 121, 21)) self.timer = QTimer() self.timer.timeout.connect(self.clear) self.timer.setSingleShot(True) self.label_3.setText("") self.label_3.setObjectName("label_3") self.pushButton.clicked.connect(self.gif) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def gif(self): self.timer.start(2500) self.lineEdit.clear() self.audio = QSound(os.getcwd() + '/groot.wav') self.audio.play() self.pix1 = QMovie('movie.gif') self.label_3.setMovie(self.pix1) self.pix1.start() self.label_3.adjustSize() def clear(self): self.label_3.clear() def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate self.pushButton.setText(_translate("MainWindow", "Send")) self.label.setText(_translate("MainWindow", "Message:"))
class App(QMainWindow): file = None wave = None def __init__(self): super().__init__() self.title = 'Projekt MN - 18723' self.left = 200 self.top = 200 self.width = 640 self.height = 480 self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.setWindowIcon(QIcon('./fav.png')) self.statusBar().showMessage(self.wave) qtRectangle = self.frameGeometry() centerPoint = QDesktopWidget().availableGeometry().center() qtRectangle.moveCenter(centerPoint) self.move(qtRectangle.topLeft()) boldFont = QFont() boldFont.setBold(True) labelFileName = QLabel(self) labelFileName.setFont(boldFont) labelFileName.setGeometry(10, 40, 100, 50) labelFileName.setText("Nazwa:") self.labelFileNameValue = QLabel(self) self.labelFileNameValue.setGeometry(100, 40, 400, 50) self.labelFileNameValue.setText("None") labelChannel = QLabel(self) labelChannel.setFont(boldFont) labelChannel.setGeometry(10, 80, 150, 50) labelChannel.setText("Kanał(y):") self.labelChannelValue = QLabel(self) self.labelChannelValue.setGeometry(120, 80, 120, 50) self.labelChannelValue.setText("None") labelSampleWidth = QLabel(self) labelSampleWidth.setGeometry(10, 120, 220, 50) labelSampleWidth.setFont(boldFont) labelSampleWidth.setText("Długość Próbki [bit]: ") self.labelSampleWidthValue = QLabel(self) self.labelSampleWidthValue.setGeometry(240, 120, 150, 50) self.labelSampleWidthValue.setText("None") labelSampleFreq = QLabel(self) labelSampleFreq.setGeometry(10, 160, 300, 50) labelSampleFreq.setFont(boldFont) labelSampleFreq.setText("Częstotliwość Próbkowania: ") self.labelSampleFreqValue = QLabel(self) self.labelSampleFreqValue.setGeometry(320, 160, 100, 50) self.labelSampleFreqValue.setText("None") labelDuration = QLabel(self) labelDuration.setFont(boldFont) labelDuration.setGeometry(10, 200, 150, 50) labelDuration.setText("Czas trwania:") self.labelDurationValue = QLabel(self) self.labelDurationValue.setGeometry(170, 200, 120, 50) self.labelDurationValue.setText("None") #Menu menuBar = self.menuBar() fileOpenAction = QAction("&Otworz", self) fileOpenAction.setShortcut("Ctrl+O") fileOpenAction.setStatusTip('Otworz plik audio') fileOpenAction.triggered.connect(self.file_open) inputSignalAction = QAction("&Sygnał wejściowy", self) inputSignalAction.setStatusTip('Wykres sygnału wejściowego') inputSignalAction.triggered.connect(self.input_signal) spectrogramAction = QAction("&Spectrogram", self) spectrogramAction.setStatusTip('Wykres Spektograficzny') spectrogramAction.triggered.connect(self.spectrogram) specrumAmplitudeAction = QAction("&Widmo amplitudowe", self) specrumAmplitudeAction.setStatusTip('Wykres widma aplitudowego') specrumAmplitudeAction.triggered.connect(self.spectrum_amplitude) specrumAmplitudeDBAction = QAction("&Widmo amplituowe [dB]", self) specrumAmplitudeDBAction.setStatusTip('Wykres widma aplitudowego w skali decybelowej') specrumAmplitudeDBAction.triggered.connect(self.spectrum_amplitude_db) periodogramAction = QAction("&Periodogram", self) periodogramAction.setStatusTip('Wykres widmowej gęstości mocy') periodogramAction.triggered.connect(self.periodogram) quitAction = QAction("&Zamknij", self) quitAction.setShortcut("Ctrl+Q") quitAction.setStatusTip('Wylacz applikacje') quitAction.triggered.connect(self.close_app) fileMenu = menuBar.addMenu('&Plik') fileMenu.addAction(fileOpenAction) fileMenu.addAction(quitAction) self.plotMenu = menuBar.addMenu('&Wykresy') self.plotMenu.addAction(inputSignalAction) self.plotMenu.addAction(spectrogramAction) self.plotMenu.addAction(periodogramAction) self.plotMenu.addAction(specrumAmplitudeAction) self.plotMenu.addAction(specrumAmplitudeDBAction) self.plotMenu.setEnabled(False) self.btn_play = QPushButton("Play", self) self.btn_play.setGeometry(0, 0, 80, 80) self.btn_play.move(240, 300) self.btn_play.setVisible(False) self.btn_play.clicked.connect(self.play_sound) self.btn_stop = QPushButton("Pause", self) self.btn_stop.setGeometry(0, 0, 80, 80) self.btn_stop.move(315, 300) self.btn_stop.setVisible(False) self.btn_stop.clicked.connect(self.stop_sound) self.show() def close_app(self): print('Close') sys.exit() def prints(self): print(self.wave) def file_open(self): try: self.file = QFileDialog.getOpenFileName(self,"Open File", os.getcwd(), 'WAV(*.wav)') self.wave = wave.openfp(self.file[0], 'rb') self.show_info() with self.wave: self.plotMenu.setEnabled(True) self.statusBar().showMessage("Wczytano plik!") self.show_info self.sound = QSound(self.file[0]) self.show_player() except FileNotFoundError: print('Nie udało się otworzyć pliku!') def show_info(self): self.labelFileNameValue.setText(os.path.basename(self.file[0])) self.labelChannelValue.setText(str(self.wave.getnchannels())) self.labelSampleFreqValue.setText(str(self.wave.getframerate()) + ' Hz') self.labelSampleWidthValue.setText(str(self.wave.getsampwidth())) self.wav_duration = self.wave.getnframes() / float(self.wave.getframerate()) self.labelDurationValue.setText(str(round(self.wav_duration, 2)) + 's') def show_player(self): self.btn_play.setVisible(True) self.btn_stop.setVisible(True) def play_sound(self): self.sound.play() def stop_sound(self): self.sound.stop() def spectrogram(self): try: i = 0 numberOfChannels = self.wave.getnchannels() sample_rate, samples = wavfile.read(self.file[0]) if numberOfChannels > 1: fig, axarr = plt.subplots(2,1,True, num="Spectrogram") while i < numberOfChannels: axarr[i].plot(i) axarr[i].set_title('Kanał ' + str(i+1)) frequencies, times, spectrogram = signal.spectrogram(samples[:,i], sample_rate) axarr[i].pcolormesh(times, frequencies, np.log(np.abs(spectrogram))) axarr[i].set_xlabel('Czas [s]') axarr[i].set_ylabel('Częstotliwość [Hz]') i += 1 else: plt.figure("Spectrogram") frequencies, times, spectrogram = signal.spectrogram(samples, sample_rate) plt.pcolormesh(times, frequencies, np.log(spectrogram)) plt.title('Kanał 1') plt.xlabel('Czas [s]') plt.ylabel('Częstotliwość [Hz]') plt.subplots_adjust(hspace = .3) plt.show() except: QMessageBox.about(self, 'Bład!', 'Nie udało się utworzyć wykresu!') print(sys.exc_info()[0]) def spectrum_amplitude(self): try: rate, spectrum = wavfile.read(self.file[0]) fig, axarr = plt.subplots(2,1, num="Amplituda Widma") fig.suptitle("Widma Sygnału") axarr[0].plot(0) axarr[0].set_title("Pełne widmo sygnału [FFT]") spectrum_with_coupling = fft(spectrum) axarr[0].plot(spectrum_with_coupling) axarr[0].set_xlabel('Indeks widma') axarr[0].set_ylabel('Amplituda widma') axarr[1].plot(1) axarr[1].set_title("Widmo \"rzeczywiste\" sygnału [RFFT]") spectrum_without_coupling = rfft(spectrum) axarr[1].plot(spectrum_without_coupling) axarr[1].set_xlabel('Indeks widma') axarr[1].set_ylabel('Amplituda widma') plt.subplots_adjust(hspace = .5) plt.show() except: QMessageBox.about(self, 'Bład!', 'Nie udało się utworzyć wykresu!') def input_signal(self): try: rate, spectrum = wavfile.read(self.file[0]) plt.figure('Sygnal Wejsciowy') plt.plot(spectrum) plt.title('Sygnał Wejsciowy') plt.xlabel('Indeks') plt.show() except: QMessageBox.about(self, 'Bład!', 'Nie udało się utworzyć wykresu!') def spectrum_amplitude_db(self): try: rate, spectrum = wavfile.read(self.file[0]) numberOfChannels = self.wave.getnchannels() if numberOfChannels > 1: frequencies, times, spectrogram = signal.spectrogram(spectrum[:,0], rate) else: frequencies, times, spectrogram = signal.spectrogram(spectrum, rate) fig, axarr = plt.subplots(2,1, num="Amplituda Widma - Skala Decybelowa") axarr[0].plot(0) axarr[0].set_title("Skala liniowa") axarr[0].plot(frequencies, np.abs(rfft(spectrogram)), 'r-') axarr[0].set_xlabel('Czestotliwosc [Hz]') axarr[1].plot(1) axarr[1].set_title("Skala logarytmiczna") axarr[1].plot(frequencies, 20*np.log10(np.abs(spectrogram)), 'r-') axarr[1].set_xlabel('Czestotliwosc [Hz]') axarr[1].set_ylabel('Aplituda widma [dB]') plt.subplots_adjust(hspace = .5) plt.show() except: QMessageBox.about(self, 'Bład!', 'Nie udało się utworzyć wykresu!') def periodogram(self): try: rate, spectrum = wavfile.read(self.file[0]) numberOfChannels = self.wave.getnchannels() if numberOfChannels > 1: freq, Pxx = signal.periodogram(spectrum[:,0], rate, 'hamming', self.wave.getnframes(), scaling='density') else: freq, Pxx = signal.periodogram(spectrum, rate, 'hamming', self.wave.getnframes(), scaling='density') plt.figure("Periodogram") plt.semilogy(freq, Pxx) plt.xlim(0, 10000) plt.xlabel('Częstotliwość [Hz]') plt.ylabel('Widmowa gęstość mocy') plt.show() except: QMessageBox.about(self, 'Bład!', 'Nie udało się utworzyć wykresu!')
class Hearthstone( QMainWindow ): # the most important variables are defined here with their starting values moneyCount = 1000 rankCount = 25 goldCount = 0 commonCards = 100 rareCards = 25 epicCards = 0 legendaryCards = 0 packCount = 0 adventureCount = 0 freeToPlay = True brawlPlayed = False questPlayed = False welcomeGift = False # the init function of the main class - setting up some sounds and timers that will be used later on, so that they can be used by other functions to not cause an AttributeError ########################################################################## def __init__(self): super(Hearthstone, self).__init__() self.initGUI() self.initMenu() self.theme = QSound("sounds/HearthstoneSoundtrack-MainTitle.wav") self.ping = QSound("sounds/WhatsApp_Original_Message.wav") self.sax = QSound("sounds/EpicSaxGuy-EpicSaxGuyCruzoRemix.wav") self.theme.play() # starting the app out with the hearthstone theme self.theme.setLoops( 100 ) # hopefully nobody will play this long... (does this cause python to crash when I close the application? Possible..) self.moneyTimer = QTimer( self ) # these timers are for use in the pay to win mode -> they make sure money is self.moneyTimer.timeout.connect( self.depleteMoney ) # taken out of the players account and ranks and gold are put in regularly self.rankTimer = QTimer(self) self.rankTimer.timeout.connect(self.increaseRank) self.goldTimer = QTimer(self) self.goldTimer.timeout.connect(self.increaseGold) def initGUI(self): self.popUpFriendsTimer = QTimer(self) self.popUpFriendsTimer.timeout.connect(self.popUpFriends) self.popUpFinancesTimer = QTimer(self) self.popUpFinancesTimer.timeout.connect(self.popUpFinances) self.popUpFriendsTimer.start( 30000 ) # this makes the 'whatsapp messages of friends' pop up, who worry about the player putting too much time into the game try: if self.moneyTimer.isActive( ) == True: # so that the money, rank and gold values keep changing when the player returns to the main screen in pay to win mode self.moneyTimer.stop() self.rankTimer.stop() self.goldTimer.stop() self.moneyTimer.start(10000) self.rankTimer.start(15000) self.goldTimer.start(5000) else: pass except AttributeError: pass # setting up allllll the GUI elements of the main screen and their signal/slot relationships ########################################################################## self.soloBut = QPushButton("Adventure") self.soloBut.setMinimumSize(100, 80) self.soloBut.clicked.connect(self.playAdventure) self.playBut = QPushButton("Play") self.playBut.setMinimumSize(100, 80) self.playBut.clicked.connect(self.play) self.brawlBut = QPushButton("Tavern Brawl") self.brawlBut.setMinimumSize(100, 80) self.brawlBut.clicked.connect(self.playBrawl) self.questBut = QPushButton("Quest") self.questBut.setMinimumSize(50, 80) self.questBut.clicked.connect(self.playQuest) self.shopBut = QPushButton("Shop") self.shopBut.setMinimumSize(50, 80) self.shopBut.clicked.connect(self.showShop) self.packBut = QPushButton("Packs") self.packBut.setMinimumSize(50, 80) self.packScreen = PackOpeningGraph( self.packCount ) # instance of the only other real custom widget class used in this app self.packBut.clicked.connect(self.updatePackOpenings) self.collectionBut = QPushButton("Collection") self.collectionBut.setMinimumSize(50, 80) self.collectionBut.clicked.connect(self.displayCollection) self.workBut = QPushButton("Work for a Month") self.workBut.setMinimumSize(100, 80) self.workBut.clicked.connect(self.work) mainBut_layout = QVBoxLayout() mainBut_layout.addWidget(self.soloBut) mainBut_layout.addStretch(2) mainBut_layout.addWidget(self.playBut) mainBut_layout.addStretch(2) mainBut_layout.addWidget(self.brawlBut) mainBut_layout.addStretch(2) mainBut_layout.addWidget(self.workBut) mainButtons = QGroupBox() mainButtons.setLayout(mainBut_layout) mainButtons.setMaximumSize(300, 370) leftBut_layout = QVBoxLayout() leftBut_layout.addWidget(self.questBut) leftBut_layout.addWidget(self.shopBut) leftButtons = QGroupBox() leftButtons.setLayout(leftBut_layout) leftButtons.setMaximumSize(300, 300) rightBut_layout = QVBoxLayout() rightBut_layout.addWidget(self.packBut) rightBut_layout.addWidget(self.collectionBut) rightButtons = QGroupBox() rightButtons.setLayout(rightBut_layout) rightButtons.setMaximumSize(300, 300) radios_layout = QHBoxLayout() self.f2p = QRadioButton("Free to Play") self.p2w = QRadioButton("Pay to Win") if Hearthstone.freeToPlay == True: self.f2p.setChecked(True) else: self.p2w.setChecked(True) self.f2p.clicked.connect(self.FreeToPlay) self.p2w.clicked.connect(self.PayToWin) radios_layout.addWidget(self.f2p) radios_layout.addStretch(2) radios_layout.addWidget(self.p2w) radiobuttons = QGroupBox() radiobuttons.setLayout(radios_layout) radiobuttons.setMaximumSize(300, 70) self.gold = QLineEdit() self.gold.setEnabled(False) # so that one cannot cheat! self.goldLabel = QLabel("Gold") self.goldLabel.setObjectName("gold") self.money = QLineEdit() self.money.setEnabled(False) self.moneyLabel = QLabel("Money") self.moneyLabel.setObjectName("money") self.rank = QLineEdit() self.rank.setEnabled(False) self.rankLabel = QLabel("Rank") self.rankLabel.setObjectName("rank") money_layout = QHBoxLayout() money_layout.addWidget(self.moneyLabel) money_layout.addWidget(self.money) moneyBox = QGroupBox() moneyBox.setLayout(money_layout) moneyBox.setMaximumSize(300, 70) rank_layout = QHBoxLayout() rank_layout.addWidget(self.rankLabel) rank_layout.addWidget(self.rank) rankBox = QGroupBox() rankBox.setLayout(rank_layout) rankBox.setMaximumSize(300, 70) gold_layout = QHBoxLayout() gold_layout.addWidget(self.goldLabel) gold_layout.addWidget(self.gold) goldBox = QGroupBox() goldBox.setLayout(gold_layout) goldBox.setMaximumSize(300, 70) grid = QGridLayout() grid.addWidget(moneyBox, 0, 0, 1, 2) grid.addWidget(rankBox, 0, 2, 1, 2) grid.addWidget(goldBox, 0, 4, 1, 2) grid.addWidget(mainButtons, 1, 2, 4, 2) grid.addWidget(leftButtons, 3, 0, 2, 1) grid.addWidget(rightButtons, 3, 5, 2, 1) grid.addWidget(radiobuttons, 4, 2, 1, 3) mainScreen = QWidget() mainScreen.setLayout(grid) mainScreen.setObjectName("main") # for the css self.setWindowTitle("Hearthstone") h = qApp.desktop().screenGeometry().height() - 100 w = qApp.desktop().screenGeometry().width() - 350 self.setGeometry(175, 0, w, h) self.setFixedSize(w, h) self.setCentralWidget(mainScreen) self.show() self.updateGoldCount( ) # so the numbers in the line edits up top are always accurate self.updateMoneyCount() self.updateRankCount() def updateGoldCount(self): try: self.gold.setText(str(Hearthstone.goldCount)) except RuntimeError: pass def updateMoneyCount(self): try: self.money.setText(str(Hearthstone.moneyCount)) except RuntimeError: pass def updateRankCount(self): try: if Hearthstone.rankCount <= 0: self.rank.setText( "LEGEND") # In Hearthstone, rank 0 is called legend else: self.rank.setText(str(Hearthstone.rankCount)) except RuntimeError: pass def updatePackOpenings( self ): # this exists so if the player buys 2 packs and only uses one, the next time he visits the open packs screen, he only has one pack left Hearthstone.packCount -= PackOpeningGraph.usedPacks PackOpeningGraph.usedPacks = 0 self.packScreen.show() def Save( self ): # saves all important variable values in text files inside the repository Hearthstone.packCount -= PackOpeningGraph.usedPacks PackOpeningGraph.usedPacks = 0 gold = open("SaveGame/gold.txt", "w") gold.write(str(Hearthstone.goldCount)) gold.close rank = open("SaveGame/rank.txt", "w") rank.write(str(Hearthstone.rankCount)) rank.close money = open("SaveGame/money.txt", "w") money.write(str(Hearthstone.moneyCount)) money.close common = open("SaveGame/common.txt", "w") common.write(str(Hearthstone.commonCards)) common.close rare = open("SaveGame/rare.txt", "w") rare.write(str(Hearthstone.rareCards)) rare.close epic = open("SaveGame/epic.txt", "w") epic.write(str(Hearthstone.epicCards)) epic.close legendary = open("SaveGame/legendary.txt", "w") legendary.write(str(Hearthstone.legendaryCards)) legendary.close packs = open("SaveGame/packs.txt", "w") packs.write(str(Hearthstone.packCount)) packs.close adventures = open("SaveGame/adventures.txt", "w") adventures.write(str(Hearthstone.adventureCount)) adventures.close def Load( self ): # loads all those important values into their respective variables gold = open("SaveGame/gold.txt") Hearthstone.goldCount = int(gold.read()) gold.close rank = open("SaveGame/rank.txt") Hearthstone.rankCount = int(rank.read()) rank.close money = open("SaveGame/money.txt") Hearthstone.moneyCount = int(money.read()) money.close common = open("SaveGame/common.txt") Hearthstone.commonCards = int(common.read()) common.close rare = open("SaveGame/rare.txt") Hearthstone.rareCards = int(rare.read()) rare.close epic = open("SaveGame/epic.txt") Hearthstone.epicCards = int(epic.read()) epic.close legendary = open("SaveGame/legendary.txt") Hearthstone.legendaryCards = int(legendary.read()) legendary.close packs = open("SaveGame/packs.txt") Hearthstone.packCount = int(packs.read()) packs.close adventures = open("SaveGame/adventures.txt") Hearthstone.adventureCount = int(adventures.read()) adventures.close self.updateGoldCount() # so that the loaded numbers are showing self.updateMoneyCount() self.updateRankCount() self.packScreen = PackOpeningGraph( self.packCount ) # it used to not show the loaded packs at first, I thought this might help..it didnt hurt, so... self.update( ) # always good to throw this in from time to time I heard... self.initGUI( ) # just to make really sure all is loaded, load up the main screen again def initMenu( self ): # this sets up the menu bar at the very top of the screen and allows the player to save and load self.menubar = self.menuBar() saveAct = QAction("Save Game", self) loadAct = QAction("Load Game", self) saveAct.triggered.connect(self.Save) loadAct.triggered.connect(self.Load) self.makeMenu = self.menubar.addMenu("Save") self.makeMenu.addAction(saveAct) self.makeMenu.addAction(loadAct) def displayCollection( self ): # shows the player the numbers of cards of different rarities they have in a pop up window Hearthstone.commonCards += PackOpeningGraph.commonCards # adds all cards obtained through pack openings to the cards already in the players collection Hearthstone.rareCards += PackOpeningGraph.rareCards Hearthstone.epicCards += PackOpeningGraph.epicCards Hearthstone.legendaryCards += PackOpeningGraph.legendaryCards PackOpeningGraph.commonCards = 0 # empties the variables for cards obtained through pack openings so that they arent constantly added on PackOpeningGraph.rareCards = 0 PackOpeningGraph.epicCards = 0 PackOpeningGraph.legendaryCards = 0 text = "Your collection: \nCommon: %d\nRare: %d\nEpic: %d\nLEGENDARY: %d\n" % ( Hearthstone.commonCards, Hearthstone.rareCards, Hearthstone.epicCards, Hearthstone.legendaryCards) collectionPopUp = QMessageBox() collectionPopUp.setText(text) collectionPopUp.exec_() # shows the pop up window # the window for playing an adventure ########################################################################## def playAdventure(self): if Hearthstone.adventureCount >= 1: # you have to have bought at least one adventure! self.adventureTimer = QTimer(self) self.adventureTimer.setSingleShot(True) self.adventureTimer.timeout.connect(self.initGUI) self.helpTimer = QTimer(self) self.helpTimer.timeout.connect( self.updateProgressBar ) # these timers are for the progress bar self.adventureProgress = QProgressBar() self.adventureProgress.setInvertedAppearance(True) self.adventureProgress.setMinimum(0) if self.f2p.isChecked() == True: self.adventureProgress.setMaximum(25000) elif self.p2w.isChecked() == True: self.adventureProgress.setMaximum( 5000) # in pay to win mode, everything is a lot faster else: pass self.progressLabel = QLabel( "Playing adventure.\nAcquiring:\n25 common cards\n15 rare cards\n10 epic cards\n5 legendary cards" ) if Hearthstone.freeToPlay == False: self.progressLabel.setStyleSheet( """ QLabel { font-size: 18px; color: white; text-align : center; font-family: "Apple Chancery"; }""" ) # so it looks different in pay to win mode - the white was most important for being readable with a background picture adventure_layout = QVBoxLayout() adventure_layout.addWidget(self.progressLabel) adventure_layout.addWidget(self.adventureProgress) adventureScreen = QWidget() adventureScreen.setLayout(adventure_layout) adventureScreen.setObjectName("adventure") self.setWindowTitle("Adventure") h = qApp.desktop().screenGeometry().height() - 550 w = qApp.desktop().screenGeometry().width() - 1000 self.setGeometry(20, 20, w, h) self.setFixedSize(w, h) self.setCentralWidget(adventureScreen) self.update() Hearthstone.commonCards += 25 Hearthstone.rareCards += 15 Hearthstone.epicCards += 10 Hearthstone.legendaryCards += 5 Hearthstone.adventureCount -= 1 # what a deal! if self.f2p.isChecked() == True: self.adventureTimer.start(25000) elif self.p2w.isChecked() == True: self.adventureTimer.start(5000) # faster... else: pass self.helpTimer.start(100) else: self.displayWarning() def updateProgressBar( self ): # updates the progress bars progress depending on the helpTimer if (self.adventureTimer.remainingTime()) >= 1: self.adventureProgress.setValue( self.adventureTimer.remainingTime()) else: pass def displayWarning( self): # in the case that the player should have 0 adventures text = "You must purchase an adventure first. Navigate to the shop to purchase an adventure!" warningPopUp = QMessageBox() warningPopUp.setText(text) warningPopUp.exec_() # a lot of this is very similar to the playAdventure function ########################################################################## def playBrawl(self): if Hearthstone.brawlPlayed == False: self.brawlTimer = QTimer(self) self.brawlTimer.setSingleShot(True) self.brawlTimer.timeout.connect(self.initGUI) self.brawlHelpTimer = QTimer(self) self.brawlHelpTimer.timeout.connect(self.updateBrawlProgressBar) self.waitTilWednesday = QTimer(self) self.waitTilWednesday.setSingleShot(True) self.waitTilWednesday.timeout.connect( self.resetBrawl ) # this is so the player cannot immediately play tavern brawl again, just like in the original self.brawlProgress = QProgressBar() self.brawlProgress.setInvertedAppearance(True) self.brawlProgress.setMinimum(0) if self.f2p.isChecked() == True: self.brawlProgress.setMaximum(25000) elif self.p2w.isChecked() == True: self.brawlProgress.setMaximum(5000) else: pass self.brawlProgressLabel = QLabel( "Playing Tavern Brawl.\nAcquiring a card pack.") if Hearthstone.freeToPlay == False: self.brawlProgressLabel.setStyleSheet(""" QLabel { font-size: 18px; color: white; text-align : center; font-family: "Apple Chancery"; }""") brawl_layout = QVBoxLayout() brawl_layout.addWidget(self.brawlProgressLabel) brawl_layout.addWidget(self.brawlProgress) brawlScreen = QWidget() brawlScreen.setLayout(brawl_layout) brawlScreen.setObjectName("brawl") self.setWindowTitle("Tavern Brawl") h = qApp.desktop().screenGeometry().height() - 500 w = qApp.desktop().screenGeometry().width() - 1000 self.setGeometry(20, 20, w, h) self.setFixedSize(w, h) self.setCentralWidget(brawlScreen) self.update() Hearthstone.packCount += 1 Hearthstone.brawlPlayed = True if self.f2p.isChecked() == True: self.brawlTimer.start(25000) elif self.p2w.isChecked() == True: self.brawlTimer.start(5000) else: pass self.brawlHelpTimer.start(100) self.waitTilWednesday.start(100000) else: self.displayBrawlWarning() def updateBrawlProgressBar(self): if (self.brawlTimer.remainingTime()) >= 1: self.brawlProgress.setValue(self.brawlTimer.remainingTime()) else: pass def displayBrawlWarning(self): text = "It is not time for a new Tavern Brawl yet! Wait until Wednesday!" warningPopUp = QMessageBox() warningPopUp.setText(text) warningPopUp.exec_() def resetBrawl(self): Hearthstone.brawlPlayed = False # resets the brawl so it can be played again after the timer waitTilWednesday has run out # a lot of this is similar to the last two functions, especially playBrawl ########################################################################## def playQuest(self): if Hearthstone.questPlayed == False: self.questTimer = QTimer(self) self.questTimer.setSingleShot(True) self.questTimer.timeout.connect(self.initGUI) self.questHelpTimer = QTimer(self) self.questHelpTimer.timeout.connect(self.updateQuestProgressBar) self.waitTilTomorrow = QTimer(self) self.waitTilTomorrow.setSingleShot(True) self.waitTilTomorrow.timeout.connect(self.resetQuest) self.questProgress = QProgressBar() self.questProgress.setInvertedAppearance(True) self.questProgress.setMinimum(0) if self.f2p.isChecked() == True: self.questProgress.setMaximum(25000) elif self.p2w.isChecked() == True: self.questProgress.setMaximum(5000) else: pass questGold = choice([40, 50, 60, 80, 100]) self.questProgressLabel = QLabel( "Playing Quest.\nAcquiring %d gold." % questGold) if Hearthstone.freeToPlay == False: self.questProgressLabel.setStyleSheet(""" QLabel { font-size: 18px; color: white; text-align : center; font-family: "Apple Chancery"; }""") quest_layout = QVBoxLayout() quest_layout.addWidget(self.questProgressLabel) quest_layout.addWidget(self.questProgress) questScreen = QWidget() questScreen.setLayout(quest_layout) questScreen.setObjectName("quest") self.setWindowTitle("Quest") h = qApp.desktop().screenGeometry().height() - 500 w = qApp.desktop().screenGeometry().width() - 1000 self.setGeometry(20, 20, w, h) self.setFixedSize(w, h) self.setCentralWidget(questScreen) self.update() Hearthstone.goldCount += questGold Hearthstone.questPlayed = True if self.f2p.isChecked() == True: self.questTimer.start(25000) elif self.p2w.isChecked() == True: self.questTimer.start(5000) else: pass self.questHelpTimer.start(100) self.waitTilTomorrow.start(50000) else: self.displayQuestWarning() def updateQuestProgressBar(self): if (self.questTimer.remainingTime()) >= 1: self.questProgress.setValue(self.questTimer.remainingTime()) else: pass def displayQuestWarning(self): text = "It is not time for a new Quest yet! Wait until tomorrow!" warningPopUp = QMessageBox() warningPopUp.setText(text) warningPopUp.exec_() def resetQuest(self): Hearthstone.questPlayed = False # still some is similar to the last 3 ########################################################################## def play(self): Hearthstone.commonCards += PackOpeningGraph.commonCards Hearthstone.rareCards += PackOpeningGraph.rareCards Hearthstone.epicCards += PackOpeningGraph.epicCards Hearthstone.legendaryCards += PackOpeningGraph.legendaryCards # same as in displayCollection -> adds all previously acquired cards to the players collection PackOpeningGraph.commonCards = 0 PackOpeningGraph.rareCards = 0 PackOpeningGraph.epicCards = 0 PackOpeningGraph.legendaryCards = 0 self.playTimer = QTimer(self) self.playTimer.setSingleShot(True) self.playTimer.timeout.connect(self.initGUI) self.playTimer.timeout.connect(self.displayDecision) self.playHelpTimer = QTimer(self) self.playHelpTimer.timeout.connect(self.updatePlayProgressBar) self.playProgress = QProgressBar() self.playProgress.setInvertedAppearance(True) self.playProgress.setMinimum(0) if self.f2p.isChecked() == True: self.playProgress.setMaximum(25000) elif self.p2w.isChecked() == True: self.playProgress.setMaximum(5000) else: pass self.playProgressLabel = QLabel( "Playing a game versus\nan online opponent.") if Hearthstone.freeToPlay == False: self.playProgressLabel.setStyleSheet(""" QLabel { font-size: 18px; color: white; text-align : center; font-family: "Apple Chancery"; }""") play_layout = QVBoxLayout() play_layout.addWidget(self.playProgressLabel) play_layout.addWidget(self.playProgress) playScreen = QWidget() playScreen.setLayout(play_layout) playScreen.setObjectName("play") self.setWindowTitle("Ranked Game") h = qApp.desktop().screenGeometry().height() - 500 w = qApp.desktop().screenGeometry().width() - 1000 self.setGeometry(20, 20, w, h) self.setFixedSize(w, h) self.setCentralWidget(playScreen) self.update() self.chance = (Hearthstone.rankCount + 25) + Hearthstone.legendaryCards + ( Hearthstone.epicCards * 0.25) if self.chance >= 99: # a calculation for the players percentage chance of winning self.chance = 98 else: pass dieThrow = randint(0, 99) if self.chance >= dieThrow: # setting up the possible outcomes of the game if Hearthstone.rankCount == 0: self.decision = "victorious" Hearthstone.goldCount += 10 else: Hearthstone.rankCount -= 1 self.decision = "victorious" Hearthstone.goldCount += 10 else: if Hearthstone.rankCount == 25: # cannot fall 'lower', numerically higher, than 25 self.decision = "defeated" else: Hearthstone.rankCount += 1 self.decision = "defeated" if self.f2p.isChecked() == True: self.playTimer.start(25000) elif self.p2w.isChecked() == True: self.playTimer.start(5000) else: pass self.playHelpTimer.start(100) def updatePlayProgressBar(self): if (self.playTimer.remainingTime()) >= 1: self.playProgress.setValue(self.playTimer.remainingTime()) else: pass def displayDecision(self): text = "You were %s!" % self.decision if self.decision == "defeated": text = text + "\nBetter luck next time!\nMaybe you need more legendary cards." else: text = text + "\nGreat job!\nYou must have a large collection of powerful, expensive cards." warningPopUp = QMessageBox() warningPopUp.setText(text) warningPopUp.exec_() # still similar... ########################################################################## def work(self): self.workTimer = QTimer(self) self.workTimer.setSingleShot(True) self.workTimer.timeout.connect(self.initGUI) self.workHelpTimer = QTimer(self) self.workHelpTimer.timeout.connect(self.updateWorkProgressBar) self.workProgress = QProgressBar() self.workProgress.setInvertedAppearance(True) self.workProgress.setMinimum(0) if self.f2p.isChecked() == True: self.workProgress.setMaximum(250000) elif self.p2w.isChecked() == True: self.workProgress.setMaximum( 500000) # this actually takes longer in pay to win mode! else: pass self.workProgressLabel = QLabel("Working.\nAcquiring 1000 Dollars") work_layout = QVBoxLayout() work_layout.addWidget(self.workProgressLabel) work_layout.addWidget(self.workProgress) workScreen = QWidget() workScreen.setLayout(work_layout) workScreen.setObjectName("work") self.setWindowTitle("Work") h = qApp.desktop().screenGeometry().height() - 500 w = qApp.desktop().screenGeometry().width() - 1000 self.setGeometry(20, 20, w, h) self.setFixedSize(w, h) self.setCentralWidget(workScreen) self.update() Hearthstone.moneyCount += 1000 if self.f2p.isChecked() == True: self.workTimer.start(250000) elif self.p2w.isChecked() == True: self.workTimer.start(500000) else: pass self.workHelpTimer.start(100) def updateWorkProgressBar(self): if (self.workTimer.remainingTime()) >= 1: self.workProgress.setValue(self.workTimer.remainingTime()) else: pass # sets up the shop and its GUI elements ########################################################################## def showShop(self): if Hearthstone.freeToPlay == True: self.buyPackBut = QPushButton("Only 100 Gold") self.buyPacksBut = QPushButton("Only 100 Dollars") self.buyAdventureBut = QPushButton("Only 3.500 Gold") self.buyAdventureMoneyBut = QPushButton("Or 350 Dollars") else: self.buyPackBut = QPushButton("Discounted: 50 Gold") self.buyPacksBut = QPushButton("Discounted: 50 Dollars") self.buyAdventureBut = QPushButton("Discounted: 1000 Gold") self.buyAdventureMoneyBut = QPushButton("Or 100 Dollars") self.buyPackBut.setObjectName("pack") self.buyPacksBut.setObjectName("packs") self.buyAdventureBut.setObjectName("adventuregold") self.buyAdventureMoneyBut.setObjectName( "adventuremoney") # all for css self.buyPackLabel = QLabel("1 Card-Pack") if Hearthstone.freeToPlay == False: # guess i could have done this just like above...oops self.buyPackLabel.setStyleSheet(""" QLabel { font-size: 18px; color: white; font-family: "Apple Chancery"; }""") self.buyPacksLabel = QLabel("50 Card-Packs") if Hearthstone.freeToPlay == False: self.buyPacksLabel.setStyleSheet(""" QLabel { font-size: 18px; color: white; font-family: "Apple Chancery"; }""") self.buyAdventureLabel = QLabel("1 Adventure") if Hearthstone.freeToPlay == False: self.buyAdventureLabel.setStyleSheet(""" QLabel { font-size: 18px; color: white; font-family: "Apple Chancery"; }""") self.buyPackBut.clicked.connect(self.buyPack) self.buyPacksBut.clicked.connect(self.buyPacks) self.buyAdventureBut.clicked.connect(self.buyAdventure) self.buyAdventureMoneyBut.clicked.connect(self.buyAdventureMoney) self.backLink = QPushButton("Go Back") self.backLink.setMaximumSize(100, 50) self.backLink.clicked.connect(self.initGUI) PackBox1 = QHBoxLayout() PackBox1.addWidget(self.buyPackLabel) PackBox1.addStretch(1) PackBox1.addWidget(self.buyPackBut) PackBox2 = QHBoxLayout() PackBox2.addWidget(self.buyPacksLabel) PackBox2.addStretch(1) PackBox2.addWidget(self.buyPacksBut) AdventureBox = QHBoxLayout() AdventureBox.addWidget(self.buyAdventureLabel) AdventureBox.addStretch(1) AdventureBox.addWidget(self.buyAdventureBut) AdventureBox.addStretch(1) AdventureBox.addWidget(self.buyAdventureMoneyBut) ShopLayout = QVBoxLayout() ShopLayout.addItem(PackBox1) ShopLayout.addStretch(2) ShopLayout.addItem(PackBox2) ShopLayout.addStretch(2) ShopLayout.addItem(AdventureBox) ShopLayout.addStretch(1) ShopLayout.addWidget(self.backLink) shopScreen = QWidget() shopScreen.setLayout(ShopLayout) shopScreen.setObjectName("shop") self.setWindowTitle("Shop") h = qApp.desktop().screenGeometry().height() - 500 w = qApp.desktop().screenGeometry().width() - 900 self.setGeometry(20, 20, w, h) self.setFixedSize(w, h) self.setCentralWidget(shopScreen) self.update() def buyAdventure( self ): # all the possibilities when one wants to buy and adventure with gold, inluding current mode if Hearthstone.freeToPlay == True: if Hearthstone.goldCount >= 3500: Hearthstone.goldCount -= 3500 Hearthstone.adventureCount += 1 else: text = "You don't have enough gold!" warningPopUp = QMessageBox() warningPopUp.setText(text) warningPopUp.exec_() else: if Hearthstone.goldCount >= 1000: Hearthstone.goldCount -= 1000 Hearthstone.adventureCount += 1 else: text = "You don't have enough gold!" warningPopUp = QMessageBox() warningPopUp.setText(text) warningPopUp.exec_() def buyAdventureMoney(self): # same as above with money instead of gold if Hearthstone.freeToPlay == True: if Hearthstone.moneyCount >= 350: Hearthstone.moneyCount -= 350 Hearthstone.adventureCount += 1 else: text = "You don't have enough money!" warningPopUp = QMessageBox() warningPopUp.setText(text) warningPopUp.exec_() else: if Hearthstone.moneyCount >= 100: Hearthstone.moneyCount -= 100 Hearthstone.adventureCount += 1 else: text = "You don't have enough money!" warningPopUp = QMessageBox() warningPopUp.setText(text) warningPopUp.exec_() def buyPack(self): # same as two above except with a pack if Hearthstone.freeToPlay == True: if Hearthstone.goldCount >= 100: Hearthstone.goldCount -= 100 Hearthstone.packCount += 1 else: text = "You don't have enough gold!" warningPopUp = QMessageBox() warningPopUp.setText(text) warningPopUp.exec_() else: if Hearthstone.goldCount >= 50: Hearthstone.goldCount -= 50 Hearthstone.packCount += 1 else: text = "You don't have enough gold!" warningPopUp = QMessageBox() warningPopUp.setText(text) warningPopUp.exec_() def buyPacks(self): # same as above, just with 50 packs and money if Hearthstone.freeToPlay == True: if Hearthstone.moneyCount >= 100: Hearthstone.moneyCount -= 100 Hearthstone.packCount += 50 else: text = "You don't have enough money!" warningPopUp = QMessageBox() warningPopUp.setText(text) warningPopUp.exec_() else: if Hearthstone.moneyCount >= 50: Hearthstone.moneyCount -= 50 Hearthstone.packCount += 50 else: text = "You don't have enough money!" warningPopUp = QMessageBox() warningPopUp.setText(text) warningPopUp.exec_() # the function that starts the craziness that is pay to win mode ########################################################################## def PayToWin(self): if Hearthstone.moneyCount > 0: # only possible if the player has at least some money if Hearthstone.freeToPlay == True: # and the mode is not yet engaged Hearthstone.freeToPlay = False self.popUpFriendsTimer.stop() self.popUpFinancesTimer.start( 17500 ) # starts the pop up messages regarding a defficiency of finances on the players end styleSheet = open("css/p2w.css") # opens the main stlyesheet qApp.setStyleSheet(styleSheet.read()) styleSheet.close() self.theme.stop() self.sax.play( ) # changes the music - FOR YOUR INFORMATION: THIS MUSIC IS COMMONLY PLAYED IN THE HEARTHSTONE COMMUNITY, self.sax.setLoops( 100 ) # WHEN IMPRESSIVE FEATS SUCH AS MASSIVE COMBOS ARE SHOWN! THAT IS WHY I CHOSE IT TO REPRESENT if Hearthstone.welcomeGift == False: # THE PLAYER WHO SPENDS MONEY ON THE GAME TO BE AS GOOD AS POSSIBLE text = "Congratulations for chosing to\nspend your money on this game!\nHave 5 complimentary adventures for your commitment." congratsPopUp = QMessageBox() congratsPopUp.setGeometry(500, 500, 500, 500) congratsPopUp.setText(text) congratsPopUp.exec_() Hearthstone.adventureCount += 5 # the first time a player enters pay to win mode, he gets 5 adventures Hearthstone.welcomeGift = True else: pass Hearthstone.moneyCount -= 100 # so there can't be gold farming, 100 dollars are subtracted immediately upon selection of pay to win mode self.updateMoneyCount() self.moneyTimer.start( 10000 ) # starts the constant subtraction/addition of values self.goldTimer.start(5000) self.rankTimer.start(15000) else: pass else: self.f2p.setChecked(True) def depleteMoney(self): try: Hearthstone.moneyCount -= 100 if Hearthstone.moneyCount <= 0: # this happens when the player runs out of money before pressing the free to play button again self.moneyTimer.stop( ) # everything changes back into free to play mode self.rankTimer.stop() self.goldTimer.stop() self.popUpFriendsTimer.start(30000) self.popUpFinancesTimer.stop() qApp.setStyleSheet("") self.sax.stop() self.theme.play() self.theme.setLoops(100) Hearthstone.moneyCount = 0 Hearthstone.freeToPlay = True self.f2p.setChecked(True) self.initGUI self.update() text = "It seems that you have run out of money...\nToo bad that we had to set you\nback to the free-to-play status." warningPopUp = QMessageBox() warningPopUp.setText(text) warningPopUp.exec_() else: pass self.updateMoneyCount() self.update() except RuntimeError: # I had some errors when the player was still in another window than the main screen when they ran out of money.. self.popUpFriendsTimer.start(30000) self.popUpFinancesTimer.stop() qApp.setStyleSheet("") self.sax.stop() self.theme.play() self.theme.setLoops(100) self.moneyTimer.stop() self.rankTimer.stop() self.goldTimer.stop() Hearthstone.moneyCount = 0 Hearthstone.freeToPlay = True text = "It seems that you have run out of money...\nToo bad that we had to set you\nback to the free-to-play status." warningPopUp = QMessageBox() warningPopUp.setText(text) warningPopUp.exec_() def increaseRank(self): Hearthstone.rankCount -= 1 self.updateRankCount() self.update() def increaseGold(self): Hearthstone.goldCount += 100 self.updateGoldCount() self.update() # this connects to the free to play button being pressed and does basically all that depleteMoney does, when the player runs out of money ########################################################################## def FreeToPlay(self): if Hearthstone.moneyCount <= 0: self.moneyTimer.stop() self.rankTimer.stop() self.goldTimer.stop() else: pass self.popUpFriendsTimer.start(30000) self.popUpFinancesTimer.stop() qApp.setStyleSheet("") self.sax.stop() self.theme.play() self.theme.setLoops(100) try: self.moneyTimer.stop() self.rankTimer.stop() self.goldTimer.stop() Hearthstone.freeToPlay = True self.f2p.setChecked(True) text = "We are sad to see you\ngo back to that place.\nCome back some time." byePopUp = QMessageBox() byePopUp.setText(text) byePopUp.exec_() self.initGUI self.update() except AttributeError: pass # randomly selects one of the 10 / 7 messages and makes them pop up ########################################################################## def popUpFriends(self): message = randint(0, 9) messages = [ "Hey dude, why aren't you at the hockey game?", "Come on out here, man!", "This is your mother. You have not come out of your room for 3 days. What are you doing in there?!", "I miss you, we should hang out again some time!", "Haven't seen you at school in some time, are you on vacation or something?", "You are playing Hearthstone again, aren't you?", "The concert last night was awesome! Why didn't you come again?", "Dude! Did you sleep through the exam this morning?!", "The weather is nice out, want to go for a hike?", "Last chance! If you want to come with me to Spain tomorrow, you gotta decide NOW!" ] self.ping.play() text = messages[message] self.friendPopUp = QMessageBox() self.friendPopUp.setText(text) self.friendPopUp.setWindowTitle("New Message") self.friendPopUp.setGeometry(0, 0, 300, 200) self.friendPopUp.setObjectName("friend") self.friendPopUp.exec_() def popUpFinances(self): message = randint(0, 6) messages = [ "Your credit card has been denied due to insuficcient funds.", "Dude, I like you, but I need you to pay the rent on time. Don't let me down..", "WHERE'S MY MONEY?!", "Hey, just checking in about the 12$ you're still owing me. I'd appreciate them back.", "Dear customer, you just went over the limit of your bank account. Thus it was closed until further notice.", "Dear, I'm so glad your mom and I can support you going to college. I hope the money lasts the month!", "Hey, just wanted to inform you that the interest for last month's loan went up to 8%, because I still don't have the money from you.." ] self.ping.play() text = messages[message] self.financePopUp = QMessageBox() self.financePopUp.setText(text) self.financePopUp.setWindowTitle("New Message") self.financePopUp.setGeometry(0, 0, 300, 200) self.financePopUp.setObjectName("finance") self.financePopUp.exec_()
def Play(self): QSound.play("dependencies/airhorn.wav")
class main(QtWidgets.QOpenGLWidget): def __init__(self, parent): QtWidgets.QOpenGLWidget.__init__(self, parent) self.started = False self.imageID_back = None self.in_scene = [] self.ornaments = [] self.elapsed_time_shoot = 0 self.elapsed_time_asteroide = 0 self.elapsed_time_inimigo = 0 self.elapsed_time_planet = 920000000000 / 3 self.elapsed_time_stars = 0 self.elapsed_time_powers = 0 self.elapsed_time_power_shoot = 0 self.elapsed_time_power_speed = 0 self.hack = False self.speed = False self.sound_laser = QSound("sound/laser.wav", self) self.sound_laser_enemy = QSound("sound/laserenemy.wav", self) self.sound_explosion = QSound("sound/explos.wav", self) self.sound_1000pts = QSound("sound/1000pts.wav", self) self.sound_inGame = QSound("sound/startScene.wav", self) self.sound_death = QSound("sound/nooo.wav", self) self.sound_power = QSound("sound/powerUp.wav", self) self.enemy_queue = Queue_rotative() self.asteroid_queue = Queue_rotative() self.bullets_queue = Queue_rotative() self.planets_queue = Queue_rotative() self.explosion_queue = Queue_rotative() self.propellant_queue = Queue_rotative() self.power_queue = Queue_rotative() self.animation_explosion = [None for i in range(EXPLOSION_FRAMES)] self.animation_propellant_enemy = [ None for i in range(PROPELLANT_FRAMES) ] self.img_planets = [None for i in range(10)] self.img_nave_azul = None self.img_nave_amarela = None self.img_nave_preta = None self.img_tiro_azul = None self.img_tiro_preto = None self.img_tiro_amarelo = None self.img_tiro = None self.logo_init = None self.logo_end = None self.power_up_vida = None self.power_up_shoot = None self.power_up_speed = None self.myLogo_i = Logo() self.myLogo_e = Logo() self.myNave = None # Inicializa as filas de pre carregamentos def init_queue(self): for i in range(20): new = Enemy() self.enemy_queue.push(new) for i in range(50): new = Asteroide() self.asteroid_queue.push(new) for i in range(100): new = Shoot() self.bullets_queue.push(new) for i in range(10): new = Planeta() self.planets_queue.push(new) for i in range(50): new = Explode() self.explosion_queue.push(new) for i in range(30): new = Propellant() self.propellant_queue.push(new) for i in range(20): new = Power_up() self.power_queue.push(new) # Prepara a cena e carrega as texturas def initializeGL(self): glClearColor(0.0, 0.0, 0.0, 0.0) glShadeModel(GL_SMOOTH) glEnable(GL_DEPTH_TEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_ALPHA_TEST) glAlphaFunc(GL_NOTEQUAL, 0.0) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(45, 1.65, 0.1, 500) gluLookAt(0, -100, 50, 0, 0, 0, 0, 1, 0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() self.myNave = Nave(self.animation_propellant_enemy, 0) self.in_scene.append(self.myNave) for i in range(EXPLOSION_FRAMES): self.animation_explosion[i] = self.loadImage("img/explosion/Comp" + str(i) + ".png") for i in range(PROPELLANT_FRAMES): self.animation_propellant_enemy[i] = self.loadImage( "img/fire/Comp" + str(i) + ".png") for i in range(10): self.img_planets[i] = self.loadImage("img/planets/planeta" + str(i) + ".png") self.img_nave_amarela = self.loadImage("img/nave4.png") self.img_nave_azul = self.loadImage("img/nave1.png") self.img_nave_preta = self.loadImage("img/nave3.png") self.img_tiro_amarelo = self.loadImage("img/nave4_pow.png") self.img_tiro_preto = self.loadImage("img/nave3_pow.png") self.img_tiro_azul = self.loadImage("img/nave1_pow.png") self.img_tiro = self.loadImage("img/nave2_pow.png") self.logo_init = self.loadImage("img/SpaceCute.png") self.logo_end = self.loadImage("img/YouDied.png") self.power_up_vida = self.loadImage("img/power_up_life.png") self.power_up_shoot = self.loadImage("img/power_up_shot.png") self.power_up_speed = self.loadImage("img/power_up_speed.png") self.myLogo_i.load("inicio", self.logo_init, self.logo_end) self.ornaments.append(self.myLogo_i) self.myLogo_i.inited = True self.myLogo_e.load("fim", self.logo_init, self.logo_end) self.init_queue() # Arrumando erros de frict fix_p = self.propellant_queue.pop() fix_p.load(self.animation_propellant_enemy, 1000, 1000, "fix") self.ornaments.append(fix_p) new_explosion = self.explosion_queue.pop() new_explosion.load(self.animation_explosion, 1000, 1000, "fix") self.ornaments.append(new_explosion) tx = 0 ambiente = [0.2, 0.2, 0.2, 1.0] difusa = [0.7, 0.7, 0.7, 1.0] especular = [1.0, 1.0, 1.0, 1.0] posicao = [0.0, 3.0, 2.0, 0.0] lmodelo_ambiente = [0.2, 0.2, 0.2, 1.0] glLightfv(GL_LIGHT0, GL_AMBIENT, ambiente) glLightfv(GL_LIGHT0, GL_DIFFUSE, difusa) glLightfv(GL_LIGHT0, GL_POSITION, posicao) glLightfv(GL_LIGHT0, GL_SPECULAR, especular) glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodelo_ambiente) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glEnable(GL_COLOR_MATERIAL) # Funcao para carregar imagens a partir de um caminho def loadImage(self, path): im = Image.open(path) ix, iy, image = im.size[0], im.size[1], im.tobytes() ID = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, ID) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image) return ID # funcoes para acoes no teclado # A = move para esquerda # D = move para direita # W = atira def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Left: self.myNave.moving_left = True if event.key() == QtCore.Qt.Key_A: self.myNave.moving_left = True if event.key() == QtCore.Qt.Key_Right: self.myNave.moving_right = True if event.key() == QtCore.Qt.Key_D: self.myNave.moving_right = True if event.key() == QtCore.Qt.Key_Space: self.myNave.shooting = True if event.key() == QtCore.Qt.Key_Up: self.myNave.moving_up = True if event.key() == QtCore.Qt.Key_W: self.myNave.moving_up = True if event.key() == QtCore.Qt.Key_Down: self.myNave.moving_down = True if event.key() == QtCore.Qt.Key_S: self.myNave.moving_down = True def keyReleaseEvent(self, event): if event.key() == QtCore.Qt.Key_Left: self.myNave.moving_left = False if event.key() == QtCore.Qt.Key_A: self.myNave.moving_left = False if event.key() == QtCore.Qt.Key_Right: self.myNave.moving_right = False if event.key() == QtCore.Qt.Key_D: self.myNave.moving_right = False if event.key() == QtCore.Qt.Key_Space: self.myNave.shooting = False if event.key() == QtCore.Qt.Key_Up: self.myNave.moving_up = False if event.key() == QtCore.Qt.Key_W: self.myNave.moving_up = False if event.key() == QtCore.Qt.Key_Down: self.myNave.moving_down = False if event.key() == QtCore.Qt.Key_S: self.myNave.moving_down = False # Funcao de desenhar a cena def paintGL(self): # Checa se a musica de fundo acabou e reinicia self.check_end_backm() self.update() # Se o player morreu, entao o jogo acaba if self.myNave.dead: self.started = False glClear(GL_COLOR_BUFFER_BIT) glLoadIdentity() self.update_time() self.spawn_planets() self.spawn_stars() glDisable(GL_DEPTH_TEST) # Desenha os ornamentos ( "Flores" ) # e retira os objetos "mortos" retornando eles para a fila for obj in self.ornaments: if not obj == None: if obj.dead: if isinstance(obj, Planeta): self.planets_queue.push(obj) self.ornaments.remove(obj) elif isinstance(obj, Star): self.ornaments.remove(obj) elif isinstance(obj, Explode): self.explosion_queue.push(obj) self.ornaments.remove(obj) elif isinstance(obj, Propellant): self.propellant_queue.push(obj) self.ornaments.remove(obj) obj.draw() obj.act() obj.check_dead() # Verifica se o jogo foi iniciado if not self.started: return glEnable(GL_DEPTH_TEST) # Desenha a cena # e retira os objetos mortos retornando ele para a fila # e instancia uma explosao no lugar for obj in self.in_scene: if not obj == None: if obj.dead: if isinstance(obj, Enemy): new_explosion = self.explosion_queue.pop() new_explosion.load(self.animation_explosion, obj.move_x + obj.position_x, obj.move_y + 6, "enemy") self.in_scene.append(new_explosion) self.enemy_queue.push(obj) self.in_scene.remove(obj) elif isinstance(obj, Asteroide): new_explosion = self.explosion_queue.pop() new_explosion.load(self.animation_explosion, obj.move_x + obj.position_x, obj.move_y + 5, "enemy") self.in_scene.append(new_explosion) self.asteroid_queue.push(obj) self.in_scene.remove(obj) elif isinstance(obj, Shoot): self.bullets_queue.push(obj) self.in_scene.remove(obj) elif isinstance(obj, Explode): obj.dead = False self.explosion_queue.push(obj) self.in_scene.remove(obj) elif isinstance(obj, Power_up): self.power_queue.push(obj) self.in_scene.remove(obj) if isinstance(obj, Nave): if obj.shooting: self.create_shoot(obj.move_x + obj.position_x) obj.draw() obj.act() obj.check_dead() # Testa as colisoes e aplica os efeitos (ganhar pontos, ou perder vida) for obj_A in self.in_scene: if isinstance(obj_A, Asteroide): for obj_B in self.in_scene: if not (obj_A == obj_B): if isinstance(obj_B, Nave) and self.collide( obj_B, obj_A): # ui.down_life() obj_A.dead = True elif isinstance(obj_B, Shoot) and self.collide( obj_B, obj_A): if not obj_B.is_enemy: obj_A.dead = True if not self.hack: obj_B.dead = True self.sound_explosion.play() ui.up_point(10) if ui.score % 1000 == 0: self.sound_1000pts.play() elif isinstance(obj_A, Enemy): obj_A.elapsed_shoot_time += time() if obj_A.elapsed_shoot_time >= SHOOT_TIME_ENEMY: pos = [obj_A.get_x()[0] + 5, obj_A.get_y()[0] + 6, 0] player = [ self.myNave.get_x()[0] + 5, self.myNave.get_y()[0] - 8, 0 ] dir = [ player[0] - pos[0], player[1] - pos[1], player[2] - pos[2] ] angle_R = math.atan2(dir[1], pos[0]) angle = math.degrees(angle_R) if obj_A.nave_type == 0: self.create_shoot(obj_A.move_x + obj_A.position_x, obj_A.move_y, obj_A.move_y + 6, True, obj_A.nave_type, obj_A.shoot_type, self.img_tiro_azul, angle) elif obj_A.nave_type == 1: self.create_shoot(obj_A.move_x + obj_A.position_x, obj_A.move_y, obj_A.move_y + 6, True, obj_A.nave_type, obj_A.shoot_type, self.img_tiro_amarelo, angle) elif obj_A.nave_type == 2: self.create_shoot(obj_A.move_x + obj_A.position_x, obj_A.move_y, obj_A.move_y + 6, True, obj_A.nave_type, obj_A.shoot_type, self.img_tiro_preto, angle) obj_A.elapsed_shoot_time = 0 for obj_B in self.in_scene: if not (obj_A == obj_B): if isinstance(obj_B, Nave) and self.collide( obj_B, obj_A): # ui.down_life() obj_A.dead = True elif isinstance(obj_B, Shoot) and self.collide( obj_B, obj_A): if not obj_B.is_enemy: obj_A.dead = True if self.hack: obj_B.dead = False else: obj_B.dead = True self.sound_explosion.play() ui.up_point(10) if ui.score % 1000 == 0: self.sound_1000pts.play() elif isinstance(obj_A, Shoot): if obj_A.is_enemy: for obj_B in self.in_scene: if not (obj_A == obj_B): if isinstance(obj_B, Nave) and self.collide( obj_B, obj_A): # ui.down_life() obj_A.dead = True elif isinstance(obj_A, Nave): if self.speed: obj_A.speed = 3 else: obj_A.speed = 0 for obj_B in self.in_scene: if not (obj_A == obj_B): if isinstance(obj_B, Power_up) and self.collide( obj_B, obj_A): obj_B.dead = True self.sound_power.play() if obj_B.skin == 0: ui.up_life() elif obj_B.skin == 1: self.hack = True self.elapsed_time_power_shoot = 0 elif obj_B.skin == 2: self.speed = True self.elapsed_time_power_speed = 0 self.spawn_asteroide() self.spawn_inimigos() self.spawn_powers() self.update() # Checa se a musica de fundo acabou e reinicia caso positivo def check_end_backm(self): if self.sound_inGame.isFinished(): self.sound_inGame.play() # Atualiza o tempo dos temporizadores def update_time(self): self.elapsed_time_shoot += time() self.elapsed_time_asteroide += time() self.elapsed_time_inimigo += time() self.elapsed_time_planet += time() self.elapsed_time_stars += time() self.elapsed_time_powers += time() if self.hack: self.elapsed_time_power_shoot += time() if self.elapsed_time_power_shoot >= POWER_UP_SHOOT: self.hack = False if self.speed: self.elapsed_time_power_speed += time() if self.elapsed_time_power_speed >= POWER_UP_SPEED: self.speed = False # Faz a criacao das estrelas, com uma posicao e escala aleatoria def spawn_stars(self): if self.elapsed_time_stars >= SPAWN_TIME_STARS: position = randint(-70, 70) scale = self.rand_tam_star() new_star = Star(position, scale) self.ornaments.append(new_star) self.elapsed_time_stars = 0 # Faz a criacao dos planetas, com uma posicao e escala aleatoria def spawn_planets(self): if self.elapsed_time_planet >= SPAWN_TIME_PLANET: position = randint(-50, 50) scale = self.rand_tam() new_planet = self.planets_queue.pop() new_planet.load(position, scale, self.img_planets) self.ornaments.append(new_planet) self.elapsed_time_planet = 0 # Retorna um tamanho aleatorio para os planetas def rand_tam(self): return float(str(randint(0, 2)) + "." + str(randint(1, 5))) # Retorna um tamanho aleatorio para as estrelas def rand_tam_star(self): return float("0." + str(randint(1, 3))) # Faz a criacao dos asteroides, com uma posicao aleatioria def spawn_asteroide(self): if self.elapsed_time_asteroide >= SPAWN_TIME: new_aste = self.asteroid_queue.pop() new_aste.load(randint(-49, 43)) self.in_scene.append(new_aste) self.elapsed_time_asteroide = 0 # Faz a criacao dos power ups, com uma posicao aleatioria def spawn_powers(self): if self.elapsed_time_powers >= POWER_UP_TIME: new_power = self.power_queue.pop() new_power.load(randint(-49, 43), 60, self.power_up_vida, self.power_up_shoot, self.power_up_speed) self.in_scene.append(new_power) self.elapsed_time_powers = 0 # Faz a criacao dos inimigos, com uma posicao aleatoria def spawn_inimigos(self): if self.elapsed_time_inimigo >= SPAWN_TIME_ENEMY: new_inimigo = self.enemy_queue.pop() new_inimigo.load(randint(-49, 43), self.animation_propellant_enemy, self.img_nave_azul, self.img_nave_amarela, self.img_nave_preta) self.in_scene.append(new_inimigo) self.elapsed_time_inimigo = 0 # Funcao para criacao dos tiros, tanto dos inimigos quanto do player def create_shoot(self, position, position_y=None, position_y_2=None, is_enemy=False, type="player", qtd=None, tiro_respectivo=None, my_angle=None): if is_enemy: if qtd == 1: new_shoot = self.bullets_queue.pop() new_shoot.load(tiro_respectivo, position, position_y, position_y_2, True, type, 0, my_angle) self.in_scene.append(new_shoot) elif qtd == 2: new_shoot = self.bullets_queue.pop() new_shoot.load(tiro_respectivo, position - 2.5, position_y, position_y_2, True, type, 0, my_angle) new_shoot2 = self.bullets_queue.pop() new_shoot2.load(tiro_respectivo, position + 2.5, position_y, position_y_2, True, type, 0, my_angle) self.in_scene.append(new_shoot) self.in_scene.append(new_shoot2) elif qtd == 3: new_shoot = self.bullets_queue.pop() new_shoot.load(tiro_respectivo, position - 5, position_y, position_y_2, True, type, 0, my_angle) new_shoot2 = self.bullets_queue.pop() new_shoot2.load(tiro_respectivo, position, position_y, position_y_2, True, type, 0, my_angle) new_shoot3 = self.bullets_queue.pop() new_shoot3.load(tiro_respectivo, position + 5, position_y, position_y_2, True, type, 0, my_angle) self.in_scene.append(new_shoot) self.in_scene.append(new_shoot2) self.in_scene.append(new_shoot3) self.sound_laser_enemy.play() return if self.elapsed_time_shoot >= SHOOT_TIME: if self.myNave.moving_right: adjust = 3 elif self.myNave.moving_left: adjust = -3 else: adjust = 0 if self.hack: new_shoot = self.bullets_queue.pop() new_shoot.load(self.img_tiro, position + adjust + 5, self.myNave.get_y()[1], self.myNave.get_y()[1] + 8, False, 1, self.myNave.get_z()[0] + 10, 0) new_shoot2 = self.bullets_queue.pop() new_shoot2.load(self.img_tiro, position + adjust - 5, self.myNave.get_y()[1], self.myNave.get_y()[1] + 8, False, 1, self.myNave.get_z()[0] + 10, 0) new_shoot3 = self.bullets_queue.pop() new_shoot3.load(self.img_tiro, position + adjust, self.myNave.get_y()[1], self.myNave.get_y()[1] + 8, False, 1, self.myNave.get_z()[0] + 10, 0) self.in_scene.append(new_shoot) self.in_scene.append(new_shoot2) self.in_scene.append(new_shoot3) self.sound_laser.play() else: new_shoot = self.bullets_queue.pop() new_shoot.load(self.img_tiro, position + adjust, self.myNave.get_y()[1], self.myNave.get_y()[1] + 8, False, 1, self.myNave.get_z()[0] + 10, 0) self.in_scene.append(new_shoot) self.sound_laser.play() self.elapsed_time_shoot = 0 # Checagem de colisao # adaptado com o eixo z def collide(self, A, B): A_colliding_B_in_x = (A.get_x()[1] >= B.get_x()[0] and A.get_x()[1] <= B.get_x()[1]) # or B_colliding_A_in_x = (B.get_x()[1] >= A.get_x()[0] and B.get_x()[1] <= A.get_x()[1]) A_colliding_B_in_y = (A.get_y()[1] >= B.get_y()[0] and A.get_y()[1] <= B.get_y()[1]) # or B_colliding_A_in_y = (B.get_y()[1] >= A.get_y()[0] and B.get_y()[1] <= A.get_y()[1]) A_colliding_B_in_z = (A.get_z()[1] >= B.get_z()[0] and A.get_z()[1] <= B.get_z()[1]) # or B_colliding_A_in_z = (B.get_z()[1] >= A.get_z()[0] and B.get_z()[1] <= A.get_z()[1]) return (A_colliding_B_in_x or B_colliding_A_in_x) and \ (A_colliding_B_in_y or B_colliding_A_in_y) and \ (A_colliding_B_in_z or B_colliding_A_in_z) def active_hack(self): self.hack = not self.hack # Reinicia o jogo, seta todas as variaveis para o inicio def reestart(self): self.reloc() self.started = False self.player_move_left = False self.player_move_right = False self.myNave = Nave(self.animation_propellant_enemy, 0) self.elapsed_time_shoot = 0 self.elapsed_time_asteroide = 0 self.elapsed_time_inimigo = 0 self.hack = False self.in_scene = [] self.in_scene.append(self.myNave) self.sound_inGame.stop() self.sound_inGame = QSound("sound/inGame.wav", self) self.sound_inGame.play() if self.myLogo_i.inited: self.ornaments.remove(self.myLogo_i) self.myLogo_i.inited = False if self.myLogo_e.inited: self.ornaments.remove(self.myLogo_e) self.myLogo_e.inited = False # Realoca os objetos atualmente na cena para suas respectivas filas def reloc(self): for obj in self.in_scene: if isinstance(obj, Enemy): self.enemy_queue.push(obj) self.in_scene.remove(obj) elif isinstance(obj, Asteroide): self.asteroid_queue.push(obj) self.in_scene.remove(obj) elif isinstance(obj, Shoot): self.bullets_queue.push(obj) self.in_scene.remove(obj) elif isinstance(obj, Explode): self.explosion_queue.push(obj) self.in_scene.remove(obj) elif isinstance(obj, Power_up): self.power_queue.push(obj) self.in_scene.remove(obj) for obj in self.ornaments: if isinstance(obj, Flor): self.flowers_queue.push(obj) self.ornaments.remove(obj) elif isinstance(obj, Planeta): self.planets_queue.push(obj) self.ornaments.remove(obj) # Para o jogo def stop(self): self.reloc() self.started = False self.sound_inGame.stop() self.sound_inGame = QSound("sound/startScene.wav", self) self.sound_inGame.play() self.in_scene = [] self.ornaments.append(self.myLogo_i) if self.myLogo_e.inited: self.ornaments.remove(self.myLogo_e) self.myLogo_e.inited = False self.myLogo_i.inited = True # Quando o jogador morre def dead(self): self.reloc() self.myNave.dead = True self.sound_inGame.stop() self.sound_inGame = QSound("sound/gameOver.wav", self) self.sound_death.play() if self.sound_death.isFinished(): self.sound_inGame.play() self.ornaments.append(self.myLogo_e) self.myLogo_e.inited = True
def Play3(self): QSound.play("dependencies/pirate.wav")
class Lobby(ventana_principal, QtClass): send_msg = core.pyqtSignal(dict) give_inputs = core.pyqtSignal(list) give_users = core.pyqtSignal(dict) close_window = core.pyqtSignal(bool) def __init__(self, cliente): super().__init__() self.setupUi(self) self.cliente = cliente self.player = None self.setFixedSize(890, 700) self.init_widgets() self.host_widgets_set = False self.send_msg.connect(self.cliente.send) self.give_inputs.connect(self.cliente.set_inputs) self.give_users.connect(self.cliente.set_users) self.close_window.connect(self.cliente.close_lobby) self.users = {} self.chat_str = "" self.soundtrack = QSound('adrenaline.wav') self.soundtrack.play() self.player_list_items = [] self.color_list = ['red', 'green', 'blue', 'yellow', 'cyan', 'purple'] self.players_error_labels = [ self.Player1ErrorDisplayer, \ self.Player2ErrorDisplayer, \ self.Player3ErrorDisplayer, \ self.Player4ErrorDisplayer ] self.labels = [ self.Player1Label, \ self.Player2Label, \ self.Player3Label, \ self.Player4Label ] self.color_lists = [ self.Player1ColorList, \ self.Player2ColorList, \ self.Player3ColorList, \ self.Player4ColorList ] self.color_lists_previous_indexes = [ self.Player1ColorList_pi, \ self.Player2ColorList_pi, \ self.Player3ColorList_pi, \ self.Player4ColorList_pi ] self.english_to_spanish = { "red" : "Rojo", \ "green" : "Verde", \ "blue" : "Azul", \ "yellow" : "Amarillo", \ "cyan" : "Cyan", \ "purple" : "Morado"} self.allListsDisabled = False self.color_checker = core.QTimer(self) self.msg_color_update = False self.color_checker.timeout.connect(self.change_color_checker) self.color_checker.start(250) self.lft_key = None self.rgt_key = None self.key_inputs = [ [self.InputPlayer1Izq, \ self.InputPlayer1Drc], \ [self.InputPlayer2Izq, \ self.InputPlayer2Drc], \ [self.InputPlayer3Izq, \ self.InputPlayer3Drc], \ [self.InputPlayer4Izq, \ self.InputPlayer4Drc] ] self.str_to_key = { 'q' : core.Qt.Key_Q, \ 'w' : core.Qt.Key_W, \ 'e' : core.Qt.Key_E, \ 'r' : core.Qt.Key_R, \ 't' : core.Qt.Key_T, \ 'y' : core.Qt.Key_Y, \ 'u' : core.Qt.Key_U, \ 'i' : core.Qt.Key_I, \ 'o' : core.Qt.Key_O, \ 'p' : core.Qt.Key_P, \ 'a' : core.Qt.Key_A, \ 's' : core.Qt.Key_S, \ 'd' : core.Qt.Key_D, \ 'f' : core.Qt.Key_F, \ 'g' : core.Qt.Key_G, \ 'h' : core.Qt.Key_H, \ 'j' : core.Qt.Key_J, \ 'k' : core.Qt.Key_K, \ 'l' : core.Qt.Key_L, \ 'ñ' : 209, \ 'z' : core.Qt.Key_Z, \ 'x' : core.Qt.Key_X, \ 'c' : core.Qt.Key_C, \ 'v' : core.Qt.Key_V, \ 'b' : core.Qt.Key_B, \ 'n' : core.Qt.Key_N, \ 'm' : core.Qt.Key_M } self.input_error_labels = [ [self.Player1IzqKeyErrorLabel, \ self.Player1DrcKeyErrorLabel], \ [self.Player2IzqKeyErrorLabel, \ self.Player2DrcKeyErrorLabel], \ [self.Player3IzqKeyErrorLabel, \ self.Player3DrcKeyErrorLabel], \ [self.Player4IzqKeyErrorLabel, \ self.Player4DrcKeyErrorLabel] ] self.poderes = [False for i in range(6)] self.fps = 1 self.win_score = 0 self.radio = 0 self.tick_corte = 0 self.tiempo_corte = 0 self.show() def init_widgets(self): self.Player1ColorList_pi = -1 self.Player2ColorList_pi = -1 self.Player3ColorList_pi = -1 self.Player4ColorList_pi = -1 self.AllDisplayer.setAutoFillBackground(True) pallete = self.palette() pallete.setColor(self.backgroundRole(), core.Qt.black) self.AllDisplayer.setPalette(pallete) self.EnviarButton.clicked.connect(self.get_msg) def init_Host_widgets(self): self.JugarButton.clicked.connect(self.start_countdown) self.FPSInput.setReadOnly(False) self.FPSButton.clicked.connect(self.set_fps) self.WinScoreInput.setReadOnly(False) self.WinScoreButton.clicked.connect(self.set_win_score) self.RadioInput.setReadOnly(False) self.RadioButton.clicked.connect(self.set_radio) self.TickCorteInput.setReadOnly(False) self.TickCorteButton.clicked.connect(self.set_tick_corte) self.TiempoCorteInput.setReadOnly(False) self.TiempoCorteButton.clicked.connect(self.set_tiempo_corte) self.UsainInput.setCheckable(True) self.UsainButton.clicked.connect(self.set_usain) self.LimpiessaInput.setCheckable(True) self.LimpiessaButton.clicked.connect(self.set_limpiessa) self.JaimeInput.setCheckable(True) self.JaimeButton.clicked.connect(self.set_jaime) self.CervessaInput.setCheckable(True) self.CervessaButton.clicked.connect(self.set_cervessa) self.FelipeInput.setCheckable(True) self.FelipeButton.clicked.connect(self.set_felipe) self.NebcoinsInput.setCheckable(True) self.NebcoinsButton.clicked.connect(self.set_nebcoins) def update_host_widgets(self, event): if self.cliente.isHost is not True: print('NO HOST') if event["parameter"] == "fps": self.FPSInput.setText(str(event["info"])) elif event["parameter"] == "win_score": self.WinScoreInput.setText(str(event["info"])) elif event["parameter"] == "radio": self.RadioInput.setText(str(event["info"])) elif event["parameter"] == "tick_corte": self.TickCorteInput.setText(str(event["info"])) elif event["parameter"] == "tiempo_corte": self.TiempoCorteInput.setText(str(event["info"])) elif event["parameter"] == "usain": self.UsainInput.setCheckState(event["info"]) elif event["parameter"] == "limpiessa": self.LimpiessaInput.setCheckState(event["info"]) elif event["parameter"] == "jaime": self.JaimeInput.setCheckState(event["info"]) elif event["parameter"] == "cervessa": self.CervessaInput.setCheckState(event["info"]) elif event["parameter"] == "felipe": self.FelipeInput.setCheckState(event["info"]) elif event["parameter"] == "nebcoins": self.NebcoinsInput.setCheckState(event["info"]) #Justificado porque esta seguido def set_fps(self): self.fps = int(self.FPSInput.text()) msg_to_send = { "type" : "parameters_update", \ "parameter" : "fps", \ "info" : self.fps} self.send_msg.emit(msg_to_send) def set_win_score(self): self.win_score = int(self.WinScoreInput.text()) msg_to_send = { "type" : "parameters_update", \ "parameter" : "win_score", \ "info" : self.win_score} self.send_msg.emit(msg_to_send) def set_radio(self): self.radio = int(self.RadioInput.text()) msg_to_send = { "type" : "parameters_update", \ "parameter" : "radio", \ "info" : self.radio} self.send_msg.emit(msg_to_send) def set_tick_corte(self): self.tick_corte = int(self.TickCorteInput.text()) msg_to_send = { "type" : "parameters_update", \ "parameter" : "tick_corte", \ "info" : self.tick_corte} self.send_msg.emit(msg_to_send) def set_tiempo_corte(self): self.tiempo_corte = int(self.TiempoCorteInput.text()) msg_to_send = { "type" : "parameters_update", \ "parameter" : "tiempo_corte", \ "info" : self.tiempo_corte} self.send_msg.emit(msg_to_send) def set_usain(self): self.poderes[0] = int(self.UsainInput.isChecked()) msg_to_send = { "type" : "parameters_update", \ "parameter" : "usain", \ "info" : self.poderes[0]} self.send_msg.emit(msg_to_send) def set_limpiessa(self): self.poderes[1] = int(self.LimpiessaInput.isChecked()) msg_to_send = { "type" : "parameters_update", \ "parameter" : "limpiessa", \ "info" : self.poderes[1]} self.send_msg.emit(msg_to_send) def set_jaime(self): self.poderes[2] = int(self.JaimeInput.isChecked()) msg_to_send = { "type" : "parameters_update", \ "parameter" : "jaime", \ "info" : self.poderes[2]} self.send_msg.emit(msg_to_send) def set_cervessa(self): self.poderes[3] = int(self.CervessaInput.isChecked()) msg_to_send = { "type" : "parameters_update", \ "parameter" : "cervessa", \ "info" : self.poderes[3]} self.send_msg.emit(msg_to_send) def set_felipe(self): self.poderes[4] = int(self.FelipeInput.isChecked()) msg_to_send = { "type" : "parameters_update", \ "parameter" : "felipe", \ "info" : self.poderes[4]} self.send_msg.emit(msg_to_send) def set_nebcoins(self): self.poderes[5] = int(self.NebcoinsInput.isChecked()) msg_to_send = { "type" : "parameters_update", \ "parameter" : "nebcoins", \ "info" : self.poderes[5]} self.send_msg.emit(msg_to_send) def keyPressEvent(self, event): izq_key = self.key_inputs[self.player - 1][0] izq_label = self.input_error_labels[self.player - 1][0] drc_key = self.key_inputs[self.player - 1][1] drc_label = self.input_error_labels[self.player - 1][1] if izq_key.text() != '': if len(izq_key.text()) == 1: try: self.lft_key = self.str_to_key[izq_key.text().lower()] except KeyError: izq_label.setText( \ 'Ingrese\n' + \ 'una\n' + \ 'letra\n' ) izq_label.setStyleSheet( \ f'font-weight: bolder; color: grey') return if self.lft_key == self.rgt_key: izq_label.setText( \ 'Tecla\n' + \ 'ya esta\n' + \ 'usada') izq_label.setStyleSheet( \ f'font-weight: bolder; color: grey') self.lft_key = None else: izq_label.setText('') else: izq_label.setText( \ 'Ingrese\n' + \ 'una\n' + \ 'letra\n' + \ 'no una\n' + \ 'palabra') izq_label.setStyleSheet( \ f'font-weight: bolder; color: grey') if drc_key.text() != '': if len(drc_key.text()) == 1: try: self.rgt_key = self.str_to_key[drc_key.text().lower()] except KeyError: drc_label.setText( \ 'Ingrese\n' + \ 'una\n' + \ 'letra\n' ) drc_label.setStyleSheet( \ f'font-weight: bolder; color: grey') return if self.rgt_key == self.lft_key: drc_label.setText( \ 'Tecla\n' + \ 'ya esta\n' + \ 'usada') drc_label.setStyleSheet( \ f'font-weight: bolder; color: grey') self.rgt_key = None else: drc_label.setText('') else: drc_label.setText( \ 'Ingrese\n' + \ 'una\n' + \ 'letra\n' + \ 'no una\n' + \ 'palabra') drc_label.setStyleSheet( \ f'font-weight: bolder; color: grey') print(self.lft_key, self.rgt_key) if event.key() == core.Qt.Key_Return: if self.ChatInput.text() != '': self.get_msg() def get_msg(self): if self.ChatInput.text() != '': msg = { "type" : "chat", \ "username" : self.cliente.user, \ "data" : self.ChatInput.text()} self.ChatInput.setText('') self.send_msg.emit(msg) def start_countdown(self): msg = { "type" : "display_update", \ "place" : "lobby", \ "info" : "start_countdown"} self.send_msg.emit(msg) def update_playerlist(self, users): if self.player is None: self.player = len(users) self.block_keys_inputs() self.update_color_lists() for user in users.keys(): if user not in self.users.keys(): self.users[user] = users[user] item = widgets.QListWidgetItem() label_user = widgets.QLabel(user) widget = widgets.QWidget() layout = widgets.QHBoxLayout() layout.addWidget(label_user) color = f'font-weight: bolder; color: {users[user]}' label_user.setStyleSheet(color) self.update_player_widgets_color(user, \ list(self.users.keys()).index(user), \ users[user]) if user == list(self.users.keys())[0]: label_host = widgets.QLabel() pixmap = gui.QPixmap('sprites/crown.png') pixmap = pixmap.scaled(pixmap.width()* \ (16*1.5/pixmap.width()), \ pixmap.height()*\ (16*1.5/pixmap.height())) label_host.setPixmap(pixmap) layout.addWidget(label_host) widget.setLayout(layout) # print(widget.layout().itemAt(0).widget().setText('Hola')) item.setSizeHint(widget.sizeHint()) self.player_list_items.append(item) self.PlayerList.addItem(item) # self.PlayerList.addItem(f'{user}') self.PlayerList.setItemWidget(item, widget) else: self.users[user] = users[user] self.update_playerlist_networking(user) if self.host_widgets_set is False: if self.cliente.isHost: self.init_Host_widgets() self.host_widgets_set = True self.color_list = ['red', 'green', 'blue', 'yellow', 'cyan', 'purple'] def update_playerlist_networking(self, user): player_index = list(self.users.keys()).index(user) color = f'font-weight: bolder; color: {self.users[user]}' print(player_index) self.PlayerList.itemWidget( \ self.PlayerList.item(player_index)).layout().itemAt( \ 0).widget().setStyleSheet(color) self.update_player_widgets_color(user, \ list(self.users.keys()).index(user), \ self.users[user]) def update_chatbox(self, msg): self.chat_str += f'{msg["username"]}: {msg["data"]}\n' self.ChatDisplayer.setText(self.chat_str) def init_countdown(self, event): if event is True: self.gridLayout_9.removeWidget(self.JugarButton) self.JugarButton.deleteLater() self.JugarButton = None self.CountDown = widgets.QLCDNumber(self) self.gridLayout_9.addWidget(self.CountDown) self.CountDown.display(5) self.CountDown.setDigitCount(len("5")) def update_countdown(self, event): self.CountDown.display(event) self.CountDown.setDigitCount(len(str(event))) if event == 0: self.give_inputs.emit([self.lft_key, self.rgt_key]) self.give_users.emit(self.users) self.close_window.emit(True) self.hide() self.soundtrack.stop() def update_msg_color(self, event): self.msg_color_update = event def change_color_checker(self): if self.player is not None and self.msg_color_update is False: player_widget = { \ 1 : [self.Player1ColorList, self.Player1ColorList_pi], \ 2 : [self.Player2ColorList, self.Player2ColorList_pi], \ 3 : [self.Player3ColorList, self.Player3ColorList_pi], \ 4 : [self.Player4ColorList, self.Player4ColorList_pi] } widget = player_widget[self.player][0] last_index = player_widget[self.player][1] if widget.currentIndex() != last_index: if self.color_list[widget.currentIndex()] not in \ self.users.values(): msg = { "type" : "color_update", \ "username" : self.cliente.user, \ "info" : self.color_list[widget.currentIndex()]} self.send_msg.emit(msg) self.msg_color_update = True else: color_usado = self.color_list[widget.currentIndex()] self.update_error_label(color_usado) def update_color_lists(self): for i in range(4): if i != self.player - 1: self.color_lists[i].setEnabled(False) def update_error_label(self, color): self.players_error_labels[self.player-1].setText( \ 'El color:\n' + \ f'{self.english_to_spanish[color]}\n' + \ 'ya esta ocupado') self.players_error_labels[self.player-1].setStyleSheet( \ f'font-weight: bolder; color: grey') self.color_lists[self.player-1].setCurrentIndex( \ self.color_lists_previous_indexes[self.player-1]) def update_player_widgets_color(self, player, player_index, color): self.labels[player_index].setText(player) self.labels[player_index].setStyleSheet( \ f'font-weight: bolder; color: {color}') self.color_lists[player_index].setCurrentIndex( \ self.color_list.index(color)) self.color_lists_previous_indexes[player_index] = \ self.color_lists[player_index].currentIndex() self.Player1ColorList_pi = self.color_lists_previous_indexes[0] self.Player2ColorList_pi = self.color_lists_previous_indexes[1] self.Player3ColorList_pi = self.color_lists_previous_indexes[2] self.Player4ColorList_pi = self.color_lists_previous_indexes[3] self.players_error_labels[self.player - 1].setText('') def block_keys_inputs(self): for i in range(4): if i != self.player - 1: for input in self.key_inputs[i]: input.setReadOnly(True)
class Popup(QtWidgets.QDialog): def __init__(self): super(self.__class__, self).__init__() self.setObjectName("formpopup") self.setGeometry(1585, 40, 330, 293) self.setMinimumSize(QtCore.QSize(0, 0)) self.setStatusTip("") self.setWindowTitle("formpopup") self.textBrowser = TextBrowser(self) self.textBrowser.setGeometry(5, 5, 322, 100) self.closebutton = QtWidgets.QPushButton(self) self.closebutton.setText('X') self.closebutton.setGeometry(304, 8, 20, 20) self.closebutton.setStyleSheet('color: red') self.closebutton.clicked.connect(self.clicked) self.duration = 10 self.browsertext = '' self.favicons = True self.popupon = True self.sound = QSound("res/popup.wav") self.soundon = True self.popup_timer = QTimer(self) self.popup_timer.setSingleShot(True) self.popup_timer.timeout.connect(self.timer) self.popup_timer2 = QTimer(self) self.popup_timer2.setInterval(1000) self.popup_timer2.timeout.connect(self.timer2) self.setWindowFlags(Qt.FramelessWindowHint) self.setWindowFlags(Qt.X11BypassWindowManagerHint) self.setWindowOpacity(0.90) self.xpos = 1585 self.shownmessages = [] def fire(self, profiles, count=1, firstrun=False, testrun=False): if testrun: if self.popupon or self.sound: if not self.isVisible(): self.textBrowser.clear() self.browsertext = '' icon = 'res/thunderbird.png' log('icon ' + icon) for tt in range(2): if self.favicons: self.browsertext += '<h3 style="color: DodgerBlue"><img height="20" width="20" src="' + icon + '"/> Twitter <[email protected]></h3><p>This is a test message' else: self.browsertext += '<h3 style="color: DodgerBlue">Mail Info:- From address</h3><p>Subject line of text' if self.popupon: self.show() self.textBrowser.setText(self.browsertext) self.setGeometry(self.xpos, 40, 330, self.textBrowser.height + 20) if self.soundon: self.sound.play() self.popup_timer.start(self.duration * 1000) self.popup_timer2.start() return if self.popupon or self.sound: popprofiles = [] fileexists = False for ss in range(len(profiles)): popprofiles.append(profiles[ss].replace('INBOX.msf', 'INBOX')) if os.path.isfile(popprofiles[ss]): fileexists = True if fileexists: mailinfo = readmessage(popprofiles, count) up = 0 for mc in range(len(mailinfo['messageid'])): if self.shownmessages.__contains__( mailinfo['messageid'][up]): mailinfo['from'].pop(up) mailinfo['subject'].pop(up) mailinfo['date'].pop(up) mailinfo['messageid'].pop(up) else: up += 1 for fr in mailinfo['messageid']: self.shownmessages.append(fr) if not firstrun and len(mailinfo['messageid']) > 0: if not self.isVisible(): self.textBrowser.clear() self.browsertext = '' for x in range(len(mailinfo['messageid'])): log('Scraped from ' + mailinfo['from'][x - 1]) log('Scraped subj ' + mailinfo['subject'][x - 1]) fromx = self.encoded_words_to_text(mailinfo['from'][x - 1]) subject = self.encoded_words_to_text( mailinfo['subject'][x - 1]) log('decoded from ' + fromx) log('decoded subj ' + subject) if self.favicons: fromxy = fromx + '&' log('from ' + fromxy) fav = re.findall( '@\S*?\.?([\w|-]*(\.\w{2,3})?\.\w{2,3})&', fromxy) if len(fav) > 0: log('get favicon ' + fav[0][0]) icon = getfavicon(fav[0][0]) else: icon = 'res/thunderbird.png' self.browsertext += '<h3 style="color: DodgerBlue"><img height="20" width="20" src="' + icon + '"/> ' + fromx + '</h3><p>' + subject else: self.browsertext += '<h3 style="color: DodgerBlue"><center>' + fromx + '</center></h3><p>' + subject if self.popupon: self.show() if self.soundon: self.sound.play() self.textBrowser.setText(self.browsertext) self.setGeometry(self.xpos, 40, 330, self.textBrowser.height + 20) self.popup_timer.start(self.duration * 1000) self.popup_timer2.start() @staticmethod def encoded_words_to_text(encoded_words): byte_string = '' encoded_word_regex = r'(.*)=\?{1}(.+)\?{1}([B|Q|b|q])\?{1}(.+)\?{1}=(.*)' if not re.match(encoded_word_regex, encoded_words): return encoded_words front, charset, encoding, encoded_text, back = re.match( encoded_word_regex, encoded_words).groups() try: if encoding is 'B' or encoding is 'b': byte_string = base64.b64decode(encoded_text) elif encoding is 'Q' or encoding is 'q': byte_string = quopri.decodestring(encoded_text) if byte_string: return front + byte_string.decode(charset) + back except: print('def encoded_words_to_text: LookupError: unknown encoding') return 'Could Not decode Subject string' def timer2(self): if self.textBrowser.hideme: self.popup_timer2.stop() self.textBrowser.hideme = False self.hide() def timer(self): self.popup_timer2.stop() self.hide() def clicked(self): self.popup_timer2.stop() self.hide()
class CrawlWindow(QWidget): def __init__(self): super(CrawlWindow, self).__init__() self.resize(325, 500) self.setWindowTitle('支付宝转账码生成器') self.setWindowIcon(QIcon(':reson/maoyan.ico')) # 初始化账户名输入文本框 self.username = QLineEdit(self) # 初始化账号输入文本框 self.account = QLineEdit(self) # 初始化转账金额输入文本框 self.money = QLineEdit(self) # 初始化银行下拉框 self.source_combobox = QComboBox(self) # 初始化启动按钮 self.start_btn = QPushButton(self) # 初始化水平布局 self.h_layout = QHBoxLayout() # 初始化垂直布局 self.v_layout = QVBoxLayout() # 初始化音频播放 self.btn_sound = QSound(':reson/btn.wav', self) self.finish_sound = QSound(':reson/finish.wav', self) # 实例化线程 self.worker = MyThread() # 实例化 self.username_init() self.account_init() self.money_init() self.source_combobox_init() self.start_btn_init() self.layout_init() # 银行名称 代码 self.bankMark = '' self.bankName = '' def username_init(self): """账户名输入文本框初始化配置""" # 设置文本框尺寸 self.username.setFixedSize(300, 35) # 设置默认文本 self.username.setPlaceholderText("请输入账户名") # 限制10个中文字符 self.username.setMaxLength(10) def account_init(self): """账号输入文本框初始化配置""" # 设置文本框尺寸 self.account.setFixedSize(300, 35) # 设置默认文本 self.account.setPlaceholderText("请输入账号") # 限制10个中文字符 self.account.setMaxLength(25) def money_init(self): """金额输入文本框初始化配置""" # 设置文本框尺寸 self.money.setFixedSize(300, 35) # 设置默认文本 self.money.setPlaceholderText("请输入备注") # 限制10个中文字符 self.money.setMaxLength(25) def source_combobox_init(self): """银行选择下拉框配置""" save_list = [ '银行选择', '中国工商银行', '中国农业银行', '中国建设银行', '招商银行', '中国银行', '中国邮政储蓄银行', '交通银行', '中信银行', '中国民生银行', '兴业银行', '浦发银行', '广发银行', '平安银行', '华夏银行', '北京银行', '上海银行', '江苏银行', '北京农商行', '江西银行' ] self.source_combobox.addItems(save_list) self.source_combobox.setFixedSize(300, 35) # 设置标签状态为可用 self.source_combobox.setEnabled(True) # 当下拉索引发生改变时发射信号触发绑定的事件 self.source_combobox.currentTextChanged.connect(self.combobox_slot) def start_btn_init(self): """ 启动按钮按钮 配置""" self.start_btn.setText('启动') self.start_btn.setEnabled(True) self.start_btn.setFixedSize(300, 35) self.start_btn.clicked.connect(self.start_btn_slot) def set_log_init(self): """输出控件 配置""" # 输出至输出文本框 self.worker.log_signal.connect(self.set_log_slot) # 调用清屏槽 self.worker.start_q.connect(self.set_start_slot) def layout_init(self): """页面布局""" # 水平布局 self.h_layout.addWidget(self.start_btn) # 垂直布局 self.v_layout.addWidget(self.username) self.v_layout.addWidget(self.account) self.v_layout.addWidget(self.money) self.v_layout.addWidget(self.source_combobox) self.v_layout.addWidget(self.start_btn) self.setLayout(self.v_layout) def start_btn_slot(self): """程序启动""" if not self.username.text(): self.pop_ups('请输入正确的用户名') return if not self.account.text(): self.pop_ups('请输入正确的银行卡号') return if not self.money.text(): self.pop_ups('请输入正确的金额') return self.btn_sound.play() self.save_to_txt(self.bankMark, self.bankName) # self.log_browser.append('<font color="green">{}程序启动{}</font>'.format('*'*20, '*'*20)) # 启动线程 self.worker.start() self.finish_sound.play() self.pop_ups('支付宝转账码生成成功!') def pop_ups(self, content): """弹窗提示""" QMessageBox.information(self, "消息提示", content, QMessageBox.Yes | QMessageBox.No) def combobox_slot(self, text): if text == '中国工商银行': self.bankMark = 'ICBC' self.bankName = '中国工商银行' elif text == '中国农业银行': self.bankMark = 'ABC' self.bankName = '中国农业银行' elif text == '中国建设银行': self.bankMark = 'CCB' self.bankName = '中国建设银行' elif text == '招商银行': self.bankMark = 'CMB' self.bankName = '招商银行' elif text == '中国银行': self.bankMark = 'BOC' self.bankName = '中国银行' elif text == '中国邮政储蓄银行': self.bankMark = 'PSBC' self.bankName = '中国邮政储蓄银行' elif text == '中信银行': self.bankMark = 'CITIC' self.bankName = '中信银行' elif text == '中国民生银行': self.bankMark = 'CMBC' self.bankName = '中国民生银行' elif text == '交通银行': self.bankMark = 'COMM' self.bankName = '交通银行' elif text == '兴业银行': self.bankMark = 'CIB' self.bankName = '兴业银行' elif text == '浦发银行': self.bankMark = 'SPDB' self.bankName = '浦发银行' elif text == '广发银行': self.bankMark = 'GDB' self.bankName = '广发银行' elif text == '平安银行': self.bankMark = 'SPABANK' self.bankName = '平安银行' elif text == '华夏银行': self.bankMark = 'HXBANK' self.bankName = '华夏银行' elif text == '北京银行': self.bankMark = 'BJBANK' self.bankName = '北京银行' elif text == '上海银行': self.bankMark = 'SHBANK' self.bankName = '上海银行' elif text == '江苏银行': self.bankMark = 'JSBANK' self.bankName = '江苏银行' elif text == '北京农商行': self.bankMark = 'JSRCU' self.bankName = '北京农商行' elif text == '江西银行': self.bankMark = 'NCB' self.bankName = '江西银行' def save_to_txt(self, bankMark, bankName): """保存为txt""" data = [] username = self.username.text() account = self.account.text() money = self.money.text() data.append(username) data.append(account) data.append(money) data.append(bankMark) data.append(bankName) with open('config.txt', 'w+', encoding='utf-8') as f: for i in data: f.write(i) f.write(',') def closeEvent(self, event): """程序退出确认弹窗""" reply = QMessageBox.question(self, '信息', '确认退出吗?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore()
class GameWindow(QWidget): def __init__(self): super().__init__() self.shapes = back_color.get_shapes() self.generate_quiz() self.initUI() self.initTimer() self.initSound() def initSound(self): self.correctSound = QSound('sound/correct.wav') self.incorrectSound = QSound('sound/incorrect.wav') def initTimer(self): self.timer = QTimer() self.timer.setInterval(500) self.timer.timeout.connect(self.timerTick) def timerTick(self): self.timer.stop() self.generate_quiz() self.repaint() def initUI(self): self.text = "Back color" self.setGeometry(0, 0, 260, 340) self.setFixedSize(260, 340) self.show() def paintEvent(self, event): qp = QPainter() qp.begin(self) qp.fillRect(event.rect(), QBrush(QColor("#FFFFFF"))) for shape in self.shapes: brush = QBrush(QColor(shape['color'])) rect = shape['rect'] qp.fillRect(rect[0], rect[1], rect[2], rect[3], brush) qp.setPen(QColor(self.quiz_color)) qp.setFont(QFont('Times New Roman', 20, QFont.Bold)) if self.quiz_type: textRect = QRectF(0, 0, 260, 60) else: textRect = QRectF(0, 280, 260, 60) qp.drawText(textRect, Qt.AlignCenter, self.quiz_text) qp.drawText(textRect, Qt.AlignRight, str(self.quiz_type)) qp.end() def generate_quiz(self): [self.quiz_text, self.quiz_color, self.quiz_type] = back_color.generate_quiz() def mouseReleaseEvent(self, mouseEvent): x = mouseEvent.x() y = mouseEvent.y() if back_color.mouse_press(x, y, self.quiz_text, self.quiz_color, self.quiz_type): self.quiz_text = 'Correct' self.correctSound.play() else: self.quiz_text = 'Incorrect' self.incorrectSound.play() self.timer.start() self.repaint()
class Notifier(QObject): def __init__(self, *, taskModel, frontendSettings, parent): super().__init__(parent) self.__taskModel = taskModel self.__frontendSettings = frontendSettings self._conn = QDBusConnection("Xware Desktop").sessionBus() self._interface = QDBusInterface(_DBUS_NOTIFY_SERVICE, _DBUS_NOTIFY_PATH, _DBUS_NOTIFY_INTERFACE, self._conn) self._notified = {} # a dict of notifyId: taskDict self.__taskModel.taskCompleted.connect(self.notifyTaskCompleted, Qt.DirectConnection) self._capabilities = self._getCapabilities() if "actions" in self._capabilities: successful = self._conn.connect(_DBUS_NOTIFY_SERVICE, _DBUS_NOTIFY_PATH, _DBUS_NOTIFY_INTERFACE, "ActionInvoked", self.slotActionInvoked) if not successful: logging.error("ActionInvoked connect failed.") self._qSound_complete = QSound(":/sound/download-complete.wav", self) @property def isConnected(self): return self._conn.isConnected() @pyqtSlot("QObject", result="void") def notifyTaskCompleted(self, taskItem): if self.__frontendSettings.getbool("notifybysound"): self._qSound_complete.play() if not self.__frontendSettings.getbool("popnotifications"): return self._dbus_notifyCompleted(taskItem) def _getCapabilities(self): # get libnotify server caps and remember it. qdBusMsg = self._interface.call("GetCapabilities") if qdBusMsg.errorName(): logging.error( "cannot get org.freedesktop.Notifications.GetCapabilities") return [] else: return qdBusMsg.arguments()[0] def _dbus_notifyCompleted(self, task: "TaskItem"): if "actions" in self._capabilities: actions = QDBusArgument(["open", "打开", "viewOneFile", "在文件夹中显示"], QMetaType.QStringList) else: actions = QDBusArgument([], QMetaType.QStringList) qdBusMsg = self._interface.call( "Notify", QDBusArgument("Xware Desktop", QMetaType.QString), # app_name QDBusArgument(0, QMetaType.UInt), # replace_id QDBusArgument("xware-desktop", QMetaType.QString), # app_icon QDBusArgument("下载完成", QMetaType.QString), # summary QDBusArgument(task.name, QMetaType.QString), # body actions, { "category": "transfer.complete", }, # hints QDBusArgument(5000, QMetaType.Int), # timeout ) if qdBusMsg.errorName(): logging.error("DBus, notifyTask {}: {}".format( qdBusMsg.errorName(), qdBusMsg.errorMessage())) else: # add it to the dict notificationId = qdBusMsg.arguments()[0] self._notified[notificationId] = task.id @pyqtSlot(QDBusMessage) def slotActionInvoked(self, msg): notifyId, action = msg.arguments() taskId = self._notified.get(notifyId, None) if not taskId: # other applications' notifications return taskItem = self.__taskModel.adapterMap.get(taskId, None) if not taskItem: logging.debug("taskItem cannot be found anymore in TaskModel.") return fullpath = taskItem.fullpath # path + name if action == "open": return systemOpen(fullpath) elif action == "viewOneFile": return viewOneFile(fullpath) elif action == "default": # Unity's notify osd always have a default action. return else: raise Exception( "Unknown action from slotActionInvoked: {}.".format(action))
class CenterOutProtocol(Protocol): def __init__(self, signals, params, name='CenterOut', update_statistics_in_the_end=True, **kwargs): kwargs['name'] = name kwargs['update_statistics_in_the_end'] = update_statistics_in_the_end super().__init__(signals, **kwargs) self.if_vanilla_co = not bool(params[4]) self.if_4_targets = not self.if_vanilla_co #self.if_4_targets = False # params[5] self.soundpath_correct = co_sound_dir_path + '/correct.wav' self.sound_correct = QSound(self.soundpath_correct) self.soundpath_end = co_sound_dir_path + '/end.wav' self.sound_end = QSound(self.soundpath_end) self.sound_end_on = False time_to_target = params[0] show_target_len = params[1] show_turn_len = params[2] time_to_move = params[3] #print('TTT:') #print(self.if_vanilla_co) #print(time_to_target) #print(show_target_len) #print(show_turn_len) #print(time_to_move) num_trials = 40 self.widget_painter = CenterOutProtocolWidgetPainter( self.if_4_targets, self.if_vanilla_co) self.is_half_time = False self.beep = SingleBeep() self.is_first_update = True self.iscenterout = 1 self.cur_state = 0 self.prev_state = 0 self.elapsed = 0 self.cur_par = 0 self.startHover = -1 self.hoverEnough = 0 self.hoverCircle = -1 self.if_last_correct = False self.sound_on = False evnts = [] tmp = [0, 0, 0] self.waitingReturnToCenter = 0 self.time_waiting_start = 0 self.overtime = 0 self.centerHoverMaintained = 0 # Construct events sequence with corresponding times # (start) # - 2s - # center on, outer passive 0 wait # - 2s - # center on, outer show (random) 1 showStart # - 1s - # center on, outer passive 0 wait # - 1s - # center angle (random), outer passive 2 showSpan # - 2s - # center dissapear, outer passive 3 getResponse # - 4s - # -- # timings, types, time to wait on the guessed circle and starting pause (better no less then 4 secs) if (self.if_vanilla_co): # timings=[1.5,3,3] timings = [time_to_target, show_target_len, time_to_move] timings_range = [0.5, 1, 0] # timings_range = [0, 0, 0] types = [0, 1, 3] else: timings = [ time_to_target, show_target_len, show_turn_len, time_to_move ] timings_range = [0.5, 1, 0, 0] # timings=[0.1,0.1,0.1,1,0.1] types = [0, 1, 2, 3] # num_events_trial = len(timings) self.onCircle = 1 start_pause = 5 if (self.if_vanilla_co): options = np.arange(8) else: options = [0, 2, 4, 6] num_types = len(options) num_each_type = num_trials // num_types assert (num_each_type * num_types == num_trials) types_order = np.zeros(num_trials) k = 0 for i in options: types_order[num_each_type * k:num_each_type * (k + 1)] = np.ones(num_each_type) * i k = k + 1 types_order = np.random.permutation(types_order) options_turn = [-4, -2, 0, 2, 4] num_types_turn = len(options_turn) num_each_type_turn = num_trials // num_types_turn assert (num_each_type_turn * num_types_turn == num_trials) types_order_turn = np.zeros(num_trials) k = 0 for i in options_turn: types_order_turn[num_each_type_turn * k:num_each_type_turn * (k + 1)] = np.ones(num_each_type_turn) * i k = k + 1 types_order_turn = np.random.permutation(types_order_turn) tr_num = 0 for i in range(0, num_events_trial * num_trials, num_events_trial): for j in range(num_events_trial): if i == 0 and j == 0: tmp[0] = 0 tmp[1] = start_pause tmp[2] = 0 else: tmp[0] = types[j] tmp[1] = evnts[i + j - 1][1] + random.uniform( timings[j] - timings_range[j], timings[j] + timings_range[j]) if types[j] == 1: if (self.if_4_targets): # options = [0,2,4,6] # mp[2] = options[random.randint(0,3)] tmp[2] = int(types_order[tr_num]) else: # tmp[2]=random.randint(0,7) tmp[2] = int(types_order[tr_num]) elif types[j] == 2: if (self.if_4_targets): # options = [-6,-4,-2,0,2,4,6] # options = [-4, -2, 0, 2, 4] # tmp[2]=options[random.randint(0,4)] tmp[2] = int(types_order_turn[tr_num]) else: tmp[2] = random.randint(-7, 7) # -360 -270 -180 -90 0 90 180 270 360 else: tmp[2] = 0 evnts.append([tmp[k] for k in range(len(tmp))]) tr_num = tr_num + 1 evnts.append([0, evnts[i + j - 1][1] + 2, 0]) evnts.append([5, evnts[i + j - 1][1] + 2, 0]) evnts.append([0, evnts[i + j - 1][1] + 1, 0]) # print(evnts) self.evnts = evnts self.pos_in_events_times = 0 def update_state(self, samples, reward, chunk_size=1, is_half_time=False, samples_counter=None): # if(samples_counter is not None): if (self.is_first_update): self.is_first_update = False self.protocol_start_time = time.time() self.elapsed = 0 self.pos_in_events_times = 0 self.widget_painter.goFullScreen() if (self.waitingReturnToCenter): [self.posx, self.posy] = self.widget_painter.getMousePos() sw = self.widget_painter.checkCenterHover(self.posx, self.posy) if (sw): if (self.centerHoverMaintained): if (time.time() >= self.startHover + self.onCircle): self.waitingReturnToCenter = 0 self.overtime = self.overtime + ( time.time() - self.time_waiting_start) self.time_waiting_start = 0 else: self.startHover = time.time() self.centerHoverMaintained = 1 else: self.centerHoverMaintained = 0 if (self.waitingReturnToCenter == 0): self.elapsed = time.time( ) - self.overtime - self.protocol_start_time self.check_times() [self.posx, self.posy] = self.widget_painter.getMousePos() if self.cur_state == 3: dat = self.widget_painter.checkHover(self.posx, self.posy) if self.hoverEnough == 1: if dat[1] == 0 or self.hoverCircle != dat[0]: self.hoverEnough = -1 self.startHover = -1 else: # mixer.music.play() # winsound.Beep(900, 150) # play(self.sound_correct) #self.if_last_correct = True if self.sound_on == False: # winsound.PlaySound(base64.b64decode(self.sound_correct), winsound.SND_MEMORY) if self.cur_par == self.hoverCircle: self.sound_correct.play() self.sound_on = True # play(self.sound_correct) # winsound.PlaySound(self.soundpath_correct, winsound.SND_FILENAME) # self.widget_painter.showCorrect(self.cur_par,self.hoverCircle,1) elif self.hoverEnough == 0: # self.widget_painter.showCorrect(self.cur_par,self.hoverCircle,0) if dat[1] == 1 and self.hoverCircle == dat[0]: if self.startHover == -1: self.startHover = self.elapsed elif self.elapsed >= self.startHover + self.onCircle: self.hoverEnough = 1 else: self.startHover = -1 self.hoverCircle = dat[0] # if self.cur_state == 0: # if self.if_last_correct: # self.sound_correct.play() # self.if_last_correct = False # if self.sound_on == False: # self.sound_on = True return None, [self.cur_state, self.cur_par, self.posx, self.posy] def check_times(self): if (self.pos_in_events_times < len(self.evnts)): # print(self.elapsed) # print(self.evnts[self.pos_in_events_times][1]) if (self.elapsed > self.evnts[self.pos_in_events_times][1]): self.pos_in_events_times = self.pos_in_events_times + 1 if (self.pos_in_events_times < len(self.evnts)): # self.widget_painter.img.setImage(self.widget_painter.image_0) self.prev_state = self.cur_state # save previous state before we update it self.cur_state = self.evnts[self.pos_in_events_times][0] self.cur_par = self.evnts[self.pos_in_events_times][2] if (self.cur_state == 0) & (self.prev_state == 3): self.waitingReturnToCenter = 1 self.time_waiting_start = time.time() self.startHover = -1 self.hoverEnough = 0 if self.cur_state == 1: self.startSpan = self.cur_par self.sound_on = False elif self.cur_state == 2: self.plusSpan = self.cur_par elif self.cur_state == 3: if (self.if_vanilla_co): self.cur_par = (8 + self.startSpan) % 8 else: self.cur_par = (8 + self.plusSpan + self.startSpan) % 8 self.startHover = -1 self.hoverEnough = 0 elif self.cur_state == 5: print('will try to close protocol') # self.close_protocol() self.experiment.next_protocol() print('tried to close protocol') self.widget_painter.doStuff(self.cur_state, self.cur_par) self.widget_painter.prev_par = self.cur_par self.widget_painter.prev_state = self.cur_state self.check_times() def close_protocol(self, **kwargs): self.is_half_time = False self.beep = SingleBeep() if self.sound_end_on == False: # winsound.PlaySound(base64.b64decode(self.sound_correct), winsound.SND_MEMORY) self.sound_end.play() self.sound_end_on = True self.widget_painter.set_message('') super(CenterOutProtocol, self).close_protocol(**kwargs)
self.viderLayout_main() self.changeJoueurnom() main = self.jeux.listeJoueur[self.jeux.joueurActuel].mainj for i in range(len(main)): d = main[i] for j in range(2): l1 = MyQLabel(self, d) p = QtGui.QPixmap('img/dice' + str(d[j]) + str(d.color) + '.png') l1.setPixmap(p) l1.clicked.connect(self.jeuxjoueur) self.ui.gridLayout_main.addWidget(l1, j, i) def boiteVictoire(self): """une boite de dialogue qui dit qui est le gagnant""" a = QtWidgets.QMessageBox(self) a.setText("victoire du joueur: " + self.jeux.listeJoueur[self.jeux.gagnant].nomjoueur + str(self.jeux.nbpointgagnant)) a.show() a.exec_() if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) s = QSound('gnagna.wav') s.setLoops(-1) s.play() window = jeuxUI() window.show() sys.exit(app.exec_())
class Notifier(QObject): _conn = None _interface = None _notifications = None # a dict of notifyId: taskDict _capabilities = None _completedTasksStat = None def __init__(self, parent): super().__init__(parent) self._conn = QDBusConnection("Xware Desktop").sessionBus() self._interface = QDBusInterface(_DBUS_NOTIFY_SERVICE, _DBUS_NOTIFY_PATH, _DBUS_NOTIFY_INTERFACE, self._conn) self._notifications = {} self._completedTasksStat = app.etmpy.completedTasksStat self._completedTasksStat.sigTaskCompleted.connect(self.notifyTask) self._capabilities = self._getCapabilities() if "actions" in self._capabilities: successful = self._conn.connect(_DBUS_NOTIFY_SERVICE, _DBUS_NOTIFY_PATH, _DBUS_NOTIFY_INTERFACE, "ActionInvoked", self.slotActionInvoked) if not successful: logging.error("ActionInvoked connect failed.") self._qSound_complete = QSound(":/sound/download-complete.wav", self) @property def isConnected(self): return self._conn.isConnected() def notifyTask(self, taskId): task = self._completedTasksStat.getTask(taskId) if task.get("state", None) == 11: # see definitions in class TaskStatistic. if app.settings.getbool("frontend", "notifybysound"): self._qSound_complete.play() self._dbus_notify(task) else: # TODO: Also notify if errors occur pass def _getCapabilities(self): # get libnotify server caps and remember it. qdBusMsg = self._interface.call("GetCapabilities") if qdBusMsg.errorName(): logging.error( "cannot get org.freedesktop.Notifications.GetCapabilities") return [] else: return qdBusMsg.arguments()[0] def _dbus_notify(self, task): if not app.settings.getbool("frontend", "popnotifications"): return if "actions" in self._capabilities: actions = QDBusArgument(["open", "打开", "openDir", "打开文件夹"], QMetaType.QStringList) else: actions = QDBusArgument([], QMetaType.QStringList) qdBusMsg = self._interface.call( "Notify", QDBusArgument("Xware Desktop", QMetaType.QString), # app_name QDBusArgument(0, QMetaType.UInt), # replace_id # app_icon QDBusArgument(os.path.join(constants.FRONTEND_DIR, "thunder.ico"), QMetaType.QString), QDBusArgument("下载完成", QMetaType.QString), # summary QDBusArgument(task["name"], QMetaType.QString), # body actions, { "category": "transfer.complete", }, # hints QDBusArgument(5000, QMetaType.Int), # timeout ) if qdBusMsg.errorName(): logging.error("DBus, notifyTask {}: {}".format( qdBusMsg.errorName(), qdBusMsg.errorMessage())) else: # add it to the dict self._notifications[qdBusMsg.arguments()[0]] = task @pyqtSlot(QDBusMessage) def slotActionInvoked(self, msg): notifyId, action = msg.arguments() task = self._notifications.get(notifyId, None) if not task: # other applications' notifications return name = task["name"] # filename path = task["path"] # location if action == "open": openPath = os.path.join(path, name) elif action == "openDir": openPath = path elif action == "default": # Unity's notify osd always have a default action. return else: raise Exception( "Unknown action from slotActionInvoked: {}.".format(action)) nativeOpenPath = app.mountsFaker.convertToNativePath(openPath) qUrl = QUrl.fromLocalFile(nativeOpenPath) QDesktopServices().openUrl(qUrl)
class GUI(QMainWindow): FRAME_WIDTH = 700 FRAME_HEIGHT = 600 FRAME_BORDER = 20 def __init__(self, config_man: ConfigManager, updater: Updater): super(GUI, self).__init__() self._config_man = config_man self._updater = updater self._subreddit_list = QListWidget() self._subreddit_text_field = QLineEdit() self._subreddit_add_btn = QPushButton() self._subreddit_del_btn = QPushButton() self._filter_text_field = QLineEdit() self._filter_add_btn = QPushButton() self._filter_del_btn = QPushButton() self._filt_rb_include = QRadioButton("Include") self._filt_rb_exclude = QRadioButton("Exclude") self._filter_phrase_list = QListWidget() self._sound_checkbox = CheckBox("Sound", self._sound_notify) self._popup_checkbox = CheckBox("Popup", self._popup_notify) self._notification_checkboxes = [self._sound_checkbox, self._popup_checkbox] self._update_button = QPushButton("Update") self._notification_sound = QSound(self._config_man.properties['notification_sound_path']) self._thread_list = QListWidget() self._status_bar = QStatusBar() self._last_updated_label = QLabel() self._refresh_rate_select = QComboBox() self._popup = None self._init_properties() self._init_layout() self._init_bindings() def _init_layout(self): self.setBaseSize(self.FRAME_WIDTH, self.FRAME_HEIGHT) self.setGeometry(QRect(100, 100, self.FRAME_WIDTH, self.FRAME_HEIGHT)) self._subreddit_list.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) self._subreddit_text_field.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) self._subreddit_add_btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self._subreddit_del_btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self._filter_text_field.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) self._filter_add_btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self._filter_del_btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self._filt_rb_include.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self._filt_rb_exclude.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self._filter_phrase_list.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) for checkbox in self._notification_checkboxes: checkbox.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) self._refresh_rate_select.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) self._update_button.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) subreddit_box = QHBoxLayout() subreddit_box.addWidget(self._subreddit_text_field) subreddit_box.addWidget(self._subreddit_add_btn) subreddit_box.addWidget(self._subreddit_del_btn) filter_box = QHBoxLayout() filter_box.addWidget(self._filter_text_field) filter_box.addWidget(self._filter_add_btn) filter_box.addWidget(self._filter_del_btn) refresh_rate_box = QHBoxLayout() label = QLabel("Refresh rate") label.setFixedSize(70, 20) refresh_rate_box.addWidget(label) refresh_rate_box.addWidget(self._refresh_rate_select) refresh_rate_box.addSpacing(5) label = QLabel("mins") label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) refresh_rate_box.addWidget(label) option_box = QVBoxLayout() label = QLabel("Subreddits") label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) option_box.addWidget(label) option_box.addWidget(self._subreddit_list) option_box.addItem(subreddit_box) option_box.addSpacing(self.FRAME_BORDER) label = QLabel("Filter phrases") label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) option_box.addWidget(label) option_box.addWidget(self._filter_phrase_list) option_box.addItem(filter_box) option_box.addWidget(self._filt_rb_include) option_box.addWidget(self._filt_rb_exclude) option_box.addSpacing(self.FRAME_BORDER) for checkbox in self._notification_checkboxes: option_box.addWidget(checkbox) option_box.addSpacing(self.FRAME_BORDER) option_box.addItem(refresh_rate_box) option_box.addSpacing(self.FRAME_BORDER) option_box.addWidget(self._update_button) self._thread_list.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self._thread_list.setIconSize(QSize(200, 200)) self._thread_list.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel) self._subreddit_list.setSelectionMode(QAbstractItemView.ExtendedSelection) self._filter_phrase_list.setSelectionMode(QAbstractItemView.ExtendedSelection) self._thread_list.setSelectionMode(QAbstractItemView.NoSelection) hbox = QHBoxLayout() hbox.addItem(option_box) hbox.addWidget(self._thread_list) main = QWidget() main.setLayout(hbox) self.setCentralWidget(main) self.setStatusBar(self._status_bar) self._status_bar.addWidget(self._last_updated_label) def _init_bindings(self): self._updater.updater_task.update.connect(self.update_reddit_posts) self._update_button.clicked.connect(self.update_reddit_posts) self._subreddit_text_field.returnPressed.connect(self._add_subreddit) self._filter_add_btn.pressed.connect(self._add_filter_phrase) self._filter_text_field.returnPressed.connect(self._add_filter_phrase) self._filter_del_btn.pressed.connect(self._del_filter_phrase) self._subreddit_add_btn.clicked.connect(self._add_subreddit) self._subreddit_del_btn.clicked.connect(self._del_subreddit) self._sound_checkbox.stateChanged.connect(lambda state: self._config_man.set('sound_notify', state)) self._popup_checkbox.stateChanged.connect(lambda state: self._config_man.set('popup_notify', state)) self._filt_rb_include.toggled.connect(self._change_filter_mode) self._filt_rb_exclude.toggled.connect(self._change_filter_mode) self._refresh_rate_select.currentIndexChanged.connect(lambda rate: self._updater.set_refresh_rate((rate+1)*60)) def _init_properties(self): for sub in self._config_man.properties['subreddits']: self._subreddit_list.addItem(QListWidgetItem(sub.lower())) for phrase in self._config_man.properties['filter_phrases']: self._filter_phrase_list.addItem(QListWidgetItem(phrase)) if self._config_man.properties['filter_mode'] == 'exclude': self._filt_rb_exclude.setChecked(True) else: self._filt_rb_include.setChecked(True) checked = True if self._config_man.properties['sound_notify'] == 2 else False self._sound_checkbox.setChecked(checked) checked = True if self._config_man.properties['popup_notify'] == 2 else False self._popup_checkbox.setChecked(checked) self._last_updated_label.setText("last updated: " + time.strftime("%d/%m/%y %I:%M%p", time.localtime(self._config_man.properties['last_updated']))) self._subreddit_add_btn.setIcon(QIcon("../resources/add_button.png")) self._subreddit_del_btn.setIcon(QIcon("../resources/del_button.png")) self._filter_add_btn.setIcon(QIcon("../resources/add_button.png")) self._filter_del_btn.setIcon(QIcon("../resources/del_button.png")) for i in range(1, 61): self._refresh_rate_select.addItem(str(i)) self._refresh_rate_select.setCurrentText(str(self._config_man.properties['refresh_rate']//60)) def update_reddit_posts(self): try: new_threads = self._updater.update() for thread in new_threads: item = ThreadItem(thread) self._thread_list.addItem(item.stub) self._thread_list.setItemWidget(item.stub, item.delegate) self._thread_list.scrollToBottom() if len(new_threads) != 0: for checkbox in self._notification_checkboxes: checkbox.execute_if_checked() self._last_updated_label.setText("last updated: " + time.strftime("%d/%m/%y %I:%M%p", time.localtime())) except UpdaterException: pass def _add_subreddit(self): entry = self._subreddit_text_field.text().lower().replace(" ", "") if not self._config_man.properties['subreddits'].__contains__(entry) and entry != "": self._subreddit_list.addItem(QListWidgetItem(entry)) self._config_man.properties['subreddits'].append(entry) self._subreddit_text_field.clear() def _add_filter_phrase(self): entry = self._filter_text_field.text().lower() if not self._config_man.properties['filter_phrases'].__contains__(entry) and entry != "": self._filter_phrase_list.addItem(QListWidgetItem(entry)) self._config_man.properties['filter_phrases'].append(entry) self._filter_text_field.clear() def _del_subreddit(self): items = self._subreddit_list.selectedItems() for item in items: row = self._subreddit_list.row(item) self._subreddit_list.takeItem(row) try: self._config_man.properties['subreddits'].remove(item.text()) except ValueError: pass def _del_filter_phrase(self): items = self._filter_phrase_list.selectedItems() for item in items: row = self._filter_phrase_list.row(item) self._filter_phrase_list.takeItem(row) try: self._config_man.properties['filter_phrases'].remove(item.text()) except ValueError: pass def closeEvent(self, a0): self._config_man.save() def _sound_notify(self): if self._config_man.properties['notification_sound_path'] == "": winsound.MessageBeep() else: self._notification_sound.play() def _popup_notify(self): self._popup = QMessageBox(QMessageBox.NoIcon, "Reddit Monitor", "") self._popup.show() self._popup.setWindowState(self._popup.windowState() & ~Qt.WindowMinimized | Qt.WindowActive) self._popup.activateWindow() def _change_filter_mode(self): if self._filt_rb_exclude.isChecked(): self._config_man.set('filter_mode', 'exclude') else: self._config_man.set('filter_mode', 'include')
class Notifier(QObject): _conn = None _interface = None _notifications = None # a dict of notifyId: taskDict _completedTasksStat = None def __init__(self, parent): super().__init__(parent) self._conn = QDBusConnection("Xware Desktop").sessionBus() self._interface = QDBusInterface(_DBUS_NOTIFY_SERVICE, _DBUS_NOTIFY_PATH, _DBUS_NOTIFY_INTERFACE, self._conn) self._notifications = {} self._completedTasksStat = app.etmpy.completedTasksStat self._completedTasksStat.sigTaskCompleted.connect(self.notifyTask) successful = self._conn.connect(_DBUS_NOTIFY_SERVICE, _DBUS_NOTIFY_PATH, _DBUS_NOTIFY_INTERFACE, "ActionInvoked", self.slotActionInvoked) if not successful: logging.error("ActionInvoked connect failed.") self._qSound_complete = QSound(":/sound/download-complete.wav", self) @property def isConnected(self): return self._conn.isConnected() def notifyTask(self, taskId): task = self._completedTasksStat.getTask(taskId) if task.get("state", None) == 11: # see definitions in class TaskStatistic. if app.settings.getbool("frontend", "notifybysound"): self._qSound_complete.play() self._dbus_notify(task) else: # TODO: Also notify if errors occur pass def _dbus_notify(self, task): if not app.settings.getbool("frontend", "popnotifications"): return qdBusMsg = self._interface.call( "Notify", QDBusArgument("Xware Desktop", QMetaType.QString), # app_name QDBusArgument(0, QMetaType.UInt), # replace_id QDBusArgument("/opt/xware_desktop/frontend/thunder.ico", QMetaType.QString), # app_icon QDBusArgument("下载完成", QMetaType.QString), # summary QDBusArgument(task["name"], QMetaType.QString), # body QDBusArgument(["open", "打开", "openDir", "打开文件夹"], QMetaType.QStringList), # actions, { "category": "transfer.complete", }, # hints QDBusArgument(5000, QMetaType.Int), # timeout ) if qdBusMsg.errorName(): logging.error("DBus, notifyTask {}: {}".format(qdBusMsg.errorName(), qdBusMsg.errorMessage())) else: # add it to the dict self._notifications[qdBusMsg.arguments()[0]] = task @pyqtSlot(QDBusMessage) def slotActionInvoked(self, msg): notifyId, action = msg.arguments() task = self._notifications.get(notifyId, None) if not task: # other applications' notifications return name = task["name"] # filename path = task["path"] # location if action == "open": openPath = os.path.join(path, name) elif action == "openDir": openPath = path else: raise Exception("Unknown action from slotActionInvoked.") nativeOpenPath = app.mountsFaker.convertToNativePath(openPath) qUrl = QUrl.fromLocalFile(nativeOpenPath) QDesktopServices().openUrl(qUrl)
class MainWindow(DATA[0], DATA[1]): def __init__(self): super().__init__() self.setupUi(self) self.scrollArea.hide() self.label_6.hide() self.pushButton.clicked.connect(self.iniciar_sesion) self.setWindowTitle("PrograPop") self.scrollArea_2.hide() self.label_tiempo = QLabel("20", self) self.label_tiempo.move(500, 300) self.label_tiempo.resize(100,100) self.label_tiempo.setFont(QFont("SansSerif", 20)) self.label_tiempo.hide() self.song_name = None self.song = None self.salas = [{"name": "Recibiendo Canciones, pulsa actualizar!", "usuarios":[], "artistas": "None", "tiempo_restante": 0}] self.a = 0 self.chat = QListWidget(self) self.chat.resize(1000, 300) self.chat.move(30,370) self.chat.hide() self.puntajes = None self.login = False def iniciar_sesion(self): self.name = self.lineEdit.text() self.setWindowTitle("PrograPop ({})".format(self.name)) self.usuario_back = BE_Client.Client_Back(self) while not self.login: pass time.sleep(2) self.usuario_back.get_salas() time.sleep(2) self.usuario_back.get_info() time.sleep(0.2) self.label_6.setText("Bienvenido {}\nTienes {} puntos".format(self.name, self.usuario_back.puntos)) self.label_6.show() self.lineEdit.hide() self.label_2.hide() self.pushButton.hide() self.titulo.setText("Elige una Sala") self.label_inferior = QLabel("Haz click sobre una sala para ingresar", self) self.label_inferior.move(500,200) self.label_inferior.show() self.lista_items = QListWidget(self) for item in self.salas: self.lista_items.addItem("Sala : {}, Usuarios: {}, artistas: {}, tº restante: {}".format(item["name"], len(item["usuarios"]), item["artistas"], item["tiempo_restante"])) self.lista_items.show() self.lista_items.resize(600,200) self.lista_items.move(300,200) self.lista_items.itemClicked.connect(self.conectarse_sala) self.actualizar = QPushButton("Actualizar", self) self.actualizar.move(1000, 100) self.actualizar.show() self.actualizar.clicked.connect(self.actualizar_salas) self.tabla_de_puntos = QPushButton("Tabla de puntajes", self) self.tabla_de_puntos.move(40, 600) self.tabla_de_puntos.resize(200,20) self.tabla_de_puntos.show() self.tabla_de_puntos.clicked.connect(self.puntos_dialog) def conectarse_sala(self, item): self.label_inferior.hide() self.tabla_de_puntos.hide() self.lista_items.hide() name = item.text().split(",")[0].split(":")[1].replace(" ", "") self.sala_actual = name self.usuario_back.connect_sala(name) self.usuario_back.get_info() self.scrollArea.hide() self.titulo.setText(name) self.label_6.hide() self.actualizar.hide() self.volver = QPushButton("Salir", self) self.volver.move(30, 30) self.volver.clicked.connect(self.volver_menu) self.volver.show() # Tabla de puntajes self.tabla_puntajes_sala = QListWidget(self) self.tabla_puntajes_sala.resize(200, 100) self.tabla_puntajes_sala.move(930, 200) self.tabla_puntajes_sala.addItem("Puntajes") self.tabla_puntajes_sala.show() # CHAT self.chat.show() self.chat.addItem("Chat") self.line_chat = QLineEdit(self) self.line_chat.move(40, 690) self.line_chat.resize(1000, 30) self.chatButton = QPushButton("Enviar", self) self.chatButton.move(1050, 690) self.chatButton.show() self.line_chat.show() self.chatButton.clicked.connect(self.enviar_mensaje) # Tabla de tiempos self.sala_tabla = QListWidget(self) self.sala_tabla.resize(200,100) self.sala_tabla.move(930,30) self.sala_tabla.addItem("Tiempos") self.sala_tabla.show() # Juego self.opcion1 = QPushButton("opcion1", self) self.opcion2 = QPushButton("opcion2", self) self.opcion3 = QPushButton("opcion3 ", self) self.opcion1.move(30, 200) self.opcion2.move(400, 200) self.opcion3.move(700, 200) self.opcion1.resize(200,30) self.opcion2.resize(200, 30) self.opcion3.resize(200, 30) self.opcion1.clicked.connect(self.opcion_selecta) self.opcion2.clicked.connect(self.opcion_selecta) self.opcion3.clicked.connect(self.opcion_selecta) while self.sala_actual != None: while not self.song_name: pass self.song = QSound(self.song_name) self.song_name = None self.song.play() self.label_tiempo.show() self.opcion1.show() self.opcion2.show() self.opcion3.show() QTest.qWait(1000) QTest.qWait(1000) self.label_tiempo.setText("19") QTest.qWait(1000) self.label_tiempo.setText("19") QTest.qWait(1000) self.label_tiempo.setText("17") QTest.qWait(1000) self.label_tiempo.setText("16") QTest.qWait(1000) self.label_tiempo.setText("15") QTest.qWait(1000) self.label_tiempo.setText("14") QTest.qWait(1000) self.label_tiempo.setText("13") QTest.qWait(1000) self.label_tiempo.setText("12") QTest.qWait(1000) self.label_tiempo.setText("11") QTest.qWait(1000) self.label_tiempo.setText("10") QTest.qWait(1000) self.label_tiempo.setText("9") QTest.qWait(1000) self.label_tiempo.setText("8") QTest.qWait(1000) self.label_tiempo.setText("7") QTest.qWait(1000) self.label_tiempo.setText("6") QTest.qWait(1000) self.label_tiempo.setText("5") QTest.qWait(1000) self.label_tiempo.setText("4") QTest.qWait(1000) self.label_tiempo.setText("3") QTest.qWait(1000) self.label_tiempo.setText("2") QTest.qWait(1000) self.label_tiempo.setText("1") QTest.qWait(1000) self.opcion1.hide() self.opcion2.hide() self.opcion3.hide() self.sala_tabla.clear() self.sala_tabla.addItem("Tiempos") self.label_tiempo.hide() self.label_tiempo.setText("20") self.chat.addItem("Server: Preparate para la siguiente ronda") self.song.stop() QTest.qWait(1000) def actualizar_salas(self): self.lista_items.clear() self.usuario_back.get_salas() time.sleep(0.2) for item in self.salas: self.lista_items.addItem("Sala : {}, Usuarios: {}, artistas: {}, tº restante : {}".format(item["name"], len(item["usuarios"]), item["artistas"], item["tiempo_restante"])) def volver_menu(self): self.tabla_puntajes_sala.clear() self.tabla_puntajes_sala.addItem("Puntajes") self.tabla_puntajes_sala.hide() self.sala_tabla.clear() self.sala_tabla.hide() self.tabla_de_puntos.show() self.chat.clear() self.chat.hide() self.usuario_back.get_salas() time.sleep(0.2) self.usuario_back.disconnect_sala(self.sala_actual) time.sleep(0.2) self.usuario_back.get_info() time.sleep(0.2) self.sala_actual = None self.song.stop() self.titulo.setText("Elige una Sala") self.label_6.setText("Bienvenido {}\nTienes {} puntos".format(self.name, self.usuario_back.puntos)) self.label_6.show() self.label.setText("Nombre: {} - Usuarios : {} - Artistas : {}" .format(self.salas[0]["name"], len(self.salas[0]["usuarios"]), self.salas[0]["artistas"])) self.lista_items.show() self.actualizar.show() self.volver.hide() self.line_chat.hide() self.chatButton.hide() self.scrollArea_2.hide() self.opcion1.hide() self.opcion2.hide() self.opcion3.hide() def enviar_mensaje(self): mensaje = self.line_chat.text() self.line_chat.setText("") self.usuario_back.chat(mensaje, self.sala_actual) def opcion_selecta(self): boton = self.sender() self.opcion1.hide() self.opcion2.hide() self.opcion3.hide() self.usuario_back.desicion(boton.text()) def puntos_dialog(self): dialog = QDialog(self) dialog.resize(500,500) tabla1 = QListWidget(dialog) tabla1.resize(150,400) tabla1.move(20,20) tabla1.addItem("Tabla de Puntajes") dialog.setWindowTitle("Puntajes - Presiona Esc para salir") self.usuario_back.get_puntajes() while not self.puntajes: pass for item in self.puntajes: tabla1.addItem("{} : {} puntos".format(item[0], item[1])) tabla1.show() label_facil = QLabel("Sala mas facil : {}".format(self.sala_facil), dialog) label_dificil = QLabel("Sala mas dificl: {}".format(self.sala_dificl), dialog) label_dificil.move(300,50) label_facil.move(300, 250) label_dificil.show() label_facil.show() dialog.show()