首页 > 解决方案 > 在 Python 中启用整数溢出

问题描述

我想创建一个 2D 环境,其中顶部和底部以及左右连接(类似于 Torus 或 Doughnut)。但是,我不想每帧检查对象的 x/y 坐标,而是使用整数溢出来模拟它。
虽然可以进行正常迭代(如下面的示例代码所示),但在某些变量上简单地启用溢出可能会更有效(尽管很危险),尤其是在每帧/迭代中处理数百或数千个对象时。

我可以找到一些示例,它们也可以像这样在 Python 中模拟整数溢出。但是,我正在寻找可以通过在某些变量中启用溢出并跳过一般检查来溢出的东西。

# With normal checking of every instance
import random

width = 100
height = 100

class item():
    global width, height

    def __init__(self):
        self.x = random.randint(0, width)
        self.y = random.randint(0, height)

items = [item for _ in range(10)] # create 10 instances

while True:
    for obj in items:
        obj.x += 10
        obj.y += 20
        while obj.x > width:
            obj.x -= width
        while obj.y > height:
            obj.y -= height
        while obj.x < width:
            obj.x += width
        while obj.y < height:
            obj.y += height

我只想为某些特定的类/对象模拟整数溢出。有没有办法让一些变量自动溢出并循环回它们的最小值/最大值?

标签: pythoninteger-overflow

解决方案


您可以使用属性来实现具有自定义行为的 getter/setter。例如像这样:

import random

WIDTH = 100
HEIGHT = 100


class item():

    def __init__(self):
        self._x = random.randint(0, WIDTH - 1)
        self._y = random.randint(0, HEIGHT - 1)

    def __str__(self):
        return '(%r, %r)' % (self._x, self._y)

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, new_value):
        self._x = new_value % WIDTH

    @property
    def y(self):
        return self._y

    @y.setter
    def y(self, new_value):
        self._y = new_value % HEIGHT


items = [item() for _ in range(10)]

while True:
    for pos in items:
        pos.x += 10
        pos.y += 20
        print(pos)  # to show the results

推荐阅读