Project - Hangman Game
Project - Hangman Game
PROJECT BOOK
NAME :
GRADE :
REG NO :
(AFFILIATED TO THE CENTRAL BOARD OF SECONDARY EDUCATION, NEW DELHI)
CERTIFICATE
EXTERNAL EXAMINER
1
ACKNOWLEDGEMENT
2
INDEX
SL NO CONTENTS PAGE NO
1 INTRODUCTION 6-7
2 METHODOLOGY 8-10
8 CONCLUSION 40
9 BIBLIOGRAPHY 42
3
4
INTRODUCTION
5
Software Requirements:
During gameplay, players see their previous guesses and receive hints after a few
incorrect attempts, with the guessed letters and remaining attempts displayed. An
ASCII-based hangman graphic visually represents each incorrect attempt, moving
through stages from a blank stand to a fully hanged figure, adding urgency to the
game.
The code’s structure and interactive features make the Hangman experience
engaging and visually appealing within a console environment.
6
METHODOLOGY
7
METHODOLOGY
The Hangman game code is structured around a series of steps that provide a
complete interactive experience. At the core of the project is the setup of a MySQL
database named `hangman_game`, which holds two key tables: `categories` and
`words`. The `categories` table stores different word categories (like Animals,
Fruits, and Countries) with unique IDs, while the `words` table stores individual
words associated with these categories. This structure makes it easy to organize
words by category, allowing players to choose their preferred category, which adds
an element of personalization and structure to the game.
To manage interactions with the database, the code features a function called
`create_connection`, which establishes a connection to MySQL each time data
needs to be accessed. This function not only ensures that the program can retrieve
category and word data from the database as needed, but also provides user
feedback on the connection status. When the connection is successful, a positive
message is displayed; if it fails, an error message appears, enhancing the program’s
reliability. Data retrieval from the database is handled by the `get_categories` and
`get_word` functions, which make the available categories visible to the player and
select a word from the chosen category, thereby improving gameplay flow and user
experience.
Upon starting the game, the player is presented with an engaging introduction
through ASCII art animations that illustrate the Hangman figure, adding visual
interest. Players can then select their preferred difficulty level—Easy, Medium, or
Hard—which determines the number of incorrect guesses they are allowed. A hint
feature provides a small advantage by showing a random letter from the target
word if the player makes a certain number of incorrect guesses, making the game
more accessible and enjoyable. Additionally, players can view a list of previously
guessed letters, and each incorrect guess updates an ASCII hangman drawing,
making the game's progression more tangible.
The game also integrates aesthetic elements for improved user experience. Using
the `colorama` module, text and background colors are customized, creating a
visually appealing and intuitive interface. The inclusion of an animated loading
sequence, achieved with a short delay and dot progression, further enhances the
immersive quality of the game. Console-clearing functionality between rounds
8
gives a clean visual reset for each game instance, helping players focus on each
new word without distractions.
9
TABLE
STRUCTURE
10
The table structure for the Hangman game in MySQL is as follows:
Database: `hangman_game`
1. Table: `categories`
‘name’ VARCHAR(50)
Name of the category,
e.g., 'Animals', 'Fruits',
'Countries'
11
2. Table: `words`
‘category_id’ INT
Foreign key linking to
`categories(id)`, defining
the word’s category.
‘word’ VARCHAR(50)
The actual word used in
the game, e.g., 'elephant',
'banana', 'canada'.
12
DATA
FLOW
DIAGRAM
13
It visually represents the steps involved in the game's execution, starting from establishing the
database connection, fetching categories, selecting a category, setting the difficulty level,
running the main game loop, and ending conditions, to prompting the player to play again.
14
USER DEFINED
FUNCTIONS
15
USER DEFINED FUNCTIONS
In the Hangman game code, the following are the user-defined functions:
16
3. display_hangman(attempts): Renders the current state of the hangman figure
based on the number of incorrect attempts, providing visual feedback to the
player.
4. print_background(): Creates an ASCII art background to enhance the visual
appeal of the game and provide a more immersive gaming experience.
5. delay_with_dots(text, delay): Introduces a short delay with a series of dots
after printing a given text, creating a sense of anticipation and improving the
user interface.
6. clear_screen(): Clears the console screen to provide a clean and focused
gaming environment, removing any clutter from previous game states.
7. hangman_intro(): Displays an animated introduction to the game, gradually
revealing the hangman figure, building excitement and setting the stage for
the game.
● Game Logic Functions:
1. select_difficulty(): Prompts the user to choose a difficulty level (easy,
medium, or hard) and adjusts the number of allowed incorrect attempts
accordingly, tailoring the game to the player's preference.
2. play_game(): Orchestrates the core gameplay loop, including:
-Selecting a random word from the chosen category.
-Displaying the current game state (hangman figure, guessed letters, and
partially revealed word).
3. main(): Serves as the entry point of the program, initializing the game and
calling the play_game() function to start the game.
18
PROGRAM CODE
AND OUTPUT
19
INTRODUCTION TO PYTHON
It is used for :
20
Why Python?
● Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
● Python has a simple syntax similar to the English language.
● Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
● Python runs on an interpreter system, meaning that code can be executed as
soon as it is written. This means that prototyping can be very quick.
● Python can be treated in a procedural way, an object-oriented way or a
functional way.
Python was designed for readability, and has some similarities to the
English language with influence from mathematics.
21
INTRODUCTION TO MYSQL
22
VISUAL STUDIO CODE
23
PROGRAM
-- Add categories
INSERT INTO categories (name) VALUES ('Animals'), ('Fruits'), ('Countries');
-- Add words
INSERT INTO words (category_id, word) VALUES
(1, 'elephant'), (1, 'giraffe'), (1, 'kangaroo'),
(2, 'banana'), (2, 'apple'), (2, 'mango'),
(3, 'canada'), (3, 'brazil'), (3, 'india');
import mysql.connector
import random
import time
from colorama import Fore, Back, Style, init
import os
# Initialize colorama
init(autoreset=True)
24
# Database connection
def create_connection():
try:
conn = mysql.connector.connect(
host="localhost",
user="your_username", # Replace with your MySQL username
password="your_password", # Replace with your MySQL password
database="hangman_game"
)
print(Fore.GREEN + "Database connection successful!")
return conn
except mysql.connector.Error as err:
print(Fore.RED + f"Error: {err}")
return None
25
cursor.close()
conn.close()
return random.choice(words)[0] if words else None
26
'''
------
| |
| O
| /|\\
|
|
''',
'''
------
| |
| O
| /
|
|
''',
'''
------
| |
| O
|
|
|
''',
'''
------
|
|
|
|
|
''',
'''
------
|
|
27
|
|
|
'''
]
28
# Display a simple animated hangman introduction
def hangman_intro():
stages = [
'''
------
| |
|
|
|
|
''',
'''
------
| |
| O
|
|
|
''',
'''
------
| |
| O
| /
|
|
''',
'''
------
| |
| O
| /|\\
|
|
'''
]
29
for stage in stages:
print(stage)
time.sleep(0.5)
clear_screen()
categories = get_categories()
if not categories:
print(Fore.RED + "No categories found or database connection failed.")
return
30
category_id = int(input("Enter category ID: "))
word = get_word(category_id)
if not word:
print(Fore.RED + "No words found in this category.")
return
word = word.upper()
guessed = "_" * len(word)
guessed_letters = []
if guess in guessed_letters:
print(Fore.RED + "You already guessed that letter. Try again.")
continue
guessed_letters.append(guess)
if guess in word:
guessed = ''.join([c if c == guess else g for c, g in zip(word, guessed)])
print(Fore.GREEN + "Correct guess!")
else:
attempts -= 1
print(Fore.RED + f"Wrong guess! Attempts left: {attempts}")
31
if attempts == 3:
print(Fore.CYAN + provide_hint(word))
while True:
play_again = input(Fore.CYAN + "Do you want to play again? (yes/no):
").lower()
if play_again == 'yes':
clear_screen() # Clear the screen between games
play_game() # Restart the game
break # Exit the loop
elif play_again == 'no':
print(Fore.CYAN + "Thanks for playing!")
break # Exit the loop
else:
print(Fore.RED + "Invalid input. Please enter 'yes' or 'no'.")
if __name__ == "__main__":
delay_with_dots("Loading Hangman", 0.3)
play_game()
32
OUTPUT
Database connection successful!
Loading Hangman...
* . * . * . * . * . * .
* . * . * . * . * . * .
. * . * . * . * . * . * .
* . * . * . * . * . * .
33
34
35
36
MERITS AND
DEMERITS
37
MERITS AND DEMERITS
All programs regardless of their efficiencies have their demerits. A successful
program is one which has more merits than demerits.Here are five merits and five
demerits of the Hangman game code:
Merits:
1. The use of a MySQL database to store categories and words allows for easy
management and updating of game content without modifying the code.
2. The game fetches words randomly based on the selected category, providing
variety and enhancing replayability.
3. The incorporation of colors and ASCII art through the Colorama library
makes the console output visually appealing and engaging for players.
4. Players can choose from different difficulty levels, adjusting the number of
incorrect attempts allowed, which caters to varying skill levels.
5. The provision of hints after a certain number of incorrect guesses helps
players continue engaging with the game, making it more enjoyable.
Demerits:
1. The code lacks comprehensive error handling, particularly for invalid inputs,
which can lead to crashes or unexpected behavior.
2. The reliance on a MySQL database means that users must set it up properly
for the game to function, limiting accessibility.
3. The ASCII art and console interface may not provide the same level of
engagement as a graphical user interface (GUI), making it less appealing to
some users.
4. The scoring system only tracks the score for the current game without
cumulative statistics, which could enhance player engagement over time.
5. Some logic is repeated in various parts of the code, indicating potential areas
for optimization and making the code less maintainable.
38
CONCLUSION
39
Conclusion
While the project showcases a solid foundation, it also highlights areas for
improvement, such as enhancing error handling, implementing a more
sophisticated scoring system, and considering a graphical user interface for a
richer experience. Overall, this project not only reinforces fundamental
programming skills but also offers valuable insights into how to create
interactive applications that can be easily expanded and maintained in the
future. As a result, the Hangman game serves as an excellent learning tool
and a stepping stone for further exploration into game development and
software design.
40
BIBLIOGRAPHY
41
BIBLIOGRAPHY
42