# L-31 MCS 275 Wed 29 Mar 2017 : taketurns.py
"""
Two players taking turns.
The scripts illustrates the sharing of an object.
"""

from threading import Thread
from time import sleep
from random import randint

class Player(Thread):
    """
    Player waits turn and makes move.
    """
    def __init__(self, t, v):
        """
        Initializes player with name t,
        and stores the shared value v.
        """
        Thread.__init__(self, name=t)
        print('player ' + t + ' born')
        self.sv = v

    def run(self):
        """
        Player checks value every 5 time units.
        If parity matches, value is decreased.
        The game is over if value == 0.
        """
        p = self.getName()
        n = int(p)
        while True:
            while True:
                sleep(5)
                v = self.sv[0]
                print(p + ' checks value %d ' % v)
                if v <= 0 or v % 2 == n:
                    break
            if v <= 0:
                break # game over
            nbr = randint(1, 10)
            s = p + ' thinks %d' % nbr
            print(s + ' time units')
            sleep(nbr)
            v = self.sv.pop(0) - 1
            print(p + ' changes value to %d ' % v)
            self.sv.append(v)

def main():
    """
    Defines two players '1' and '2'
    and starts the game.
    """
    shared = []
    one = Player('1', shared)
    two = Player('2', shared)
    print('starting the game')
    shared.append(3)
    one.start()
    two.start()
    print('The game has started ...')

if __name__ == "__main__":
    main()
