保持变量在python的范围内(keeping a variable inside a range

2019-11-01 05:10发布

我试图写的游戏乒乓一个代码,但我面对试图控制桨位置的范围时出了问题,问题是:有没有在Python的方式来保持一定的范围之内的变量(用当变量的变化(将被增加),它会停留在该范围的最大值,并且当该变量减小它会粘在最小值最大值和最小值)? 。

我曾写过这样的代码:

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]  

当桨叶位置的值(paddle1_pos [1]和paddle2_pos [1])被外出断开范围我不能够更新其位置的任何更多的使用键盘(通过变量(paddle1_vel [1]和paddle2_val [2 ])所以,我认为在python,让我更新paddle_pos,当我到达的范围内的一侧,它让我在那边等我扭转更新的方向可能存在的东西。希望这个问题是清楚的。

谢谢

Answer 1:

你可以定义自己的“近忧”数字类型。 例如,如果paddle1_pos[1]是一个整数值,您可以创建一个类像下面,并用它来代替

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

输出:

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


Answer 2:

为了完整这里的另一个答案,说明如何以编程方式添加的所有整数必须使用元类的自定义类的算术方法。 注意:目前还不清楚是否有意义在各种情况下具有相同范围的操作数返回BoundedInt。 该代码还与两者的Python 2&3兼容。

class MetaBoundedInt(type):
    # int arithmetic methods that return an int
    _specials = ('abs add and div floordiv invert lshift mod mul neg or pos '
                 'pow radd rand rdiv rfloordiv rlshift rmod rmul ror rpow '
                 'rrshift rshift rsub rtruediv rxor sub truediv xor').split()
    _ops = set('__%s__' % name for name in _specials)

    def __new__(cls, name, bases, attrs):
        classobj = type.__new__(cls, name, bases, attrs)
        # create wrappers for specified arithmetic operations
        for name, meth in ((n, m) for n, m in vars(int).items() if n in cls._ops):
            setattr(classobj, name, cls._WrappedMethod(cls, meth))
        return classobj

    class _WrappedMethod(object):
        def __init__(self, cls, func):
            self.cls, self.func = cls, func

        def __get__(self, obj, cls=None):
            def wrapper(*args, **kwargs):
                # convert result of calling self.func() to cls instance
                return cls(self.func(obj, *args, **kwargs), bounds=obj._bounds)
            for attr in '__module__', '__name__', '__doc__':
                setattr(wrapper, attr, getattr(self.func, attr, None))
            return wrapper

def with_metaclass(meta, *bases):
    """ Py 2 & 3 compatible way to specifiy a metaclass. """
    return meta("NewBase", bases, {})

class BoundedInt(with_metaclass(MetaBoundedInt, int)):
    def __new__(cls, *args, **kwargs):
        lower, upper = bounds = kwargs.pop('bounds')
        val = int.__new__(cls, *args, **kwargs)  # supports all int() args
        val = super(BoundedInt, cls).__new__(cls, min(max(lower, val), upper))
        val._bounds = bounds
        return val

if __name__ == '__main__':
    # all results should be BoundInt instances with values within bounds
    v = BoundedInt('64', 16, bounds=(0, 100))  # 0x64 == 100
    print('type(v)={}, value={}, bounds={}'.format(type(v).__name__, v, v._bounds))
    v += 10
    print('type(v)={}, value={}, bounds={}'.format(type(v).__name__, v, v._bounds))
    w = v + 10
    print('type(w)={}, value={}, bounds={}'.format(type(w).__name__, w, w._bounds))
    x = v - 110
    print('type(x)={}, value={}, bounds={}'.format(type(x).__name__, x, x._bounds))

输出:

type(v)=BoundedInt, value=100, bounds=(0, 100)
type(v)=BoundedInt, value=100, bounds=(0, 100)
type(w)=BoundedInt, value=100, bounds=(0, 100)
type(x)=BoundedInt, value=0, bounds=(0, 100)


文章来源: keeping a variable inside a range in python
标签: python pong