class Round(EstadoTimer): gong = QSound('sounds/gong.wav') beep = QSound('sounds/beep-7.wav') next_beep = 10 def __init__(self, numero=1, minutos=2, segundos=0, label=None, window=None): self.numero = numero super(Round, self).__init__(minutos=minutos, segundos=segundos, label=label, window=window) def __str__(self): return "Round "+str(self.numero) def timerEvent(self, event): elapsed_time = time.time() - self.start_time segundos = self.segundos - elapsed_time if segundos <= self.next_beep and self.next_beep > 0: self.next_beep -= 1 self.beep.play() if segundos < 0: segundos = 0 self.set_text(segundos/60, segundos%60, (segundos%1)*100) if segundos == 0: self.gong.play() self.emit(SIGNAL("ESTADO_TIMER_FINALIZADO")) self.timer.stop()
def timed_job(self): conn = sqlite3.connect('serm.db') with conn: df = pd.read_sql_query("SELECT * from data", conn); df.humidity = np.array(df.humidity.astype(float)) df.temperature = np.array(df.temperature.astype(float)) df.smoke = np.array(df.smoke.astype(float)) df.co = np.array(df.co.astype(float)) df.lpg = np.array(df.lpg.astype(float)) df.windspeed = np.array(df.windspeed.astype(float)) df.ffwi = np.array(df.ffwi.astype(float)) datetm = calendar.timegm(time.strptime(str(time.strftime('%Y-%m-%d %H:%M:%S')), '%Y-%m-%d %H:%M:%S')) datedt = time.strftime('%Y-%m-%d %H:%M:%S') winddir = df.winddir.tail(1).iget(0) predict_risk.input['FFWI'] = df.ffwi.mean() predict_risk.input['SMOKE'] = df.smoke.mean() predict_risk.compute() risk = predict_risk.output['RISK'] conn.execute("INSERT INTO data_means(timestamp,datetime,smoke,lpg,co,temperature,humidity,windspeed,winddir,ffwi,risk) VALUES (?,?,?,?,?,?,?,?,?,?,?)", (datetm,datedt,round(df.smoke.mean(),3),round(df.lpg.mean(),3),round(df.co.mean(),3),round(df.temperature.mean(),3),round(df.humidity.mean(),3),round(df.windspeed.mean(),3),winddir,round(df.ffwi.mean(),3),round(risk,3))) conn.commit() sql = "DELETE FROM data WHERE recid <= ( SELECT recid FROM (SELECT recid FROM data ORDER BY recid DESC LIMIT 1 OFFSET 20)foo)" conn.execute(sql) conn.commit() # self.lcdNumber_ffwi.display(str(round(df.ffwi.mean(),-1))) self.lcdNumber_ffwi.display(str(df.ffwi.mean())) self.lcdNumber_risk.display((risk)) palette = QtGui.QPalette() if risk < 10: palette.setColor(QtGui.QPalette.Foreground,QtCore.Qt.green) self.lbl_RiskStateValue.setPalette(palette) self.lbl_RiskStateValue.setText("LOW") elif risk >= 10 and risk < 30: palette.setColor(QtGui.QPalette.Foreground,QtCore.Qt.yellow) self.lbl_RiskStateValue.setPalette(palette) self.lbl_RiskStateValue.setText("AVERAGE") else: palette.setColor(QtGui.QPalette.Foreground,QtCore.Qt.red) self.lbl_RiskStateValue.setPalette(palette) self.lbl_RiskStateValue.setText("HIGH") sound = QSound("smoke-detector-1.wav") sound.play()
class Descanso(EstadoTimer): beep_descanso = QSound('sounds/beep-9.wav') rest_beep = 10 play_beep = True def __init__(self, minutos=1, segundos=0, label=None, window=None): super(Descanso, self).__init__(minutos=minutos, segundos=segundos, label=label, window=window) def __str__(self): return "Descanso" def timerEvent(self, event): elapsed_time = time.time() - self.start_time segundos = self.segundos - elapsed_time if segundos <= self.rest_beep and self.play_beep == True: self.play_beep = False self.beep_descanso.play() if segundos < 0: segundos = 0 self.set_text(segundos/60, segundos%60, (segundos%1)*100) if segundos == 0: self.emit(SIGNAL("ESTADO_TIMER_FINALIZADO")) self.timer.stop()
def play(self): (opened, file) = tempfile.mkstemp() os.close(opened) if self.captured_area_container.is_released: self._played_start = self.captured_area_container.start wave_state = self.wave_state.get_part(self._played_start, len(self.wave_state)) else: self._played_start = 0 wave_state = self.wave_state wave_state.save_to_file(file) self._q_sound_object = QSound(file) self._temp_sound_file = file self._q_sound_object.play() self._time_of_start = time.time() self._play_sound_timer.start(Track.UPDATE_PLAYING_TRACK_TIME)
def _drawAttentionWindows(self, audioFile, openTray): if openTray: try: ctypes.windll.WINMM.mciSendStringW(u"set cdaudio door open", None, 0, None) except: self.logger.exception("notify error: eject error (open)") try: from PyQt4.QtGui import QSound q = QSound(audioFile) q.play() except: self.logger.exception("notify error: sound") if openTray: try: ctypes.windll.WINMM.mciSendStringW(u"set cdaudio door open", None, 0, None) except: self.logger.exception("notify error: eject error (close)")
def __init__(self): super(MainWindow, self).__init__() self.setupUi(self) self.timer = QTimer(self) self.timer.setInterval(self.INTERVAL) self.timer.timeout.connect(self.capture) self.camera = cv2.VideoCapture() self.image = None self.sound = QSound('alert.wav') self.sound.setLoops(2) self.monitor_last_shoot = None self.frame = None self.video = None self.prev_frame = None self.motion_history = None self.hsv = None self.is_recording = False self.is_monitoring = False self.threshold_spin.setValue(self.DEFAULT_THRESHOLD) self.shoot_delay_spin.setValue(self.DEFAULT_MONITOR_DELAY) self.shoot_button.setEnabled(False) self.record_button.setEnabled(False) self.monitor_button.setEnabled(False) self.visual_radio_1.setEnabled(False) self.visual_radio_2.setEnabled(False) self.visual_radio_3.setEnabled(False) self.visual_radio_4.setEnabled(False) self.threshold_label.setEnabled(False) self.threshold_spin.setEnabled(False) self.threshold_slider.setEnabled(False) self.record_check.setEnabled(False) self.shoot_check.setEnabled(False) self.shoot_delay_label.setEnabled(False) self.shoot_delay_spin.setEnabled(False) self.shoot_delay_slider.setEnabled(False) self.sound_check.setEnabled(False) self.open_button.clicked.connect(self.open_camera) self.shoot_button.clicked.connect(self.shoot) self.record_button.clicked.connect(self.start_record) self.monitor_button.clicked.connect(self.start_monitor) self.record_check.toggled.connect(self.record_toggled) self.shoot_check.toggled.connect(self.shoot_toggled)
def __init__(self): if (SoundManager.instance is None): SoundManager.instance = self else: return SoundClass = None self.play_func = None self.stop_func = None self.available = True if (QSound.isAvailable()): SoundClasse = QSound self.play_func = pyqt_play_sound self.stop_func = pyqt_stop_sound else: try: import pygame pygame.init() pygame.mixer.set_num_channels(12) SoundClass = pygame.mixer.Sound self.play_func = pygame_play_sound self.stop_func = pygame_stop_sound except: QMessageBox.warning(None,'PyAsteroids - Sound', 'This platform does not provide sound facilites through Qt nor PyGame. \ Sound is disabled') self.available = False return self.sounds = {} for sec in ConfigManager.getSections('sounds'): self.sounds[sec] = {} for audio_descr in ConfigManager.getOptions('sounds', sec): file, vol = map(str.strip, ConfigManager.getVal('sounds',sec,audio_descr).split('||')) vol = float(vol) sound = SoundClass(file) if (not (SoundClass is QSound)): sound.set_volume(vol) self.sounds[sec][audio_descr] = sound
class MainWindow(QMainWindow, Ui_MainWindow): INTERVAL = 1000/24 # 单位为毫秒 MHI_DURATION = 0.5 DEFAULT_THRESHOLD = 32 MAX_TIME_DELTA = 0.25 MIN_TIME_DELTA = 0.05 VIDEO_FOLDER = 'video' PHOTO_FOLDER = 'photo' DEFAULT_MONITOR_DELAY = 5 # 单位为秒 def __init__(self): super(MainWindow, self).__init__() self.setupUi(self) self.timer = QTimer(self) self.timer.setInterval(self.INTERVAL) self.timer.timeout.connect(self.capture) self.camera = cv2.VideoCapture() self.image = None self.sound = QSound('alert.wav') self.sound.setLoops(2) self.monitor_last_shoot = None self.frame = None self.video = None self.prev_frame = None self.motion_history = None self.hsv = None self.is_recording = False self.is_monitoring = False self.threshold_spin.setValue(self.DEFAULT_THRESHOLD) self.shoot_delay_spin.setValue(self.DEFAULT_MONITOR_DELAY) self.shoot_button.setEnabled(False) self.record_button.setEnabled(False) self.monitor_button.setEnabled(False) self.visual_radio_1.setEnabled(False) self.visual_radio_2.setEnabled(False) self.visual_radio_3.setEnabled(False) self.visual_radio_4.setEnabled(False) self.threshold_label.setEnabled(False) self.threshold_spin.setEnabled(False) self.threshold_slider.setEnabled(False) self.record_check.setEnabled(False) self.shoot_check.setEnabled(False) self.shoot_delay_label.setEnabled(False) self.shoot_delay_spin.setEnabled(False) self.shoot_delay_slider.setEnabled(False) self.sound_check.setEnabled(False) self.open_button.clicked.connect(self.open_camera) self.shoot_button.clicked.connect(self.shoot) self.record_button.clicked.connect(self.start_record) self.monitor_button.clicked.connect(self.start_monitor) self.record_check.toggled.connect(self.record_toggled) self.shoot_check.toggled.connect(self.shoot_toggled) def record_toggled(self): if self.record_check.isChecked() and self.shoot_check.isChecked(): self.shoot_check.setChecked(False) self.monitor_last_shoot = clock() self.shoot_delay_label.setText('录像最短时间') if not self.record_check.isChecked() and self.is_recording: self.stop_record() def shoot_toggled(self): # if not self.shoot_check.isChecked(): # self.shoot_delay_spin.setEnabled(False) # self.shoot_delay_slider.setEnabled(False) if self.shoot_check.isChecked(): self.shoot_delay_spin.setEnabled(True) self.shoot_delay_slider.setEnabled(True) self.shoot_delay_label.setText('拍照间隔') if self.record_check.isChecked(): self.record_check.setChecked(False) def open_camera(self): self.camera.open(0) assert self.camera.isOpened() self.timer.start() self.open_button.setText('关闭摄像头(&O)') self.shoot_button.setEnabled(True) self.record_button.setEnabled(True) self.monitor_button.setEnabled(True) self.open_button.clicked.disconnect(self.open_camera) self.open_button.clicked.connect(self.close_camera) def close_camera(self): if self.is_recording: self.stop_record() if self.is_monitoring: self.stop_monitor() self.timer.stop() self.camera.release() self.image = QImage() self.screen.setPixmap(QPixmap.fromImage(self.image)) self.open_button.setText('打开摄像头(&O)') self.shoot_button.setEnabled(False) self.record_button.setEnabled(False) self.monitor_button.setEnabled(False) self.open_button.clicked.disconnect(self.close_camera) self.open_button.clicked.connect(self.open_camera) #self.open_button.setWindowTitle('打开摄像头') def shoot(self): filename = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '.jpg' filepath = os.path.join(self.PHOTO_FOLDER, filename) if not os.path.exists(self.PHOTO_FOLDER): os.makedirs(self.PHOTO_FOLDER) if cv2.imwrite(filepath, self.frame): print('saved to %s' % filepath) def start_record(self): filename = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '.avi' filepath = os.path.join(self.VIDEO_FOLDER, filename) if not os.path.exists(self.VIDEO_FOLDER): os.makedirs(self.VIDEO_FOLDER) fourcc = CV_FOURCC(ord('X'), ord('2'), ord('6'), ord('4')) self.video = cv2.VideoWriter(filepath, fourcc, 6, (640, 480)) print('start recording...') print('saving to %s' % filepath) self.is_recording = True self.record_button.setText('停止(&R)') self.record_button.clicked.disconnect(self.start_record) self.record_button.clicked.connect(self.stop_record) def stop_record(self): print('stop record') self.is_recording = False self.video.release() self.record_button.setText('录像(&R)') self.record_button.clicked.disconnect(self.stop_record) self.record_button.clicked.connect(self.start_record) def capture(self): ret, frame = self.camera.read() self.frame = frame if self.is_recording: #frame = cv2.flip(frame, 0) self.video.write(frame) if self.is_monitoring: frame = self.detect() if self.is_recording: delay = self.shoot_delay_spin.value() print(clock() - self.monitor_last_shoot) if clock() - self.monitor_last_shoot >= delay: self.stop_record() self.display(frame) def display(self, frame): height, width, bytes_per_component = frame.shape bytes_per_line = bytes_per_component * width #print(width, height) self.image = QImage(frame.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped() self.screen.setPixmap(QPixmap.fromImage(self.image)) def start_monitor(self): height, width = self.frame.shape[:2] self.prev_frame = self.frame.copy() self.motion_history = np.zeros((height, width), np.float32) self.hsv = np.zeros((height, width, 3), np.uint8) self.hsv[:, :, 1] = 255 print('start monitor...') self.is_monitoring = True self.monitor_button.setText('停止监控(&M)') self.record_button.setEnabled(False) self.visual_radio_1.setEnabled(True) self.visual_radio_2.setEnabled(True) self.visual_radio_3.setEnabled(True) self.visual_radio_4.setEnabled(True) self.threshold_label.setEnabled(True) self.threshold_spin.setEnabled(True) self.threshold_slider.setEnabled(True) self.record_check.setEnabled(True) self.shoot_check.setEnabled(True) self.shoot_delay_label.setEnabled(True) self.shoot_delay_spin.setEnabled(True) self.shoot_delay_slider.setEnabled(True) self.sound_check.setEnabled(True) self.monitor_button.clicked.disconnect(self.start_monitor) self.monitor_button.clicked.connect(self.stop_monitor) def stop_monitor(self): print('stop monitor...') self.is_monitoring = False if self.is_recording: self.stop_record() self.monitor_button.setText('开始监控(&M)') self.record_button.setEnabled(True) self.visual_radio_1.setEnabled(False) self.visual_radio_2.setEnabled(False) self.visual_radio_3.setEnabled(False) self.visual_radio_4.setEnabled(False) self.threshold_label.setEnabled(False) self.threshold_spin.setEnabled(False) self.threshold_slider.setEnabled(False) self.record_check.setEnabled(False) self.shoot_check.setEnabled(False) self.shoot_delay_label.setEnabled(False) self.shoot_delay_spin.setEnabled(False) self.shoot_delay_slider.setEnabled(False) self.sound_check.setEnabled(False) self.monitor_button.clicked.disconnect(self.stop_monitor) self.monitor_button.clicked.connect(self.start_monitor) def detect(self): # print('detect...') # visuals = ['input', 'frame_diff', 'motion_hist', 'grad_orient'] # cv2.createTrackbar('visual', 'motempl', 2, len(visuals)-1, nothing) # cv2.createTrackbar('threshold', 'motempl', DEFAULT_THRESHOLD, 255, nothing) height, width = self.frame.shape[:2] frame_diff = cv2.absdiff(self.frame, self.prev_frame) gray_diff = cv2.cvtColor(frame_diff, cv2.COLOR_BGR2GRAY) thrs = self.threshold_spin.value() # thrs = cv2.getTrackbarPos('threshold', 'motempl') ret, motion_mask = cv2.threshold(gray_diff, thrs, 1, cv2.THRESH_BINARY) timestamp = clock() cv2.updateMotionHistory(motion_mask, self.motion_history, timestamp, self.MHI_DURATION) mg_mask, mg_orient = cv2.calcMotionGradient(self.motion_history, self.MAX_TIME_DELTA, self.MIN_TIME_DELTA, apertureSize=5) seg_mask, seg_bounds = cv2.segmentMotion(self.motion_history, timestamp, self.MAX_TIME_DELTA) for radio in (self.visual_radio_1, self.visual_radio_2, self.visual_radio_3, self.visual_radio_4): if radio.isChecked(): visual_name = str(radio.text()) break # visual_name = visuals[cv2.getTrackbarPos('visual', 'motempl')] # visual_name = 'input' if visual_name == 'input': vis = self.frame.copy() elif visual_name == 'frame_diff': vis = frame_diff.copy() elif visual_name == 'motion_hist': vis = np.uint8(np.clip((self.motion_history-(timestamp-self.MHI_DURATION)) / self.MHI_DURATION, 0, 1)*255) vis = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR) elif visual_name == 'grad_orient': self.hsv[:, :, 0] = mg_orient/2 self.hsv[:, :, 2] = mg_mask*255 vis = cv2.cvtColor(self.hsv, cv2.COLOR_HSV2BGR) for i, rect in enumerate([(0, 0, width, height)] + list(seg_bounds)): x, y, rw, rh = rect area = rw*rh if area < 64**2: continue silh_roi = motion_mask[y:y+rh, x:x+rw] orient_roi = mg_orient[y:y+rh, x:x+rw] mask_roi = mg_mask[y:y+rh, x:x+rw] mhi_roi = self.motion_history[y:y+rh, x:x+rw] if cv2.norm(silh_roi, cv2.NORM_L1) < area*0.05: continue angle = cv2.calcGlobalOrientation(orient_roi, mask_roi, mhi_roi, timestamp, self.MHI_DURATION) color = ((255, 0, 0), (0, 0, 255))[i == 0] self.draw_motion_comp(vis, rect, angle, color) if i == 0: # 检测到目标运动 if self.record_check.isChecked(): self.monitor_last_shoot = clock() if not self.is_recording: self.start_record() elif self.shoot_check.isChecked(): # print(self.monitor_last_shoot) # print(clock()) delay = self.shoot_delay_spin.value() if (not self.monitor_last_shoot) or (clock() - self.monitor_last_shoot >= delay): self.shoot() self.monitor_last_shoot = clock() if self.sound_check.isChecked(): self.play_sound() self.draw_str(vis, (20, 20), visual_name) self.prev_frame = self.frame.copy() return vis @staticmethod def draw_motion_comp(vis, (x, y, w, h), angle, color): cv2.rectangle(vis, (x, y), (x+w, y+h), (0, 255, 0)) r = min(w/2, h/2) cx, cy = x+w/2, y+h/2 angle = angle*np.pi/180 cv2.circle(vis, (cx, cy), r, color, 3) cv2.line(vis, (cx, cy), (int(cx+np.cos(angle)*r), int(cy+np.sin(angle)*r)), color, 3)
def Play(self): QSound.play("fly-high.mp3")
def measurementStopped(self): finishedSound = QSound('sounds/finished.wav') finishedSound.play() self.prepareInterfaceToStart()
def setupSounds(self): self.beep = QSound("sounds/beep.wav") self.buzzer = QSound("sounds/buzzer.wav")
class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setupUi(self) def keyPressEvent(self, event): if type(event) == QKeyEvent: if self.isBuzzer(event.text()): if not self.teamIsHighlighted(): if not self.timeUp: for team in self.teamObjectList: if event.text() in team.buzzerList: buzzerIndex = team.buzzerList.index( event.text()) playerIndex = int( team.activePlayerList[buzzerIndex]) playerPicture = team.playerPictureList[ playerIndex] playerName = team.playerNameList[playerIndex] self.currentBuzzedPlayerId = team.playerIdList[ buzzerIndex] teamWidget = team.teamWidget self.buzzed(playerPicture, playerName, teamWidget) else: self.functionHandler(event.text()) def bonusModeChooser(self, points): if config.bonusMode: self.changeScore(points) else: self.changeScoreFinal(points) def buzzed(self, playerPicture, playerName, teamWidget): self.beep.play() self.changePlayerWidget(playerPicture, playerName) self.highlightTeam(teamWidget) def blankPlayerWidget(self): self.playerWidget.updateWidget(config.blankPlayerPicture, '') def changePlayerWidget(self, picture, name): self.playerWidget.updateWidget(picture, name) def changeScoreBonus(self, scoreChange): for team in self.teamObjectList: if team.teamWidget.isHighlighted() and team.teamWidget.isBonus(): team.teamWidget.setScore(team.teamWidget.getScore() + scoreChange) self.deHighlightTeam(team.teamWidget) team.teamWidget.bonusOff() self.blankPlayerWidget() def changeScoreTossup(self, scoreChange): for team in self.teamObjectList: if team.teamWidget.isHighlighted( ) and not team.teamWidget.isBonus(): teamNumber = self.teamObjectList.index(team) + 1 score = team.teamWidget.getScore() + scoreChange team.teamWidget.setScore(score) from modules import databaseaccess databaseaccess.submit_Score(self.gameId, self.questionNumber, self.currentBuzzedPlayerId, scoreChange, teamNumber) if config.bonusMode: team.teamWidget.bonusOn() else: self.clearBuzzers() def changeScoreTossupNeg(self, scoreChange): for team in self.teamObjectList: if team.teamWidget.isHighlighted( ) and not team.teamWidget.isBonus(): teamNumber = self.teamObjectList.index(team) + 1 score = team.teamWidget.getScore() + scoreChange team.teamWidget.setScore(score) from modules import databaseaccess databaseaccess.submit_Score(self.gameId, self.questionNumber, self.currentBuzzedPlayerId, scoreChange, teamNumber) self.clearBuzzers() def clearBuzzers(self): self.stopTimer() self.setTimerDisplay(5) self.timeUp = False self.currentBuzzedPlayerId = "" for team in self.teamObjectList: if team.teamWidget.isHighlighted(): self.deHighlightTeam(team.teamWidget) team.teamWidget.bonusOff() self.blankPlayerWidget() def constructTeams(self, team1, team2): self.teamObjectList = [] """ for team in config.teamList: teamFile = open(team, 'r') teamName = teamFile.readline().rstrip() playerPictureList = [] playerNameList = [] for line in teamFile: lineList = line.rstrip().split() playerNameList.append(lineList[0]) playerPictureList.append(team.rsplit('/', 1)[0] + '/' + lineList[1]) teamFile.close() """ """ ##buzzerList = config.buzzerList[config.teamList.index(team)] activePlayerList = config.activePlayerList[config.teamList.index(team)] teamWidget = TeamWidget(team1) self.teamsLayout.addWidget(teamWidget) teamWidget = TeamWidget(team2) self.teamsLayout.addWidget(teamWidget) """ from modules import databaseaccess team_Pic1 = databaseaccess.get_Team_Pic(team1) playerPictureList1 = [team_Pic1, team_Pic1, team_Pic1, team_Pic1] playerNameList1 = databaseaccess.get_Player_Name_By_Team_Id(self.team1) playerIdList1 = databaseaccess.get_Player_Id_By_Team_Id(self.team1id) ##playerNameList1 = ['qq', 'ww', 'ee', 'rr'] buzzerList1 = ['q', 'w', 'e', 'r'] activePlayerList1 = [0, 1, 2, 3] teamWidget1 = TeamWidget(team1) teamObject1 = TeamObject(team1, playerPictureList1, playerNameList1, playerIdList1, buzzerList1, activePlayerList1, teamWidget1) self.team1Layout.addWidget(teamWidget1) self.teamObjectList.append(teamObject1) team_Pic2 = databaseaccess.get_Team_Pic(team2) playerPictureList2 = [team_Pic2, team_Pic2, team_Pic2, team_Pic2] playerNameList2 = databaseaccess.get_Player_Name_By_Team_Id(self.team2) playerIdList2 = databaseaccess.get_Player_Id_By_Team_Id(self.team2id) buzzerList2 = ['t', 'y', 'u', 'i'] activePlayerList2 = [0, 1, 2, 3] teamWidget2 = TeamWidget(team2) teamObject2 = TeamObject(team2, playerPictureList2, playerNameList2, playerIdList2, buzzerList2, activePlayerList2, teamWidget2) self.team2Layout.addWidget(teamWidget2) self.teamObjectList.append(teamObject2) def deHighlightTeam(self, teamWidget): teamWidget.deHighlight() def functionHandler(self, keyPress): if keyPress == config.clearButton: self.clearBuzzers() elif keyPress == config.negButton: self.changeScoreTossupNeg(config.negPoints) elif keyPress == config.correctButton: self.changeScoreTossup(config.correctPoints) elif keyPress == config.powerButton: self.changeScoreTossup(config.powerPoints) if keyPress == config.oneBonus: self.changeScoreBonus(config.bonusPoints) elif keyPress == config.twoBonus: self.changeScoreBonus(2 * config.bonusPoints) elif keyPress == config.threeBonus: self.changeScoreBonus(3 * config.bonusPoints) elif keyPress == config.startTimer: self.startTimer(5) elif keyPress == config.previousQuestion: self.emit(SIGNAL('previousQuestion')) elif keyPress == config.nextQuestion: self.emit(SIGNAL('nextQuestion')) def highlightTeam(self, teamWidget): teamWidget.highlight() def isBuzzer(self, text): status = False self.stopTimer() for team in self.teamObjectList: if text in team.buzzerList: status = True return status def setTimerDisplay(self, time): time = round(time, 1) time = float(time) self.lcdTimer.display(time) def setupGame(self, team1, team2): self.questionNumber = 0 self.roundNumber = str(1) self.tournamentId = str(2) from modules import databaseaccess self.gameId = databaseaccess.create_Game(self.tournamentId, self.roundNumber, self.team1id, self.team2id) self.tournamentName = "Capstone Tournament of Champions" self.setWindowTitle('Quizbowl Scorekeeper') self.tournamentLabel.setText(self.tournamentName) self.roundLabel.setText('Round: ' + self.roundNumber) self.playerWidget = PlayerWidget() self.playerWidgetLayout.addWidget(self.playerWidget) self.blankPlayerWidget() self.constructTeams(team1, team2) self.timer = QTimer(self) self.timer.timeout.connect(self.tick) self.setupSounds() self.timeUp = False self.emit(SIGNAL('nextQuestion')) def setupSounds(self): self.beep = QSound("sounds/beep.wav") self.buzzer = QSound("sounds/buzzer.wav") def startTimer(self, time=0): if time == 0: ##Just restarting the timer pass else: self.activeTime = time self.setTimerDisplay(time) self.timer.start(100) def stopTimer(self): self.timer.stop() def tick(self): self.activeTime -= .1 if self.activeTime <= 0.001: self.timeUp = True self.stopTimer() self.buzzer.play() self.setTimerDisplay(self.activeTime) def teamIsHighlighted(self): status = False for team in self.teamObjectList: if team.teamWidget.isHighlighted(): status = True return status
class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent = None): QMainWindow.__init__(self, parent) self.setupUi(self) def keyPressEvent(self, event): if type(event) == QKeyEvent: if self.isBuzzer(event.text()): if not self.teamIsHighlighted(): if not self.timeUp: for team in self.teamObjectList: if event.text() in team.buzzerList: buzzerIndex = team.buzzerList.index(event.text()) playerIndex = int(team.activePlayerList[buzzerIndex]) playerPicture = team.playerPictureList[playerIndex] playerName = team.playerNameList[playerIndex] self.currentBuzzedPlayerId = team.playerIdList[buzzerIndex] teamWidget = team.teamWidget self.buzzed(playerPicture, playerName, teamWidget) else: self.functionHandler(event.text()) def bonusModeChooser(self, points): if config.bonusMode: self.changeScore(points) else: self.changeScoreFinal(points) def buzzed(self, playerPicture, playerName, teamWidget): self.beep.play() self.changePlayerWidget(playerPicture, playerName) self.highlightTeam(teamWidget) def blankPlayerWidget(self): self.playerWidget.updateWidget(config.blankPlayerPicture, '') def changePlayerWidget(self, picture, name): self.playerWidget.updateWidget(picture, name) def changeScoreBonus(self, scoreChange): for team in self.teamObjectList: if team.teamWidget.isHighlighted() and team.teamWidget.isBonus(): team.teamWidget.setScore(team.teamWidget.getScore() + scoreChange) self.deHighlightTeam(team.teamWidget) team.teamWidget.bonusOff() self.blankPlayerWidget() def changeScoreTossup(self, scoreChange): for team in self.teamObjectList: if team.teamWidget.isHighlighted() and not team.teamWidget.isBonus(): teamNumber = self.teamObjectList.index(team) + 1 score = team.teamWidget.getScore() + scoreChange team.teamWidget.setScore(score) from modules import databaseaccess databaseaccess.submit_Score(self.gameId, self.questionNumber, self.currentBuzzedPlayerId, scoreChange, teamNumber) if config.bonusMode: team.teamWidget.bonusOn() else: self.clearBuzzers() def changeScoreTossupNeg(self, scoreChange): for team in self.teamObjectList: if team.teamWidget.isHighlighted() and not team.teamWidget.isBonus(): teamNumber = self.teamObjectList.index(team) + 1 score = team.teamWidget.getScore() + scoreChange team.teamWidget.setScore(score) from modules import databaseaccess databaseaccess.submit_Score(self.gameId, self.questionNumber, self.currentBuzzedPlayerId, scoreChange, teamNumber) self.clearBuzzers() def clearBuzzers(self): self.stopTimer() self.setTimerDisplay(5) self.timeUp = False self.currentBuzzedPlayerId = "" for team in self.teamObjectList: if team.teamWidget.isHighlighted(): self.deHighlightTeam(team.teamWidget) team.teamWidget.bonusOff() self.blankPlayerWidget() def constructTeams(self, team1, team2): self.teamObjectList = [] """ for team in config.teamList: teamFile = open(team, 'r') teamName = teamFile.readline().rstrip() playerPictureList = [] playerNameList = [] for line in teamFile: lineList = line.rstrip().split() playerNameList.append(lineList[0]) playerPictureList.append(team.rsplit('/', 1)[0] + '/' + lineList[1]) teamFile.close() """ """ ##buzzerList = config.buzzerList[config.teamList.index(team)] activePlayerList = config.activePlayerList[config.teamList.index(team)] teamWidget = TeamWidget(team1) self.teamsLayout.addWidget(teamWidget) teamWidget = TeamWidget(team2) self.teamsLayout.addWidget(teamWidget) """ from modules import databaseaccess team_Pic1 = databaseaccess.get_Team_Pic(team1) playerPictureList1 = [team_Pic1, team_Pic1, team_Pic1, team_Pic1] playerNameList1 = databaseaccess.get_Player_Name_By_Team_Id(self.team1) playerIdList1 = databaseaccess.get_Player_Id_By_Team_Id(self.team1id) ##playerNameList1 = ['qq', 'ww', 'ee', 'rr'] buzzerList1 = ['q', 'w', 'e', 'r'] activePlayerList1 = [0, 1, 2, 3] teamWidget1 = TeamWidget(team1) teamObject1 = TeamObject(team1, playerPictureList1, playerNameList1, playerIdList1, buzzerList1, activePlayerList1, teamWidget1) self.team1Layout.addWidget(teamWidget1) self.teamObjectList.append(teamObject1) team_Pic2 = databaseaccess.get_Team_Pic(team2) playerPictureList2 = [team_Pic2, team_Pic2, team_Pic2, team_Pic2] playerNameList2 = databaseaccess.get_Player_Name_By_Team_Id(self.team2) playerIdList2 = databaseaccess.get_Player_Id_By_Team_Id(self.team2id) buzzerList2 = ['t', 'y', 'u', 'i'] activePlayerList2 = [0, 1, 2, 3] teamWidget2 = TeamWidget(team2) teamObject2 = TeamObject(team2, playerPictureList2, playerNameList2, playerIdList2, buzzerList2, activePlayerList2, teamWidget2) self.team2Layout.addWidget(teamWidget2) self.teamObjectList.append(teamObject2) def deHighlightTeam(self, teamWidget): teamWidget.deHighlight() def functionHandler(self, keyPress): if keyPress == config.clearButton: self.clearBuzzers() elif keyPress == config.negButton: self.changeScoreTossupNeg(config.negPoints) elif keyPress == config.correctButton: self.changeScoreTossup(config.correctPoints) elif keyPress == config.powerButton: self.changeScoreTossup(config.powerPoints) if keyPress == config.oneBonus: self.changeScoreBonus(config.bonusPoints) elif keyPress == config.twoBonus: self.changeScoreBonus(2 * config.bonusPoints) elif keyPress == config.threeBonus: self.changeScoreBonus(3 * config.bonusPoints) elif keyPress == config.startTimer: self.startTimer(5) elif keyPress == config.previousQuestion: self.emit(SIGNAL('previousQuestion')) elif keyPress == config.nextQuestion: self.emit(SIGNAL('nextQuestion')) def highlightTeam(self, teamWidget): teamWidget.highlight() def isBuzzer(self, text): status = False self.stopTimer() for team in self.teamObjectList: if text in team.buzzerList: status = True return status def setTimerDisplay(self, time): time = round(time, 1) time = float(time) self.lcdTimer.display(time) def setupGame(self, team1, team2): self.questionNumber = 0 self.roundNumber = str(1) self.tournamentId = str(2) from modules import databaseaccess self.gameId = databaseaccess.create_Game(self.tournamentId, self.roundNumber, self.team1id, self.team2id) self.tournamentName = "Capstone Tournament of Champions" self.setWindowTitle('Quizbowl Scorekeeper') self.tournamentLabel.setText(self.tournamentName) self.roundLabel.setText('Round: ' + self.roundNumber) self.playerWidget = PlayerWidget() self.playerWidgetLayout.addWidget(self.playerWidget) self.blankPlayerWidget() self.constructTeams(team1, team2) self.timer = QTimer(self) self.timer.timeout.connect(self.tick) self.setupSounds() self.timeUp = False self.emit(SIGNAL('nextQuestion')) def setupSounds(self): self.beep = QSound("sounds/beep.wav") self.buzzer = QSound("sounds/buzzer.wav") def startTimer(self, time = 0): if time == 0: ##Just restarting the timer pass else: self.activeTime = time self.setTimerDisplay(time) self.timer.start(100) def stopTimer(self): self.timer.stop() def tick(self): self.activeTime -= .1 if self.activeTime <= 0.001: self.timeUp = True self.stopTimer() self.buzzer.play() self.setTimerDisplay(self.activeTime) def teamIsHighlighted(self): status = False for team in self.teamObjectList: if team.teamWidget.isHighlighted(): status = True return status
class Track(QtGui.QWidget): UPDATE_PLAYING_TRACK_TIME = 100 def __init__(self, track_model, window): super(Track, self).__init__(window) track_model.call_after_wave_state_changed.append(self.update_track) track_model.call_after_change.append(self.repaint) self.track_model = track_model self.window = window self.channels_list = ChannelsList(self.track_model) self.horizontal_layout = QtGui.QHBoxLayout() self.horizontal_layout.addWidget(self.channels_list) self.actions_panel = ActionsPanel(self.parent()) self.horizontal_layout.addWidget(self.actions_panel) self.setLayout(self.horizontal_layout) self._temp_sound_file = None self._q_sound_object = None self._time_of_start = 0 self._played_start = 0 self._play_sound_timer = QtCore.QTimer() self._play_sound_timer.setSingleShot(False) self._play_sound_timer.timeout.connect(self.tick_timer) self.play_pause_button = None @property def captured_area_container(self): return self.track_model.captured_area_container @property def wave_state(self): return self.track_model.wave_state def update_track(self): self.channels_list.update_track() def _delete_temp_sound_file(self): if self._temp_sound_file is not None: os.remove(self._temp_sound_file) self._temp_sound_file = None self._q_sound_object = None def play(self): (opened, file) = tempfile.mkstemp() os.close(opened) if self.captured_area_container.is_released: self._played_start = self.captured_area_container.start wave_state = self.wave_state.get_part(self._played_start, len(self.wave_state)) else: self._played_start = 0 wave_state = self.wave_state wave_state.save_to_file(file) self._q_sound_object = QSound(file) self._temp_sound_file = file self._q_sound_object.play() self._time_of_start = time.time() self._play_sound_timer.start(Track.UPDATE_PLAYING_TRACK_TIME) def tick_timer(self): cur_time = time.time() passed_time = cur_time - self._time_of_start frame_number = self._played_start + int( self.wave_state.frame_rate * passed_time) if frame_number > len(self.wave_state): self.window.switch_play_pause(self) else: self.captured_area_container.capture_segment(frame_number, 0) self.track_model.update() def set_play_pause_button(self, button): self.play_pause_button = button def stop(self): if self._q_sound_object is not None: self._q_sound_object.stop() self._play_sound_timer.stop() self._delete_temp_sound_file() def closeEvent(self, event): self._delete_temp_sound_file()
def __init__(self): super().__init__() self.setGeometry(200, 100, 1024, 768) self.setWindowTitle('BoBlo - Bottle Blocks') self.setWindowIcon(QIcon(get_absolute_path('images/icon2.png'))) self.screenShape = QDesktopWidget().screenGeometry() self.bg_width = 1280 self.bg_height = 990 # self.resize(self.screenShape.width(), self.screenShape.height()) self.combinations = list() self.plastic = 0 self.button_stylesheet = "QPushButton {background-color: #8FCBF4;" \ "border-style: outset;" \ "border-width: 2px;" \ "border-radius: 10px;" \ "border-color: #C6E2FF;" \ "font: bold 15pt \"Comic Sans MS\";" \ "min-width: 10em;" \ "padding: 6px;}" \ "QPushButton:pressed {background-color: #4F94CD}" self.background = QLabel(self) self.background.setGeometry(375, 0, self.bg_width, self.bg_height) self.background.setPixmap( QPixmap(get_absolute_path("./images/background.jpg")).scaled( self.bg_width, self.bg_height)) self.label_grs1 = QLabel(str(self.plastic), self) self.label_grs1.setFont(QFont("Comic Sans MS", 40, QFont.Bold)) self.label_grs1.setGeometry(640, 270, 310, 120) self.label_grs1.setAlignment(Qt.AlignRight) self.label_grs1.hide() self.label_grs2 = QLabel(str(self.plastic), self) self.label_grs2.setFont(QFont("Comic Sans MS", 40, QFont.Bold)) self.label_grs2.setGeometry(820, 58, 310, 120) self.label_grs2.setAlignment(Qt.AlignCenter) self.label_grs2.hide() self.label_blocks = QLabel(str(plastic_to_blocks(self.plastic)), self) self.label_blocks.setFont(QFont("Comic Sans MS", 50, QFont.Bold)) self.label_blocks.setGeometry(700, 330, 310, 150) self.label_blocks.setAlignment(Qt.AlignRight) self.label_blocks.hide() self.text_dato = QLabel(self) self.text_dato.move(570, 550) self.text_dato.setPixmap( QPixmap(get_absolute_path("./images/dato1.png"))) self.text1 = QLabel(self) self.text1.move(570, 100) self.text1.setPixmap(QPixmap(get_absolute_path("./images/text1.png"))) self.pic1 = QLabel(self) self.pic1.move(1070, 400) self.pic1.setPixmap( QPixmap(get_absolute_path("./images/image_step1.png"))) self.text2 = QLabel(self) self.text2.move(570, 50) self.text2.setPixmap(QPixmap(get_absolute_path("./images/text2.png"))) self.text2.hide() self.text3 = QLabel(self) self.text3.move(930, 260) self.text3.setPixmap(QPixmap(get_absolute_path("./images/text3.png"))) self.text3.hide() self.text4 = QLabel(self) self.text4.move(570, 50) self.text4.setPixmap(QPixmap(get_absolute_path("./images/text4.png"))) self.text4.hide() self.pic2 = QLabel(self) self.pic2.move(1070, 350) self.pic2.setPixmap(QPixmap(get_absolute_path("./images/boblo1.png"))) self.pic2.hide() self.text5 = QLabel(self) self.text5.move(570, 50) self.text5.setPixmap(QPixmap(get_absolute_path("./images/text5.png"))) self.text5.hide() self.to_step3 = QPushButton("&Quiero mis piezas", self) self.to_step3.setGeometry(1120, 570, 300, 90) self.to_step3.setStyleSheet(self.button_stylesheet) self.to_step3.hide() self.icon_arrow = QIcon(get_absolute_path("./images/arrow.png")) self.to_step4 = QPushButton("", self) self.to_step4.setIcon(self.icon_arrow) self.to_step4.setIconSize(QSize(250, 60)) self.to_step4.setGeometry(1120, 570, 300, 90) self.to_step4.setStyleSheet(self.button_stylesheet) self.to_step4.hide() self.icon_arrowi = QIcon(get_absolute_path("./images/arrowi.png")) self.back_to_step2 = QPushButton("", self) self.back_to_step2.setIcon(self.icon_arrowi) self.back_to_step2.setIconSize(QSize(250, 60)) self.back_to_step2.setGeometry(644, 570, 300, 90) self.back_to_step2.setStyleSheet(self.button_stylesheet) self.back_to_step2.hide() self.to_step5 = QPushButton("", self) self.to_step5.setIcon(self.icon_arrow) self.to_step5.setIconSize(QSize(250, 60)) self.to_step5.setGeometry(1140, 610, 300, 90) self.to_step5.setStyleSheet(self.button_stylesheet) self.to_step5.hide() # self.options = OptionsList(self) self.options = OptionsTable(self) self.options.setGeometry(620, 170, 824, 430) self.options.hide() self.text6 = QLabel(self) self.text6.move(570, 100) self.text6.setPixmap(QPixmap(get_absolute_path("./images/text6.png"))) self.text6.hide() self.text7 = QLabel(self) self.text7.move(570, 480) self.text7.setPixmap(QPixmap(get_absolute_path("./images/text7.png"))) self.text7.hide() self.text_process = QLabel(self) self.text_process.move(570, 480) self.text_process.setPixmap( QPixmap(get_absolute_path("./images/process1.png"))) self.text_process.hide() self.restart = QPushButton("&OK", self) self.restart.setGeometry(1120, 570, 300, 90) self.restart.setStyleSheet(self.button_stylesheet) self.restart.hide() self.audio = QSound(get_absolute_path("./audio/boblo.wav")) # threading self.start_thread()