Функция 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 ответ
Этот ответ был предоставлен @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)