Search code examples
pythonpong

keeping a variable inside a range in python


i am trying to write a code for the game pong but i am facing a problem when trying to control the range of the paddles positions , the question is that : is there a way in python to keep a variable inside a certain range (with a maximum value and minimum value )that when the variable changes (to be increasing ) it will stuck on the maximum value of that range , and when this variable decreases it will stuck on the minimum value ? .

i had written this code :

Range = range(HALF_PAD_HEIGHT, HEIGHT - HALF_PAD_HEIGHT) 
if (paddle1_pos[1] in Range) and (paddle2_pos[1] in Range):    
      paddle1_pos[1] += paddle1_vel[1]
      paddle2_pos[1] += paddle2_vel[1]  

when the values of the paddles positions (paddle1_pos[1] and paddle2_pos[1] ) are going out off the range i am not able to update its position any more using the keyboard ( through the variables (paddle1_vel[1] and paddle2_val[2]) so , i am thinking that maybe exist something in python that allow me to update paddle_pos and when i reach one side of the range it keeps me on that side till i reverse the direction of updating . hopefully the question is clear .

thanks


Solution

  • You could define your own "bounded" numeric type. For example if paddle1_pos[1] was an integer value you could create a class like the following and use it instead

    class BoundedInt(int):
        def __new__(cls, *args, **kwargs):
            lower, upper = bounds = kwargs.pop('bounds')
    
            val = int.__new__(cls, *args, **kwargs)  # supports all int() args
            val = lower if val < lower else upper if val > upper else val
    
            val = super(BoundedInt, cls).__new__(cls, val)
            val._bounds = bounds
            return val
    
        def __add__(self, other):
            return BoundedInt(int(self)+other, bounds=self._bounds)
        __iadd__ = __add__
    
        def __sub__(self, other):
            return BoundedInt(int(self)-other, bounds=self._bounds)
        __isub__ = __sub__
    
        def __mul__(self, other):
            return BoundedInt(int(self)*other, bounds=self._bounds)
        __imul__ = __mul__
    
        # etc, etc...
    
    if __name__ == '__main__':
        v = BoundedInt(100, bounds=(0, 100))
        print type(v), v
        v += 10
        print type(v), v
        w = v + 10
        print type(w), w
        x = v - 110
        print type(x), x
    

    Output:

    <class '__main__.BoundedInt'> 100
    <class '__main__.BoundedInt'> 100
    <class '__main__.BoundedInt'> 100
    <class '__main__.BoundedInt'> 0