def __init__(self): try: logger.info("Инициализация настроек") mainDir = AppEnv.getMainDir() logger.info("Главная папка: " + mainDir) iniFile = os.path.join(mainDir, "app.ini") parser.read(iniFile, encoding='utf-8') value = readPosKeyValue('Settings', 'Screen resolution') logger.info("Считывание разрешения экрана") if value: self.screenResolution = value intValue = readIntKeyValue('Settings', 'FPS') if intValue: self.fps = intValue intValue = readIntKeyValue('Settings', 'Number of answers') if intValue: self.numberOfAnswers = intValue intValue = readIntKeyValue('Settings', 'Number of flyers') if intValue: self.numberOfFlyers = intValue intValue = readIntKeyValue('Fonts', 'Questions font size') if intValue: self.fontSize = intValue value = readPosKeyValue('Settings', 'Flyers speed') if value: self.flyersSpeed = value strValue = readStrKeyValue('Settings', 'Words delimiter') if strValue: self.wordsDelimiter = strValue strValue = readStrKeyValue('Dictionaries', 'Direction') if strValue: self.straightDictDir = (strValue.upper() != 'BACKWARD') strValue = readStrKeyValue('Dictionaries', 'Default dictionary name') if strValue: self.dictDefaultFileName = strValue strValue = readStrKeyValue('Dictionaries', 'User dictionary name') if strValue: self.dictFileName = strValue if (not self.dictFileName): self.dictFileName = self.dictDefaultFileName if (not self.dictFileName): Exception("Не указан файл словаря") pygame.font.init() self.fontSettings = FontSettings() self.fontSettings.loadFontSettings(AppEnv.getDataDir()) #if we are changed word and translate - change fonts if not self.straightDictDir: self.fontSettings.switchFonts() self.sounds = self.loadSounds() if (not self.fontSettings.loadingStatus): Exception("Не загружены один или более шрифтов") except: logger.fatal("Работа невозможна из-за ошибок в настройках: %s" % str(sys.exc_info()))
def onAnswerClicked(self, mousePos, group=Config.answers): pointer = MousePointer(mousePos) spriteAnswer = pygame.sprite.spritecollideany(pointer, group) className = type(spriteAnswer).__name__ if className == "Answer": return spriteAnswer elif className == "NoneType": if (group != Config.allsprites): self.onAnswerClicked(mousePos, Config.allsprites) return elif className == "MsgMulti": spriteAnswer.kill() return elif className == "SoundBtn": #TODO сделать звук, здесь же как в Скрече - графические кнопки: загрузить звук, рисунок, записать звук if AppEnv.loadCustomSound(spriteAnswer.soundPath).play() == None: Config.appLog.warning( "Невозможно загрузить звуковую подсказку " + spriteAnswer.soundPath) return None elif className == "Actor": if self.state == ActorsStatus.WaitingForAnswer: self.showImageTip() return None else: return None
def checkUserAnswer(self, mousePos): spriteAnswer = self.onAnswerClicked(mousePos) if spriteAnswer == None: return key = self.question.word translate = spriteAnswer.answer if translate == self.question.trnslt: #если ответ на котором щелкнули, правильный (соответствует переводу) if (cfg.sounds): soundGood = AppEnv.loadSound(cfg.sounds[0]) if soundGood: soundGood.play() self.questionAccepted() if self.question.state == 0: #если статус вопроса "новый" - т.е. до этого не было неправильных ответов, увеличим счетчик успешных self.answered[key].state = self.question.state self.successed, self.failed = self.question.changeState( True, self.successed, self.failed) self.showResult(self.question.state == 1) self.state = ActorsStatus.Ready else: #ответ неправильный, изменяем вид надписи... spriteAnswer.showAnswerBad() spriteAnswer.update() self.answered[key].state = self.question.state self.successed, self.failed = self.question.changeState( False, self.successed, self.failed) self.result.changeState(self.successed, self.failed)
def playSoundError(self): if not self.badSound: sounds = cfg.sounds if sounds: self.badSound = AppEnv.loadSound(sounds[1]) if (self.badSound): self.badSound.play()
def setupLogger(): # create logger logger = logging.getLogger('wordscaster') logger.setLevel(logging.INFO) # create file handler and set level to info logFileName = os.path.join(AppEnv.getMainDir(), 'wordscaster.log') ch = logging.FileHandler(logFileName) ch.setLevel(level=logging.INFO) # create formatter formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch ch.setFormatter(formatter) # add ch to logger logger.addHandler(ch) return logger
def _checkOrCreateDictionarySubfolders(self, dictName): nameWithoutExt = os.path.splitext(dictName) pureName = os.path.split(nameWithoutExt[0]) folderName = os.path.join(AppEnv.getDictDir(), pureName[1]) try: if not (os.path.exists(folderName) and os.path.isdir(folderName)): os.mkdir(folderName) soundsFolder = os.path.join(folderName, "sounds") if not (os.path.exists(soundsFolder) and os.path.isdir(soundsFolder)): os.mkdir(soundsFolder) imagesFolder = os.path.join(folderName, "images") if not (os.path.exists(imagesFolder) and os.path.isdir(imagesFolder)): os.mkdir(imagesFolder) AppEnv.soundsDir = soundsFolder AppEnv.imagesDir = imagesFolder except: AppEnv.soundsDir = "" AppEnv.imagesDir = "" Config.appLog.warning("Невозможно создать папку для пользовательского словаря. "+str(sys.exc_info()))
def loadBackground(self, screen): try: bckgrFileName = readStrKeyValue('Skins', 'Background') if bckgrFileName: background = AppEnv.loadImage(bckgrFileName, -1) if not background: return self._loadPlainBackground(screen) screenWidth = screen.get_rect()[2] screenHeight = screen.get_rect()[3] #если размер картинки равен размеру экрана программы - больше ничего не делаем if (background.get_rect()[2] == screenWidth) and (background.get_rect()[3] == screenHeight): return background #если размеры разные - пытаемся подогнать background = pygame.transform.scale( background, (screenWidth, screenHeight)) return background else: return self._loadPlainBackground(screen) except: Config.appLog.warning("Ошибка {} при загрузке фона {}".format( bckgrFileName, str(sys.exc_info()))) return self._loadPlainBackground(screen)
def loadSound(self, name): return AppEnv.loadSound(name)
def loadImages(self, fileNames): images = [] for fileName in fileNames: image = AppEnv.loadImage(fileName, -1) images.append(image) return images
def __init__(self): self.words = [] self.cfg = cfg self.dictFileName = os.path.join(AppEnv.getDictDir(), self.cfg.dictFileName) self.defDictFileName = os.path.join(AppEnv.getDictDir(), self.cfg.dictDefaultFileName)
def _loadImageTip(self): if not self.imgPath: return None return AppEnv.loadImage(self.imgPath, -1)
def _loadSound(self): if WordRecord.sound: return None return AppEnv.loadSound(self.soundPath)
def main(): #Initialize Everything logger.info("Запуск программы") pygame.init() #it's surface mode = cfg.screenResolution screen = pygame.display.set_mode(mode) pygame.display.set_caption(" ") icon = AppEnv.loadImage("hatul_gold.png", -1) pygame.display.set_icon(icon) pygame.mouse.set_visible(1) #Create The Backgound - now white surface logger.info("Загрузка фона") background = cfg.loadBackground(screen) #Display The Background screen.fill([255, 255, 255]) screen.blit(background, (0, 0)) pygame.display.flip() #Prepare Game Objects clock = pygame.time.Clock() try: #who casts new word's choice initialized = True actor = Actor(screen) logger.info("Актор инициализирован") actor.setAppearance(5, 255) Config.allsprites.add(actor, actor.result) initalMsgPos = screen.get_rect().midtop if actor.status != "": initialized = False msg = MsgMulti(screen, actor.status + ". Нажмите <ESC> - для выхода", initalMsgPos, 'board.png') else: msg = MsgMulti( screen, "Нажмите клавишу <Пробел> для запуска, <ESC> - для выхода. Щелкните мышкой по этой надписи, чтобы начать", initalMsgPos, 'board.png') Config.allsprites.add(actor, msg) #Main Loop going = True while going: clock.tick(cfg.FPS) #Handle Input Events for event in pygame.event.get(): if event.type == pygame.QUIT: going = False elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: going = False elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: if (Config.allsprites.has(msg)): msg.kill() if initialized: actor.cast() elif event.type == pygame.MOUSEBUTTONDOWN: actor.checkUserAnswer(pygame.mouse.get_pos()) actor.castAnswers() Config.allsprites.update() #Draw Everything screen.fill([255, 255, 255]) screen.blit(background, (0, 0)) Config.allsprites.draw(screen) pygame.display.flip() except: logger.fatal(str(sys.exc_info())) else: pass #close all here pygame.quit()