ThalesGroup / kessler-game

Kessler is a simulation environment loosely modeled after our internal project PsiBee and the external project Fuzzy Asteroids. The game has ships that shoot bullets at asteroids to gain score. Ships can collide with asteroids and other ships and lose lives.
https://github.com/ThalesGroup/kessler-game
Apache License 2.0
8 stars 5 forks source link

Asteroid/ship wrapping could be simplified #37

Closed Jie-F closed 6 months ago

Jie-F commented 7 months ago

Currently the way asteroids and ships are wrapped is functionally equivalent to the following function, which is as simple and fast as I can get it:

def wrap_position(position: tuple, bounds: tuple):
    x, y = position
    x_bound, y_bound = bounds

    if x > x_bound:
        x -= x_bound
    elif x + x_bound < x_bound: # This statement can be mathematically simplified to subtract y_bound from both sides, but due to floating point funkiness we have to redundantly do this
        x += x_bound

    if y > y_bound:
        y -= y_bound
    elif y + y_bound < y_bound: # This statement can be mathematically simplified to subtract y_bound from both sides, but due to floating point funkiness we have to redundantly do this
        y += y_bound

    return x, y

It would be faster and more robust to do:

def wrap_position(position: tuple, bounds: tuple):
    x, y = position
    x_bound, y_bound = bounds
    return x%x_bound, y%y_bound

Another advantage of this, is that if we have an asteroid moving so fast that within one timestep it can move more than the width or height of the map, that asteroid will also get wrapped. The current wrapping code will allow such asteroids to escape.