Skip to content

Commit ec2b701

Browse files
committed
Add a hangman game created using class
1 parent b32ea1a commit ec2b701

File tree

2 files changed

+132
-0
lines changed

2 files changed

+132
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
Hangman Game
2+
3+
This is a Hangman game created using object-oriented Python programming language (classes).
4+
5+
This game runs and can be interacted in a console.
6+
7+
By studying this code, you can learn how to apply classes and objects in your code, use "random" module to randomize values, and get a bit familiar of list comprehension.
8+
9+
This hangman game has 3 categories of words: fruit, vegetable, and animal. However, you can easily add more categories by following the examples in assign_words_for_category() function.
10+
11+
You can also configure how each difficulties as you want. The current list of difficulties includes easy, normal, and hard.
12+
13+
To create a class instance, you can start by taking a look at line 100th.
14+
In this case, it is my_hangman = Hangman("fruit", "hard")
15+
instance_name = class_name(argument(s))
16+
The "my_hangman" is an instance, Hangman is a class, and "fruit" and "hard" are arguments.
17+
The next 2 lines are function callings.
18+
To start the game, we have to call these two functions namely welcome_message() to print out a welcome message, and start_the_game() to start the game.
19+
20+
Normally, when we want to call a function, we only need to type function_name(). However, in this case, the functions are in the class, so we have to "instance_name.function_name()" to call a function in a class.
21+
22+
Finally, you can learn more by looking at this code.
23+
24+
Also don't forget to "import random".
25+
26+
27+
This is my second contribution in my entire life so far. If you don't mind, I want to showcase this in my portfolio.
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
import random
2+
3+
class Hangman:
4+
def __init__(self, category, difficulty):
5+
self.category = category
6+
self.difficulty = difficulty
7+
self.word = None
8+
self.word_list = None
9+
self.hint_words = None
10+
self.hint_indices = None
11+
self.num_of_hint_words = None
12+
self.guess_display = None
13+
self.user_guess = None
14+
self.game_active = None
15+
self.attempts = None
16+
self.restart = None
17+
18+
def assign_words_for_category(self): # you can add more categories here.
19+
if self.category == "fruit":
20+
self.word_list = ["apple", "banana", "orange", "grape", "strawberry", "mango", "pineapple",
21+
"kiwi", "pear", "peach", "plum", "watermelon", "melon", "cherry", "blueberry", "raspberry"]
22+
elif self.category == "vegetable":
23+
self.word_list = ['carrot', 'potato', 'broccoli', 'cauliflower', 'cucumber', 'lettuce', 'kale',
24+
'cabbage', 'onion', 'garlic', 'tomato', 'eggplant', 'beetroot', 'radish', 'asparagus', 'beans', 'peas']
25+
elif self.category == "animal":
26+
self.word_list = ["dog", "cat", "lion", "tiger", "elephant", "giraffe", "monkey", "kangaroo", "penguin",
27+
"whale", "dolphin", "shark", "alligator", "crocodile", "snake", "spider", "bee", "ant", "bird", "fish"]
28+
29+
def randomize_words(self):
30+
self.word = random.choice(self.word_list)
31+
32+
def create_hint(self): # this creates hint letters as indices.
33+
self.hint_indices = random.sample(range(len(self.word)), self.num_of_hint_words)
34+
35+
def set_difficulty(self): # here you can configure different difficulties
36+
if self.difficulty == "easy":
37+
self.num_of_hint_words = round(len(self.word)*0.4) # amounts of hints equals to 40% of length
38+
self.attempts = 10
39+
elif self.difficulty == "normal":
40+
self.num_of_hint_words = round(len(self.word)*0.3) # amounts of hints equals to 30% of length
41+
self.attempts = 7
42+
elif self.difficulty == "hard":
43+
self.num_of_hint_words = round(len(self.word)*0.2) # amounts of hints equals to 20% of length
44+
self.attempts = 5
45+
46+
def start_the_game(self):
47+
self.assign_words_for_category()
48+
self.randomize_words()
49+
self.set_difficulty()
50+
self.create_hint()
51+
self.place_chars()
52+
self.input_guess()
53+
self.ask_if_restart()
54+
55+
def welcome_message(self):
56+
print("Welcome to Hangman!")
57+
print("Here you can try guessing letters of a randomly generated words based on hints!")
58+
print(f"Category: {self.category}")
59+
print("Good luck!")
60+
61+
def place_chars(self):
62+
self.guess_display = ["_" for char in self.word]
63+
for i in self.hint_indices:
64+
self.guess_display[i] = self.word[i]
65+
print("--------------------------------------")
66+
print(" ".join(self.guess_display))
67+
68+
def input_guess(self):
69+
self.game_active = True
70+
while self.game_active and self.attempts > 0:
71+
self.user_guess = input("Guess a letter: ")
72+
73+
if self.user_guess in self.word:
74+
self.guess_display = [self.user_guess if list(self.word)[i] == self.user_guess else char for i, char in enumerate(self.guess_display)]
75+
print("--------------------------------------")
76+
print(" ".join(self.guess_display))
77+
78+
else:
79+
print("wrong!")
80+
self.attempts -= 1
81+
print(f"{self.attempts} attempt(s) remaining")
82+
83+
if "_" not in self.guess_display:
84+
print("You won!")
85+
break
86+
87+
if self.attempts == 0:
88+
print("You ran out of attempts!")
89+
break
90+
91+
def ask_if_restart(self):
92+
self.restart = input("Do you want to play more? [Y/N]: ")
93+
if self.restart == "Y" or self.restart == "y":
94+
self.start_the_game()
95+
elif self.restart == "N" or self.restart == "n":
96+
quit()
97+
98+
# This is where you create an instance
99+
try:
100+
my_hangman = Hangman("fruit", "hard") # (Category, Difficulty) Categories: fruit, vegetable, animal. Difficulties: easy, normal, hard.
101+
my_hangman.welcome_message()
102+
my_hangman.start_the_game()
103+
104+
except:
105+
print("Please make sure the initialization arguments are strings.")

0 commit comments

Comments
 (0)