コード例 #1
0
ファイル: test_menu.py プロジェクト: Henry-Benito/sudokuB
 def test_display_select_setting_name_modify_attributes_should_update_attribute_for_level(self):
     sudoku_menu = Menu()
     sudoku_setting = Settings()
     old_value = sudoku_setting.get_attribute_value_for_setting("Level", "Easy","max")
     sudoku_menu.display_select_setting_name_to_modify_attributes("Level")
     new_value = sudoku_setting.get_attribute_value_for_setting("Level", "Easy","max")
     self.assertEqual(old_value, new_value)
コード例 #2
0
    def _getThemeFiles(self, directory, extensionOnly=False):
        # First read from the NFO file if it exists
        nfoRead = NfoReader(directory, self.debug_logging_enabled)
        themeFiles = nfoRead.getThemeFiles()

        # Get the theme directories that are referenced and process the data in them
        for nfoDir in nfoRead.getThemeDirs():
            # Do not want the theme keyword if looking at an entire directory
            themeFiles = themeFiles + self._getThemeFiles(nfoDir, True)

        del nfoRead
        log("ThemeFiles: Searching %s for %s" % (directory, Settings.getThemeFileRegEx(directory, extensionOnly, self.audioOnly)), self.debug_logging_enabled)

        # check if the directory exists before searching
        if dir_exists(directory):
            dirs, files = list_dir(directory)
            for aFile in files:
                m = re.search(Settings.getThemeFileRegEx(directory, extensionOnly, self.audioOnly), aFile, re.IGNORECASE)
                if m:
                    path = os_path_join(directory, aFile)
                    log("ThemeFiles: Found match: %s" % path, self.debug_logging_enabled)
                    # Add the theme file to the list
                    themeFiles.append(path)

        return themeFiles
コード例 #3
0
ファイル: test_settings.py プロジェクト: cdicle/labelImg
 def test_basic(self):
     wSetting = Settings()
     wSetting['test0'] = 'hello'
     wSetting['test1'] = 10
     wSetting['test2'] = [0, 2, 3]
     self.assertEqual(wSetting.get('test3', 3), 3)
     self.assertEqual(wSetting.save(), True)
コード例 #4
0
ファイル: sync.py プロジェクト: StickNClutch/ownNotes
    def __init__(self,):
        self._running = False
        self._lock = None

        settings = Settings()
        self.logger = logger.Logger(
            debug=settings.get('WebDav', 'debug'))
コード例 #5
0
ファイル: default.py プロジェクト: noba3/KoTos
    def show(self):
        log("SonosArtistSlideshow: About to show window")
        # First show the window
        SonosControllerWindow.show(self)

        # Work out how many lines there are on the screen to show lyrics
        if Settings.isLyricsInfoLayout():
            lyricControl = self.getControl(SonosArtistSlideshow.LYRICS)
            if lyricControl is not None:
                listitem = xbmcgui.ListItem()
                while xbmc.getInfoLabel('Container(%s).NumPages' % SonosArtistSlideshow.LYRICS) != '2':
                    lyricControl.addItem(listitem)
                    xbmc.sleep(10)
                self.lyricListLinesCount = lyricControl.size() - 1
                lyricControl.reset()

        self.windowId = xbmcgui.getCurrentWindowId()

        log("SonosArtistSlideshow: After show window %s" % self.windowId)

        # Set the sonos icon
        if not Settings.hideSonosLogo():
            xbmcgui.Window(self.windowId).setProperty('SonosAddonIcon', __icon__)

        # Set option to make the artist slideshow full screen
        if Settings.fullScreenArtistSlideshow():
            xbmcgui.Window(self.windowId).setProperty('SonosAddonSlideshowFullscreen', "true")

        # Now make sure that Artist Slideshow is running
        self.athread = threading.Thread(target=self.runArtistSlideshow)
        self.athread.setDaemon(True)
        self.athread.start()
        log("SonosArtistSlideshow: ArtistSlideShow thread started")
コード例 #6
0
ファイル: test.py プロジェクト: imclab/alfred-mailto
 def test_settings_load(self):
     self.assertFalse(os.path.exists(self.test_settings_path))
     s = Settings()
     for key, value in s.default_settings.items():
         self.assert_(s[key] == value)
         self.assert_(s.get(key) == value)
     self.assert_(os.path.exists(s.settings_path))
コード例 #7
0
ファイル: helpers.py プロジェクト: hadrons123/FedoraReview
    def check_rpmlint_errors(out, log):
        """ Check the rpmlint output, return(ok, errmsg)
        If ok, output is OK and there is 0 warnings/errors
        If not ok, and errmsg!= None there is system errors,
        reflected in errmsg. If not ok and msg == None parsing
        is ok but there are warnings/errors"""

        problems = re.compile('(\d+)\serrors\,\s(\d+)\swarnings')
        lines = out.split('\n')[:-1]
        err_lines = filter( lambda l: l.lower().find('error') != -1,
                            lines)
        if len(err_lines) == 0:
            Settings.get_logger().debug('Cannot parse rpmlint output: '
                                         + out)
            return False, 'Cannot parse rpmlint output:'

        res = problems.search(err_lines[-1])
        if res and len(res.groups()) == 2:
            errors, warnings = res.groups()
            if errors == '0' and warnings == '0':
                return True, None
            else:
                return False, None
        else:
            log.debug('Cannot parse rpmlint output: ' + out )
            return False, 'Cannot parse rpmlint output:'
コード例 #8
0
    def _generateThemeFilelist(self, rawPath):
        # Get the full path with any network alterations
        workingPath = self._getUsablePath(rawPath)

        themeList = self._getThemeFiles(workingPath)

        # If no themes have been found
        if len(themeList) < 1:
            # TV shows stored as ripped disc folders
            if ('VIDEO_TS' in workingPath) or ('BDMV' in workingPath):
                log("ThemeFiles: Found VIDEO_TS or BDMV in path: Correcting the path for DVDR tv shows", self.debug_logging_enabled)
                workingPath = os_path_split(workingPath)[0]
                themeList = self._getThemeFiles(workingPath)
                if len(themeList) < 1:
                    workingPath = os_path_split(workingPath)[0]
                    themeList = self._getThemeFiles(workingPath)
            else:
                # If no theme files were found in this path, look at the parent directory
                workingPath = os_path_split(workingPath)[0]

                # Check for the case where there is the theme forlder settings, we want to
                # check the parent folders themes directory
                if Settings.isThemeDirEnabled():
                    themeDir = os_path_join(workingPath, Settings.getThemeDirectory())
                    themeList = self._getThemeFiles(themeDir)

                # If there are still no themes, just check the parent directory
                if len(themeList) < 1:
                    themeList = self._getThemeFiles(workingPath)

        log("ThemeFiles: Playlist size = %d" % len(themeList), self.debug_logging_enabled)
        log("ThemeFiles: Working Path = %s" % workingPath, self.debug_logging_enabled)

        return themeList
コード例 #9
0
ファイル: service.py プロジェクト: MrMC/script.pinsentry
    def check(self):
        # If we have found the correct user, then we need to ensure we are
        # in the valid time duration and have not exceeded the limit
        if not self.isEnabled:
            return True
        # Check for the case where we didn't get the user ID - this means we are
        # already shutting down
        if self.userId in [None, ""]:
            return False

        log("UserPinControl: Performing check for user %s" % self.userId)

        # First check that the current time is within the allowed boundaries
        localTime = time.localtime()
        currentTime = (localTime.tm_hour * 60) + localTime.tm_min

        if self.allowedStartTime > currentTime or self.allowedEndTime < currentTime:
            log("UserPinControl: User not allowed access until %d to %d currently %d" % (self.allowedStartTime, self.allowedEndTime, currentTime))
            self.shutdown(32130)
            return False

        # Check if the screensaver is running, if so we need to make sure we do not
        # class that as time used by the user
        if xbmc.getCondVisibility("System.ScreenSaverActive"):
            if self.screensaverStart < 1:
                self.screensaverStart = currentTime
        else:
            # Not the screensaver, check to see if this is the first check
            # after the screensaver stopped
            if self.screensaverStart > 0:
                screensaverDuration = currentTime - self.screensaverStart
                self.screensaverStart = 0
                log("UserPinControl: Updating duration for screensaver, %d minutes" % screensaverDuration)
                # Now we roll the time forward that we started viewing so that
                # we are not counting the screensaver
                self.startedViewing = self.startedViewing + screensaverDuration

            # Check to see if we need to update the record for how long the user has already been viewing
            viewingLimit = Settings.getUserViewingLimit(self.userId)
            self.usedViewingLimit = currentTime - self.startedViewing
            log("UserPinControl: Time used by user is %d" % self.usedViewingLimit)

            # Update the settings record for how much this user has viewed so far
            Settings.setUserViewingUsedTime(self.userId, self.usedViewingLimit)

            # Now check to see if the user has exceeded their limit
            if self.usedViewingLimit >= viewingLimit:
                self.shutdown(32133)
                return False

            # Check if we need to warn the user that the time is running out
            warningTime = Settings.getWarnExpiringTime()
            if (not self.warningDisplayed) and ((self.usedViewingLimit + warningTime) >= viewingLimit):
                self.warningDisplayed = True
                # Calculate the time left
                remainingTime = viewingLimit - self.usedViewingLimit
                msg = "%d %s" % (remainingTime, __addon__.getLocalizedString(32134))
                xbmcgui.Dialog().notification(__addon__.getLocalizedString(32001).encode('utf-8'), msg, __icon__, 3000, False)

        return True
コード例 #10
0
ファイル: setpin.py プロジェクト: Stevie-Bs/repository.xvbmc
def setUserPin(pinId):
    # Prompt the user for the pin
    numberpad = NumberPad.createNumberPad(32106)
    numberpad.doModal()

    # Get the code that the user entered
    enteredPin = numberpad.getPin()
    del numberpad

    # Check to ensure the user has either set no password or one the correct length
    if (len(enteredPin) > 0) and (Settings.getPinLength() > len(enteredPin)):
        log("SetPin: Incorrect length pin entered, expecting %d digits" % Settings.getPinLength())
        xbmcgui.Dialog().ok(__addon__.getLocalizedString(32001).encode('utf-8'), __addon__.getLocalizedString(32109).encode('utf-8'))
    elif Settings.checkUserPinClash(enteredPin, pinId):
        # This pin clashes with an existing pin
        log("SetPin: Entered pin clashes with an existing pin")
        xbmcgui.Dialog().ok(__addon__.getLocalizedString(32001).encode('utf-8'), __addon__.getLocalizedString(32112).encode('utf-8'))
    else:
        # Now double check the value the user entered
        numberpad = NumberPad.createNumberPad(32107)
        numberpad.doModal()

        # Get the code that the user entered
        enteredPin2 = numberpad.getPin()
        del numberpad

        if enteredPin == enteredPin2:
            Settings.setUserPinValue(enteredPin, pinId)
        else:
            log("SetPin: Pin entry different, first: %s, second %s" % (enteredPin, enteredPin2))
            xbmcgui.Dialog().ok(__addon__.getLocalizedString(32001).encode('utf-8'), __addon__.getLocalizedString(32108).encode('utf-8'))
コード例 #11
0
ファイル: deps.py プロジェクト: timlau/FedoraReview
def listpaths(pkg_filename):
    ''' Return lists of files and dirs in local pkg. '''

    cmd = ['rpm', '-ql', '--dump', '-p', pkg_filename]
    Settings.get_logger().debug("Running: " + ' '.join(cmd))
    try:
        rpm = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    except OSError:
        Settings.get_logger().warning("Cannot run " + " ".join(cmd))
        return []
    files = []
    dirs = []
    while True:
        try:
            line = rpm.stdout.next().strip()
        except StopIteration:
            return dirs, files
        try:
            path, mode = line.rsplit(None, 10)[0:5:4]
        except ValueError:
            # E. g., when given '(contains no files)'
            continue
        mode = int(mode, 8)
        if mode & 040000:
            dirs.append(path)
        else:
            files.append(path)
コード例 #12
0
ファイル: review_helper.py プロジェクト: timlau/FedoraReview
    def _do_report(self, outfile=None):
        ''' Create a review report'''
        clock = time.time()
        self.log.info('Getting .spec and .srpm Urls from : '
                      + self.bug.get_location())

        Settings.dump()
        if not self.bug.find_urls():
            raise self.HelperError('Cannot find .spec or .srpm URL(s)')
        self.log.debug("find_urls completed: %.3f"
                       % (time.time() - clock))
        clock = time.time()

        if not ReviewDirs.is_inited:
            wd = self.bug.get_dirname()
            ReviewDirs.workdir_setup(wd)
        if Mock.is_available():
            Mock.init()

        if not self.bug.download_files():
            raise self.HelperError('Cannot download .spec and .srpm')
        self.log.debug("Url download completed: %.3f" % (time.time() - clock))

        Settings.name = self.bug.get_name()
        self._run_checks(self.bug.spec_file, self.bug.srpm_file, outfile)
コード例 #13
0
ファイル: start.py プロジェクト: thorlund/gyldnesnit
def main():
	#Set this to true if you want to create a personal database
	testdatabase = False
	#Set this due to how large you want your testdatabase
	count = 10
	#creating a settings to be used with run
	cuts = environment.generateCuts()
	settings = Settings(cuts)
	environment.setSettings(settings)
	settings.setMethod("expanded")
	globalSettings = GlobalSettings()
	environment.setGlobalSettings(globalSettings)
	db = Database(globalSettings)
	#making a testdatabase if the varible is set
	if testdatabase == True:
		currentDBCount= m.Painting.select().count()
		count = count - currentDBCount
		if count > 0:
			db.setCount(count)
			db.constructDatabase()
	else:
		db.constructDatabase()
	run = m.createNewRun(settings)
	paintings = m.Painting.select(m.Painting.q.form=="painting")
	for painting in paintings:
		if os.path.isfile(painting.filepath):
			try:
				paintingContainer = Painting(painting)
				print "working on"
				print painting.filepath
				paintingContainer.setResults(paintingAnalyzer.analyze(paintingContainer,settings))
				m.saveResults(run.id,paintingContainer)
			except:
				pass
コード例 #14
0
ファイル: themePlayer.py プロジェクト: kodibrasil/KodiBrasil
    def updateVideoRefreshRate(self, themePlayList):
        # Check if the setting is enabled to switch the refresh rate
        if not Settings.blockRefreshRateChange():
            self.original_refreshrate = 0
            return

        log("ThemePlayer: Checking for update of refresh rate")

        try:
            # Check if we have any videos in the PlayList
            hasVideoFiles = True
            i = 0
            while i < themePlayList.size():
                if Settings.isVideoFile(themePlayList[i].getfilename()):
                    hasVideoFiles = True
                    break
                i = i + 1

            if hasVideoFiles:
                # Save off the existing refresh setting
                jsonresponse = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Settings.GetSettingValue",  "params": { "setting": "videoplayer.adjustrefreshrate" }, "id": 1}')
                data = simplejson.loads(jsonresponse)
                if 'result' in data:
                    if 'value' in data['result']:
                        self.original_refreshrate = data['result']['value']
                        # Check if the refresh rate is currently set
                        log("ThemePlayer: Video refresh rate currently set to %d" % self.original_refreshrate)

                # Check if the refresh rate is currently set, if it is, then we need
                if self.original_refreshrate != 0:
                    # Disable the refresh rate setting
                    log("ThemePlayer: Disabling refresh rate")
                    xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Settings.SetSettingValue",  "params": { "setting": "videoplayer.adjustrefreshrate", "value": 0 }, "id": 1}')
        except:
            log("ThemePlayer: Failed to process video refresh")
コード例 #15
0
ファイル: review_helper.py プロジェクト: timlau/FedoraReview
 def _do_run(self, outfile=None):
     ''' Initiate, download url:s, run checks a write report. '''
     Settings.init()
     make_report = True
     if Settings.list_checks:
         self._list_checks()
         make_report = False
     elif Settings.list_flags:
         self._list_flags()
         make_report = False
     elif Settings.version:
         self._print_version()
         make_report = False
     elif Settings.list_plugins:
         self._list_plugins()
         make_report = False
     elif Settings.url:
         self.log.info("Processing bug on url: " + Settings.url)
         self.bug = UrlBug(Settings.url)
     elif Settings.bug:
         self.log.info("Processing bugzilla bug: " + Settings.bug)
         self.bug = BugzillaBug(Settings.bug)
     elif Settings.name:
         self.log.info("Processing local files: " + Settings.name)
         self.bug = NameBug(Settings.name)
     if make_report:
         if not Mock.is_available() and not Settings.prebuilt:
             raise ReviewError("Mock unavailable, --prebuilt must be used.")
         self._do_report(outfile)
コード例 #16
0
ファイル: views.py プロジェクト: collective/wc.pageturner
    def convert(self):
        if self.enabled():
            settings = Settings(self.context)
            settings.last_updated = DateTime('1999/01/01').ISO8601()
            queue_job(self.context)

        self.request.response.redirect(self.context.absolute_url() + '/view')
コード例 #17
0
ファイル: views.py プロジェクト: collective/wc.pageturner
    def convert_all(self):
        confirm = self.request.get('confirm', 'no')
        if confirm != 'yes':
            return 'You must append "?confirm=yes"'
        else:
            ptool = getToolByName(object, 'portal_properties')
            site_props = getattr(ptool, 'site_properties', None)
            auto_layout = site_props.getProperty(
                'page_turner_auto_select_layout', False)

            catalog = getToolByName(self.context, 'portal_catalog')
            files = catalog(object_provides=IFileContent.__identifier__)
            for brain in files:
                file = brain.getObject()
                if file.getContentType() not in ('application/pdf',
                        'application/x-pdf', 'image/pdf'):
                    continue

                if auto_layout and file.getLayout() != 'page-turner':
                    file.setLayout('page-turner')

                self.request.response.write(
                    'Converting %s to flex paper...\n' % file.absolute_url())
                settings = Settings(file)
                settings.last_updated = DateTime('1999/01/01').ISO8601()
                queue_job(file)
コード例 #18
0
ファイル: main.py プロジェクト: maks-skynet/zombot-1
def get_vk():
    settings = Settings()
    users = settings.getUsers()
    selected_user = UserPrompt().prompt_user("Select user:", users)
    settings.setUser(selected_user)
    vk = vkutils.VK(settings)
    return vk
コード例 #19
0
    def _updatePlaylistForSettings(self, playlist):
        if playlist.size() < 1:
            return playlist

        filename = playlist[0].getfilename()
        duration = self._getVideoDuration(filename)
        log("Duration is %d for file %s" % (duration, filename))

        startTime = 0

        # Check if we have a random start time
        if Settings.isRandomStart():
            startTime = random.randint(0, int(duration * 0.75))

        clockStart = Settings.getTimeForClock(filename, duration)
        if clockStart > 0:
            startTime = clockStart

        # Set the random start
        if (startTime > 0) and (duration > 10):
            listitem = xbmcgui.ListItem()
            # Record if the theme should start playing part-way through
            listitem.setProperty('StartOffset', str(startTime))

            log("Setting start of %d for %s" % (startTime, filename))

            # Remove the old item from the playlist
            playlist.remove(filename)
            # Add the new item at the start of the list
            playlist.add(filename, listitem, 0)

        return playlist
コード例 #20
0
ファイル: stylesheet.py プロジェクト: JoonyLi/veusz
    def __init__(self, **args):
        """Create the default settings."""
        Settings.__init__(self, 'StyleSheet', setnsmode='stylesheet', **args)
        self.pixmap = 'settings_stylesheet'

        for subset in self.registeredsettings:
            self.add( subset() )
コード例 #21
0
ファイル: context.py プロジェクト: MaxMorais/skink
class Context(object):
    def __init__(self, root_dir):
        self.bus = Bus()
        self.settings = Settings(root_dir=root_dir)

    def load_settings(self, config_path):
        self.settings.load(config_path)
コード例 #22
0
ファイル: themeFinder.py プロジェクト: kodibrasil/KodiBrasil
    def __init__(self, rawPath, pathList=None, videotitle=None, debug_logging_enabled=True, audioOnly=False):
        self.debug_logging_enabled = debug_logging_enabled
        self.forceShuffle = False
        self.doNotShuffle = False
        self.audioOnly = audioOnly
        self.rawPath = rawPath
        if rawPath in [None, ""]:
            self.clear()
        else:
            # Check for the case where there is a custom path set so we need to use
            # the custom location rather than the rawPath
            if Settings.isCustomPathEnabled() and (videotitle not in [None, ""]):
                customRoot = Settings.getCustomPath()
                # Make sure that the path passed in has not already been converted
                if customRoot not in self.rawPath:
                    self.rawPath = os_path_join(customRoot, normalize_string(videotitle))
                    log("ThemeFiles: Setting custom path to %s" % self.rawPath, self.debug_logging_enabled)

            if (pathList is not None) and (len(pathList) > 0):
                self.themeFiles = []
                for aPath in pathList:
                    subThemeList = self._generateThemeFilelistWithDirs(aPath)
                    # add these files to the existing list
                    self.themeFiles = self._mergeThemeLists(self.themeFiles, subThemeList)
                # If we were given a list, then we should shuffle the themes
                # as we don't always want the first path playing first
                self.forceShuffle = True
            else:
                self.themeFiles = self._generateThemeFilelistWithDirs(self.rawPath)

        # Check if we need to handle the ordering for video themes
        if not audioOnly:
            self.doNotShuffle = self._filterForVideoThemesRule()
            self.forceShuffle = False
コード例 #23
0
ファイル: database.py プロジェクト: paladin8818/RTSSystem
def get_db():
    config = Settings()
    return pymysql.connect(host=config.setting("dbhost"),
        user=config.setting("dbuser"),
        passwd=config.setting("dbpassword"),
        db=config.setting("dbbase"),
        charset="utf8")
コード例 #24
0
ファイル: info.py プロジェクト: AlexSatrapa/EliteOCR
class InfoDialog(QDialog, Ui_Info):
    def __init__(self):
        QDialog.__init__(self)
        self.setupUi(self)
        self.settings = Settings()
        self.permit_close = False
        
        self.ok.clicked.connect(self.accepted)
        self.wait = 10
        self.stimer = QTimer
        self.ok.setText(unicode(self.wait))
        self.stimer.singleShot(1000, self.updateTimer)
    
    def updateTimer(self):
        self.wait -= 1
        self.ok.setText(unicode(self.wait))
        if self.wait > 0:
            self.stimer.singleShot(1000, self.updateTimer)
        else:
            self.ok.setEnabled(True)
            self.ok.setText("OK")
    
    def accepted(self):
        if self.understood.isChecked():
            self.permit_close = True
            self.settings.setValue('info_accepted', True)
            self.close()
    
    def closeEvent(self, evnt):
        if self.permit_close:
            super(InfoDialog, self).closeEvent(evnt)
        else:
            evnt.ignore()
コード例 #25
0
ファイル: map.py プロジェクト: Pent00/rpg-map
class MapFrame(wx.Frame):

    def __init__(self, parent, id=wx.ID_ANY, title="", pos=wx.DefaultPosition,
        size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, name="MapFrame"):
        super(MapFrame, self).__init__(parent, id, title, pos,
            (MAX_COL*CELL_X, MAX_ROW*CELL_Y+20),
            style, name)

        self.SetIcon(wx.Icon("img/icon.png", wx.BITMAP_TYPE_PNG))

        self.settings = Settings()
        global board, colors, player, tiled
        board = self.settings.load_map('config/map1.txt')
        colors = self.settings.load_colors()
        tiled = Tiled()

        player = Player()

        self.panel = MapPanel(self)
        self.InitUI()

        #~ ag = wx.animate.GIFAnimationCtrl(self.panel, -1, self.player.src,
            #~ pos=(10, 10))
        #~ ag.GetPlayer().UseBackgroundColour(True)
        #~ ag.Play()

        self.Centre()
        self.Show(True)

    def InitUI(self):
        menubar = wx.MenuBar()
        fileMenu = wx.Menu()
        menubar.Append(fileMenu, '&File')
        self.SetMenuBar(menubar)
コード例 #26
0
class StatusBar():
    def __init__(self, window):
        self.window = window
        self.settings = Settings()

    def update(self):
        if ProcessCache.empty():
            return self.erase()

        status_bar_tasks = self.settings.get('status_bar_tasks', False)

        if status_bar_tasks:
            task_names = set([process.get_task_name() for process in ProcessCache.get()])

            if status_bar_tasks != True:
                if not isinstance(status_bar_tasks, list):
                    status_bar_tasks = [status_bar_tasks]

                task_names = task_names.intersection(set(status_bar_tasks))

            if task_names:
                defer_sync(lambda: self.set(', '.join(task_names)))

    def set(self, text):
        text_format = self.settings.get('status_bar_format', '{task_name}')
        status = text_format.format(task_name=text)
        self.window.active_view().set_status(Settings.PACKAGE_NAME, status)

    def erase(self):
        self.window.active_view().erase_status(Settings.PACKAGE_NAME)
コード例 #27
0
    def checkEnding(self):
        if self.isPlayingAudio() and (self.startTime > 0):
            # Get the current time
            currTime = int(time.time())

            # Time in minutes to play for
            durationLimit = Settings.getPlayDurationLimit()
            if durationLimit > 0:
                expectedEndTime = self.startTime + (60 * durationLimit)

                if currTime > expectedEndTime:
                    self.endPlaying(slowFade=True)
                    return

            # Check for the case where only a given amount of time of the track will be played
            # Only skip forward if there is a track left to play - otherwise just keep
            # playing the last track
            if (self.playlistSize > 1) and (self.remainingTracks != 0):
                trackLimit = Settings.getTrackLengthLimit()
                if trackLimit > 0:
                    if currTime > self.trackEndTime:
                        log("Player: Skipping to next track after %s" % self.getPlayingFile())
                        self.playnext()
                        if self.remainingTracks != -1:
                            self.remainingTracks = self.remainingTracks - 1
                        self._setNextSkipTrackTime(currTime)
コード例 #28
0
ファイル: plugin.py プロジェクト: angelblue05/script.tvtunes
    def _moveToThemeFolder(self, directory):
        log("moveToThemeFolder: path = %s" % directory)

        # Handle the case where we have a disk image
        if (os_path_split(directory)[1] == 'VIDEO_TS') or (os_path_split(directory)[1] == 'BDMV'):
            directory = os_path_split(directory)[0]

        dirs, files = list_dir(directory)
        for aFile in files:
            m = re.search(Settings.getThemeFileRegEx(directory), aFile, re.IGNORECASE)
            if m:
                srcpath = os_path_join(directory, aFile)
                log("fetchAllMissingThemes: Found match: %s" % srcpath)
                targetpath = os_path_join(directory, Settings.getThemeDirectory())
                # Make sure the theme directory exists
                if not dir_exists(targetpath):
                    try:
                        xbmcvfs.mkdir(targetpath)
                    except:
                        log("fetchAllMissingThemes: Failed to create directory: %s" % targetpath, True, xbmc.LOGERROR)
                        break
                else:
                    log("moveToThemeFolder: directory already exists %s" % targetpath)
                # Add the filename to the path
                targetpath = os_path_join(targetpath, aFile)
                if not xbmcvfs.rename(srcpath, targetpath):
                    log("moveToThemeFolder: Failed to move file from %s to %s" % (srcpath, targetpath))
コード例 #29
0
ファイル: scraper.py プロジェクト: angelblue05/script.tvtunes
    def _doesThemeExist(self, directory):
        log("doesThemeExist: Checking directory: %s" % directory)
        # Check for custom theme directory
        if Settings.isThemeDirEnabled():
            themeDir = os_path_join(directory, Settings.getThemeDirectory())
            # Check if this directory exists
            if not dir_exists(themeDir):
                workingPath = directory
                # If the path currently ends in the directory separator
                # then we need to clear an extra one
                if (workingPath[-1] == os.sep) or (workingPath[-1] == os.altsep):
                    workingPath = workingPath[:-1]
                # If not check to see if we have a DVD VOB
                if (os_path_split(workingPath)[1] == 'VIDEO_TS') or (os_path_split(workingPath)[1] == 'BDMV'):
                    # Check the parent of the DVD Dir
                    themeDir = os_path_split(workingPath)[0]
                    themeDir = os_path_join(themeDir, Settings.getThemeDirectory())
            directory = themeDir

        # check if the directory exists before searching
        if dir_exists(directory):
            # Generate the regex
            themeFileRegEx = Settings.getThemeFileRegEx(audioOnly=True)

            dirs, files = list_dir(directory)
            for aFile in files:
                m = re.search(themeFileRegEx, aFile, re.IGNORECASE)
                if m:
                    log("doesThemeExist: Found match: " + aFile)
                    return True
        return False
コード例 #30
0
ファイル: nerdtabu.py プロジェクト: Skyr/nerdtabu
def main():
    global screen
    print("Nerd Tabu")
    # Parse command line
    parser = argparse.ArgumentParser()
    parser.add_argument('quizfile', type=argparse.FileType('r'), help='Name of the quiz file')
    parser.add_argument('teamA', nargs='?', metavar='teamname_A', default='Team A', help='Name of team A')
    parser.add_argument('teamB', nargs='?', metavar='teamname_B', default='Team B', help='Name of team B')
    parser.add_argument('-d', '--datadir', default='.', help='Resource directory')
    parser.add_argument('-f', '--fullscreen', help='Run fullscreen', action='store_true')
    args = parser.parse_args()
    # Update settings
    settings = Settings(args.quizfile, args.datadir)
    settings.teams = [ args.teamA, args.teamB ]
    theme = Theme(args.datadir)
    # Initial game data
    cards = settings.get_random_cards()
    current_team = 0
    # Main game loop
    pygame.init()
    if args.fullscreen:
        # screen = pygame.display.set_mode(theme.screen_size, pygame.FULLSCREEN)
        screen = pygame.display.set_mode(theme.screen_size, pygame.RESIZABLE | pygame.NOFRAME)
    else:
        screen = pygame.display.set_mode(theme.screen_size)
    theme.load_data()
    while len(cards)>0:
        team_get_ready(theme, settings, current_team)
        play_round(theme, settings, current_team, cards)
        current_team = (current_team + 1) % len(settings.teams)
    show_final_scores(theme, settings)
    pygame.quit()
コード例 #31
0
ファイル: cmp_parse.py プロジェクト: reynirf/Greynir
import sys
from timeit import default_timer as timer
import subprocess

# Hack to make this Python program executable from the utils subdirectory
basepath, _ = os.path.split(os.path.realpath(__file__))
_UTILS = os.sep + "utils"
if basepath.endswith(_UTILS):
    basepath = basepath[0:-len(_UTILS)]
    sys.path.append(basepath)

from settings import Settings
from db import SessionContext
from treeutil import TreeUtility as tu

Settings.read(os.path.join(basepath, "config", "Greynir.conf"))
Settings.DEBUG = False
TEXTI = 'þróunarsafn_texti.txt'
SBR = 'þróunarsafn.txt'
SKIPUN = './EVALB/evalb -p ./stillingar.prm'  # Þróunarsafnið kemur fyrst, svo þáttun til að prófa


class Comparison():
    def start(self):
        # Sækja setningar úr þróunarmálheild
        print("Sæki setningar...\n")
        setningar = self.fá_setningar()
        print("Komið! Sæki þáttun... \n")
        # Fá þáttun frá Greyni á svigaformi sem búið er að hreinsa
        þáttun = self.fá_þáttun(
            setningar
コード例 #32
0
import tensorflow as tf
import numpy as np
import cv2

import os
import sys
import time

import matplotlib.pyplot as plt

sys.path.append('./')
import data_loader
from settings import Settings
CONFIG = Settings(required_args=["gpu", "config", "checkpoint"])


# Computes softmax
def softmax(x):
    e_x = np.exp(x)
    return e_x / np.expand_dims(np.sum(e_x, axis=2), axis=2)


# Erase line in stdout
def erase_line():
    sys.stdout.write("\033[F")


# Compute scores for a single image
def compute_iou_per_class(pred, label, mask, n_class):

    pred = np.argmax(pred[..., 0:n_class], axis=2) * mask
コード例 #33
0
ファイル: gui.py プロジェクト: vanyaadev/wow-bot
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.classic_settings = Settings()
        self.bfa_settings = Settings()

        with open('settings.txt', 'r', encoding='utf-8') as file:
            settings = json.loads(file.read())

        if 'classic' in settings:
            self.classic_settings.__dict__ = settings['classic']
        if 'bfa' in settings:
            self.bfa_settings.__dict__ = settings['bfa']

        self.classic_settings_window = SettingsWindow(self.classic_settings)
        self.bfa_settings_window = SettingsWindow(self.bfa_settings)

        self.init_widgets()

        self.dispatcher = Dispatcher(self.classic_settings, self.bfa_settings)
        self.dispatcher.start()  # it is paused now and ready to start

    def init_widgets(self):

        # Init settings windows

        open_classic_settings = QAction('Classic', self)
        open_bfa_settings = QAction('BFA', self)

        open_classic_settings.triggered.connect(self.open_classic_settings)
        open_bfa_settings.triggered.connect(self.open_bfa_settings)

        self.menuBar().addAction(open_classic_settings)
        self.menuBar().addAction(open_bfa_settings)
        self.open_classic_settings()

        # Init buttons
        self.toolbar = QToolBar()
        self.toolbar.setStyleSheet('''
            font-family: Serif;
            font-size: 16px;
            font-weight: bold;
        ''')

        self.start_button = QAction('Start', self)
        self.start_button.triggered.connect(self.start_button_clicked)
        self.toolbar.addAction(self.start_button)

        self.update_from_excel_button = QAction('Add/Update from xls', self)
        self.update_from_excel_button.triggered.connect(
            self.update_from_excel_button_clicked)
        self.toolbar.addAction(self.update_from_excel_button)

        self.scan_now = QAction('Scan now', self)
        self.scan_now.triggered.connect(self.scan_now_clicked)
        self.toolbar.addAction(self.scan_now)

        self.activate_orders = QAction('Activate all orders', self)
        self.activate_orders.triggered.connect(self.activate_orders_clicked)
        self.toolbar.addAction(self.activate_orders)

        self.deactivate_orders = QAction('Deactivate all orders', self)
        self.deactivate_orders.triggered.connect(
            self.deactivate_orders_clicked)
        self.toolbar.addAction(self.deactivate_orders)

        self.set_delivery_time = QAction('Set delivery', self)
        self.set_delivery_time.triggered.connect(self.change_order_time)
        self.toolbar.addAction(self.set_delivery_time)

        self.save_settings_button = QAction('Save settings', self)
        self.save_settings_button.setToolTip(
            'Save settings to use in the next run')
        self.save_settings_button.triggered.connect(
            self.save_settings_button_clicked)
        self.toolbar.addAction(self.save_settings_button)

        self.addToolBar(self.toolbar)

        self.setGeometry(200, 200, 900, 500)
        self.show()

    def start_button_clicked(self):
        if self.start_button.text() == 'Start':
            self.dispatcher.classic_settings = self.classic_settings
            self.dispatcher.bfa_settings = self.bfa_settings
            self.dispatcher.unpause()
            self.start_button.setText('Stop')
        else:
            self.dispatcher.pause()
            self.start_button.setText('Start')

    def update_from_excel_button_clicked(self):
        try:
            fd = QFileDialog.getOpenFileName(self, "Choose xls file",
                                             os.getcwd())[0]

            was_paused = self.dispatcher.paused
            self.dispatcher.pause()
            while not self.dispatcher.pause_accepted:
                time.sleep(0.5)

            self.dispatcher.add_orders_from_excel(fd)

            self.dispatcher.paused = was_paused

        except:
            QMessageBox.warning(self, 'Error', str(sys.exc_info()[0]))

    def scan_now_clicked(self):
        self.dispatcher.classic_last_update = 0
        self.dispatcher.bfa_last_update = 0

    def activate_orders_clicked(self):
        was_paused = self.dispatcher.paused
        self.dispatcher.pause()
        while not self.dispatcher.pause_accepted:
            time.sleep(1)

        self.dispatcher.activate_all_orders()
        self.dispatcher.paused = was_paused

    def deactivate_orders_clicked(self):
        was_paused = self.dispatcher.paused
        self.dispatcher.pause()
        while not self.dispatcher.pause_accepted:
            time.sleep(1)

        self.dispatcher.deactivate_all_orders()
        self.dispatcher.paused = was_paused

    def change_order_time(self):
        was_paused = self.dispatcher.paused
        self.dispatcher.pause()
        while not self.dispatcher.pause_accepted:
            time.sleep(1)

        orders = self.dispatcher.bot.active_orders('eu', active_status=False) + \
                    self.dispatcher.bot.active_orders('us', active_status=False)

        for order in orders:
            hrs = self.classic_settings.delivery_time if 'classic' in order.server.lower(
            ) else self.bfa_settings.delivery_time
            order.online_hrs = hrs
            self.dispatcher.bot.change_order(order)

        self.dispatcher.paused = was_paused

    def save_settings_button_clicked(self):
        self.classic_settings.save('classic')
        self.bfa_settings.save('bfa')

    def open_classic_settings(self):
        self.setWindowTitle('Classic settings')
        self.takeCentralWidget()
        self.setCentralWidget(self.classic_settings_window)

    def open_bfa_settings(self):
        self.setWindowTitle('BFA settings')
        self.takeCentralWidget()
        self.setCentralWidget(self.bfa_settings_window)
コード例 #34
0
    def draw(self, gc):
        size = self.client_size

        imgw = self.rawImgW
        imgh = self.rawImgH
        aspectRatio = imgw / imgh
        topMargin = 0
        # Resize it, but keep the aspect ratio. Add 'margins' to ensure.
        height = size.height
        width = min(size.width, round(height * aspectRatio))
        if width == size.width:
            height = round(width / aspectRatio)
            topMargin = round((size.height - height) / 2)

        leftMargin = round((size.width) - width) / 2

        gc.DrawBitmap(self.bm, leftMargin, topMargin, width, height)
        refWidth = 314
        refWidthContentSize = 10
        multiplicator = width / refWidth

        if not self.connected:
            # Darken background and tell user what to do to connect.
            brush = wx.Brush(wx.Colour(0, 0, 0, 0xff * 0.8),
                             wx.BRUSHSTYLE_SOLID)
            gc.SetBrush(brush)
            gc.DrawRectangle(leftMargin, topMargin, width, height)

            font = gc.CreateFont(
                wx.Font(refWidthContentSize * multiplicator, wx.SWISS,
                        wx.NORMAL, wx.BOLD), wx.Colour(255, 255, 255))
            gc.SetFont(font)

            text = "Not connected to Forza Horizon 4.\n\nPlease enter the following details at\nHome > Settings > Hud in the game:\n\nIP Address: " + (
                str)(Settings.getLocalIp()) + "\nPort: " + (str)(
                    Settings.getPort())
            textSize = gc.GetTextExtent(text)

            textX = leftMargin + (width / 2) - (textSize[0] / 2)
            textY = topMargin + (height / 2) - (textSize[1] / 2)
            gc.DrawText(text, textX, textY)
        else:
            xp, yp = Settings.getPixelPos(self.x, self.z)

            # We know got the pixel location. But this is according to the source image, not to the current size which is displayed.
            # Calibration was very hard. This was supposed to be calculated against the image size, but I had to manually adjust them. Nothing to worry, just leave it like that.
            xp *= (width / 1461)
            yp *= (height / 1417)

            # Also consider the margin, if it has any.
            xp += leftMargin
            yp += topMargin

            refcw = 10
            cw = refcw * multiplicator

            # draw a secondary circle that lights up the area, to make the users eye catch the position more early
            scs = cw * 15
            brush = wx.Brush(wx.Colour(255, 255, 255, 0xff * 0.15))
            gc.SetBrush(brush)
            gc.DrawEllipse(xp - scs / 2, yp - scs / 2, scs, scs)

            # draw main position circle
            brush = wx.Brush(wx.Colour(0, 0, 100, 0xff * 0.4))
            gc.SetBrush(brush)
            pen = wx.Pen(wx.Colour(255, 0, 0), cw / 12)
            gc.SetPen(pen)
            gc.DrawEllipse(xp - cw / 2, yp - cw / 2, cw, cw)

            gc.SetPen(wx.Pen())

            # inner dot

            ids = cw / 10
            brush = wx.Brush(wx.Colour(255, 255, 0))
            gc.SetBrush(brush)
            gc.DrawEllipse(xp - ids / 2, yp - ids / 2, ids, ids)

            # draw a car inside of it, Note: Commented it out. Looks ugly because bitmaps are always placed by full pixel for some reason, only drawables are smooth.
            # carCs = cw/1.5
            # dc.DrawBitmap(self.carBm, xp- carCs/2,yp- carCs/2, carCs, carCs)

            # draw yaw angle graphic
            gc.SetBrush(wx.Brush())
            gc.SetPen(wx.Pen(wx.Colour(100, 0, 255, 0xff * 0.7), cw / 8))
            path = gc.CreatePath()
            distance = math.pi / 4
            yaw = self.yaw - math.pi / 2  # default orientation is incorrect, so fixing it here.
            path.AddArc(xp, yp, (cw / 2) + cw / 6, yaw - distance,
                        yaw + distance, True)

            gc.DrawPath(path)
コード例 #35
0
from constants import *
from display import Display
from fever import Fever
from game import Game
from menu import GameMenu
from settings import Settings

# Set up
myDisplay = Display()
mySettings = Settings()
myMenu = GameMenu(myDisplay, mySettings)
# myPowerup = PowerUp(myDisplay.surface)
myFever = Fever(myDisplay.surface, myDisplay, mySettings)
# myPowerup.set_track(myFever.track)
myGame = Game(myMenu, myDisplay, myFever, mySettings)
running = True

# Game loop
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    myGame.run()

# Quit the game
pygame.quit()
quit()


コード例 #36
0
class Game(GameBase, FSM):
    def __init__(self):
        GameBase.__init__(self, debug=True)
        FSM.__init__(self, "GUI FSM")
        base.disableMouse()

        self.menu = Menu()
        self.settings = Settings()
        self.missionScreen = MissionScreen()
        self.debrief = Debrief()
        self.hud = Hud()
        self.missionSelect = MissionSelect()

        base.camLens.setFov(90)

        self.setMusic("audio/music.mp3", volume=0.5)
        self.setMusic("audio/engine1.wav", volume=0.3)

        self.request("Menu")
        base.taskMgr.add(self.missionOverTask, "is mission over")

    def enterMenu(self):
        self.menu.show()
        self.accept("menu-start", self.request, ["MissionSelect"])
        self.accept("menu-instructions", self.request, ["Instructions"])
        self.accept("menu-quit", sys.exit)
        self.accept("menu-settings", self.request, ["Settings"])

    def exitMenu(self):
        self.menu.hide()
        self.ignore("menu-start")
        self.ignore("menu-instructions")
        self.ignore("menu-quit")

    def enterSettings(self):
        self.settings.show()
        self.accept("settings-back", self.request, ["Menu"])

    def exitSettings(self):
        self.settings.hide()
        self.ignore("settings-back")

    def enterMissionSelect(self):
        self.missionSelect.show()
        self.accept("missionselect-m1", self.setMission, ["m1"])
        self.accept("missionselect-m2", self.setMission, ["m2"])
        self.accept("missionselect-test", self.setMission, ["test"])

    def exitMissionSelect(self):
        self.missionSelect.hide()
        self.ignore("missionselect-m1")
        self.ignore("missionselect-m2")

    def enterMissionScreen(self):
        self.missionScreen.showWithTitle(self.currentMission.objective)
        self.accept("mission-start", self.request, ["Game"])

    def exitMissionScreen(self):
        self.missionScreen.hide()
        self.ignore("mission-start")

    def enterGame(self):
        self.world = World(self.currentMission.mapName)
        self.startTime = "Not yet set - not loaded"  #set in self.missionOverTask
        self.player = Player(self.world)
        self.accept("player-into-Collision", self.player.reset)
        self.accept("game-quit", self.request, ["Menu"])
        self.accept("game-finished", self.request, ["Debrief"])

    def exitGame(self):
        self.world.destroy()
        self.player.model.removeNode()
        del self.player
        base.taskMgr.remove("hud update")
        self.hud.timer.setText("")
        self.hud.hide()
        base.taskMgr.remove("update player")
        self.ignore("game-quit")

    def enterDebrief(self):
        self.debrief.show()
        self.debrief.setTitle(self.currentMission.question, isAnswer=False)
        self.debrief.setButtons(self.currentMission)
        self.accept("debrief-correct", self.debrief.setTitle, ["Correct"])
        self.accept("debrief-wrong", self.debrief.setTitle, ["Wrong"])
        self.accept("debrief-back", self.request, ["Menu"])
        self.accept("debrief-restart", self.request, ["Game"])

    def exitDebrief(self):
        self.debrief.hide()
        self.ignore("debrief-correct")
        self.ignore("debrief-wrong")
        self.debrief.initialise(
        )  #clear all settings on it, ie title and buttons, as they are mission specific

    def setMission(self, name):
        self.currentMission = missions[name]
        self.request("MissionScreen")

    def missionOverTask(self, task):
        if self.state == "Game" and self.world.loaded and self.startTime == "Not yet set - not loaded":
            self.startTime = time.time()
            self.hud.show()
            self.hud.initialise(self.currentMission.objective,
                                self.currentMission.timeAllowed)
            base.taskMgr.add(self.hud.hudTask, "hud update")
        if self.state == "Game" and self.world.loaded:
            if time.time() - self.startTime > self.currentMission.timeAllowed:
                self.request("Debrief")
        return task.cont
コード例 #37
0
def run_game():
    # Initialize game and create a screen object
    pygame.init()

    si_settings = Settings()

    screen = pygame.display.set_mode((si_settings.screen_width, si_settings.screen_height))
    pygame.display.set_caption("Space Invaders")

    # Make the Menu and the Play Game and High Scores buttons.
    menu = Menu(si_settings, screen)
    play_button = Button(si_settings, screen, "PLAY GAME", (si_settings.screen_width * 2.75) / 7, (si_settings.screen_height * 5.25) / 7)
    high_scores_button = Button(si_settings, screen, "HIGH SCORES", (si_settings.screen_width * 2.65) / 7, (si_settings.screen_height * 6) / 7)

    # Create an instance to store game statistics and create a scoreboard.
    stats = GameStats(si_settings)
    sb = Scoreboard(si_settings, screen, stats)

    # Make a ship, a group of bullets, and a group of aliens
    ship = Ship(si_settings, screen)
    bullets = Group()
    alienBullets = Group()
    aliens = Group()

    images = ["images/alien1.png", "images/alien2.png", "images/alien3.png"]

    random = randint(0, 10)
    ufo_random = randint(0, 10)
    start_ticks = pygame.time.get_ticks()

    # Create the ufo
    ufo = None

    # Create the fleet of aliens.
    gf.create_fleet(si_settings, screen, ship, aliens, images)

    # Load the background music
    # bg_music = pygame.mixer.music("audio/background_music.mp3")

    # Start the main loop for the game
    while True:
        # Watch for keyboard and mouse events.
        gf.check_events(si_settings, screen, stats, sb, menu, play_button, high_scores_button, ship, aliens, bullets, alienBullets, images)

        if stats.game_active:
            seconds = int((pygame.time.get_ticks() - start_ticks) / 1000)
            if seconds - previous_time == random:
                gf.fire_back(si_settings, screen, aliens, alienBullets)
                previous_time = seconds
                random = randint(5, 10)
            if seconds - ufo_previous_time == ufo_random:
                ufo = gf.create_ufo(si_settings)
                ufo_previous_time = seconds
                ufo_random = randint(20, 30)
                print("UFO Random: " + str(ufo_random) + "    Seconds: " + str(seconds) + "   UFO Previous Time: " + str(ufo_previous_time))
            ship.update()
            gf.update_bullets(si_settings, screen, stats, sb, ship, aliens, bullets, alienBullets, images)
            gf.update_aliens(si_settings, screen, stats, sb, ship, aliens, bullets, alienBullets, images, (seconds - previous_time), ufo)
        else:
            previous_time = int(pygame.time.get_ticks() / 1000)
            ufo_previous_time = int(pygame.time.get_ticks() / 1000)

        gf.update_screen(si_settings, screen, stats, sb, ship, aliens, bullets, alienBullets, menu, play_button, high_scores_button)
コード例 #38
0
import firebase_admin
from firebase_admin import db
from telegram.ext import BasePersistence
from ast import literal_eval
from collections import defaultdict
from typing import Dict
from settings import Settings

cred = firebase_admin.credentials.Certificate(Settings.fb_creds())
firebase_admin.initialize_app(cred, {"databaseURL": Settings.db_url()})


class FirebasePersistence(BasePersistence):

    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = super(FirebasePersistence, cls).__new__(cls)
        return cls.instance

    def __init__(self):
        # cred = firebase_admin.credentials.Certificate(credentials)
        # self.app = app
        self.fb_user_data = db.reference("user_data")
        self.users = db.reference("users")

        self.purchases = db.reference("ticket_purchases")
        self.tickets = db.reference("tickets")

        self.merch_purchases = db.reference("merch_purchases")
        self.merch = db.reference("merch")
コード例 #39
0
 def open_settings(self):
     """ 
     Obri la finestra dels settings on es canviaràn els temps màxims i mínims del segments i total.
     """
     self.new_window = Settings()
コード例 #40
0
ファイル: nn_training.py プロジェクト: jwvanderbeck/EliteOCR
    def __init__(self):
        settings = Settings()
        self.trainingImageDir = dirname(settings.app_path + "\\nn_training_images\\"
        self.splitTrainingImageFolderName = 'split_training_images'
        self.splitTrainingImageDir = self.trainingImageDir + self.splitTrainingImageFolderName + "\\"

        self.checkAndMakeDir(self.trainingImageDir)
        self.checkAndMakeDir(self.splitTrainingImageDir)

        self.minSegmentArea = 600
        self.maxSegmentWidth = 0
        self.maxSegmentHeight = 0

    def checkAndMakeDir(self, directory):
        if not os.path.exists(directory):
            os.makedirs(directory)

    def getImageList(self):
        #@TODO: store images already converted, and filter them from this list
        trainingImageNames = os.listdir(self.trainingImageDir)
        trainingImageNames.remove(self.splitTrainingImageFolderName)
        return map(lambda trainingImageNames: self.trainingImageDir + trainingImageNames, trainingImageNames)

    def processImages(self, imageFilePaths, objectColor, threshold):
        processedImages = []
        for i, imageFilePath in zip(range(0, len(imageFilePaths) - 1), imageFilePaths):
            if i%100 == 0.0:
                print 'Chopped', i, 'images so far...'
            processedImages.append(self.processImage(imageFilePath, objectColor, threshold))
        return processedImages

    def processImage(self, imageFilePath, objectColor, threshold):
        if type(imageFilePath) == list:
            return self.processImages(imageFilePath, objectColor, threshold)
        img = cv2.imread(imageFilePath)
        head, tail = ntpath.split(imageFilePath)
        value, rand = tail.split('_')
        res = [0, 0]  # @TODO: return original source image resolution
        imgBig = self.scaleImageToHeight(img, 100)
        segments = self.segmentImage(imgBig, objectColor, threshold)
        for val, segment in zip(value, segments):
            #cv2.imshow('asd', numpy.asarray(segment[0]))
            #cv2.waitKey(0)
            #cv2.destroyAllWindows()

            cv2.imwrite(self.splitTrainingImageDir + val + '_' + rand + '.png', segment[0])
            s = segment[0]
            h = len(s)
            w = len(s[0])
            self.trackMaxSegmentSize(w, h)
        return [value, res, segments]

    def trackMaxSegmentSize(self, width, height):
        if width > self.maxSegmentWidth:
            self.maxSegmentWidth = width
        if height > self.maxSegmentHeight:
            self.maxSegmentHeight = height

    def segmentImage(self, img, objectColor, threshold):
        horizontalSlices = []
        verticalSlices = self.segmentImageVertical(img, objectColor, threshold)  #first we segment vertically
        for verticalSlice in verticalSlices:
            if len(verticalSlice):
                horizontalSlice = self.segmentImageHorizontal(verticalSlice, objectColor, threshold)  #then we segment those segments horizontally
                if len(horizontalSlice):
                    horizontalSlices.append(horizontalSlice)
        return horizontalSlices

    def scaleImageToHeight(self, img, newHeight):
        h = float(img.shape[0])
        w = float(img.shape[1])
        ratio = (newHeight / h)
        newWidth = int(round(w * ratio, 0))
        return cv2.resize(img, (newWidth, newHeight))

    def segmentImageHorizontal(self, img, objectColor, threshold):
        imgBig = img
        height = len(imgBig)
        width = len(imgBig[0])
        horizontalBounds = []
        topSide = -1
        matched = False
        for y in range(0, height - 1):
            for x in range(0, width - 1):
                if self.colorMatch(imgBig[y][x], objectColor, threshold):  #we found objectColor
                    matched = True
            if matched:
                if topSide < 0:  #we don't have a value for the topSide yet, so this must be the first horizontal
                    topSide = max(y - 1, 0)  #move one up (if we can) to capture any potential antialiasing we may have missed through threshold

            else:  #we're off objectColor
                if topSide >= 0:  #if we've already found the topSide, then this must be the bottom one
                    horizontalBounds.append([topSide, y])
                    topSide = -1
            matched = False

        #print 'image dimensions: ' + str(width) + 'x' + str(height), len(imgBig[0][0])
        imageSlices = []
        for horizontalBound in horizontalBounds:
            y = horizontalBound[0]
            h = horizontalBound[1] - y
            x = 0
            w = width
            if w * h > self.minSegmentArea:  #remove pesky commas/periods from the images
                imageSlices.append(numpy.array(imgBig[y:y + h, x:x + w]))
                #cv2.rectangle(imgBig, (x, y), (x + w, y + h), (0, 255, 0), 1)
        return numpy.array(imageSlices)

    def segmentImageVertical(self, img, objectColor, threshold):
        imgBig = img
        height = len(imgBig)
        width = len(imgBig[0])
        verticalBounds = []
        leftSide = -1
        matched = False

        for x in range(0, width - 1):
            for y in range(0, height - 1):
                if self.colorMatch(imgBig[y][x], objectColor, threshold):  #we found objectColor
                    matched = True
            if matched:
                if leftSide < 0:  #we don't have a value for the left side yet, so this must be the first vertical
                    leftSide = max(x - 1, 0)  #move one left (if we can) to capture any potential antialiasing we may have missed through threshold

            else:  #we are off objectColor
                if leftSide >= 0:  #if we've already found the left side, then this must be the right one
                    verticalBounds.append([leftSide, x + 1])
                    leftSide = -1
            matched = False

        #print 'image dimensions: ' + str(width) + 'x' + str(height), len(imgBig[0][0])
        imageSlices = []
        for verticalBound in verticalBounds:
            x = verticalBound[0]
            w = verticalBound[1] - x
            y = 0
            h = height
            if w * h > self.minSegmentArea:  #remove pesky commas/periods from the images
                imageSlices.append(numpy.array(imgBig[y:y + h, x:x + w]))
                #cv2.rectangle(imgBig, (x, y), (x + w, y + h), (0, 255, 0), 1)
        return imageSlices

    def colorMatch(self, color1, color2, threshold):
        dist = 0.0
        for c1, c2 in zip(color1, numpy.asarray(color2)):
            dist += pow((c1 - c2), 2)
        return pow(dist, 0.5) <= threshold


print 'Conversion of images beginning...'
train = nnTraining()
imgList = train.getImageList()
imgPaths = imgList  #[0:10]
#imgPaths = './nn_training_images/1462_1417536191-38695.png'
print 'Found', len(imgPaths), 'images to chop'
print 'Chopping...'
train.processImage(imgPaths, [0, 0, 0], 350)
print 'Chopping completed.'
print 'Max digit image dimensions:', train.maxSegmentWidth, train.maxSegmentHeight

cv2.waitKey(0)
コード例 #41
0
import os
import pdb
import sys
import matplotlib as M
M.use('gtkagg')
import matplotlib.pyplot as plt
import numpy as N

sys.path.append('/home/jrlawson/gitprojects/')

from WEM.postWRF import WRFEnviron
from settings import Settings
import WEM.utils as utils
#from WEM.postWRF.postWRF.rucplot import RUCPlot

config = Settings()
p = WRFEnviron(config)

skewT = 0
plot2D = 0
streamlines = 0
rucplot = 0
coldpoolstrength = 0
spaghetti = 0
std = 0
profiles = 0
frontogenesis = 1
upperlevel = 0

# enstype = 'STCH'
# enstype = 'ICBC'
コード例 #42
0
            attack, counter.subtype.select(hold_expired, counter - 1, 0),
            hang - 1))
    max_hold_new_val = audio.subtype.select(
        attack, max_hold.subtype.select(hold_expired, max_hold, decay_new_val),
        attack_new_val)
    max_hold.d(audio.subtype.select(reset, max_hold_new_val, 0))

    #remove extra bits (except one to allow for addition)
    max_hold = (max_hold >> max_factor).resize(audio_bits)

    return max_hold


if __name__ == "__main__" and "sim" in sys.argv:

    settings = Settings()
    settings.agc_frame_size = 100
    settings.agc_frames = 4
    clk = Clock("clk")
    data_in = Signed(16).input("data_in")
    stb_in = Boolean().input("stb_in")
    magnitude = measure_magnitude(clk, data_in, stb_in, 0, 0)

    stimulus = []
    for i in range(1000):
        stimulus.append(100)
    for i in range(20000):
        stimulus.append(0)

    response = []
コード例 #43
0
ファイル: main_page.py プロジェクト: Handosonic/Python
from tkinter import *
from tkinter.ttk import Combobox
from PIL import Image,ImageTk
from password_encrypt import encrypt_pass
from tkinter import messagebox
from login_data import get_login_information
from password_encrypt import check_password
from settings import Settings

se = Settings()

def donoting():
    pass
class main_page():
    def __init__(self, setting, user, data):
        self.sheet_information = data
        self.user_info = user
        self.set = setting
        self.root2 = Tk()
        resolution = self.set.main_menu_width +'x'+ self.set.main_menu_length
        self.root2.geometry(resolution)
        self.length = len(self.sheet_information)
        self.root2.title("Үндсэн хуудас")
        self.root2.resizable(0,0)
        print(self.user_info)
        self.menubar = Menu(self.root2)
        filemenu = Menu(self.menubar, tearoff=0)
        filemenu.add_command(label="Нууц үг солих", command = self.change_password)
        if(self.user_info[1] == 'admin'):
            filemenu.add_command(label="Шинээр эрх үүсгэх", command = self.new_member_create)
        filemenu.add_separator()
コード例 #44
0
 def __init__(self, *args, **kwargs):
     self.settings = Settings()
     self.btc_eth_candles = List("BTC_ETH")
     self.usdt_eth_candles = List("USDT_ETH")
     self.usdt_btc_candles = List("USDT_BTC")
コード例 #45
0
ファイル: ui.py プロジェクト: alchemist1234/QTracker
    def __init__(self, main: QMainWindow, settings: Settings):
        self.main = main
        if not main.objectName():
            main.setObjectName('MainWindow')
        height = settings.int_value(default_settings.main_height)
        width = settings.int_value(default_settings.main_width)
        main.resize(width, height)
        self.central_widget = QWidget(main)
        self.vbox_central = QVBoxLayout()
        self.central_widget.setLayout(self.vbox_central)
        self.widget = QWidget(self.central_widget)
        self.vbox_widget = QVBoxLayout()
        self.widget.setLayout(self.vbox_widget)

        # Menu Bar
        # self.menu_bar = QMenuBar()
        # main.setMenuBar(self.menu_bar)
        # self.menu_file = self.menu_bar.addMenu('file')
        # self.action_open = self.menu_file.addAction('open')

        # Tool Bar
        self.tool_bar = main.addToolBar('tool bar')
        icon_open = QIcon(resource_path('images/open-line.png'))
        icon_setting = QIcon(resource_path('images/settings-line.png'))
        icon_analyze = QIcon(resource_path('images/cpu-line.png'))
        icon_export = QIcon(resource_path('images/content-save.png'))
        self.bt_open_file = QPushButton(icon_open, '', self.widget)
        self.bt_settings = QPushButton(icon_setting, '', self.widget)
        self.bt_load_file = QPushButton(icon_analyze, '', self.widget)
        self.bt_export = QPushButton(icon_export, '', self.widget)
        self.tool_bar.addWidget(self.bt_open_file)
        self.tool_bar.addWidget(self.bt_settings)
        self.tool_bar.addWidget(self.bt_load_file)
        self.tool_bar.addSeparator()
        self.tool_bar.addWidget(self.bt_export)

        # Top Layout
        self.vbox_top = QVBoxLayout()
        self.lb_file_path = QLabel(self.widget)
        self.lb_file_path.setText(main.tr(constant.msg_file_unselected))
        self.vbox_top.addWidget(self.lb_file_path)
        self.vbox_widget.addLayout(self.vbox_top)

        # Middle Layout
        self.hbox_middle = QHBoxLayout()
        self.view = VideoView(main)
        self.scene = VideoScene(self.view, settings)
        self.view.setScene(self.scene)
        self._btg_view = ViewButtonGroup(settings, self.widget)
        self.hbox_middle.addWidget(self.view)
        self.view.add_fixed_widget(self._btg_view, Qt.AlignRight | Qt.AlignTop)
        self.vbox_widget.addLayout(self.hbox_middle)

        # Bottom Layout
        self.hbox_bottom = QHBoxLayout()
        self.lb_frames = QLabel(self.widget)
        self.sl_frames = QSlider(Qt.Horizontal, self.widget)
        self.sl_frames.setMinimum(1)
        self.sl_frames.setMaximum(1)
        self.sl_frames.setSingleStep(1)
        self.sl_frames.setPageStep(1)
        self.lcd_current_frame = QLCDNumber(self.widget)
        self.lcd_current_frame.setSegmentStyle(QLCDNumber.Flat)
        self.lcd_current_frame.setDigitCount(9)
        icon_play = QIcon(resource_path('images/play-circle-outline.png'))
        self.bt_play = QPushButton(icon_play, '', self.widget)
        self.le_filter = QLineEdit(self.widget)
        self.hbox_bottom.addWidget(self.lb_frames)
        self.hbox_bottom.addWidget(self.sl_frames)
        self.hbox_bottom.addWidget(self.lcd_current_frame)
        self.hbox_bottom.addWidget(self.bt_play)
        self.hbox_bottom.addWidget(self.le_filter)
        self.vbox_widget.addLayout(self.hbox_bottom)

        # Status Bar
        self.status_bar = QStatusBar(main)
        self.status_progress = QProgressBar(self.status_bar)
        self.status_progress.setRange(0, 100)
        self.status_progress.setValue(0)
        self.status_progress.setFixedWidth(200)
        self.status_bar.showMessage(main.tr(constant.status_ready))
        self.status_bar.addPermanentWidget(self.status_progress)
        main.setStatusBar(self.status_bar)

        # Global
        self.vbox_central.addWidget(self.widget)
        self.main.setCentralWidget(self.central_widget)

        self.translate()
コード例 #46
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    #pygame.display.set_mode返回一个surface对象
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    bullet_sound = pygame.mixer.Sound('sound/bullet.wav')
    bullet_sound.set_volume(0.3)
    pygame.mixer.music.load('sound/game_music.wav')
    pygame.mixer.music.play(-1, 0.0)
    pygame.mixer.music.set_volume(0.25)
    enemy1_down_sound = pygame.mixer.Sound("sound/enemy1_down.wav")
    enemy2_down_sound = pygame.mixer.Sound("sound/enemy2_down.wav")
    enemy3_down_sound = pygame.mixer.Sound("sound/enemy3_down.wav")
    game_over_sound = pygame.mixer.Sound('sound/game_over.wav')
    enemy1_down_sound.set_volume(0.3)
    enemy2_down_sound.set_volume(0.4)
    enemy3_down_sound.set_volume(0.5)
    game_over_sound.set_volume(0.3)
    shoot_frequency = 0
    enemy_frequency = 0
    background = pygame.image.load("images\\background_1.png").convert()
    _game_over = pygame.image.load('images/gameover.png')
    game_over = pygame.transform.scale(_game_over, (320, 568))
    pygame.display.set_caption("plane_war")
    play_button = Button(ai_settings, screen, "play")
    stats = GameStats(ai_settings)
    s = Score(ai_settings, screen, stats)
    plane = Plane(ai_settings, screen)
    bullets = Group()
    framerate = pygame.time.Clock()
    Heroplane = Mysprite(screen)
    Heroplane.load("images//hero_plane_1.png", 66, 80, 2)
    group = pygame.sprite.Group()
    group.add(Heroplane)
    enemys = Group()
    middle = Group()
    middle_frequency = 0
    enemies_down = pygame.sprite.Group()
    breakplane = Group()
    middle_down = pygame.sprite.Group()
    bosses = Group()
    break_boss = Group()
    delay = 0
    delay_1 = 0
    delay_2 = 0
    delay_3 = 0
    while True:
        framerate.tick(60)
        #blit用于在screen上绘制图像
        screen.blit(background, (0, 0))
        gf.check_events(ai_settings, screen, stats, play_button, plane, enemys,
                        bullets, bullet_sound, s)
        if stats.game_active and not stats.boss_state:
            plane.update()
            middle.update()
            gf.update_bullets(ai_settings, screen, plane, enemys, bullets,
                              stats, s, shoot_frequency, enemies_down,
                              enemy1_down_sound, middle, middle_down,
                              enemy2_down_sound, bosses, break_boss,
                              enemy3_down_sound)
            gf.update_enemys(ai_settings, stats, screen, plane, enemys,
                             bullets, s, play_button, breakplane,
                             game_over_sound, enemies_down, middle,
                             middle_down, bosses)
            if enemy_frequency % 60 == 0 and len(
                    enemys) < ai_settings.min_enemy_number:
                gf.create_fleet(ai_settings, screen, plane, enemys)
            else:
                enemy_frequency += 1
            if middle_frequency % 100 == 0 and len(
                    middle) < ai_settings.min_middle_number:
                gf.create_middle_enemys(ai_settings, screen, middle)
            else:
                middle_frequency += 1
        if stats.game_active and stats.boss_state:
            plane.update()
            gf.update_bullets(ai_settings, screen, plane, enemys, bullets,
                              stats, s, shoot_frequency, enemies_down,
                              enemy1_down_sound, middle, middle_down,
                              enemy2_down_sound, bosses, break_boss,
                              enemy3_down_sound)
            gf.update_bosses(ai_settings, plane, breakplane, stats, s,
                             game_over_sound, play_button, bosses)
            if (len(bosses) <= 0):
                gf.create_boss(ai_settings, screen, bosses)
            bosses.update()
        if not stats.game_active and stats.game_state:
            enemys.empty()
            bullets.empty()
            screen.blit(game_over, (0, 0))
        for planes in breakplane:
            if delay < 10:
                planes.image = pygame.image.load("images\\hero_break1.png")
                delay += 1
            elif delay < 20:
                planes.image = pygame.image.load("images\\hero_break2.png")
                delay += 1
            elif delay < 30:
                planes.image = pygame.image.load("images\\hero_break3.png")
                delay += 1
            elif delay < 40:
                planes.image = pygame.image.load("images\\hero_break4.png")
                delay += 1
            screen.blit(planes.image, plane.rect)
            if delay >= 40:
                delay = 0
                breakplane.remove(plane)
        for enemy_down in enemies_down:
            if delay_1 < 10:
                enemy_down.image = pygame.image.load("images\\enemy1_1.png")
                delay_1 += 1
            elif delay_1 < 20:
                enemy_down.image = pygame.image.load("images\\enemy1_2.png")
                delay_1 += 1
            elif delay_1 < 30:
                enemy_down.image = pygame.image.load("images\\enemy1_3.png")
                delay_1 += 1
            elif delay_1 < 40:
                enemy_down.image = pygame.image.load("images\\enemy1_4.png")
                delay_1 += 1

            screen.blit(enemy_down.image, enemy_down.rect)
            if delay_1 >= 40:
                delay_1 = 0
                enemies_down.remove(enemy_down)
        for mi_down in middle_down:
            if delay_2 < 10:
                mi_down.image = pygame.image.load("images\\middle_1.png")
                delay_2 += 1
            elif delay_2 < 20:
                mi_down.image = pygame.image.load("images\\middle_2.png")
                delay_2 += 1
            elif delay_2 < 30:
                mi_down.image = pygame.image.load("images\\middle_3.png")
                delay_2 += 1
            elif delay_2 < 40:
                mi_down.image = pygame.image.load("images\\middle_4.png")
                delay_2 += 1

            screen.blit(mi_down.image, mi_down.rect)
            if delay_2 >= 40:
                delay_2 = 0
                middle_down.remove(mi_down)
        for boss_down in break_boss:
            if delay_3 < 10:
                boss_down.image = pygame.image.load("images\\boss_1.png")
                delay_3 += 1
            elif delay_3 < 20:
                boss_down.image = pygame.image.load("images\\boss_2.png")
                delay_3 += 1
            elif delay_3 < 30:
                boss_down.image = pygame.image.load("images\\boss_3.png")
                delay_3 += 1
            elif delay_3 < 40:
                boss_down.image = pygame.image.load("images\\boss_4.png")
                delay_3 += 1
            elif delay_3 < 50:
                boss_down.image = pygame.image.load("images\\boss_4.png")
                delay_3 += 1
            elif delay_3 < 60:
                boss_down.image = pygame.image.load("images\\boss_4.png")
                delay_3 += 1

            screen.blit(boss_down.image, boss_down.rect)
            if delay_3 >= 60:
                delay_3 = 0
                break_boss.remove(boss_down)
        gf.update_screen(ai_settings, screen, stats, plane, enemys, bullets,
                         play_button, s, middle, bosses)

        pygame.display.update()
コード例 #47
0
ファイル: alien_invasion.py プロジェクト: goku-77/alien
class AlienInvasion:
    def __init__(self):
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption('Alien Invasion')
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)
        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self._create_fleet()
        self.play_button = Button(self, "Play")

    def run_game(self):
        while True:
            self._check_events()
            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()
            self._update_screen()

    def _check_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            self.stats.reset_stats()
            self.stats.game_active = True
            self.sb.prep_score()
            self.sb.prep_level()
            self.sb.prep_ships()

            self.aliens.empty()
            self.bullets.empty()

            self._create_fleet()
            self.ship.center_ship()

            pygame.mouse.set_visible(False)
            self.settings.initialize_dynamic_settings()

    def _check_keydown_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    def _check_keyup_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def _fire_bullet(self):
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_bullets(self):
        self.bullets.update()
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)
        self._check_bullet_alien_collisions()

    def _check_bullet_alien_collisions(self):
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)
        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
                self.sb.prep_score()
                self.sb.check_high_score()
        if not self.aliens:
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()
            self.stats.level += 1
            self.sb.prep_level()

    def _create_fleet(self):
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)

        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (5 * alien_height) -
                             ship_height)
        number_rows = available_space_y // (2 * alien_height)
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def _update_aliens(self):
        self._check_fleet_edges()
        self.aliens.update()
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()
        self._check_aliens_bottom()

    def _check_fleet_edges(self):
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _check_aliens_bottom(self):
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                self._ship_hit()
                break

    def _change_fleet_direction(self):
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _ship_hit(self):
        if self.stats.ships_left > 0:
            self.stats.ships_left -= 1
            self.sb.prep_ships()
            self.aliens.empty()
            self.bullets.empty()
            self._create_fleet()
            self.ship.center_ship()
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _update_screen(self):
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)
        if not self.stats.game_active:
            self.play_button.draw_button()
        self.sb.show_score()
        pygame.display.flip()
コード例 #48
0
ファイル: game.py プロジェクト: marcinstelmaszyk/Aliengame
class Game():
    def __init__(self):
        pygame.init()
        self.ai_settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.ai_settings.screen_width, self.ai_settings.screen_height))
        pygame.display.set_caption("Inwazja obcych")

        # Utworzenie przycisku Gra
        self.play_button = Button(self.ai_settings, self.screen, 'Gra')

        # Utworzenie egzemplarza przenaczonego do przechowywania danych
        # statystycznych gry oraz utworzenie egzemplarza klasy Scoreboard
        self.stats = GameStats(self.ai_settings)
        self.sb = Scoreboard(self.ai_settings, self.screen, self.stats)

        #Utworzenie statku kosmicznego, grupy pocisków oraz grupy obcych
        self.ship = Ship(self.ai_settings, self.screen)
        self.bullets = Group()
        self.aliens = Group()

        # Utworzenie floty obcych
        self.create_fleet()

    def run(self):
        while True:
            self.check_events()
            if self.stats.game_active:
                self.ship.update()
                self.update_bullets()
                self.update_aliens()
            self.update_screen()

    def create_fleet(self):
        '''Utworzenie pełnej floty obcych.'''
        alien = Alien(self.ai_settings, self.screen)
        number_aliens_x = self.get_number_aliens_x(alien.rect.width)
        number_rows = self.get_number_rows(alien.rect.height)

        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self.create_alien(alien_number, row_number)

    def get_number_aliens_x(self, alien_width):
        '''Ustalenie liczby obcych, którzy zmieszczą się w rzędzie.'''
        available_space_x = self.ai_settings.screen_width - 2 * alien_width
        number_aliens_x = int(available_space_x / (2 * alien_width))
        return number_aliens_x

    def get_number_rows(self, alien_height):
        '''Ustalenie ile rzędów obcych zmieści się na ekranie'''
        available_space_y = (self.ai_settings.screen_height -
                             3 * alien_height - self.ship.rect.height)
        number_rows = int(available_space_y / (2 * alien_height))
        return number_rows

    def create_alien(self, alien_number, row_number):
        '''Utwórz nowego obcego.'''
        alien = Alien(self.ai_settings, self.screen)
        alien_width = alien.rect.width
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def check_events(self):
        '''Reakcja na zdarzenia generowane przez klawiaturę i mysz.'''
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self.check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self.check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_x, mouse_y = pygame.mouse.get_pos()
                self.check_play_button(mouse_x, mouse_y)

    def check_keydown_events(self, event):
        '''Reakcja na naciśnięcie klawisza.'''
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_SPACE:
            self.fire_bullet()
        elif event.key == pygame.K_g:
            self.start_game()
        elif event.key == pygame.K_q:
            sys.exit()

    def fire_bullet(self):
        # Utworzenie nowego pocisku i dodanie go do grupy pocisków
        if len(self.bullets) < self.ai_settings.bullets_allowed:
            new_bullet = Bullet(self.ai_settings, self.screen, self.ship)
            self.bullets.add(new_bullet)

    def start_game(self):
        '''Rozpoczęcie gry poprzez wywołanie domyślnych ustawień.'''
        if not self.stats.game_active:
            # Wyzerowanie ustawień dotyczących gry.
            self.ai_settings.initialize_dynamic_settings()
            # Ukrycie kursora myszy
            pygame.mouse.set_visible(False)
            # Wyzerowanie danych statystycznych gry
            self.stats.reset_stats()
            self.stats.game_active = True
            # Wyzerowanie obrazów tablicy wyników.
            self.sb.prep_score()
            self.sb.prep_high_score()
            self.sb.prep_level()
            # Usunięcie zawartości list aliens i bullets
            self.aliens.empty()
            self.bullets.empty()
            # Utworzenie nowej floty i wyśrodkowanie statku
            self.create_fleet()
            self.ship.center_ship()

    def check_keyup_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def check_play_button(self, mouse_x, mouse_y):
        '''Rozpoczęcie nowej gry po kliknięciu przycisku Gra przez użytkownika'''
        button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)
        if button_clicked and not self.stats.game_active:
            self.start_game()

    def update_bullets(self):
        self.bullets.update()
        # Usunięcie pocisków, które znajdą się poza ekranem
        for bullet in self.bullets.copy():
            if bullet.rect.bottom < 0:
                self.bullets.remove(bullet)

        self.check_bullet_alien_collisions()

    def check_bullet_alien_collisions(self):
        '''Reakcja na kolizję między pociskiem i obcym.'''
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)
        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.ai_settings.alien_points * len(aliens)
                self.sb.prep_score()
            self.check_high_score()
        if len(self.aliens) == 0:
            # Jeżeli cała flota została zniszczona, gracz przechodzi na kolejny poziom.
            self.bullets.empty()
            self.ai_settings.increase_speed()

            # Inkrementacja numeru poziomu.
            self.stats.level += 1
            self.sb.prep_level()

            self.create_fleet()

    def check_high_score(self):
        '''Sprawdzenie, czy mamy nowy najlpeszy wynik osiągnięty dotąd w grze.'''
        if self.stats.score > self.stats.high_score:
            self.stats.high_score = self.stats.score
            self.sb.prep_high_score()

    def update_aliens(self):
        '''Uaktualnienie położenia wszystkich obcych we flocie'''
        self.check_fleet_edges()
        self.aliens.update()
        # Wykrywanie kolizji między obcym i statkiem
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self.ship_hit()
        # Wyszukiwanie obcych docierających do dolnej krawędzi ekranu
        self.check_aliens_bottom()

    def check_fleet_edges(self):
        '''Odpowiednia reakcja, gdy obcy dotrze do krawędzi ekranu.'''
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self.change_fleet_direction()
                break

    def change_fleet_direction(self):
        '''Przesunięcie całej floty w dół i zmiana kierunku, w którym się ona porusza.'''
        for alien in self.aliens.sprites():
            alien.rect.y += self.ai_settings.fleet_drop_speed
        self.ai_settings.fleet_direction *= -1

    def ship_hit(self):
        '''Reakcja na uderzenie obcego w statek.'''
        if self.stats.ships_left > 0:
            # Zmniejszenie wartości przechowywanej w ships_left
            self.stats.ships_left -= 1
            # Uaktualnienie tablicy wyników.
            self.sb.prep_ships()
            # Usunięcie zawartości list aliens i bullets
            self.aliens.empty()
            self.bullets.empty()
            # Utworzenie nowej floty i wyśrodkowanie statku
            self.create_fleet()
            self.ship.center_ship()
            # Pauza
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def check_aliens_bottom(self):
        '''Sprawdzenie, czy którykolwiek obcy dotarł do dolnej krawędzi ekranu'''
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                self.ship_hit()
                break

    def update_screen(self):
        '''Uaktualnienie obrazów na ekranie i przejście do nowego ekranu.'''
        self.screen.fill(self.ai_settings.bg_color)
        # Ponowne wyświetlenie wszystkich pocisków pod warstwami statku kosmicznego i obcych
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.ship.blitme()
        self.aliens.draw(self.screen)
        # Wyświetlenie informacji o punktacji.
        self.sb.show_score()
        # Wyświetlenie przycisku tylko wtedy, gdy gra jest nieaktywna
        if not self.stats.game_active:
            self.play_button.draw_button()

        pygame.display.flip()
コード例 #49
0
def save_only(iface):
    import common.network as network
    from common import nailyfactersettings
    from settings import Settings
    import netifaces
    #Naily.facts translation map from astute.yaml format
    facter_translate = \
        {
            "ADMIN_NETWORK/interface": "internal_interface",
            "ADMIN_NETWORK/ipaddress": "internal_ipaddress",
            "ADMIN_NETWORK/netmask": "internal_netmask",
            "ADMIN_NETWORK/dhcp_pool_start": "dhcp_pool_start",
            "ADMIN_NETWORK/dhcp_pool_end": "dhcp_pool_end",
            "ADMIN_NETWORK/static_pool_start": "static_pool_start",
            "ADMIN_NETWORK/static_pool_end": "static_pool_end",
        }
    #Calculate and set Static/DHCP pool fields
    #Max IPs = net size - 2 (master node + bcast)
    try:
        ip = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr']
        netmask = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['netmask']
    except:
        print "Interface %s does is missing either IP address or netmask" \
            % (iface)
        sys.exit(1)
    net_ip_list = network.getNetwork(ip, netmask)
    try:
        half = int(len(net_ip_list) / 2)
        #In most cases, skip 10.XXX.0.1
        static_pool = list(net_ip_list[1:half])
        dhcp_pool = list(net_ip_list[half:])
        static_start = str(static_pool[0])
        static_end = str(static_pool[-1])
        dynamic_start = str(dhcp_pool[0])
        dynamic_end = str(dhcp_pool[-1])
    except:
        print "Unable to define DHCP pools"
        sys.exit(1)
    settings = \
        {
            "ADMIN_NETWORK/interface": iface,
            "ADMIN_NETWORK/ipaddress": ip,
            "ADMIN_NETWORK/netmask": netmask,
            "ADMIN_NETWORK/dhcp_pool_start": dynamic_start,
            "ADMIN_NETWORK/dhcp_pool_end": dynamic_end,
            "ADMIN_NETWORK/static_pool_start": static_start,
            "ADMIN_NETWORK/static_pool_end": static_end,
        }
    newsettings = dict()
    for setting in settings.keys():
        if "/" in setting:
            part1, part2 = setting.split("/")
            if part1 not in newsettings.keys():
                newsettings[part1] = {}
            newsettings[part1][part2] = settings[setting]
        else:
            newsettings[setting] = settings[setting]
    #Write astute.yaml
    Settings().write(newsettings, defaultsfile=None, outfn="/etc/astute.yaml")
    #Prepare naily.facts
    factsettings = dict()
    for key in facter_translate.keys():
        factsettings[facter_translate[key]] = settings[key]
    n = nailyfactersettings.NailyFacterSettings()
    n.write(factsettings)
コード例 #50
0
DELAY_BEFORE_QUITTING = 1000
N_PHYSICS_SUBSTEPS = 10
MAX_N_OBSTS = 10

BORDER_S_WIDTH = 1 / 4
CAM_DAMPING_FACTOR = 8

SCORE_ADD_FACTOR = 1.0
SCORE_EXPADD_FACTOR = 0.00002

N_PLAYERS = 1

SEED = 0
DIFFICULTY_PRESET = DifficultyPreset.der_2
SETTINGS = Settings(difficulty_preset=DIFFICULTY_PRESET, fps=FPS)

LOAD = True
SAVE = True

if DIFFICULTY_PRESET == DifficultyPreset.test:
    LOAD = False
    SAVE = False

SAVE_DIR = "saves"
SAVE_PROFILES = [
    f"p1_l{DIFFICULTY_PRESET.value}_s{SEED}",
    f"p2_l{DIFFICULTY_PRESET.value}_s{SEED}",
    f"p3_l{DIFFICULTY_PRESET.value}_s{SEED}",
]
SAVE_PATHS = [
コード例 #51
0
def run_pipeline():
    """Initiate and run analysis on US wildfires."""
    # initialize settings
    start_time = time.time()
    ml_settings = Settings()

    # Collect data
    data_collector.collate_data(ml_settings)

    # Separate data into training, validation, and test sets
    X_train, X_val, X_test, y_train, y_val, y_test = training.separate_time_data(
        ml_settings)

    prep_pipeline = training.prep_pipeline(ml_settings)

    X_train_prepared = prep_pipeline.fit_transform(X_train)
    X_val_prepared = prep_pipeline.transform(X_val)

    # Create a deep learning neural network then train the model on data
    print('WILL BELL Trains DEEP Neural Network:')
    tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
    dnn_clf = models.DNNClassifier(
        random_state=42,
        n_hidden_layers=ml_settings.n_hidden_layers,
        n_neurons=ml_settings.n_neurons,
        batch_size=ml_settings.batch_size,
        batch_norm_momentum=ml_settings.batch_norm_momentum,
        dropout_rate=ml_settings.dropout_rate,
        learning_rate=ml_settings.learning_rate,
        activation=ml_settings.activation)

    dnn_clf.fit(X_train_prepared,
                y_train,
                n_epochs=1000,
                X_valid=X_val_prepared,
                y_valid=y_val)

    # Perform a randomized hyperparameter search using a time series cross validation
    if ml_settings.hp_search:
        # Define time series cross validation and parameter distribution.
        ts_cv = TimeSeriesSplit(n_splits=3).split(X_train_prepared)
        param_distribs = {
            "n_neurons": [50, 100, 200, 300],
            "batch_size": [50, 100, 500],
            "learning_rate": [0.01, 0.02, 0.05, 0.1],
            "activation": [tf.nn.elu, tf.nn.leaky_relu],
            "n_hidden_layers": [1, 2, 3, 4, 5],
            "batch_norm_momentum": [0.9, 0.95, 0.99, 0.999],
            "dropout_rate": [0.2, 0.4, 0.6],
        }

        # Run randomized hyperparameter search.
        rnd_search = RandomizedSearchCV(models.DNNClassifier(random_state=42),
                                        param_distribs,
                                        n_iter=50,
                                        cv=ts_cv,
                                        random_state=42,
                                        verbose=1,
                                        n_jobs=-1)
        rnd_search.fit(X_train_prepared,
                       y_train,
                       n_epochs=1000,
                       X_valid=X_val_prepared,
                       y_valid=y_val)
        print(rnd_search.best_params_, '\n')


# Measure trained model on test set.
    X_test_prepared = prep_pipeline.transform(X_test)

    if ml_settings.hp_search:
        testing.measure_performance(X_test_prepared,
                                    y_test,
                                    rnd_search,
                                    show_classification_report=True,
                                    show_confusion_matrix=True)

    else:
        testing.measure_performance(X_test_prepared,
                                    y_test,
                                    dnn_clf,
                                    show_classification_report=True,
                                    show_confusion_matrix=True)

    # Save trained neural network.
    if ml_settings.hp_search:
        rnd_search.best_estimator_.save(ml_settings.MODEL_PATH)
    else:
        dnn_clf.save(ml_settings.MODEL_PATH)

    # Report computational time.
    end_time = time.time()
    total_time = end_time - start_time
    print('Time: ', total_time)
コード例 #52
0
class AlienInvasion:
    def __init__(self):
        """ИНИЦИАЛИЗАЦИЯ ИГРЫ"""
        pygame.init()  #HERE IS EVERYTHING ALRIGHT
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))  # 4
        self.screen_rect = self.screen.get_rect()
        # ЕС ХОТИТЕ СДЕЛАТЬ НА ФУЛ ЭКРАН - УБИРАЙТЕ # В 1 , 2 , 3 ПУНКТЕ И ПОСТАВЬТЕ # В 4 ПУНКТЕ
        # self.screen=pygame.display.set_mode((0,0), pygame.FULLSCREEN)  # 1
        # self.settings.screen_width=self.screen.get_rect().width        # 2
        # self.settings.screen_height=self.screen.get_rect().height      # 3
        pygame.display.set_caption("ALIEN INVASION")

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)
        self.aliens = pygame.sprite.Group()  #объявление группы пришельцев
        #self.charecter=Character(self) # MB I WILL DO IT

        self._create_fleet()  #при первом вызыове
        self.play_button = Button(self, "LETS START")

        self.filename = "saved_data.json"

    def run_game(self):
        """ЗАПУСК ИГРЫ"""

        while True:  #ОТСЛЕЖИВАНИЕ ДЕЙСТВИЙ С КЛАВЫ
            self._check_events()
            if self.stats.game_active:
                self.ship.update()
                self._update_bullet()
                self._update_aliens()
            self._update_screen()

    def _update_screen(self):  #отвечает за то, что вообще на экране творится
        self.screen.fill(
            self.settings.bg_colour)  #Заполнить экран определенным цветом
        self.ship.blitme()  # Использовать метод показа корабля
        #self.charecter.blitme()  #MB I WILL DO IT
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(
            self.screen)  #показывает пришельцев на self.screen (общий экран)
        if not self.stats.game_active:
            self.play_button.draw_button()
        self.sb.show_score()  #Метод показа очков
        pygame.display.flip()  #обновление экрана

    def _check_events(self):  #общая проверка ивентов
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keyDOWN(event)

            elif event.type == pygame.KEYUP:
                self._check_keyUP(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_keyDOWN(self, event):  #проверка нажатой клавиши
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        if event.key == pygame.K_UP:
            self.ship.moving_up = True
        elif event.key == pygame.K_DOWN:
            self.ship.moving_down = True
        elif event.key == pygame.K_ESCAPE:  #стоп слово
            some_score = self.stats.high_score
            with open(self.filename, "w") as f:  #Открытие файла
                print("d")  #Лоигрование, что запись в файл идет
                json.dump(some_score, f)  #Сохранение результата
            sys.exit()

        elif event.key == pygame.K_SPACE:  #Вызов метода стрельбы пули
            self._fire_bullet()

    def _check_keyUP(
            self, event):  #проверка, какую клавишу отпустили  (или отпущена)
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False
        elif event.key == pygame.K_UP:
            self.ship.moving_up = False
        elif event.key == pygame.K_DOWN:
            self.ship.moving_down = False

    def _check_play_button(self, mouse_pos):
        button_clicked = self.play_button.rect.collidepoint(
            mouse_pos)  #проверка нажатия кнопки
        if button_clicked and not self.stats.game_active:  #если кнопка нажата и игра не запущена начинается игра
            self.settings.initialize_dynamic_settings()
            self.stats.reset_stats()
            self.stats.game_active = True
            self.sb.prep_score()
            self.sb.prep_level()
            self.sb.prep_ships()

            self.aliens.empty()
            self.bullets.empty()

            self._create_fleet()
            self.ship.center_ship()

            pygame.mouse.set_visible(False)  #Метод, чтобы мышка исчезла

    def _fire_bullet(self):  #отвечает за запуск пули
        if len(
                self.bullets
        ) < self.settings.bullet_allowed:  #Если длина меньше кол-во разрешенных пуль
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_bullet(
        self
    ):  #отвечает за устраниение пули, когда она достигнет определенной точки
        self.bullets.update()
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)
        #print (len(self.bullets))
        self._check_bullet()

    def _check_bullet(self):
        collisions = pygame.sprite.groupcollide(
            self.bullets, self.aliens, False,
            True)  #Проверка взаимодействия группы пули и группы пришельцев
        if collisions:  #Если есть коллизия
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_score * len(aliens)
            self.sb.prep_score()
            self.sb.check_high_score()
        if not self.aliens:  #Если группа пришельцев пустая
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()
            self.stats.level += 1
            self.sb.prep_level()

    def _ship_hit(self):  #Проверка был ли удра корабля
        if self.stats.ships_left >= 0:  #Если кол-во кораблей больше или равно нулю - продолжать действие
            self.stats.ships_left -= 1
            self.sb.prep_ships()

            self.aliens.empty()
            self.bullets.empty()

            self._create_fleet()
            self.ship.center_ship()

            sleep(0.5)  #Остановить игру на 0.5 сек
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _create_fleet(self):  #Создание флота пришельцев
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size  #метод alien.rect.size возвращает ширину и длину пришельца
        ship_height = self.ship.rect.height  #высота корабля
        available_space_x = self.settings.screen_width - (
            2 * alien_width
        )  #настройки экрана - ширина пришельца * 2 (чтобы было место)
        available_space_y = self.settings.screen_height - (
            3 * alien_height
        ) - ship_height  #получаем настройки, чтобы узнать кол-во рядов, мы можем сделать
        number_rows = available_space_y // (
            2 * alien_height
        )  #считаем точное кол-во, чтобы у игрока был шанс нормально играть без проблем
        number_aliends = available_space_x // (2 * alien_width
                                               )  #кол-во пришельцев в ряду
        for row in range((number_rows - 2) // 2):  #допилить вариацию ряда
            for number in range(
                    number_aliends):  # вводим цикл для каждого пришельца
                self._create_alien(
                    number, row
                )  #для каждого нового пришельца, мы вызываем метод создания пришельца (указываем кол-во в ряду и кол-во рядом)
                self._create_alien_1(number, row + 1)

    def _create_alien(self, alien_number, row):  # создание пришельца
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size  #Сначала идет ширина потом длина пришельца
        alien.x = alien_width + 2 * alien_width * alien_number  #определили расстояние между инепрешеленцами
        alien.rect.x = alien.x  #Расположение пришельца
        alien.rect.y = alien_height + 2 * alien_height * row
        self.aliens.add(alien)  #добавление пришельца в "список пришельцев"

    def _create_alien_1(self, alien_number, row):
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = 2 * alien_height * row
        self.aliens.add(alien)

    def _update_aliens(self):
        self.aliens.update()

        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()

        self._aliens_check_bottom()
        self._check_fleet()

    def _aliens_check_bottom(self):  #Проверка достиг ли пришелец дна
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= self.screen_rect.bottom:
                self._ship_hit()
                break

    def _check_fleet(self):  #Проверка дошел ли пришелец до края
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_direction()
                break

    def _change_direction(self):  #Смена направления
        for alien in self.aliens.sprites(
        ):  #меняем направление каждого пришельца с помощью группы спрайт
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1
コード例 #53
0
ファイル: autocanary.py プロジェクト: Stasonhub/autocanary
class AutoCanaryGui(QtGui.QWidget):
    def __init__(self, app, gpg, headlines):
        super(AutoCanaryGui, self).__init__()
        self.app = app
        self.gpg = gpg
        self.headlines = headlines
        self.settings = Settings()
        self.setWindowTitle('AutoCanary')
        self.setWindowIcon(QtGui.QIcon(common.get_image_path('icon.png')))

        # frequency, year
        self.date_col1_layout = QtGui.QVBoxLayout()

        self.frequency_layout = QtGui.QHBoxLayout()
        self.frequency_label = QtGui.QLabel('Frequency')
        self.frequency = QtGui.QComboBox()
        frequency_options = ["Weekly", "Monthly", "Quarterly", "Semiannually"]
        for option in frequency_options:
            self.frequency.addItem(option)
        option = self.settings.get_frequency()
        if option in frequency_options:
            self.frequency.setCurrentIndex(frequency_options.index(option))
        self.frequency_layout.addWidget(self.frequency_label)
        self.frequency_layout.addWidget(self.frequency)
        self.frequency.activated.connect(self.update_date)

        self.year_layout = QtGui.QHBoxLayout()
        self.year_label = QtGui.QLabel('Year')
        self.year = QtGui.QComboBox()
        y = datetime.date.today().year
        year_options = [str(y - 1), str(y), str(y + 1)]
        for option in year_options:
            self.year.addItem(option)
        option = self.settings.get_year()
        if option in year_options:
            self.year.setCurrentIndex(year_options.index(option))
        self.year_layout.addWidget(self.year_label)
        self.year_layout.addWidget(self.year)
        self.year.activated.connect(self.update_date)

        # weekly dropdown
        self.weekly_layout = QtGui.QHBoxLayout()
        self.weekly_label = QtGui.QLabel('Week')
        self.weekly_dropdown = QtGui.QComboBox()
        self.weekly_layout.addWidget(self.weekly_label)
        self.weekly_layout.addWidget(self.weekly_dropdown)

        # monthly dropdown
        self.monthly_layout = QtGui.QHBoxLayout()
        self.monthly_label = QtGui.QLabel('Month')
        self.monthly_dropdown = QtGui.QComboBox()
        monthly_options = [
            "January", "February", "March", "April", "May", "June", "July",
            "August", "September", "October", "November", "December"
        ]
        for option in monthly_options:
            self.monthly_dropdown.addItem(option)
        self.monthly_layout.addWidget(self.monthly_label)
        self.monthly_layout.addWidget(self.monthly_dropdown)

        # quarterly radio buttons
        self.quarterly_layout = QtGui.QHBoxLayout()
        self.quarterly_label = QtGui.QLabel('Quarter')
        self.quarterly_q1 = QtGui.QRadioButton("")
        self.quarterly_q2 = QtGui.QRadioButton("")
        self.quarterly_q3 = QtGui.QRadioButton("")
        self.quarterly_q4 = QtGui.QRadioButton("")
        self.quarterly_layout.addWidget(self.quarterly_label)
        self.quarterly_layout.addWidget(self.quarterly_q1)
        self.quarterly_layout.addWidget(self.quarterly_q2)
        self.quarterly_layout.addWidget(self.quarterly_q3)
        self.quarterly_layout.addWidget(self.quarterly_q4)

        # semiannual radio buttons
        self.semiannually_layout = QtGui.QHBoxLayout()
        self.semiannually_label = QtGui.QLabel('Semester')
        self.semiannually_q12 = QtGui.QRadioButton("")
        self.semiannually_q34 = QtGui.QRadioButton("")
        self.semiannually_layout.addWidget(self.semiannually_label)
        self.semiannually_layout.addWidget(self.semiannually_q12)
        self.semiannually_layout.addWidget(self.semiannually_q34)

        # date layout
        self.date_layout = QtGui.QVBoxLayout()
        self.date_layout.addLayout(self.frequency_layout)
        self.date_layout.addLayout(self.year_layout)
        self.date_layout.addLayout(self.weekly_layout)
        self.date_layout.addLayout(self.monthly_layout)
        self.date_layout.addLayout(self.quarterly_layout)
        self.date_layout.addLayout(self.semiannually_layout)

        self.update_date()

        # status
        self.status_layout = QtGui.QHBoxLayout()
        self.status_label = QtGui.QLabel('Status')
        self.status = QtGui.QComboBox()
        status_options = ["All good", "It's complicated"]
        for option in status_options:
            self.status.addItem(option)
        option = self.settings.get_status()
        if option in status_options:
            self.status.setCurrentIndex(status_options.index(option))
        self.status_layout.addWidget(self.status_label)
        self.status_layout.addWidget(self.status)

        # canary text box
        self.textbox = QtGui.QTextEdit()
        self.textbox.setText(self.settings.get_text())

        # headlines controls: [checkbox, button, button].
        self.headlines_controls = self.get_headlines_controls()

        # key selection
        seckeys = gpg.seckeys_list()
        self.key_selection = QtGui.QComboBox()
        for seckey in seckeys:
            uid = seckey['uid']
            if len(uid) >= 53:
                uid = '{0}...'.format(uid[:50])
            fp = seckey['fp'][-8:]
            text = '{0} [{1}]'.format(uid, fp)
            self.key_selection.addItem(text)
        fp = self.settings.get_fp()
        if fp:
            key_i = 0
            for i, seckey in enumerate(seckeys):
                if seckey['fp'] == fp:
                    key_i = i
            self.key_selection.setCurrentIndex(key_i)

        # buttons
        self.buttons_layout = QtGui.QHBoxLayout()
        self.sign_save_button = QtGui.QPushButton('Save and Sign')
        self.sign_save_button.clicked.connect(self.sign_save_clicked)
        self.sign_once = QtGui.QPushButton('One-Time Sign')
        self.sign_once.clicked.connect(self.sign_once_clicked)
        self.buttons_layout.addWidget(self.sign_save_button)
        self.buttons_layout.addWidget(self.sign_once)

        # headlines controls.
        self.headline_controls_layout = QtGui.QHBoxLayout()
        for hl_control in self.headlines_controls:
            self.headline_controls_layout.addWidget(hl_control)

        # layout
        self.layout = QtGui.QVBoxLayout()
        self.layout.addLayout(self.date_layout)
        self.layout.addLayout(self.status_layout)
        self.layout.addWidget(self.textbox)
        self.layout.addLayout(self.headline_controls_layout)
        self.layout.addWidget(self.key_selection)
        self.layout.addLayout(self.buttons_layout)
        self.setLayout(self.layout)
        self.show()

    def update_date(self):
        frequency = self.frequency.currentText()
        year = self.year.currentText()

        if frequency == 'Weekly':
            self.weekly_label.show()
            self.weekly_dropdown.show()

            # regenerate the weekly dropdown options based on the current year
            self.weekly_dropdown.clear()

            one_week = datetime.timedelta(7)
            cur_date = datetime.datetime(int(year), 1, 1)

            def get_monday_of_week(d):
                days_past = d.isoweekday() - 1
                d = d - datetime.timedelta(days_past)
                return d

            def get_sunday_of_week(d):
                days_future = 7 - d.isoweekday()
                d = d + datetime.timedelta(days_future)
                return d

            while cur_date.year == int(year):
                date_str = ''

                # figure out the start and end dates of the week
                monday_date = get_monday_of_week(cur_date)
                sunday_date = get_sunday_of_week(cur_date)

                if sunday_date.year != int(year):
                    break

                date_str += '{0} to {1}'.format(monday_date.strftime('%b %d'),
                                                sunday_date.strftime('%b %d'))
                self.weekly_dropdown.addItem(date_str)

                cur_date += one_week

        else:
            self.weekly_label.hide()
            self.weekly_dropdown.hide()

        if frequency == 'Monthly':
            self.monthly_label.show()
            self.monthly_dropdown.show()
        else:
            self.monthly_label.hide()
            self.monthly_dropdown.hide()

        if frequency == 'Quarterly':
            self.quarterly_label.show()
            self.quarterly_q1.show()
            self.quarterly_q2.show()
            self.quarterly_q3.show()
            self.quarterly_q4.show()

            # make sure a quarterly radio button is checked
            if not self.quarterly_q1.isChecked(
            ) and not self.quarterly_q2.isChecked(
            ) and not self.quarterly_q3.isChecked(
            ) and not self.quarterly_q4.isChecked():
                self.quarterly_q1.setChecked(True)
        else:
            self.quarterly_label.hide()
            self.quarterly_q1.hide()
            self.quarterly_q2.hide()
            self.quarterly_q3.hide()
            self.quarterly_q4.hide()

        if frequency == 'Semiannually':
            self.semiannually_label.show()
            self.semiannually_q12.show()
            self.semiannually_q34.show()

            # make sure a semiannually radio button is checked
            if not self.semiannually_q12.isChecked(
            ) and not self.semiannually_q34.isChecked():
                self.semiannually_q12.setChecked(True)
        else:
            self.semiannually_label.hide()
            self.semiannually_q12.hide()
            self.semiannually_q34.hide()

        # update freqency text

        # the QString objects which represent the widget state are unicode
        # strings, hence the u'...'
        self.quarterly_q1.setText(u'Q1 {}'.format(year))
        self.quarterly_q2.setText(u'Q2 {}'.format(year))
        self.quarterly_q3.setText(u'Q3 {}'.format(year))
        self.quarterly_q4.setText(u'Q4 {}'.format(year))
        self.semiannually_q12.setText(u'Q1 and Q2 {}'.format(year))
        self.semiannually_q34.setText(u'Q3 and Q4 {}'.format(year))

    def get_year_period(self):
        frequency = self.frequency.currentText()

        if frequency == 'Weekly':
            year_period = self.weekly_dropdown.currentText()

        elif frequency == 'Monthly':
            year_period = self.monthly_dropdown.currentText()

        elif frequency == 'Quarterly':
            if self.quarterly_q1.isChecked():
                year_period = 'Q1'
            if self.quarterly_q2.isChecked():
                year_period = 'Q2'
            if self.quarterly_q3.isChecked():
                year_period = 'Q3'
            if self.quarterly_q4.isChecked():
                year_period = 'Q4'

        elif frequency == 'Semiannually':
            if self.semiannually_q12.isChecked():
                year_period = 'Q12'
            if self.semiannually_q34.isChecked():
                year_period = 'Q34'

        return year_period

    def sign_save_clicked(self):
        self.save()
        self.sign()

    def sign_once_clicked(self):
        self.sign()

    def save(self):
        frequency = self.frequency.currentText()
        year = self.year.currentText()
        year_period = self.get_year_period()
        status = str(self.status.currentText())
        text = self.textbox.toPlainText()

        self.settings.set_frequency(frequency)
        self.settings.set_year(year)
        self.settings.set_status(status)
        self.settings.set_text(text)

        key_i = self.key_selection.currentIndex()
        fp = self.gpg.seckeys_list()[key_i]['fp']
        self.settings.set_fp(fp)

        self.settings.save()

    def sign(self):
        frequency = self.frequency.currentText()
        year = self.year.currentText()
        year_period = self.get_year_period()
        status = str(self.status.currentText())
        text = str(self.textbox.toPlainText())

        if self.headlines.enabled and self.headlines.have_headlines:
            text = '\n\n'.join([text, self.headlines.headlines_str, ''])

        # add headers
        period_date = year_period
        if frequency == 'Quarterly':
            if year_period == 'Q1':
                period_date = 'January 1 to March 31'
            elif year_period == 'Q2':
                period_date = 'April 1 to June 30'
            elif year_period == 'Q3':
                period_date = 'July 1 to September 30'
            elif year_period == 'Q4':
                period_date = 'October 1 to December 31'
        elif frequency == 'Semiannually':
            if year_period == 'Q12':
                period_date = 'January 1 to June 30'
            elif year_period == 'Q34':
                period_date = 'July 1 to December 31'

        # the QString objects which represent the widget state are unicode
        # strings, hence the u'...'
        message = u'Status: {}\nPeriod: {}, {}\n\n{}'.format(
            status, period_date, year, text)

        # sign the file
        key_i = self.key_selection.currentIndex()
        fp = self.gpg.seckeys_list()[key_i]['fp']
        signed_message = self.gpg.sign(message, fp)

        if signed_message:
            # display signed message
            dialog = OutputDialog(self.app, signed_message)
            dialog.exec_()
        else:
            common.alert('Failed to sign message.')

    def get_headlines_controls(self):
        checkbox = QtGui.QCheckBox('Add Recent News Headlines')
        button_fetch = QtGui.QPushButton('Fetch Headlines')
        button_fetch.setDisabled(True)
        button_preview = QtGui.QPushButton('Preview Headlines')
        button_preview.setDisabled(True)

        def fetch_headlines():
            # synchronous.
            self.headlines.fetch_headlines()
            button_fetch.setDisabled(False)
            self.setCursor(QtCore.Qt.ArrowCursor)
            if self.headlines.have_headlines:
                button_preview.setDisabled(False)

        def cb_clicked():
            if checkbox.isChecked():
                button_fetch.setDisabled(False)
                self.headlines.enabled = True
                if self.headlines.have_headlines:
                    button_preview.setDisabled(False)
                else:
                    button_preview.setDisabled(True)
            else:
                self.headlines.enabled = False
                button_fetch.setDisabled(True)
                button_preview.setDisabled(True)

        def fetch_clicked():
            self.setCursor(QtCore.Qt.WaitCursor)
            button_fetch.setDisabled(True)
            # allow the widgets a chance to refresh (disabled/wait).
            QtCore.QTimer().singleShot(1, fetch_headlines)

        def preview_clicked():
            dialog = QtGui.QDialog()
            dialog.setModal(True)
            dialog.setWindowFlags(QtCore.Qt.WindowCloseButtonHint)
            layout = QtGui.QVBoxLayout()
            text = QtGui.QTextEdit()
            text.setText(self.headlines.headlines_str)
            button_close = QtGui.QPushButton('Close')
            button_close.clicked.connect(dialog.close)
            layout.addWidget(text)
            layout.addWidget(button_close)
            dialog.setLayout(layout)
            dialog.exec_()

        button_fetch.clicked.connect(fetch_clicked)
        button_preview.clicked.connect(preview_clicked)
        checkbox.clicked.connect(cb_clicked)
        return [checkbox, button_fetch, button_preview]
コード例 #54
0
ファイル: autocanary.py プロジェクト: Stasonhub/autocanary
    def __init__(self, app, gpg, headlines):
        super(AutoCanaryGui, self).__init__()
        self.app = app
        self.gpg = gpg
        self.headlines = headlines
        self.settings = Settings()
        self.setWindowTitle('AutoCanary')
        self.setWindowIcon(QtGui.QIcon(common.get_image_path('icon.png')))

        # frequency, year
        self.date_col1_layout = QtGui.QVBoxLayout()

        self.frequency_layout = QtGui.QHBoxLayout()
        self.frequency_label = QtGui.QLabel('Frequency')
        self.frequency = QtGui.QComboBox()
        frequency_options = ["Weekly", "Monthly", "Quarterly", "Semiannually"]
        for option in frequency_options:
            self.frequency.addItem(option)
        option = self.settings.get_frequency()
        if option in frequency_options:
            self.frequency.setCurrentIndex(frequency_options.index(option))
        self.frequency_layout.addWidget(self.frequency_label)
        self.frequency_layout.addWidget(self.frequency)
        self.frequency.activated.connect(self.update_date)

        self.year_layout = QtGui.QHBoxLayout()
        self.year_label = QtGui.QLabel('Year')
        self.year = QtGui.QComboBox()
        y = datetime.date.today().year
        year_options = [str(y - 1), str(y), str(y + 1)]
        for option in year_options:
            self.year.addItem(option)
        option = self.settings.get_year()
        if option in year_options:
            self.year.setCurrentIndex(year_options.index(option))
        self.year_layout.addWidget(self.year_label)
        self.year_layout.addWidget(self.year)
        self.year.activated.connect(self.update_date)

        # weekly dropdown
        self.weekly_layout = QtGui.QHBoxLayout()
        self.weekly_label = QtGui.QLabel('Week')
        self.weekly_dropdown = QtGui.QComboBox()
        self.weekly_layout.addWidget(self.weekly_label)
        self.weekly_layout.addWidget(self.weekly_dropdown)

        # monthly dropdown
        self.monthly_layout = QtGui.QHBoxLayout()
        self.monthly_label = QtGui.QLabel('Month')
        self.monthly_dropdown = QtGui.QComboBox()
        monthly_options = [
            "January", "February", "March", "April", "May", "June", "July",
            "August", "September", "October", "November", "December"
        ]
        for option in monthly_options:
            self.monthly_dropdown.addItem(option)
        self.monthly_layout.addWidget(self.monthly_label)
        self.monthly_layout.addWidget(self.monthly_dropdown)

        # quarterly radio buttons
        self.quarterly_layout = QtGui.QHBoxLayout()
        self.quarterly_label = QtGui.QLabel('Quarter')
        self.quarterly_q1 = QtGui.QRadioButton("")
        self.quarterly_q2 = QtGui.QRadioButton("")
        self.quarterly_q3 = QtGui.QRadioButton("")
        self.quarterly_q4 = QtGui.QRadioButton("")
        self.quarterly_layout.addWidget(self.quarterly_label)
        self.quarterly_layout.addWidget(self.quarterly_q1)
        self.quarterly_layout.addWidget(self.quarterly_q2)
        self.quarterly_layout.addWidget(self.quarterly_q3)
        self.quarterly_layout.addWidget(self.quarterly_q4)

        # semiannual radio buttons
        self.semiannually_layout = QtGui.QHBoxLayout()
        self.semiannually_label = QtGui.QLabel('Semester')
        self.semiannually_q12 = QtGui.QRadioButton("")
        self.semiannually_q34 = QtGui.QRadioButton("")
        self.semiannually_layout.addWidget(self.semiannually_label)
        self.semiannually_layout.addWidget(self.semiannually_q12)
        self.semiannually_layout.addWidget(self.semiannually_q34)

        # date layout
        self.date_layout = QtGui.QVBoxLayout()
        self.date_layout.addLayout(self.frequency_layout)
        self.date_layout.addLayout(self.year_layout)
        self.date_layout.addLayout(self.weekly_layout)
        self.date_layout.addLayout(self.monthly_layout)
        self.date_layout.addLayout(self.quarterly_layout)
        self.date_layout.addLayout(self.semiannually_layout)

        self.update_date()

        # status
        self.status_layout = QtGui.QHBoxLayout()
        self.status_label = QtGui.QLabel('Status')
        self.status = QtGui.QComboBox()
        status_options = ["All good", "It's complicated"]
        for option in status_options:
            self.status.addItem(option)
        option = self.settings.get_status()
        if option in status_options:
            self.status.setCurrentIndex(status_options.index(option))
        self.status_layout.addWidget(self.status_label)
        self.status_layout.addWidget(self.status)

        # canary text box
        self.textbox = QtGui.QTextEdit()
        self.textbox.setText(self.settings.get_text())

        # headlines controls: [checkbox, button, button].
        self.headlines_controls = self.get_headlines_controls()

        # key selection
        seckeys = gpg.seckeys_list()
        self.key_selection = QtGui.QComboBox()
        for seckey in seckeys:
            uid = seckey['uid']
            if len(uid) >= 53:
                uid = '{0}...'.format(uid[:50])
            fp = seckey['fp'][-8:]
            text = '{0} [{1}]'.format(uid, fp)
            self.key_selection.addItem(text)
        fp = self.settings.get_fp()
        if fp:
            key_i = 0
            for i, seckey in enumerate(seckeys):
                if seckey['fp'] == fp:
                    key_i = i
            self.key_selection.setCurrentIndex(key_i)

        # buttons
        self.buttons_layout = QtGui.QHBoxLayout()
        self.sign_save_button = QtGui.QPushButton('Save and Sign')
        self.sign_save_button.clicked.connect(self.sign_save_clicked)
        self.sign_once = QtGui.QPushButton('One-Time Sign')
        self.sign_once.clicked.connect(self.sign_once_clicked)
        self.buttons_layout.addWidget(self.sign_save_button)
        self.buttons_layout.addWidget(self.sign_once)

        # headlines controls.
        self.headline_controls_layout = QtGui.QHBoxLayout()
        for hl_control in self.headlines_controls:
            self.headline_controls_layout.addWidget(hl_control)

        # layout
        self.layout = QtGui.QVBoxLayout()
        self.layout.addLayout(self.date_layout)
        self.layout.addLayout(self.status_layout)
        self.layout.addWidget(self.textbox)
        self.layout.addLayout(self.headline_controls_layout)
        self.layout.addWidget(self.key_selection)
        self.layout.addLayout(self.buttons_layout)
        self.setLayout(self.layout)
        self.show()
コード例 #55
0
ファイル: gui.py プロジェクト: vanyaadev/wow-bot
class SettingsWindow(QWidget):
    def __init__(self, settings: Settings = None):
        super(SettingsWindow, self).__init__()
        if settings:
            self.settings = settings
        else:
            self.settings = Settings()

        self.init_widgets()

    def set_value(self, widget, param):
        try:
            value = type(self.settings.get_value(param))(widget.text(
            ) if type(widget) == QLineEdit else widget.toPlainText())
            self.settings.set_val(param, value)
            widget.setStyleSheet('background: white')
        except ValueError:
            widget.setStyleSheet('background: pink')

    def set_list(self, widget, param):
        try:
            value = (widget.text() if type(widget) == QLineEdit else
                     widget.toPlainText()).split('\n')
            self.settings.set_val(param, value)
            widget.setStyleSheet('background: white')
        except:
            widget.setStyleSheet('background: pink')

    def text_changed(self, *args):
        editor_iterator = iter(self.editor_widgets)
        for param, value in self.settings.__dict__.items():
            if type(value) == list:
                self.set_list(editor_iterator.__next__(), param)
            else:
                self.set_value(editor_iterator.__next__(), param)

    def init_widgets(self):
        self.label_font = QFont('Arial', 12)
        self.label_font.setBold(True)
        self.editor_font = QFont('Arial', 12)

        self.grid = QGridLayout()
        self.editor_widgets = []
        for param, value in self.settings.__dict__.items():
            editor_name = param.replace('_', ' ').capitalize()
            label = QLabel(editor_name)
            label.setFont(self.label_font)

            if type(value) == list:
                editor = QTextEdit('\n'.join(self.settings.get_value(param)))
                editor.textChanged.connect(self.text_changed)
            else:
                editor = QLineEdit(str(self.settings.get_value(param)))
                editor.textChanged.connect(self.text_changed)
            editor.setFont(self.editor_font)

            self.grid.addWidget(label, len(self.editor_widgets), 0)
            self.grid.addWidget(editor, len(self.editor_widgets), 1)
            self.editor_widgets.append(editor)

        self.setLayout(self.grid)
コード例 #56
0
def run_game():
    radio = pygame.mixer
    radio.init()
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption("Mario")

    clips = [
        radio.Sound('sounds/bg_music.wav'),
        radio.Sound('sounds/block_bump.wav'),
        radio.Sound('sounds/brick_break.wav'),
        radio.Sound('sounds/coin.wav'),
        radio.Sound('sounds/death.wav'),
        radio.Sound('sounds/extra_life.wav'),
        radio.Sound('sounds/fireball.wav'),
        radio.Sound('sounds/jump.wav'),
        radio.Sound('sounds/kill.wav'),
        radio.Sound('sounds/pipe.wav'),
        radio.Sound('sounds/power_spawn.wav'),
        radio.Sound('sounds/powerup.wav'),
        radio.Sound('sounds/stage_clear.wav'),
        radio.Sound('sounds/star.wav')
    ]

    pipes = Group()
    secret_pipes = Group()
    bricks = Group()
    secret_bricks = Group()
    upgrades = Group()
    enemies = Group()
    poles = Group()
    fireballs = Group()
    flags = Group()
    ground = Group()  # +

    stats = Stats()
    for i in range(6, 8):
        pipe = Pipe(screen, settings, i)
        secret_pipes.add(pipe)

        # Create and initialize flag and pole before storing in group
    flag = Flag(screen, settings, stats)
    flags.add(flag)
    pole = Pole(screen, settings)
    poles.add(pole)

    mario = Mario(screen, settings, pipes, bricks, upgrades, stats, enemies,
                  poles, radio, clips, fireballs, secret_bricks, secret_pipes,
                  ground)
    lvl_map = None
    level = Level(screen, settings, pipes, lvl_map, bricks, upgrades, enemies,
                  flags, poles)
    display = Display(screen, stats)

    clips[0].play(-1)
    while True:
        # Checks if Mario is in the main level and sets the map, generate the bricks, pipes, flags, and pole
        # Does this only once
        if stats.activate_main_lvl:
            lvl_map = Map(screen, settings, bricks, pipes, mario, enemies,
                          ground, upgrades, stats, secret_bricks)
            lvl_map.build_brick()
            # generate pipes and flag/pole
            for i in range(0, 6):
                pipe = Pipe(screen, settings, i)
                pipes.add(pipe)
            flag = Flag(screen, settings, stats)
            flags.add(flag)
            pole = Pole(screen, settings)
            poles.add(pole)
            stats.activate_main_lvl = False

        # Checks if Mario has activated the secret level and sets the map, clears all of the main level
        # Does this only once
        if stats.activate_secret:
            # Clears everything belonging to main level to prevent lag
            pipes.empty()
            bricks.empty()
            enemies.empty()
            poles.empty()
            flags.empty()
            lvl_map = Map(screen, settings, bricks, pipes, mario, enemies,
                          ground, upgrades, stats, secret_bricks)
            lvl_map.build_brick()

            stats.activate_secret = False
            stats.main_level = False

        if stats.game_active:
            gf.check_events(mario, stats, clips, fireballs)

            # If the player gets near the right side, shift the world left (-x)
            if mario.rect.right >= 600 and stats.main_level:
                diff = mario.rect.right - 600
                mario.rect.right = 600
                level.shifting_world(-diff)

            # If the player gets near the left side, shift the world right (+x)
            # if mario.rect.left <= 100:
            #    diff = 100 - mario.rect.left
            #    mario.rect.left = 100
            #    level.shifting_world(diff)

            gf.update_screen(screen, mario, settings, level, pipes, display,
                             stats, bricks, upgrades, enemies, flags, poles,
                             radio, clips, fireballs, secret_bricks,
                             secret_pipes)
            pygame.display.flip()
コード例 #57
0
ファイル: plane_war.py プロジェクト: liu1477191139/Pygame
def run_game():

    # 初始化游戏并创建一个屏幕对象:初始化背景设置,让Pygame能够正确地工作

    pygame.init()

    # 初始化全部音频,并加载爆炸声音乐

    pygame.mixer.init()

    # 爆炸声

    explode_sound = pygame.mixer.Sound("sound\EXPLO6.wav")

    # 子弹射击的声音

    bullet_sound = pygame.mixer.Sound("sound\shot1.wav")

    pw_settings = Settings()
    """实参(1200, 800)是一个元组,指定了游戏窗口的尺寸。

            通过将这些尺寸值传递给pygame.display.set_mode()

            我们创建了一个宽1200像素、高800像素的游戏窗口"""
    """调用pygame.display.set_mode()来创建一个名为screen的显示窗口,

    这个游戏的所有图形元素都将在其中绘制。每个元素(如外星人或飞船)都是一个surface对象"""

    screen = pygame.display.set_mode(
        (pw_settings.screen_width, pw_settings.screen_height))

    # 窗口标题

    pygame.display.set_caption('Plane War')

    # 创建Play按钮

    play_button = Button(pw_settings, screen, "Play")

    # 创建一个用于存储游戏统计信息的实例,并创建记分牌

    stats = GameStats(pw_settings)

    sb = Scoreboard(pw_settings, screen, stats)

    # 创建一艘飞船、一个子弹编组和一个外星人编组

    # 创建一艘飞船

    ship = Ship(pw_settings, screen)

    # 创建一个用于存储子弹的编组,添加进去实例后对bullets调用 就能对bullets里面的每个bullet调用

    bullets = Group()

    # 创建一个外星人编组

    aliens = Group()

    # 创建外星人群

    gf.create_fleet(pw_settings, screen, aliens)

    timer = 1

    # 开始游戏的主循环

    while True:

        timer += 1

        gf.check_events(pw_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets, bullet_sound)

        if stats.game_active:

            ship.update()

            gf.update_bullets(pw_settings, screen, stats, sb, ship, aliens,
                              bullets, explode_sound)

            gf.update_aliens(pw_settings, screen, stats, sb, ship, aliens,
                             bullets)

        gf.update_screen(pw_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
コード例 #58
0
"""All the files are integrated here."""

# Local files
import keyboard
from settings import Settings
from model import model, load_model, train_model
from realtime import Realtime

print('Everything is successfully imported')
settings = Settings()
print('Settings is done')
model = load_model()
print('Model is loaded')
realtime = Realtime(settings)
print('Realtime is done')

print('start')
while True:
    if keyboard.is_pressed('q'):
        break

    realtime.refresh_audio()
    y = model.predict(realtime.x)
    realtime.check_trigger(y)
    print('Done')
コード例 #59
0
class AlienInvasion:
    """Overall class to manage game assets and behavior."""
    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        # self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
        # self.settings.screen_width = self.screen.get_rect().width
        # self.settings.screen_height = self.screen.get_rect().height

        pygame.display.set_caption("Alien Invasion")

        # Create an instance to store game statistics
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        # Make the play button.
        self.play_button = Button(self, "Play")

    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self._check_envents()

            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()

            self._update_screen()

    def _check_envents(self):
        """Respond to keypresses and mouse events."""
        # Watch for keyboard and mouse events.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        """Start a new game when the player clicks Play"""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            # Reset the game settings.
            self.settings.initialize_dynamic_settings()

            # Reset the game statistics.
            self.stats.reset_stats()
            self.stats.game_active = True
            self.sb.prep_score()
            self.sb.prep_level()
            self.sb.prep_ships()

            # Get rid of any remaining aliens and bullets
            self.aliens.empty()
            self.bullets.empty()

            # Create a new fleet and center the ship.
            self._create_fleet()
            self.ship.center_ship()

            # Hide the mouse cursor.
            pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    def _check_keyup_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def _fire_bullet(self):
        """Create a new bullet and add it to the bullets group."""
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_bullets(self):
        """Update position of bullets and get rid of old bullets."""
        # Update bullet positions.
        self.bullets.update()

        # Get rid of bullets that have disappeared.
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        # Check for any bullets that have hit aliens.
        # If so, get rid of the bullet and the alien.
        self._check_bullet_alien_collisions()

    def _check_bullet_alien_collisions(self):
        """Respond to bullet-alien collisions."""
        # Remove any bullets and aliens that have collided.
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)

        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
            self.sb.prep_score()
            self.sb.check_high_score()
        if not self.aliens:
            # Destroy existing bullets and create new fleet.
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()

            # Increase level.
            self.stats.level += 1
            self.sb.prep_level()

    def _update_aliens(self):
        """update the positions of all aliens in the fleet."""
        self._check_fleet_edges()
        self.aliens.update()

        # Look for alien-ship collisions.
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()

        # Look for aliens htting the bottom of the screen.
        self._check_aliens_bottom()

    def _create_fleet(self):
        """Create the fleet of aliens."""
        # Make an alien.
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)

        # Determine the number of rows of aliens that fit on the screen.
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (3 * alien_height) -
                             ship_height)
        number_rows = available_space_y // (2 * alien_height)

        # Create the full fleet of aliens.
        for row_number in range(number_rows):
            # Create the first row of aliens.
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        """Create an alien and place it in the row."""
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def _check_fleet_edges(self):
        """Respond appropriately if any aliens have reched an edge."""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        """Drop the entire fleet and change the fleet's direction."""
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _check_aliens_bottom(self):
        """Check if any aliens have reached the bottom of the screen."""
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                # Treat this the same as if the ship got hit.
                self._ship_hit()
                break

    def _ship_hit(self):
        """Respond to the ship being hit by an alien."""
        if self.stats.ships_left > 0:
            # Decrement ship_left, and update scoreoard
            self.stats.ships_left -= 1
            self.sb.prep_ships()

            # Get rif of any remaining aliens and bullets.
            self.aliens.empty()
            self.bullets.empty()

            # Create a new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

            # Pause.
            sleep(1)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _update_screen(self):
        """Update image on the screen, and flip to the new screen."""
        # Redraw the screen during each pass through the loop.
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)

        # Draw the score information.
        self.sb.show_score()

        #Draw the play button if the game is inactive.
        if not self.stats.game_active:
            self.play_button.draw_button()

        # Make the most recently drawn screen visible.
        pygame.display.flip()
コード例 #60
0
import matplotlib.pyplot as plt

# SQUEEZESEG DATASET
# Channels description:
# 0: X
# 1: Y
# 2: Z
# 3: REFLECTANCE
# 4: DEPTH
# 5: LABEL

# imports Settings manager
sys.path.append('./')
import data_loader
from settings import Settings
CONFIG = Settings(required_args=["config"])


# Generates tfrecords for training
def make_tfrecord():

    # Creates each tfrecord (train and val)

    list_subfolders_with_paths = [f[0] for f in os.walk(CONFIG.DATA_ROOT_PATH)]
    train_folder_name = open(CONFIG.DATA_ROOT_PATH + "train.txt", "r")
    val_folder_name = open(CONFIG.DATA_ROOT_PATH + "val.txt", "r")
    test_folder_name = open(CONFIG.DATA_ROOT_PATH + "test.txt", "r")
    train_image_idx = []
    val_image_idx = []
    test_image_idx = []
    for subfolder in train_folder_name: