python - 在 Python 中启用整数溢出

标签 python integer-overflow

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

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

# 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

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

最佳答案

您可以使用properties实现具有自定义行为的 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

关于python - 在 Python 中启用整数溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56314358/

相关文章:

c++ - 是否从任何被视为未定义行为的整数中减去 INT_MIN?

python - Python3中的整数溢出

python - 使用正则表达式从给定目录中提取文件名

java - 为什么大型的计算循环无论输入如何都会产生相同的输出?

c - INT_MIN 的绝对值

python - 在幕后,子类化用户和创建一对一字段之间有什么区别?

c++ - gcc 会跳过这个有符号整数溢出检查吗?

python - 我的 Flask-Admin ModelView 的 __init__ 没有应用程序上下文——它通常什么时候获得一个?

python 3 : Unroll arguments from tuple

python - 关于python3.4.1客户端连接redis中的char b前缀