我正在用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
最佳答案
原文链接:https://www.f2er.com/python/439761.html