Welcome, guest | Sign In | My Account | Store | Cart

Here is my version of the Game of Hangman in Python. I worte for my blog Captain DeadBones Chronicles

Python, 80 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import random

board = [
'  +---+   \n  |   |   \n      |   \n      |   \n      |   \n      |   \n========= \n',
'  +---+   \n  |   |   \n  0   |   \n      |   \n      |   \n      |   \n========= \n',
'  +---+   \n  |   |   \n  0   |   \n  |   |   \n      |   \n      |   \n========= \n',
'  +---+   \n  |   |   \n  0   |   \n /|   |   \n      |   \n      |   \n========= \n',
'  +---+   \n  |   |   \n  0   |   \n /|\\  |   \n      |   \n      |   \n========= \n',
'  +---+   \n  |   |   \n  0   |   \n /|\\  |   \n /    |   \n      |   \n========= \n',
'  +---+   \n  |   |   \n  0   |   \n /|\\  |   \n / \\  |   \n      |   \n========= \n'
]

class Hangman:
	def __init__(self,word):
		self.word = word
		self.missed_letters = []
		self.guessed_letters = []
		
	def guess(self,letter):
		if letter in self.word and letter not in self.guessed_letters:
			self.guessed_letters.append(letter)
		elif letter not in self.word and letter not in self.missed_letters:
			self.missed_letters.append(letter)
		else:
			return False
		return True
		
	def hangman_over(self):
		return self.hangman_won() or (len(self.missed_letters) == 6)
		
	def hangman_won(self):
		if '_' not in self.hide_word():
			return True
		return False
		
	def hide_word(self):
		rtn = ''
		for letter in self.word:
			if letter not in self.guessed_letters:
				rtn += '_'
			else:
				rtn += letter
		return rtn
		
	def print_game_status(self):
		print board[len(self.missed_letters)]
		print 'Word: ' + self.hide_word()
		print 'Letters Missed: ', 
		for letter in self.missed_letters:
			print letter, 
		print 
		print 'Letters Guessed: ',
		for letter in self.guessed_letters:
			print letter,
		print 

def rand_word():
	
	bank = ['the','living','pearl','.com','captain','deadbones']
	return bank[random.randint(0,len(bank))]

def main():
	
	game = Hangman(rand_word())
	while not game.hangman_over():
		game.print_game_status()
		user_input = raw_input('\nEnter a letter: ')
		game.guess(user_input)

	game.print_game_status()	
	if game.hangman_won():
		print '\nCongratulations! You are the winner of Hangman!'
	else:
		print '\nSorry, you have lost in the game of Hangman...'
		print 'The word was ' + game.word
		
	print '\nGoodbye!\n'
		
if __name__ == "__main__":
	main()
	
	

5 comments

jay 10 years, 10 months ago  # | flag

As a beginner i find your chronicles and code a good resource. One could learn alot from you. Thank you i look forward to more of your articles and code.

regards jay.

Fan Risun 10 years, 10 months ago  # | flag

I have error in line 60,it says:list index out of range. And I check the help about random.randint(a, b) : Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

So should I use the (0,(len(bank)-1)) #means (0,5) instead (0,len(bank)) #means(0,6) because use the latter, it may appear the integer 6, but it is not allowed in bank[i]

neftas 10 years, 9 months ago  # | flag

Hey there! I read your script and ran it a few times, enjoyed it. I noticed that you can enter any amount of characters you want, so user_imput 'random amount of characters' also gets added to self.missed_letters. So I added a few lines of code to fix that.

def main():

    game = Hangman(rand_word())
    while not game.hangman_over():
    game.print_game_status()
        user_input = raw_input('\nEnter a letter: ')
        if len(user_input) >= 2:
            while True:
                print "\nEnter only ONE letter at a time!\n"
                try_again = raw_input('Try again: ')
                if len(try_again) == 1:
                    game.guess(try_again)
                    break
                else:
                    continue
        else:
            game.guess(user_input)
Captain DeadBones (author) 10 years, 9 months ago  # | flag

Thank you all for your comments. I am glad you are downloading the code and modifying it. I try to keep everything as simple as I can so you can get a chance to better understand what is going on and tweak things yourself.

Kaneki ken 8 years, 10 months ago  # | flag

i have an error on line 67. The variable raw_input isn't defined. im not that good at python so i dont really know what to put :(