在python中保持变量在一个范围内

2024-05-18 23:40:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个乒乓球的代码,但是我在试图控制球拍位置的范围时遇到了一个问题,问题是:在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]  

当桨叶位置(桨叶1_pos[1]和桨叶2_pos[1])的值超出范围时,我无法再使用键盘(通过变量(slade1_vel[1]和padle2_val[2])更新其位置,因此,我在想,python中可能存在一些东西,允许我更新padle_pos,当我到达范围的一个侧面时,它会让我保持在那一边,直到我改变更新的方向。 希望问题是清楚的。在

谢谢


Tags: 方法代码inposrangeheightpad乒乓球
2条回答

为了完整起见,下面是另一个答案,它展示了如何使用元类以编程方式将整数所拥有的所有算术方法添加到自定义类中。注意,不清楚在任何情况下返回与操作数边界相同的BoundedInt是否有意义。该代码还与python2&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))

输出:

^{pr2}$

您可以定义自己的“有界”数值类型。例如,如果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

输出:

^{pr2}$

相关问题 更多 >

    热门问题