Open shazz opened 2 years ago
I forked the code and tried a few modifications, looks to be better:
@awaitable(run_game_loop)
async def run_game_loop(self, interval: float = 0.02) -> None: # pylint: disable=function-redefined
# pylint: disable=missing-docstring
if self._game_state_store.get_game_state().game_status == GameStatus.get("Paused"):
self._game_state_store.push_update(
GameStateUpdate(
self._game_state_store.get_game_state().time_order + 1, game_status=GameStatus.get("Active")
)
)
game_state = self._game_state_store.get_game_state()
dt = interval
self._game_loop_is_running = True
logger.info(f"State machine starting game loop with interval of {interval} seconds.")
while game_state.game_status == GameStatus.get("Active"):
t0 = time.perf_counter()
update_dict = self.time_step(game_state, dt)
while not self._event_queue.empty():
event = await self._event_queue.get()
event_update = await self._universal_event_handler.handle(event, game_state=game_state, dt=dt)
update_dict.update(event_update)
if time.perf_counter() - t0 > 0.95 * interval:
break
self._game_state_store.push_update(GameStateUpdate(game_state.time_order + 1, **update_dict))
game_state = self._game_state_store.get_game_state()
# real elapsed time since the loop start
real_elapsed_time = time.perf_counter() - t0
# consume the remaining time to reach the interval
delta = interval - real_elapsed_time
while delta > 0.0000001:
delta = interval - (time.perf_counter() - t0)
# adding the real spent time to the game time
dt = interval - delta
self.game_time += dt
logger.info(f"loop time: {round(dt, 4)} vs expected {round(interval, 4)} => delta {round(dt - interval, 6)}")
logger.info("Game loop stopped.")
self._game_loop_is_running = False
Hi, I hope you'll see this issue this time :D (no worries)
In my game using pygase I had the feeling it was a little too fast compared to the local version. For example I have a counter which add 10 points every second and definitively it happens faster than every second.
So I added a check in time_step to see how much time was elapsed since the last call (which should be equal to
dt
meaning 0.02) But as expected it looks to be around 0.016 in average.So
time_step
is called 50x in 0.80s in average and not 1s so 20% fasterHere is the code I added in the chase example to check:
Results
Did I misunderstand something ?
Moreover, could you add in the Backend
run()
method the interval (if not 0.02 by default) ?Thanks !