python - 无限循环是不好的做法吗?

标签 python loops iterator

我正在用 Python 实现一个纸牌游戏,为了让我的类处理玩家 PlayerHandler,我最近实现了 __next__ 来简单地调用 next_player。因为游戏玩法可以被认为是一个无限循环(玩家将继续玩直到他们退出或赢/输),所以停止迭代没有意义。但是,如果 for 循环导致无限循环,这似乎令人困惑,那么我应该在某处引发 StopIteration 吗?

class PlayerHandler():
    """Holds and handles players and order"""
    def __init__(self, players=None, order=1):
        if players is None:
            self.players = []
        else:
            self.players = list(players)
        self.current_player = None
        self.next_player()
        self.order = order

    def get_player(self, interval):
        assert type(interval) == int, "Key must be an integer!"
        if not interval and self.players:
            return self.current_player
        elif self.players:
            step = interval * self.order
            index = self.players.index(self.current_player) + step
            while index >= len(self.players):
                index -= len(self.players)
            while index <= -(len(self.players)):
                index += len(self.players)
            return self.players[index]
        else:
            raise KeyError("No players in the list!")

    def next_player(self):
        """Sets the current player to the next player to play"""
        if not self.current_player:
            if self.players:
                self.current_player = self.players[0]
            else:
                self.current_player = None
        else:
            self.current_player = self.get_player(1)

    def __iter__(self):
        return self

    def __next__(self):
        self.next_player()
        return self.current_player

最佳答案

重要的是你的代码是可读的。如果您担心,请添加评论 - 这就是他们的目的!

# Endless loop
for p in players:
    # Do game things...

话虽如此,也许您应该在没有更多玩家时停止迭代。

关于python - 无限循环是不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23122552/

相关文章:

python - Flask - 如何结合 Flask-WTF 和 Flask-SQLAlchemy 来编辑数据库模型?

python - 使用 python strftime() 识别文本文件中月份和日期没有零填充的日期值

python - 替换 Pandas 数据框中的行

r - 将蒙特卡罗 p 值排列成不同样本大小和方差估计量的矩阵

PHP 按时间对数组进行排序并找到与 X 数字最接近的匹配项

C 语言 - WHILE 循环的工作量超出了预期

Python 笛卡尔幂发生器在幂列表上

python修改可变迭代器

python - 为什么我会收到一个显示 "takes no arguments (1 given)"的 TypeError?

java - for-each 循环如何知道从哪里开始?