# Code for use in Hangman Exercise import random try: word_file = open("dict_words.txt", 'r') except IOError: print("Can't open input file") os._exit(1) word_list = word_file.readlines() word = random.choice(word_list).strip() word_file.close() board = HangmanBoard(word, 8) print(board) #extend this code to prompt the user for a letter at a time #and play the game hangman ###Demonstration of Class Inheritance (and basic time simulation) ##import random ## ###Simulates a particle that can only move between ###x = 0 and x = 10 ##class Particle(object): ## def __init__(self, x , velocity): ## self.x = x ## self.velocity = velocity ## ## def move(self): ## self.x += self.velocity ## if self.x <0: ## self.x = -self.x ## self.velocity = -self.velocity ## if self.x>10: ## self.x = 20 - self.x ## self.velocity = -self.velocity ## ## def __str__(self): ## return "Particle at position " + str(self.x) ## ## ## ###Instantiate a Particle and make it move. ##p1 = Particle(0, 1) ##for i in range(100): ## print(p1) ## p1.move() class ParticlePlotter(object): def __init__(self, particle): self.particle = particle def update(self): print("Particle:" + " " * int(self.particle.x) + "X") ###Instantiate a Particle and make it move. ##p1 = Particle(0, 1) ##plotter = ParticlePlotter(p1) ##for i in range(100): ## plotter.update() ## p1.move() class BrownianParticle(Particle): def __init__(self): Particle.__init__(self, 5,0) def move(self): self.velocity = random.choice([-1,1]) Particle.move(self) #try changing move() so the particle moves right #with probability 0.6 ###Instantiate a BrownianParticle and make it move ##p2 = BrownianParticle() ##plotter = ParticlePlotter(p2) ##for i in range(100): ## plotter.update() ## p2.move() from tkinter import * class ParticleCanvasPlotter(Canvas, ParticlePlotter): def __init__(self, master, particle, width=600, height = 60): self.particle = particle self.width = width Canvas.__init__(self, master, width=width, height=height) self.pack() self.circ = self.create_oval(self.particle.x * self.width / 10,10, self.particle.x * self.width / 10 + 30 ,40, fill="red") def update(self): self.coords(self.circ, self.particle.x * self.width / 10, 10, self.particle.x * self.width / 10 + 30 ,40) Canvas.update(self) ###Demo ParticleCanvasPlotter ##p1 = Particle(0, 1) ##master = Tk() ##plotter = ParticleCanvasPlotter(master, p1) ## ##for i in range(100): ## print(p1) ## p1.move() ## plotter.update() ## ##plotter.mainloop() ##Exercise: Create an extension of Particle, GravityParticle. ##in every time period, subtract 0.1 from velocity before moving. ##Start the particle at position 0 with velocity 1.5 ##Exercise 2: Create two particles that are attracted to each other. ##if a particle's partner is to its right, increase its velocity ##by 0.1 in every time period. Otherwise, decrease its velocity by 0.1 ##revise particle plotter so it can plot more than one particle at ##the same time.