类的Cycle()函数

时间:2018-07-14 23:22:13

标签: python function class python-3.5 cycle

我想利用功能循环来轮换我的游戏中的玩家。我做了如下:

class Pong:
    """Summary of class here.

       Longer class information....
       Longer class information....

       """


    def __init__(self, max_score):
        self.max_score = max_score
        self.game_over = 0
        self.p1_score = 10000
        self.p2_score = 2
        self.players_list = [self.p1_score, self.p2_score]

    def play(self, ball_pos, player_pos):
        import itertools
        """" ball = 1 pixel height
            paddles = 7 pixels height

            """
        player_time = itertools.cycle(self.players_list)
        print(next(player_time))

        return ""
g = Pong(2)
g.play(50,51)
g.play(50,51)
g.play(50,51)
g.play(50,51)

但是我的输出仅到达第一个元素p1_score。有人可以帮助我了解为什么next()在这种情况下不起作用以及如何解决吗?

预先感谢

1 个答案:

答案 0 :(得分:0)

此答案由@ user3483203在评论中提供

  

您每次调用play时都会创建一个循环生成器,   想要在您的 init 函数

中做到这一点
 class Pong:
    """Summary of class here.

       Longer class information....
       Longer class information....

       """


    def __init__(self, max_score):
        self.max_score = max_score
        self.game_over = 0
        self.p1_score = 10000
        self.p2_score = 2
        self.players_list = [self.p1_score, self.p2_score]
        self.player_time = itertools.cycle(self.players_list)


    def play(self, ball_pos, player_pos):
        import itertools
        """" ball = 1 pixel height
            paddles = 7 pixels height

            """

        print(next(self.player_time))

        return ""
g = Pong(2)
g.play(50,51)
g.play(50,51)
g.play(50,51)
g.play(50,51)