-3

I was wondering if anyone had any ideas on how to alternate between two players until a specific condition has been met? I had while statements in mind but I'm not sure if I can actually put it into practise.

Any ideas would be appreciated!

Bach
  • 6,145
  • 7
  • 36
  • 61
monkey334
  • 327
  • 2
  • 8
  • 23
  • 3
    There are.... so many ways to do this. Assuming you're making a game, you could have just a variable that records which player is the "active" player. This would work if you've got an actual game loop which is running regardless of input. If that's not the case, then just have a loop for each player, and loop between those. Really there are a million ways to do this... – SubSevn Feb 19 '14 at 15:00
  • 1
    This is very very broad. Too many answers can be given. It is not a technical questions. Try to explain what problem you're having when you're trying to implement it. – Paco Feb 19 '14 at 15:17

2 Answers2

3
from itertools import cycle

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

This is nice because it is extendable to any number of players.

Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
1

In the very broadest terms, as a sort of guessing game (first correct answer wins) and assuming a Player class with name attribute and an answer(question) method for taking user input:

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
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437