【发布时间】:2019-05-26 14:24:01
【问题描述】:
我想创建一个上下和左右相连的 2D 环境(类似于 Torus 或 Doughnut)。但是,我不想每帧检查对象的 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
我只想为某些特定的类/对象模拟整数溢出。有没有办法让一些变量自动溢出并循环回到它们的最小值/最大值?
【问题讨论】:
-
Python 整数不会溢出。如果他们这样做了,它们不会在 100 或您选择的任何其他值处溢出,它们会根据计算机的位大小以 2 的幂次方溢出。例如,您只需要
obj.x = (obj.x + 10) % width。 -
如果最大值为100,当
item.x为99时item.x += 10会产生item.x --> 9或item.x --> 0? -
jasonharper 的
obj.x = (obj.x + 10) % width非常像我正在寻找的东西,其中 99 + 10 等于 9。我希望能够启用溢出,即使它仅适用于 2^x 整数.