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


Python Display.init方法代码示例

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


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

示例1: main

# 需要导入模块: from display import Display [as 别名]
# 或者: from display.Display import init [as 别名]
def main(myAddr, clAddr):
    myDisplay = Display()
    myDisplay.init()
    
    backSender = BackSender(clAddr)
    
    # start threads
    displayThread = threading.Thread(None, displayMain, 'display', (myDisplay, ))
    displayThread.start()
    
    serverThread = threading.Thread(None, displayServerMain, 'displayserver', (myDisplay, myAddr))
    serverThread.start()
    
    connectTread = threading.Thread(None, connectMain, 'connection', (myAddr, backSender))
    connectTread.start()
    
    inputThread = threading.Thread(None, inputMain, 'input', (myDisplay, backSender))
    inputThread.start()
    
    # wait till threads end
    while displayThread.is_alive() and serverThread.is_alive():
        try:
            littlePause = 0.1
            displayThread.join(littlePause)
        except KeyboardInterrupt:
            logging.info('exit on keyboard interrupt')
            myDisplay.quit = True
        except Exception as err:
            logging.error('unhandled exception in main thread:')
            logging.error(str(err))
            logging.debug(traceback.format_exc())
开发者ID:caryoscelus,项目名称:tam-rogue,代码行数:33,代码来源:main.py

示例2: main

# 需要导入模块: from display import Display [as 别名]
# 或者: from display.Display import init [as 别名]
def main(args):
    # Initialize main transport
    transport = get_transport(args.transport, args.path)

    # Initialize hardware (screen, buttons)
    but = Buttons(hw=args.shield, stdin=not args.shield, pygame=not args.shield)
    buff = DisplayBuffer(DISPLAY_WIDTH, DISPLAY_HEIGHT)
    display = Display(buff, spi=args.shield, virtual=not args.shield)
    display.init()

    # Initialize layout driver
    layout = Layout(buff)

    # Startup state machine and switch it to default state
    machine = StateMachine(args.keyfile, layout)

    display.refresh()

    # Main cycle
    while True:
        # Set True if device does something
        # False = device will sleep for a moment
        is_active = False

        try:
            # Read button states
            button = but.read()
        except KeyboardInterrupt:
            # User requested to close the app
            break

        if button is not None:
            print "Button", button
            is_active = True

            resp = machine.press_button(button)
            if resp is not None:
                print "Sending", resp
                transport.write(resp)

        # Handle main connection
        msg = transport.read()
        if msg is not None:
            print "Received", msg.__class__.__name__  # , msg
            resp = machine.process_message(msg)
            if resp is not None:
                print "Sending", resp.__class__.__name__, resp
                transport.write(resp)
                is_active = True

        # Display scrolling
        is_active |= layout.update()

        if layout.need_refresh:
            # Update display
            display.refresh()

        if not is_active:
            # Nothing to do, sleep for a moment
            time.sleep(0.1)

    # Close transports
    transport.close()
开发者ID:slush0,项目名称:trezor-signer,代码行数:65,代码来源:__init__.py

示例3: main

# 需要导入模块: from display import Display [as 别名]
# 或者: from display.Display import init [as 别名]
def main(args):
    # Initialize debuglink transport
    if args.debuglink:
        print "Starting debug connection on '%s'" % args.debuglink_path
        print "Debug connection is for unit tests only. NEVER use debug connection with real wallet!"
        debug_transport = get_transport(args.debuglink_transport, args.debuglink_path)
    else:
        debug_transport = get_transport('fake', None)

    # Initialize main transport
    transport = get_transport(args.transport, args.path)

    # Load persisted data. Create new wallet if file doesn't exist
    print "Loading wallet..."
    wallet = Wallet(args.wallet)
    print wallet.struct

    # Initialize hardware (screen, buttons)
    but = Buttons(hw=args.shield, stdin=not args.shield, pygame=not args.shield)
    buff = DisplayBuffer(DISPLAY_WIDTH, DISPLAY_HEIGHT)
    display = Display(buff, spi=args.shield, virtual=not args.shield)
    display.init()

    # Initialize layout driver
    layout = Layout(buff)

    # Startup state machine and switch it to default state
    machine = StateMachine(wallet, layout)

    #tx1 = proto.TxOutput(address='1BRMLAB7nryYgFGrG8x9SYaokb8r2ZwAsX', amount=112000000)
    #tx2 = proto.TxOutput(address='1MarekMKDKRb6PEeHeVuiCGayk9avyBGBB', amount=12340123400)
    #layout.show_transactions([tx1, tx2 ], False)

    display.refresh()

    # Main cycle
    while True:
	#d=datetime.now()
	#layout.show_message([d.strftime("%d %B %Y %H:%M:%S")],question=False)
        # Set True if device does something
        # False = device will sleep for a moment
        is_active = False

        try:
            # Read button states
            button = but.read()
        except KeyboardInterrupt:
            # User requested to close the app
            break

        # Handle debug link connection
        msg = debug_transport.read()
        if msg is not None:
            print "Received debuglink", msg.__class__.__name__, msg
            if isinstance(msg, proto.DebugLinkDecision):
                # Press the button
                button = msg.yes_no
            else:
                resp = machine.process_message(msg)
                if resp is not None:
                    print "Sending debuglink", resp.__class__.__name__, resp
                    debug_transport.write(resp)
                    is_active = True

            '''
            elif isinstance(msg, proto.DebugLinkGetState):
                # Report device state
                resp = machine.get_state(msg)
                print "Sending debuglink", resp.__class__.__name__, resp
                debug_transport.write(resp)
            else:
                raise Exception("Got unexpected object %s" % msg.__class__.__name__)
            '''

        if button is not None:
            print "Button", button
            is_active = True

            resp = machine.press_button(button)
            if resp is not None:
                print "Sending", resp
                transport.write(resp)

        '''
        if button == True:
            layout.show_transactions([tx1, tx2 ], False)
            layout.show_question_dummy()

        if button == False:
            layout.show_logo(logo)
        '''

        # Handle main connection
        msg = transport.read()
        if msg is not None:
            print "Received", msg.__class__.__name__, msg
            resp = machine.process_message(msg)
            if resp is not None:
                print "Sending", resp.__class__.__name__, resp
                transport.write(resp)
#.........这里部分代码省略.........
开发者ID:jackjack-jj,项目名称:trezor-emu-jj,代码行数:103,代码来源:__init__.py

示例4: readline_from_socket

# 需要导入模块: from display import Display [as 别名]
# 或者: from display.Display import init [as 别名]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.connect(("127.0.0.1", 5050))

display = None
board = None
players = None

for line in readline_from_socket(s):
    try:
        data = json.loads(line)
        if not display:
            board = GameBoardClient(*data["map_size"])
            players = [Player(None, name=player["name"]) for player in data["players"]]
            display = Display(600, 600, board.width, board.height)
            display.init()

        board.update(data["map"])
        display.clear()
        display.draw_board(board, players)
        display.update(fps=0)

    except Exception, e:
        print("Error parsing:", e.message)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            print("Game terminated by host.")
            sys.exit(0)
开发者ID:etse,项目名称:AI-compo-strategic-war,代码行数:31,代码来源:testObserver.py

示例5: __init__

# 需要导入模块: from display import Display [as 别名]
# 或者: from display.Display import init [as 别名]
class GameServer:
    def __init__(self, port, mapfile, rounds_per_second, w, h, observers):
        self._port = port
        self.players = []
        self.observers = []
        self.numObservers = observers
        self.numPlayers = 0  # Will be overwritten by loadmap. (but included here to make PyCharm happy)
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.bind(('', port))
        self.socket.listen(3)
        self.loadmap(mapfile)
        self.display = Display(w, h, self.board.width, self.board.height)
        self.rounds_per_second = rounds_per_second

    def start(self):
        print("Server started on port {}.".format(self._port))
        self.wait_for_observsers()
        self.wait_for_players()
        print("All players are ready, game is now starting.")
        self.send_gamestate_to_observers(unfiltered=True)

        self.display.init()
        first_round = True
        while True:
            self.display.clear()

            self.start_next_turn()
            self.resolve_food_harvest()
            self.move_and_spawn_units()
            self.resolve_fights()
            self.destroy_spawners()

            if random.randrange(0, 100) < 17:
                self.board.spawn_food()

            self.send_gamestate_to_players()
            self.send_gamestate_to_observers()

            self.display.draw_board(self.board, self.players)
            if first_round:
                self.wait_for_next_round(1)
                first_round = False
            if self.wait_for_next_round(self.rounds_per_second):
                return True


    def wait_for_next_round(self, rounds_per_seconds):
        num_updates = int(20 / rounds_per_seconds)
        for _ in range(num_updates):
            self.display.update(20)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    print("Game terminated by host.")
                    return True
        return False

    def wait_for_observsers(self):
        print("Waiting for {} observer(s) to connect...".format(self.numObservers))
        for _ in range(self.numObservers):
            observer = self.get_player_from_socket()
            observer.name = "Observer"
            self.observers.append(observer)

    def wait_for_players(self):
        print("Waiting for {} player(s) to connect...".format(self.numPlayers))
        for _ in range(self.numPlayers):
            player = self.get_player_from_socket()
            player.start()
            self.players.append(player)

        while not self.check_players_ready():
            time.sleep(0.5)

    def start_next_turn(self):
        for player in self.players:
            player.start_next_turn()

    def get_player_from_socket(self):
        conn, addr = self.socket.accept()
        print("Recieved new connection from {}:{}".format(*addr))
        return Player(conn)

    def check_players_ready(self):
        for player in self.players:
            if not player.ready:
                return False
        return True

    def move_and_spawn_units(self):
        for playerNum, player in enumerate(self.players):
            # Set new spawning mode for the player
            mode = player.command.get("mode", "standard")
            if mode == "standard":
                player.mode = Unit
            elif mode == "harvester":
                player.mode = Harvester
            elif mode == "soldier":
                player.mode = Soldier

            # move all the units he sent a command for
#.........这里部分代码省略.........
开发者ID:etse,项目名称:AI-compo-strategic-war,代码行数:103,代码来源:server.py

示例6: __init__

# 需要导入模块: from display import Display [as 别名]
# 或者: from display.Display import init [as 别名]
class GameAI:
    def __init__(self, name):
        self.name = name
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.display = None
        self.board = None
        self.players = None
        self.my_id = None

    def sendline(self, line):
        self.sock.send((line+"\n").encode('UTF-8'))

    def send_command(self, command):
        self.sendline(json.dumps(command))

    def start(self, ip, port):
        self.sock.connect((ip, port))
        self.sendline("name {}".format(self.name))

        for line in readline_from_socket(self.sock):
            data = json.loads(line)
            if "status" in data:
                self.handle_status_message(data)
                continue

            if not self.display:
                self.board = GameBoardClient(*data["map_size"])
                self.players = [Player(None, name="Player"+str(i)) for i in range(data["num_players"])]
                self.my_id = data["player_id"]
                self.players[self.my_id].name = self.name
                self.display = Display(600, 600, self.board.width, self.board.height)
                self.display.init()

            self.board.update(data["map"])
            self.display.clear()
            self.display.draw_board(self.board, self.players)
            self.display.update(fps=0)
            self.resolve_round()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    print("Game terminated by host.")
                    sys.exit(0)

    def handle_status_message(self, command):
        '''
        Implement how to handle status-messages here. The current implementation
        will ignore any "Status OK" and print everything else.

        :param command: The data recieved from server (must be a status message)
        '''
        if command.get("status", "ok").lower() != "ok":
            print("Status: {} - Message: {}".format(command.get("status", "ok"), command.get("msg", "")))

    def resolve_round(self):
        '''
        This function will be called once each turn. Any login with the AI should be implemented here.
        Make sure that this command sends a new command to the server before it returns.

        The map-state is stored in self.board.
        '''

        # Simple implementation
        command = {"mode": random.choice(["standard", "harvester", "soldier"]), "moves": []}
        for unit in filter(lambda u: u.owner == self.my_id, self.board.units):
            x, y = unit.position
            legal_directions = ["north", "south", "west", "east"]
            direction = random.choice(legal_directions)
            command["moves"].append([x, y, direction])
            self.board.move_unit(x, y, direction)
        self.send_command(command)
开发者ID:etse,项目名称:AI-compo-strategic-war,代码行数:74,代码来源:testClient.py

示例7: main

# 需要导入模块: from display import Display [as 别名]
# 或者: from display.Display import init [as 别名]
def main(args):
    monkeypatch_google_protobuf_text_format()

    # Initialize debuglink transport
    if args.debuglink:
        print "Starting debug connection on '%s'" % args.debuglink_path
        print "Debug connection is for unit tests only. NEVER use debug connection with real wallet!"
        debug_transport = get_transport(args.debuglink_transport, args.debuglink_path)
    else:
        debug_transport = get_transport('fake', None)

    # Initialize main transport
    transport = get_transport(args.transport, args.path)

    # Load persisted data. Create new wallet if file doesn't exist
    print "Loading wallet..."
    storage = Storage(args.wallet, bootloader_mode=args.bootloader_mode)
    # storage.struct.settings.label = 'Slushova penezenka'
    print storage.struct

    # Initialize hardware (screen, buttons)
    but = Buttons(hw=args.shield, stdin=not args.shield, pygame=not args.shield)
    buff = DisplayBuffer(DISPLAY_WIDTH, DISPLAY_HEIGHT)
    display = Display(buff, spi=args.shield, virtual=not args.shield)
    display.init()

    # Initialize layout driver
    layout = Layout(buff, display)

    # Process exponential backoff if there was unsuccesfull PIN attempts
    if storage.get_pin_delay():
        delay = storage.get_pin_delay()
        print "Waiting %s seconds until boot up" % delay
        layout.show_pin_backoff_progress(delay)

    # Startup state machine and switch it to default state
    machine = StateMachine(storage, layout)

    display.refresh()

    # Main cycle
    while True:
        try:
            # Read button states
            button = but.read()
        except KeyboardInterrupt:
            # User requested to close the app
            break

        # Set is_active=True if device does something
        # False = device will sleep for a moment to prevent CPU load
        # Set button=None to use event only for rendering
        # and hide it against state machine
        (is_active, button) = layout.update(button)

        # Handle debug link connection
        msg = debug_transport.read()
        if msg is not None:
            print "Received debuglink", msg.__class__.__name__, msg
            if isinstance(msg, proto.DebugLinkDecision):
                # Press the button
                button = msg.yes_no
            else:
                resp = machine.process_debug_message(msg)
                if resp is not None:
                    print "Sending debuglink", resp.__class__.__name__, resp
                    debug_transport.write(resp)
                    is_active = True

        if button is not None:
            print "Button", button
            is_active = True

            resp = machine.press_button(button)
            if resp is not None:
                print "Sending", resp
                transport.write(resp)

        # Handle main connection
        msg = transport.read()
        if msg is not None:
            print "Received", msg.__class__.__name__, msg
            resp = machine.process_message(msg)
            if resp is not None:
                print "Sending", resp.__class__.__name__, resp
                transport.write(resp)
                is_active = True

        if not is_active:
            # Nothing to do, sleep for a moment
            time.sleep(0.05)

    # Close transports
    transport.close()
    debug_transport.close()
开发者ID:adballar,项目名称:trezor-emu,代码行数:97,代码来源:__init__.py


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