当前位置: 首页>>代码示例>>Python>>正文


Python Gui.update方法代码示例

本文整理汇总了Python中gui.Gui.update方法的典型用法代码示例。如果您正苦于以下问题:Python Gui.update方法的具体用法?Python Gui.update怎么用?Python Gui.update使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在gui.Gui的用法示例。


在下文中一共展示了Gui.update方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from gui import Gui [as 别名]
# 或者: from gui.Gui import update [as 别名]
class Othello:

    def __init__(self):
        self.gui = Gui()
        self.setup_game()

    def read_board_file(self, file_name):
        f = open(file_name)
        lines = [line.strip() for line in f]
        f.close()
        board = np.zeros((8, 8), dtype=np.integer)
        # Read In Board File
        i = 0
        for line in lines[:8]:
            j = 0
            for char in line.split():
                board[i][j] = int(char)
                j += 1
            i += 1
        # Set Current Turn
        if int(lines[8]) == WHITE:
            self.now_playing, self.other_player = self.other_player, self.now_playing

        return board

    def setup_game(self):
        options = self.gui.show_options()
        if options['player_1'] == COMPUTER:
            self.now_playing = player.ComputerPlayer(BLACK, int(options['player_1_time']), self.gui)
        else:
            self.now_playing = player.HumanPlayer(BLACK, gui=self.gui)
        if options['player_2'] == COMPUTER:
            self.other_player = player.ComputerPlayer(WHITE, int(options['player_2_time']), self.gui)
        else:
            self.other_player = player.HumanPlayer(WHITE, gui=self.gui)
        if options.has_key('load_file'):
            self.board = board.Board(self.read_board_file(options['load_file']))
        else:
            self.board = board.Board()

    def run(self):
        self.gui.show_game(self.board)
        while True:
            winner = self.board.game_won()
            if winner is not None:
                break
            self.now_playing.set_current_board(self.board)
            if self.board.get_valid_moves(self.now_playing.color) != []:
                self.board = self.now_playing.get_move()
            self.gui.update(self.board, self.other_player)
            self.now_playing, self.other_player = self.other_player, self.now_playing
        self.gui.show_winner(winner, self.board)
        self.restart()

    def restart(self):
        self.setup_game()
        self.run()
开发者ID:rgruener,项目名称:othello,代码行数:59,代码来源:othello.py

示例2: TPBattStat

# 需要导入模块: from gui import Gui [as 别名]
# 或者: from gui.Gui import update [as 别名]
class TPBattStat():
  def __init__(self, mode, forceDelay=None, forceIconSize=None):
    self.mode = mode
    self.forceDelay = forceDelay

    self.prefs = Prefs()
    self.battStatus = BattStatus(self.prefs)
    self.actions = Actions(self.prefs, self.battStatus)
    if self.mode == "gtk" or self.mode == "prefs":
      self.gui = Gui(self.prefs, self.battStatus)
    elif self.mode == "json" or self.mode == "dzen":
      self.guiMarkupPrinter = GuiMarkupPrinter(
        self.prefs, self.battStatus, forceIconSize)
      
  def getGui(self):
    return self.gui
  def startUpdate(self):
    self.curDelay = -1
    self.update()
  def update(self):
    try:
      self.prefs.update()
    except Exception as e:
      print 'ignoring prefs'
      print e.message
    if self.forceDelay != None:
      self.prefs['delay'] = self.forceDelay
    self.battStatus.update(self.prefs)

    self.actions.performActions()
    if self.mode == "gtk":
      self.gui.update()
    elif self.mode == "json" or self.mode == "dzen":
      try:
        if self.mode == "json":
          markup = self.guiMarkupPrinter.getMarkupJson()
        elif self.mode == "dzen":
          markup = self.guiMarkupPrinter.getMarkupDzen()
        print markup
        sys.stdout.flush()
      except IOError, e:
        print >> sys.stderr, "STDOUT is broken, assuming external gui is dead"
        sys.exit(1)

    if self.prefs['delay'] != self.curDelay:
      self.curDelay = self.prefs['delay']
      if self.curDelay <= 0:
        self.curDelay = 1000
      gobject.timeout_add(self.curDelay, self.update)
      return False
    else:
      return True
开发者ID:teleshoes,项目名称:tpbattstat,代码行数:54,代码来源:tpbattstat.py

示例3: ClientGame

# 需要导入模块: from gui import Gui [as 别名]
# 或者: from gui.Gui import update [as 别名]
class ClientGame (Engine):
    """ Plays the game. Does not have any game logic. It send player input to
    the server which will eventually tell the client's game what to do. """
    # Constructor {{{1
    def __init__ (self, loop, forum, world):
        print 'C: Begin game engine.'
        Engine.__init__ (self, loop)

        self.forum = forum
        self.world = world
        
        # Set up the relays.
        publisher = self.forum.get_publisher()
        subscriber = self.forum.get_subscriber()

        self.reflex = Reflex(self, subscriber, self.world)
        self.player_relay = PlayerRelay(self, publisher, self.world)

        self.gui = Gui(self.world, self.player_relay)

    def setup (self):
        self.reflex.setup()
        self.player_relay.setup()
        self.gui.setup()

        self.forum.lock()
    
    # Update {{{1
    def update (self, time):
        self.forum.update()
        self.reflex.update(time)
        self.player_relay.update(time)
        self.world.update(time)
        self.gui.update(time)

    # Methods {{{1
    def game_over(self):
        # Called by the Reflex?
        print 'Game over.'
        self.exit_engine()

    def successor (self):
        self.forum.unlock()
        return ClientPostgame(self.loop, self.forum, self.world, self.gui)
    
    def teardown (self):
        time.sleep(1)
开发者ID:alexmitchell,项目名称:PurplePeopleEater,代码行数:49,代码来源:engines.py

示例4: Game

# 需要导入模块: from gui import Gui [as 别名]
# 或者: from gui.Gui import update [as 别名]
class Game(object):
    def __init__(self, width=1280, height=720, fps=120):
        pygame.init()

        self.width = width
        self.height = height
        self.screen = pygame.display.set_mode((width, height), pygame.DOUBLEBUF)
        self.background = pygame.Surface(self.screen.get_size()).convert()
        self.clock = pygame.time.Clock()
        self.fps = fps
        self.wave = 0

        self.font = pygame.font.Font(None, 30)
        self.score = 0

        self.event_dispatch = EventDispatcher()

        #Init all user interface staff
        self.gui = Gui()
        self.gui.set_event_dispatcher(self.event_dispatch)

        #Init all entities
        self.entities = Entities()
        self.entities.set_event_dispatcher(self.event_dispatch)

    def run(self):
        while True:
            event = pygame.event.poll()

            if event.type == pygame.QUIT:
                break

            self.clock.tick(self.fps)
            self.screen.fill(pygame.Color("#3d863d"))

            self.entities.update()
            self.gui.update()

            pygame.display.flip()

        pygame.quit()

    def display_gameover(self):
        font = pygame.font.Font(None, 72)
        text = font.render("WASTED", 1, (255, 255, 255))
        #TODO: Bad idea. Later: why? Comment more clearly
        self.screen.blit(text, (640, 360))
开发者ID:matanaliz,项目名称:PyLand,代码行数:49,代码来源:main.py

示例5: App

# 需要导入模块: from gui import Gui [as 别名]
# 或者: from gui.Gui import update [as 别名]
class App(object):
	"""Manage application controllers, respond to user input, run master loop.

	This class wraps together the various components of the application. It is
	the application entry point. On startup, it creates an instance of each
	controller. The run() method starts each controller and runs the master loop
	until the user quits.

	Settings:
		experimentName: used to label the output directory and in output metadata
		keyBindings: a dictionary where the keys are 'quit', 'toggleStimulator',
			and 'triggerStimulator', and the values are one-character strings
			representing the button that triggers the action specified by the key
		outputRootDir: directory where the folder containing trial data will be
			created
	"""

	def __init__(self, **kwargs):
		"""Initialize the keycode bindings and all controllers, create output dir."""
		settings = {
			'experimentName' : 'someNameHere',
			'outputRootDir' : os.path.normpath(os.path.expanduser("~/kauferdata")),
			'keyBindings' : {
				'quit' : 'q',
				'toggleStimulator' : 't',
				'triggerStimulator' : 's'
				},
			'audio' : {},
			'gui' : {},
			'stimulator' : { 'activeProtocolName' : 'nucleusAccumbensExample' },
			'tracker' : {},
			'videoIn' : {},
			'videoOut' : {},
			'writer' : {},
			}
		settings.update(kwargs)
		trialDir = "{0}_{1}_{2}".format(time.strftime("%y%m%d%H%M%S"),
				settings['experimentName'], settings['stimulator']['activeProtocolName'])
		settings['outputDataDir'] = os.path.join(settings['outputRootDir'], trialDir)
		self.keyBindings = settings['keyBindings']
		self.keycodeBindings = {k: getattr(opencvgui.keycodes, v)
				for k,v in self.keyBindings.items() }
		os.makedirs(os.path.join(settings['outputDataDir'], 'audio'))
		self.writeExperimentData(settings)
		for x in ['audio', 'videoOut', 'writer']:
			kwargs[x] = {} if not kwargs.has_key(x) else kwargs[x]
			kwargs[x]['outputDataDir'] = settings['outputDataDir']

		# gui and writer both need a reference to the app instance because they
		# draw on the state of so many other controllers
		self.audio = Audio(**settings['audio'])
		self.gui = Gui(self, **settings['gui'])
		self.stimulator = Stimulator(**settings['stimulator'])
		self.tracker = Tracker(**settings['tracker'])
		self.videoIn = VideoIn(**settings['videoIn'])
		self.videoOut = VideoOut(**settings['videoOut'])
		self.writer = Writer(self, **settings['writer'])

	def run(self):
		"""Respond to user input and run the master application loop.

		This method has three basic sections. Before the loop starts, the start()
		method is called on all controllers. The central loop calls update() on
		each controller until it is terminated by a user-issued quit keystroke.
		Keystrokes are listened for at the start of each loop iteration.
		"""
		self.printKeybindings()
		self.startTime = self.lastTime = time.clock()
		self.audio.start()
		self.gui.start()
		self.stimulator.start()
		self.tracker.start()
		self.videoIn.start()
		self.videoOut.start()
		self.writer.start()

		while True:

			# respond to user input
			lastKeyStroke = cv2.waitKey(20)  # 20 is the number of ms to wait for key
			if lastKeyStroke != -1: # -1 means there was no keystroke
				if lastKeyStroke == self.keycodeBindings['quit']:
					break
				if lastKeyStroke == self.keycodeBindings['triggerStimulator']:
					self.stimulator.trigger()
				if lastKeyStroke == self.keycodeBindings['toggleStimulator']:
					self.stimulator.toggle()

			# update state
			self.currTime = time.clock()
			self.totalTimeElapsed = self.currTime - self.startTime
			self.audio.update()
			self.videoIn.update()
			self.tracker.update(self.videoIn, self.currTime)
			self.stimulator.update(self.currTime, self.tracker)
			self.videoOut.update(self.videoIn, self.tracker, self.stimulator)
			self.gui.update()
			self.lastTime = self.currTime
			self.writer.update()

#.........这里部分代码省略.........
开发者ID:smackesey,项目名称:kaufer_prosocial,代码行数:103,代码来源:app.py

示例6: Recorder

# 需要导入模块: from gui import Gui [as 别名]
# 或者: from gui.Gui import update [as 别名]
class Recorder(object):
    def __init__(self, num_frames=settings.BUFFER_LENGTH, limit_fps=None):
        if SHOW_WINDOW:
            cv2.namedWindow("preview")

        self.last_video_frame = None

        self.num_frames = num_frames
        self.frames = [None] * self.num_frames
        self.current_jpg_frame = None
        self.buffer_index = 0

        self.keep_running = True
        self.frame_rate = 0
        self.last_frame = time.time()
        self.limit_fps = limit_fps

        self.api = Api(self)
        self.api_lock = threading.Lock()

        self.motion_detector = MotionDetector()

        self.ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
        self.encoding_subprocesses = []
        self.last_serial_command = None
        self.encoding_started = datetime.datetime.now()

        if settings.UI_ENABLED:
            if settings.UI_RESOLUTION:
                self.gui = Gui(width=settings.UI_RESOLUTION[0], height=settings.UI_RESOLUTION[1])
            else:
                self.gui = Gui()

            # Test recording button
            base_state = (
                self.gui.recording_button,
                [150, 150, 90],
                {}
            )
            hover_state = (
                self.gui.recording_button,
                [150, 150, 90],
                {'highlight':True}
            )
            active_state = (
                self.gui.recording_button,
                [150, 150, 90],
                {'active':True}
            )
            callback = lambda: self.log("triggered")#self.calibrate

            self.gui.add_element(element_id=2, base_state=base_state, hover_state=hover_state, active_state=active_state, callback=callback)

            base_state = (
                self.gui.button,
                [100, 100, 200, 30, 'Yeah buttons Baby'],
                {}
            )
            hover_state = (
                self.gui.button,
                [98, 98, 204, 34, 'Yeah buttons Baby'],
               {'fill_color': Color(0.95, 0.95, 0.95), 'bold':True}
            )
            active_state = (
                self.gui.button,
                [98, 98, 204, 34, 'Yeah buttons Baby'],
                {'fill_color': Color(0.9, 0.9, 0.9), 'bold': True}
            )
            callback = self.calibrate
            #self.gui.add_element(element_id=1, base_state=base_state, hover_state=hover_state, active_state=active_state, callback=callback)

            self.gui.update()
        else:
            self.gui = None

    def start_encoding_animation(self):
        self.encoding_started = datetime.datetime.now()
        self.last_serial_command = 'f'
        self.ser.write('f')

    def stop_encoding_animation(self):
        if self.last_serial_command != 's':
            self.last_serial_command = 's'
            self.ser.write('s')

    def log(self, text):
        print text

    def array(self, image):
        return numpy.asarray(image[:,:])

    def threshold(self, grayscale_array, low, high, value=1):
        grayscale_array = value * numpy.logical_and(grayscale_array >= low, grayscale_array < high)
        return grayscale_array

    def update_frame_rate(self):
        # FIXME: save some kind of average for the fps
        self.frame_diff = time.time() - self.last_frame

        if self.limit_fps:
#.........这里部分代码省略.........
开发者ID:kirberich,项目名称:poolrecorder,代码行数:103,代码来源:recorder.py

示例7: World

# 需要导入模块: from gui import Gui [as 别名]
# 或者: from gui.Gui import update [as 别名]
from __future__ import division

import sys
from world import World
from gui import Gui

import pygame
from pygame.locals import *

clock  = pygame.time.Clock()
frequency = 40

world = World()
gui = Gui(world)

while world.is_running():
    time = clock.tick(frequency) / 1000

    world.update(time)
    gui.update(time)

print "Have a nice day!"
开发者ID:kxgames,项目名称:MapMaker,代码行数:24,代码来源:main.py


注:本文中的gui.Gui.update方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。