# E-2 MCS 275 Fri 16 Apr 2010 : ex2q4.py # Define a Thread class to model floating disks on a canvas. # Before sleeping one second the disks move their position at random. # After each move the disks check whether they have collided # with another disk. Disks no longer move after a collision. # Disks also stop moving after 15 moves. from threading import * from random import randint from time import sleep class Disk(Thread): """ Floating disks on canvas. """ def __init__(self,n,p,L): """ Disk n is initialized with a start position with coordinates in p and a list L of all positions of all other disks. We have the L[n] with equal the position of the n-th disk. """ Thread.__init__(self,name=n) self.position = p self.stopped = False self.others = L self.moves = 15 def collision(self): """ Returns k if the position of the disk is the same of some other disk at position k, otherwise returns -1. """ n = int(self.getName()) for i in range(0,len(self.others)): if i != n: if self.position == self.others[i]: return i return -1 def run(self): """ If not yet stopped or if no other disk has collided with it, the disk will make a random move. """ sleep(1) n = self.getName() while not self.stopped and (self.moves > 0): k = self.collision() if k != -1: self.stopped = True print 'Thread ' + n + ' collided with ' + str(k) else: a = randint(-1,+1); b = randint(-1,+1) self.position[0] = self.position[0] + a self.position[1] = self.position[1] + b s = 'Thread ' + n + ' moves to ' + str(self.position) self.others[int(n)] = self.position self.moves = self.moves - 1 k = self.collision() if k != -1: self.stopped = True s = s + ' collided with ' + str(k) print s def main(): """ Prompts user for number of disks, generates as many disks as the number entered. """ n = input('give number of threads : ') print 'creating', n, 'threads ...' L = []; T = [] for i in range(0,n): L.append([i,0]) T.append(Disk(str(i),[i,0],L)) print 'starting', n, 'threads ...' for t in T: t.start() main()