python – 是一个无限的循环不良练​​习?

前端之家收集整理的这篇文章主要介绍了python – 是一个无限的循环不良练​​习?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在用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...

话虽如此,也许你应该在没有更多玩家的情况下进行StopIteration.

原文链接:https://www.f2er.com/python/439761.html

猜你在找的Python相关文章