示例#1
0
    def run(self):
        menu = Menu(self.screen)
        hs_screen = HighScoreScreen(self.screen, self.score_keeper)
        intro_seq = Intro(self.screen)
        e_loop = EventLoop(
            loop_running=True,
            actions={pygame.MOUSEBUTTONDOWN: menu.check_buttons})

        while e_loop.loop_running:
            self.clock.tick(60)  # 60 fps limit
            e_loop.check_events()
            self.screen.fill(PacManPortalGame.BLACK_BG)
            if not menu.hs_screen:
                intro_seq.update()  # display intro/menu
                intro_seq.blit()
                menu.update()
                menu.blit()
            else:
                hs_screen.blit()  # display highs score screen
                hs_screen.check_done()
            if menu.ready_to_play:
                pygame.mixer.music.stop()  # stop menu music
                self.play_game()  # player selected play, so run game
                for g in self.ghosts:
                    g.reset_speed()
                menu.ready_to_play = False
                self.score_keeper.save_high_scores(
                )  # save high scores only on complete play
                hs_screen.prep_images()  # update high scores page
                hs_screen.position()
            elif not pygame.mixer.music.get_busy():
                pygame.mixer.music.play(-1)  # music loop
            pygame.display.flip()
示例#2
0
 def test_push_back(self):
     reader, writer = os.pipe()
     try:
         data = 'Lorem ipsum dolor sit.'
         assert os.write(writer, data) == len(data)
         
         loop = EventLoop()
         
         state = [1]
         
         @loop.push_back_reader(reader, max_block_size=5)
         def new_block(data, push_back):
             if state[0] == 1:
                 assert data == 'Lorem'
             elif state[0] == 2:
                 assert data == ' ipsu'
                 push_back(data)
             elif state[0] == 3:
                 assert data == ' ipsum dol'
                 push_back('d')
                 push_back('ol')
             elif state[0] == 4:
                 assert data == 'dolor si'
             elif state[0] == 5:
                 assert data == 't.'
                 loop.stop()
             else:
                 assert False
             state[0] += 1
         
         loop.run()
         assert state[0] == 6
     finally:
         os.close(reader)
         os.close(writer)
    def play_game(self):
        """Run the game's event loop, using an EventLoop object"""
        e_loop = EventLoop(loop_running=True,
                           actions={
                               **self.player.event_map,
                               **self.actions
                           })
        # game init signal
        # pygame.time.set_timer(PacManPortalGame.START_EVENT, self.level_transition.transition_time)
        self.level_transition.set_show_transition()
        self.game_over = False
        if self.player.dead:
            self.player.revive()
            self.score_keeper.reset_level()
            self.life_counter.reset_counter()
            self.rebuild_maze()

        while e_loop.loop_running:
            self.clock.tick(60)  # 60 fps limit
            e_loop.check_events()
            self.update_screen()
            if self.game_over:
                pygame.mixer.stop()
                self.score_keeper.reset_level()
                e_loop.loop_running = False
示例#4
0
    def _simple(self, reader, writer):
        loop = EventLoop()
        nb_reads = [0]

        @loop.block_reader(reader)
        def incoming(data):
            assert data == 'foo'
            nb_reads[0] += 1
            loop.stop()
        
        assert os.write(writer, 'foo') == 3
        loop.run()
        assert nb_reads[0] == 1
示例#5
0
def on_connection(sock):
    conn, address = sock.accept()
    print("get connection: ", address)

    loop = EventLoop.instance()
    callback = functools.partial(on_recieve, conn)
    loop.register(conn.fileno(), EVENT_READ, callback)
示例#6
0
    def run(self):
        """Run the application loop so that the menu can be displayed and the game started"""
        loop = EventLoop(loop_running=True, actions=self.menu.action_map)

        while True:
            loop.check_events()
            self.update()
            if self.menu.start:
                self.game_active = True
                self.timer = 400
                self.time_warn = False
                self.start_game()
                self.menu.start = False
                self.game_active = False
                self.game_won = False
                self.init_world()
示例#7
0
文件: test.py 项目: defcyy/practise
def on_connection(sock):
    conn, address = sock.accept()
    print("get connection: ", address)
    
    loop = EventLoop.instance()
    callback = functools.partial(on_recieve, conn)
    loop.register(conn.fileno(), EVENT_READ, callback)
示例#8
0
    def test_timing(self):
        reader, writer = os.pipe()
        try:
            loop = EventLoop()
            
            data = [
                'Lorem ipsum\n',
                'dolor\nsit\namet, ',
                'consectetur',
                ' adipiscing ',
                'elit.\nAliquam magna dolor, ', # no newline character at the end
            ]
            # Reverse because list.pop() pops at the end.
            data = data[::-1]
            
            @loop.add_timer(.01, repeat=True)
            def slow_write():
                if data:
                    os.write(writer, data.pop())
                else:
                    loop.stop()
            
            lines = []
            @loop.line_reader(reader)
            def new_line(line):
                lines.append(line)
                expected_time = {
                    'L': .01, 'd': .02, 's': .02, 'a': .05}[line[0]]
                assert round(time.time() - start, 2) == expected_time

            time.sleep(.02)
            # Reset so that the timing is correct in spite of the sleep we
            # just did.
            slow_write.reset()
            start = time.time()
            loop.run()
            
            assert lines == [
                'Lorem ipsum\n',
                'dolor\n',
                'sit\n',
                'amet, consectetur adipiscing elit.\n'
            ]
        finally:
            os.close(reader)
            os.close(writer)
示例#9
0
    def test_pipe(self):
        reader, writer = os.pipe()
        try:
            loop = EventLoop()
            nb_reads = [0]
            nb_writes = [0]
            
            duration = .1
            interval = .0095
            expected_nb = 10
            assert expected_nb == duration // interval
            # Avoid a race condition between the loop stop and the last read.
            assert expected_nb < duration / interval
            
            start = time.time()
            loop.add_timer(duration)(loop.stop)
            
            @loop.add_timer(interval, repeat=True)
            def write_something():
                assert os.write(writer, 'foo') == 3
                nb_writes[0] += 1

            @loop.block_reader(reader)
            def incoming(data):
                assert data == 'foo'
                nb_reads[0] += 1
            
            loop.run()
            assert round(time.time() - start, 2) == duration
            assert nb_writes[0] == expected_nb, nb_writes
            assert nb_reads[0] == expected_nb, nb_reads
        finally:
            os.close(reader)
            os.close(writer)
示例#10
0
    def play_game(self):
        e_loop = EventLoop(loop_running=True,
                           actions={
                               **self.player.event_map,
                               **self.actions
                           })
        self.level_transition.set_show_transition()
        self.game_over = False
        if self.player.dead:
            self.player.revive()
            self.score_keeper.reset_level()
            self.life_counter.reset_counter()
            self.rebuild_maze()

        while e_loop.loop_running:
            self.clock.tick(60)  # 60 fps limit
            e_loop.check_events()
            self.update_screen()
            if self.game_over:
                pygame.mixer.stop()
                self.score_keeper.reset_level()
                e_loop.loop_running = False
示例#11
0
    def setUp(self):
        self.mod_tessumod = None
        self.ts_client_query_server = None
        self.__ts_plugin_info = None
        self.event_loop = EventLoop()
        self.__verifiers = []
        self.__max_end_time = None
        self.__min_end_time = None
        self.__event_handlers = {}

        shutil.rmtree(TMP_DIRPATH, ignore_errors=True)

        if FAKES_DIRPATH not in sys.path:
            sys.path.append(FAKES_DIRPATH)
        if MOD_SCRIPTS_DIRPATH not in sys.path:
            sys.path.append(MOD_SCRIPTS_DIRPATH)

        os.makedirs(MODS_VERSION_DIRPATH)

        shutil.copytree(os.path.join(MOD_SRC_DIRPATH, "gui"),
                        os.path.join(MODS_VERSION_DIRPATH, "gui"))

        import ResMgr
        ResMgr.RES_MODS_VERSION_PATH = MODS_VERSION_DIRPATH

        mod_settings.INI_DIRPATH = INI_DIRPATH
        mod_settings.reset_cache_file()
        mod_settings.reset_settings_file()
        self.change_mod_settings(
            General={
                # "log_level": "0", # enable for debug logging
                "speak_stop_delay": "0"  # makes tests execute faster
            },
            TSClientQueryService={
                "polling_interval": "0"  # makes tests execute faster
            })
        # create empty ts plugin installer file
        open(TS_PLUGIN_INSTALLER_PATH, "w").close()
示例#12
0
    def test_packets(self):
        reader, writer = os.pipe()
        try:
            loop = EventLoop()
            original_packets = [
                'foo',
                '',
                'Lorem ipsum dolor sit amet.',
                '42',
            ]
            packets = []

            def callback(packet):
                packets.append(packet)
                assert packet_reader.dropped_bytes == {
                    1: 0,  2: 1,  3: 3,  4: 6
                }[len(packets)]
                if len(packets) == len(original_packets):
                    loop.stop()

            def write(data):
                assert os.write(writer, data) == len(data)
                
            for i, packet in enumerate(original_packets):
                write('blah'[:i]) # non-packet garbage
                write(PacketReader.PACKET_DELIMITER)
                write(chr(len(packet) + 1))
                write(packet)
                
            # Choose a very small block size on purpose to (hopefully)
            # test more code paths such as half packets
            packet_reader = PacketReader(loop, reader, callback,
                                         max_block_size=3)
            loop.run()
            assert packets == original_packets
        finally:
            os.close(reader)
            os.close(writer)
示例#13
0
    def start_game(self):
        """Launch the game and begin checking for events"""
        loop = EventLoop(loop_running=True, actions=self.action_map)
        self.score = 0
        self.lives = 3
        self.coins = 0

        while loop.loop_running and self.game_active:
            self.clock.tick(60)  # 60 fps cap
            loop.check_events()
            self.update()
            if self.mario.state_info['death_finish']:
                self.handle_player_killed()
            elif not pygame.mixer.music.get_busy() and self.game_won:
                self.menu.high_score.save(self.score)
                self.game_active = False
            elif not pygame.mixer.music.get_busy(
            ) and self.mario.state_info['dead']:
                pygame.mixer.music.load('audio/Mario-Die.wav')
                pygame.mixer.music.play()
            elif not pygame.mixer.music.get_busy() and not self.paused:
                pygame.mixer.music.load('audio/BG-Main.wav')
                pygame.mixer.music.play(-1)
示例#14
0
def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(("", 8000))
    sock.setblocking(False)
    sock.listen(128)

    loop = EventLoop.instance()
    callback = functools.partial(on_connection, sock)
    loop.register(sock.fileno(), EVENT_READ | EVENT_WRITE, callback)

    call_time = time.time() + 5
    loop.call_at(call_time, on_timeout)
    # stop_time = time.time() + 10
    # loop.call_at(stop_time, loop.stop)

    print("io loop start: ", time.time())
    loop.start()
示例#15
0
文件: test.py 项目: defcyy/practise
def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(("", 8000))
    sock.setblocking(False)
    sock.listen(128)

    loop = EventLoop.instance()
    callback = functools.partial(on_connection, sock)
    loop.register(sock.fileno(), EVENT_READ | EVENT_WRITE, callback)

    call_time = time.time() + 5
    loop.call_at(call_time, on_timeout)
    # stop_time = time.time() + 10
    # loop.call_at(stop_time, loop.stop)

    print("io loop start: ", time.time())
    loop.start()
示例#16
0
	def setUp(self):
		self.mod_tessumod = None
		self.ts_client_query_server = None
		self.__ts_plugin_info = None
		self.event_loop = EventLoop()
		self.__verifiers = []
		self.__max_end_time = None
		self.__min_end_time = None
		self.__event_handlers = {}

		shutil.rmtree(TMP_DIRPATH, ignore_errors=True)

		if FAKES_DIRPATH not in sys.path:
			sys.path.append(FAKES_DIRPATH)
		if MOD_SCRIPTS_DIRPATH not in sys.path:
			sys.path.append(MOD_SCRIPTS_DIRPATH)

		os.makedirs(MODS_VERSION_DIRPATH)

		shutil.copytree(os.path.join(MOD_SRC_DIRPATH, "gui"), os.path.join(MODS_VERSION_DIRPATH, "gui"))

		import ResMgr
		ResMgr.RES_MODS_VERSION_PATH = MODS_VERSION_DIRPATH

		mod_settings.INI_DIRPATH = INI_DIRPATH
		mod_settings.reset_cache_file()
		mod_settings.reset_settings_file()
		self.change_mod_settings(
			General = {
				# "log_level": "0", # enable for debug logging
				"speak_stop_delay": "0" # makes tests execute faster
			},
			TSClientQueryService = {
				"polling_interval": "0" # makes tests execute faster
			}
		)
		# create empty ts plugin installer file
		open(TS_PLUGIN_INSTALLER_PATH, "w").close()
示例#17
0
    def play(self):
        pacman = self.pacman
        maze = self.maze
        ghost = []
        for i in range(1):
            g = Ghost(self.screen)
            g.type = i
            g.x += 30 * i
            g.prep_ghost()
            ghost.append(g)

        eloop = EventLoop(status=False)

        while not eloop.finished:
            eloop.check_events(pacman)
            eloop.update_screen(pacman)
            pacman.update(maze, self.gamestats, self.pacmanGroup)
            for i in range(1):
                ghost[i].blit()
            self.update_screen()
示例#18
0
 def test_line_reader(self):
     reader, writer = os.pipe()
     try:
         loop = EventLoop()
         
         data = [
             'Lorem ipsum\n',
             'dolor\nsit\namet, ',
             'consectetur',
             ' adipiscing ',
             'elit.\nAliquam magna dolor, ', # no newline character at the end
         ]
         # Reverse because list.pop() pops at the end.
         data = data[::-1]
         
         start = time.time()
         @loop.add_timer(.01, repeat=True)
         def slow_write():
             if data:
                 d = data.pop()
                 assert os.write(writer, d) == len(d)
             else:
                 loop.stop()
         
         lines = []
         loop.line_reader(reader, max_block_size=5)(lines.append)
             
         loop.run()
         
         assert lines == [
             'Lorem ipsum\n',
             'dolor\n',
             'sit\n',
             'amet, consectetur adipiscing elit.\n'
         ]
     finally:
         os.close(reader)
         os.close(writer)
示例#19
0
class SubReactorThread(Thread):
    def __init__(self, name, common_conn_que):
        Thread.__init__(self)
        self.name = name
        self.common_conn_que = common_conn_que
        self.__loop = EventLoop(self.get_new_conn, self.get_conn, self.remove_conn)
        self.__fd_to_conns = {}

    def get_new_conn(self):
        new_conn = self.common_conn_que.get(1)
        new_conn.set_loop(self.__loop)
        self.__fd_to_conns[new_conn.get_fd()] = new_conn
        return new_conn

    def wake_up_loop(self):
        """
        唤醒loop去添加新连接的事件描述符
        :return:
        """
        self.__loop.wake_up_self(flag=Flag.ADD_NEW_CONN_EVENT)
        pass

    def get_conn(self, fd):
        return self.__fd_to_conns[fd]

    def remove_conn(self, fd):
        del self.__fd_to_conns[fd]

    def run(self):
        logger.simple_log('正在运做')
        self.__loop.loop()

    def stop(self):
        self.__loop.un_loop()

    def get_conn_count(self):
        return len(self.__fd_to_conns.keys())
                    #				print(callback.__name__)
                    callback(key.fileobj, mask)
            except EventLoopAppException:
                pass


if __name__ == "__main__":
    env = 'development'
    cache_policy = LRU
    if len(sys.argv) > 1:
        env = sys.argv[1]
        if len(sys.argv) == 3:
            cache_policy = sys.argv[2]
    print('Event loop app is starting in ' + env + ' environment with ' +
          cache_policy + ' cache policy.')

    event_queue = EventQueue()
    app = EventLoopApp(env, event_queue)
    event_loop = EventLoop(event_queue, cache_policy)

    try:
        conn_process = Thread(name='conn_process', target=app.start)
        event_loop_process = Thread(name='event_loop_process',
                                    target=event_loop.start)
        conn_process.start()
        event_loop_process.start()
    except KeyboardInterrupt:
        app.SERVER_SOCKET.close()
        print('You pressed CTRL + C')
        print('Server terminated gracefully')
示例#21
0
def main():
    window_with_plot = Window(b"Lab 3")
    EventLoop(window_with_plot).run()
    return 0
示例#22
0
class TestCaseBase(unittest.TestCase):

	def setUp(self):
		self.mod_tessumod = None
		self.ts_client_query_server = None
		self.__ts_plugin_info = None
		self.event_loop = EventLoop()
		self.__verifiers = []
		self.__max_end_time = None
		self.__min_end_time = None
		self.__event_handlers = {}

		shutil.rmtree(TMP_DIRPATH, ignore_errors=True)

		if FAKES_DIRPATH not in sys.path:
			sys.path.append(FAKES_DIRPATH)
		if MOD_SCRIPTS_DIRPATH not in sys.path:
			sys.path.append(MOD_SCRIPTS_DIRPATH)

		os.makedirs(MODS_VERSION_DIRPATH)

		shutil.copytree(os.path.join(MOD_SRC_DIRPATH, "gui"), os.path.join(MODS_VERSION_DIRPATH, "gui"))

		import ResMgr
		ResMgr.RES_MODS_VERSION_PATH = MODS_VERSION_DIRPATH

		mod_settings.INI_DIRPATH = INI_DIRPATH
		mod_settings.reset_cache_file()
		mod_settings.reset_settings_file()
		self.change_mod_settings(
			General = {
				# "log_level": "0", # enable for debug logging
				"speak_stop_delay": "0" # makes tests execute faster
			},
			TSClientQueryService = {
				"polling_interval": "0" # makes tests execute faster
			}
		)
		# create empty ts plugin installer file
		open(TS_PLUGIN_INSTALLER_PATH, "w").close()

	def tearDown(self):
		if self.__ts_plugin_info:
			self.__ts_plugin_info.close()
		if self.ts_client_query_server:
			self.ts_client_query_server.stop()
		sys.path.remove(FAKES_DIRPATH)
		sys.path.remove(MOD_SCRIPTS_DIRPATH)

	def start_ts_client(self, **state):
		assert self.ts_client_query_server == None, "Cannot start TS client if it is already running"
		self.ts_client_query_server = TSClientQueryService()
		self.ts_client_query_server.start()
		self.change_ts_client_state(**state)

	def enable_ts_client_tessumod_plugin(self, version=0):
		self.__ts_plugin_info = mmap.mmap(0, 1, "TessuModTSPluginInfo", mmap.ACCESS_WRITE)
		self.__ts_plugin_info.write(struct.pack("=B", version))

	def get_shared_memory_contents(self, memory):
		assert memory == "TessuModTSPlugin3dAudio" # currently this is only memory supported
		shmem = mmap.mmap(0, 1024, memory, mmap.ACCESS_READ)
		(
			timestamp,
			camera_pos_x,
			camera_pos_y,
			camera_pos_z,
			camera_dir_x,
			camera_dir_y,
			camera_dir_z,
			client_count
		) = struct.unpack("=I3f3fB", shmem.read(4+3*4+3*4+1))
		clients = {}
		for client_index in range(0, client_count):
			client_id, x, y, z = struct.unpack("=h3f", shmem.read(2+3*4))
			clients[self.ts_client_query_server.get_user(clid=client_id).name] = {
				"position": (x, y, z)
			}

		return {
			"timestamp": timestamp,
			"camera": {
				"position": (camera_pos_x, camera_pos_y, camera_pos_z),
				"direction": (camera_dir_x, camera_dir_y, camera_dir_z)
			},
			"clients": clients
		}

	def on_event(self, name, callback):
		def call_wrapper(callback, *args, **kwargs):
			callback()
		wrapped_callback = partial(call_wrapper, callback)
		if not self.__install_event_handler(name, wrapped_callback):
			if name not in self.__event_handlers:
				self.__event_handlers[name] = []
			self.__event_handlers[name].append(wrapped_callback)

	def __install_event_handler(self, name, callback):
		if self.mod_tessumod is not None:
			cq = sys.modules["tessumod.infrastructure.di"].get_provided("chatclient").get_clientquery()
			if name == "on_connected_to_ts_server":
				cq.on("connected-server-name", callback)
			elif name == "on_connected_to_ts_client":
				cq.on("connected", callback)
			elif name == "on_disconnected_from_ts_client":
				cq.on("disconnected", callback)
			else:
				raise RuntimeError("No such event: {0}".format(name))
			return True
		return False

	def start_game(self, **game_state):
		import mod_tessumod
		self.mod_tessumod = mod_tessumod
		self.mod_tessumod.init()

		for name, callbacks in self.__event_handlers.iteritems():
			for callback in callbacks:
				self.__install_event_handler(name, callback)

		self.change_game_state(**game_state)

	def run_in_event_loop(self, timeout=20):
		self.event_loop.call(self.__on_loop, repeat=True, timeout=0.05)
		self.event_loop.call(self.__check_verify, repeat=True, timeout=1)
		self.__max_end_time = time.time() + timeout
		if self.__min_end_time is None:
			self.__min_end_time = time.time()
		self.event_loop.execute()

	def change_ts_client_state(self, **state):
		assert self.ts_client_query_server, "TS client must be running to change its state"
		if "running" in state:
			if not state["running"]:
				self.ts_client_query_server.stop()
				self.ts_client_query_server = None
		if "connected_to_server" in state:
			self.ts_client_query_server.set_connected_to_server(state["connected_to_server"])
		if "users" in state:
			for name, data in state["users"].iteritems():
				self.ts_client_query_server.set_user(name, **data)

	def change_game_state(self, **state):
		import BigWorld, Avatar, Account
		assert self.mod_tessumod, "Mod must be loaded first before changing game state"

		if state["mode"] == "battle":
			BigWorld.player(Avatar.Avatar())
			if "players" in state:
				for player in state["players"]:
					vehicle_id = random.randint(0, 1000000)
					dbid = random.randint(0, 1000000)
					BigWorld.player().arena.vehicles[vehicle_id] = {
						"accountDBID": dbid,
						"name":        player["name"],
						"isAlive":     True
					}
					if vehicle_id not in BigWorld.entities:
						BigWorld.entities[vehicle_id] = BigWorld.Entity()
					if "position" in player:
						BigWorld.player().arena.positions[vehicle_id] = player["position"]
						BigWorld.entities[vehicle_id].position = BigWorld.Vector(*player["position"])
			if "camera" in state:
				if "position" in state["camera"]:
					BigWorld.camera().position = BigWorld.Vector(*state["camera"]["position"])
				if "direction" in state["camera"]:
					BigWorld.camera().direction = BigWorld.Vector(*state["camera"]["direction"])
		elif state["mode"] == "lobby":
			BigWorld.player(Account.PlayerAccount())
			if "players" in state:
				for id, player in enumerate(state["players"]):
					BigWorld.player().prebattle.rosters[0][id] = {
						"name": player["name"],
						"dbID": random.randint(0, 1000000)
					}

	def get_player_id(self, name):
		import BigWorld
		if hasattr(BigWorld.player(), "arena"):
			for vehicle in BigWorld.player().arena.vehicles.itervalues():
				if vehicle["name"] == name:
					return vehicle["accountDBID"]

	def get_vehicle_id(self, name):
		import BigWorld
		if hasattr(BigWorld.player(), "arena"):
			for vehicle_id, vehicle in BigWorld.player().arena.vehicles.iteritems():
				if vehicle["name"] == name:
					return vehicle_id

	def change_mod_settings(self, **groups):
		for group_name, variables in groups.iteritems():
			for var_name, var_value in variables.iteritems():
				mod_settings.set_setting(group_name, var_name, var_value)

	def change_mod_user_cache(self, **groups):
		for group_name, variables in groups.iteritems():
			for var_name, var_value in variables.iteritems():
				mod_settings.set_cache_entry(group_name, var_name, var_value)

	def change_mod_state_variables(self, **variables):
		states_dirpath = os.path.join(INI_DIRPATH, "states")
		if not os.path.exists(states_dirpath):
			os.makedirs(states_dirpath)
		for key, value in variables.iteritems():
			with open(os.path.join(states_dirpath, key), "w") as file:
				file.write(json.dumps(value))

	def get_mod_state_variable(self, key):
		states_dirpath = os.path.join(INI_DIRPATH, "states")
		key_path = os.path.join(states_dirpath, key)
		if os.path.exists(key_path):
			with open(key_path, "r") as file:
				return json.loads(file.read())

	def call_later(self, callback, timeout=0):
		self.event_loop.call(callback, timeout=timeout)

	def __on_loop(self):
		import BigWorld
		BigWorld.tick()
		if self.ts_client_query_server:
			self.ts_client_query_server.check()
		self.assertLess(time.time(), self.__max_end_time, "Execution took too long")

	def __check_verify(self):
		try:
			if time.time() >= self.__min_end_time and all(verifier() for verifier in self.__verifiers):
				self.event_loop.exit()
		except Exception as error:
			print "{0} in __check_verify: {1}".format(error.__class__.__name__, error)

	def assert_finally_equal(self, a, b):
		actual_getter = a if callable(a) else b
		expected = b if callable(a) else a
		self.__verifiers.append(lambda: actual_getter() == expected)

	def assert_finally_true(self, x):
		self.__verifiers.append(x)

	def assert_finally_false(self, x):
		self.__verifiers.append(lambda: not x())

	def wait_at_least(self, secs):
		self.__min_end_time = time.time() + secs
示例#23
0
 def __init__(self, name, common_conn_que):
     Thread.__init__(self)
     self.name = name
     self.common_conn_que = common_conn_que
     self.__loop = EventLoop(self.get_new_conn, self.get_conn, self.remove_conn)
     self.__fd_to_conns = {}
示例#24
0
        logging.info("src fd:%s listing server port:%s",
                     self.server_sock.fileno(), port)
        self.loop = None  # type: EventLoop

    def handle_event(self, sock, fd, mode):
        # type: (socket.socket,int,int) -> None
        if sock == self.server_sock:
            local_sock, addr = sock.accept()
            logging.info("receive event fd:%s addr:%s", local_sock.fileno(),
                         addr)
            TCPEvent(local_sock, self.loop)
        else:
            raise Exception("no this socket")

    def add_loop(self, loop):
        # type: (EventLoop) -> None
        self.loop = loop
        loop.add(self.server_sock, POLL_IN | POLL_ERR, self)


if __name__ == '__main__':
    server_port = 1082
    logging.basicConfig(
        level=logging.DEBUG,
        format=
        '%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s'
    )
    loop = EventLoop()
    TCPServerEvent(server_port).add_loop(loop)
    loop.run()
示例#25
0
class TestCaseBase(unittest.TestCase):
    def setUp(self):
        self.mod_tessumod = None
        self.ts_client_query_server = None
        self.__ts_plugin_info = None
        self.event_loop = EventLoop()
        self.__verifiers = []
        self.__max_end_time = None
        self.__min_end_time = None
        self.__event_handlers = {}

        shutil.rmtree(TMP_DIRPATH, ignore_errors=True)

        if FAKES_DIRPATH not in sys.path:
            sys.path.append(FAKES_DIRPATH)
        if MOD_SCRIPTS_DIRPATH not in sys.path:
            sys.path.append(MOD_SCRIPTS_DIRPATH)

        os.makedirs(MODS_VERSION_DIRPATH)

        shutil.copytree(os.path.join(MOD_SRC_DIRPATH, "gui"),
                        os.path.join(MODS_VERSION_DIRPATH, "gui"))

        import ResMgr
        ResMgr.RES_MODS_VERSION_PATH = MODS_VERSION_DIRPATH

        mod_settings.INI_DIRPATH = INI_DIRPATH
        mod_settings.reset_cache_file()
        mod_settings.reset_settings_file()
        self.change_mod_settings(
            General={
                # "log_level": "0", # enable for debug logging
                "speak_stop_delay": "0"  # makes tests execute faster
            },
            TSClientQueryService={
                "polling_interval": "0"  # makes tests execute faster
            })
        # create empty ts plugin installer file
        open(TS_PLUGIN_INSTALLER_PATH, "w").close()

    def tearDown(self):
        if self.__ts_plugin_info:
            self.__ts_plugin_info.close()
        if self.ts_client_query_server:
            self.ts_client_query_server.stop()
        sys.path.remove(FAKES_DIRPATH)
        sys.path.remove(MOD_SCRIPTS_DIRPATH)

    def start_ts_client(self, **state):
        assert self.ts_client_query_server == None, "Cannot start TS client if it is already running"
        self.ts_client_query_server = TSClientQueryService()
        self.ts_client_query_server.start()
        self.change_ts_client_state(**state)

    def enable_ts_client_tessumod_plugin(self, version=0):
        self.__ts_plugin_info = mmap.mmap(0, 1, "TessuModTSPluginInfo",
                                          mmap.ACCESS_WRITE)
        self.__ts_plugin_info.write(struct.pack("=B", version))

    def get_shared_memory_contents(self, memory):
        assert memory == "TessuModTSPlugin3dAudio"  # currently this is only memory supported
        shmem = mmap.mmap(0, 1024, memory, mmap.ACCESS_READ)
        (timestamp, camera_pos_x, camera_pos_y, camera_pos_z, camera_dir_x,
         camera_dir_y, camera_dir_z,
         client_count) = struct.unpack("=I3f3fB",
                                       shmem.read(4 + 3 * 4 + 3 * 4 + 1))
        clients = {}
        for client_index in range(0, client_count):
            client_id, x, y, z = struct.unpack("=h3f", shmem.read(2 + 3 * 4))
            clients[self.ts_client_query_server.get_user(
                clid=client_id).name] = {
                    "position": (x, y, z)
                }

        return {
            "timestamp": timestamp,
            "camera": {
                "position": (camera_pos_x, camera_pos_y, camera_pos_z),
                "direction": (camera_dir_x, camera_dir_y, camera_dir_z)
            },
            "clients": clients
        }

    def on_event(self, name, callback):
        def call_wrapper(callback, *args, **kwargs):
            callback()

        wrapped_callback = partial(call_wrapper, callback)
        if not self.__install_event_handler(name, wrapped_callback):
            if name not in self.__event_handlers:
                self.__event_handlers[name] = []
            self.__event_handlers[name].append(wrapped_callback)

    def __install_event_handler(self, name, callback):
        if self.mod_tessumod is not None:
            cq = sys.modules["tessumod.infrastructure.di"].get_provided(
                "chatclient").get_clientquery()
            if name == "on_connected_to_ts_server":
                cq.on("connected-server-name", callback)
            elif name == "on_connected_to_ts_client":
                cq.on("connected", callback)
            elif name == "on_disconnected_from_ts_client":
                cq.on("disconnected", callback)
            else:
                raise RuntimeError("No such event: {0}".format(name))
            return True
        return False

    def start_game(self, **game_state):
        import mod_tessumod
        self.mod_tessumod = mod_tessumod
        self.mod_tessumod.init()

        for name, callbacks in self.__event_handlers.iteritems():
            for callback in callbacks:
                self.__install_event_handler(name, callback)

        self.change_game_state(**game_state)

    def run_in_event_loop(self, timeout=20):
        self.event_loop.call(self.__on_loop, repeat=True, timeout=0.05)
        self.event_loop.call(self.__check_verify, repeat=True, timeout=1)
        self.__max_end_time = time.time() + timeout
        if self.__min_end_time is None:
            self.__min_end_time = time.time()
        self.event_loop.execute()

    def change_ts_client_state(self, **state):
        assert self.ts_client_query_server, "TS client must be running to change its state"
        if "running" in state:
            if not state["running"]:
                self.ts_client_query_server.stop()
                self.ts_client_query_server = None
        if "connected_to_server" in state:
            self.ts_client_query_server.set_connected_to_server(
                state["connected_to_server"])
        if "users" in state:
            for name, data in state["users"].iteritems():
                self.ts_client_query_server.set_user(name, **data)

    def change_game_state(self, **state):
        import BigWorld, Avatar, Account
        assert self.mod_tessumod, "Mod must be loaded first before changing game state"

        if state["mode"] == "battle":
            BigWorld.player(Avatar.Avatar())
            if "players" in state:
                for player in state["players"]:
                    vehicle_id = random.randint(0, 1000000)
                    dbid = random.randint(0, 1000000)
                    BigWorld.player().arena.vehicles[vehicle_id] = {
                        "accountDBID": dbid,
                        "name": player["name"],
                        "isAlive": True
                    }
                    if vehicle_id not in BigWorld.entities:
                        BigWorld.entities[vehicle_id] = BigWorld.Entity()
                    if "position" in player:
                        BigWorld.player(
                        ).arena.positions[vehicle_id] = player["position"]
                        BigWorld.entities[
                            vehicle_id].position = BigWorld.Vector(
                                *player["position"])
            if "camera" in state:
                if "position" in state["camera"]:
                    BigWorld.camera().position = BigWorld.Vector(
                        *state["camera"]["position"])
                if "direction" in state["camera"]:
                    BigWorld.camera().direction = BigWorld.Vector(
                        *state["camera"]["direction"])
        elif state["mode"] == "lobby":
            BigWorld.player(Account.PlayerAccount())
            if "players" in state:
                for id, player in enumerate(state["players"]):
                    BigWorld.player().prebattle.rosters[0][id] = {
                        "name": player["name"],
                        "dbID": random.randint(0, 1000000)
                    }

    def get_player_id(self, name):
        import BigWorld
        if hasattr(BigWorld.player(), "arena"):
            for vehicle in BigWorld.player().arena.vehicles.itervalues():
                if vehicle["name"] == name:
                    return vehicle["accountDBID"]

    def get_vehicle_id(self, name):
        import BigWorld
        if hasattr(BigWorld.player(), "arena"):
            for vehicle_id, vehicle in BigWorld.player(
            ).arena.vehicles.iteritems():
                if vehicle["name"] == name:
                    return vehicle_id

    def change_mod_settings(self, **groups):
        for group_name, variables in groups.iteritems():
            for var_name, var_value in variables.iteritems():
                mod_settings.set_setting(group_name, var_name, var_value)

    def change_mod_user_cache(self, **groups):
        for group_name, variables in groups.iteritems():
            for var_name, var_value in variables.iteritems():
                mod_settings.set_cache_entry(group_name, var_name, var_value)

    def change_mod_state_variables(self, **variables):
        states_dirpath = os.path.join(INI_DIRPATH, "states")
        if not os.path.exists(states_dirpath):
            os.makedirs(states_dirpath)
        for key, value in variables.iteritems():
            with open(os.path.join(states_dirpath, key), "w") as file:
                file.write(json.dumps(value))

    def get_mod_state_variable(self, key):
        states_dirpath = os.path.join(INI_DIRPATH, "states")
        key_path = os.path.join(states_dirpath, key)
        if os.path.exists(key_path):
            with open(key_path, "r") as file:
                return json.loads(file.read())

    def call_later(self, callback, timeout=0):
        self.event_loop.call(callback, timeout=timeout)

    def __on_loop(self):
        import BigWorld
        BigWorld.tick()
        if self.ts_client_query_server:
            self.ts_client_query_server.check()
        self.assertLess(time.time(), self.__max_end_time,
                        "Execution took too long")

    def __check_verify(self):
        try:
            if time.time() >= self.__min_end_time and all(
                    verifier() for verifier in self.__verifiers):
                self.event_loop.exit()
        except Exception as error:
            print "{0} in __check_verify: {1}".format(error.__class__.__name__,
                                                      error)

    def assert_finally_equal(self, a, b):
        actual_getter = a if callable(a) else b
        expected = b if callable(a) else a
        self.__verifiers.append(lambda: actual_getter() == expected)

    def assert_finally_true(self, x):
        self.__verifiers.append(x)

    def assert_finally_false(self, x):
        self.__verifiers.append(lambda: not x())

    def wait_at_least(self, secs):
        self.__min_end_time = time.time() + secs