python - 在 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
我只想为某些特定的类/对象模拟整数溢出。有没有办法让一些变量自动溢出并循环回它们的最小值/最大值?
解决方案
您可以使用属性来实现具有自定义行为的 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
推荐阅读
- gcc - 如何结合 c11 和 c99 编译器
- android-recyclerview - 如何在不锁定 UI 或显示加载图标的情况下加载 - 将项目充气到 Recycler 视图?
- apache-spark - 在集群模式下运行 Spark 应用程序的替代方法是什么?
- makefile - 有没有办法从 Makefile 调用编译成摘要的自定义 Zsh 函数?
- c++ - 我的比较功能有什么问题?
- c# - DockPanel - 拉伸控件以填充与其兄弟姐妹相关的剩余空间
- c++ - AWS 开发工具包 CPP 和 EBS 连接
- r - 有没有办法在 ggplot2 中调用 tidyverse 创建的数据框两次或更多次?
- amazon-web-services - AWS ELB 重定向到 https 公开内部主机名
- javascript - 匹配对象数组中的对象键并返回键,具有最高音量值的值