加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 23:54:07 所属栏目:Python 来源:网络整理
导读:我正在用Python实现一个纸牌游戏,为了我的班级来处理玩家,PlayerHandler,我最近实现了__next__来简单地调用next_player.因为游戏玩法可以被认为是无限循环(玩家将继续玩,直到他们退出或赢/输),它停止迭代是没有意义的.但是,如果for循环导致无限循环,那么它可

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读