gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:15:15 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com