如何在两名球员之间交替?

时间:2014-02-19 14:55:39

标签: python python-3.x python-3.3

我想知道是否有人对如何在两个玩家之间进行替换直到满足特定条件有任何想法?我记得有些陈述,但我不确定我是否真的可以将它付诸实践。

任何想法都将不胜感激!

2 个答案:

答案 0 :(得分:3)

from itertools import cycle

for player in cycle(["player1", "player2"]):
    do_turn(player)
    if game_over():
        break

这很好,因为它可以扩展到任何数量的玩家。

答案 1 :(得分:1)

在最广泛的术语中,作为一种猜谜游戏(第一个正确答案获胜)并假设Player类具有name属性和answer(question)方法来获取用户输入:

active, passive = Player("One"), Player("Two") # create two Players

while True:
    if active.answer(question) == correct_answer: # active player guesses
        break # correct answer, leave the loop
    active, passive = passive, active # switch Players

print("{0.name} was correct.".format(active)) # announce winner