# Q-12 MCS 275 Tue 6 Apr 2010 : quiz12a.py # We simulate a particular card came representing the # 4 players by threads 0, 1, 2, and 3. # The are four cards, labeled A, B, C, and D, # distributed so each player has exactly one card. # The cards are shuffled before distributing to the four players. # The game is played as follows. First the player who holds card A # puts the card on the table. Then comes the player with card B, # followed by the player with C, and then finally card D is # shown by the player who holds it. The shared variable between the # players is a list with those cards currently on the table. # Players check the cards on the table and print their name when # it is their turn to put their card on the table. # 1. Write the code for the main program that sets up # and simulates the game. # 2. Write the code for the {\tt run} in a Player thread. from threading import * import time import random class Player(Thread): """ simulating one round in card game """ def __init__(self,n,t,c): """ Initializes player with name n, the table t, and card c. """ Thread.__init__(self,name=n) print 'player ' + n + ' is born' self.t = t self.c = c def run(self): """ players put cards down in turn """ s = self.getName() if self.c == 'A': self.t.append('A') print 'table :', self.t else: print 'player %s waits ...' % s done = False while True: time.sleep(1) if len(self.t) > 0: last = self.t[len(self.t)-1] if chr(ord(self.c)-1) == last: self.t.append(self.c) print 'table :', self.t done = True if done: break print 'player %s has %s' % (s,self.c) def main(): """ Deals the cards and starts the simulation. """ L = ['A','B','C','D'] random.shuffle(L) table = [] T = [] for i in range(0,4): T.append(Player(str(i),table,L[i])) print 'starting the game' for t in T: t.start() print 'game has started' if __name__ == "__main__": main()