0% found this document useful (0 votes)
44 views43 pages

Project - Hangman Game

Uploaded by

Aamy Maria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views43 pages

Project - Hangman Game

Uploaded by

Aamy Maria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

(AFFILIATED TO THE CENTRAL BOARD OF SECONDARY EDUCATION, NEW DELHI)

Thiruvaniyoor P.O., via Chottanikkara, Kochi – 682308.

PROJECT BOOK

NAME :

GRADE :

REG NO :
(AFFILIATED TO THE CENTRAL BOARD OF SECONDARY EDUCATION, NEW DELHI)

(Affiliation No: 930816)

Thiruvaniyoor P.O., via Chottanikkara, Kochi – 682308.

COMPUTER SCIENCE PROJECT

CERTIFICATE

Certified to be the bonafide record of the Project Work done by


________________________________________________________________
of Grade _______________, Global Public School, Thiruvaniyoor P.O.,

Via Chottanikkara, KOCHI – 682308 during the academic year 2024-‘25

TEACHER –IN-CHARGE SCHOOL SEAL PRINCIPAL

EXTERNAL EXAMINER

1
ACKNOWLEDGEMENT

It gives me great pleasure to acknowledge the


guidance, motivation and support extended by my teachers and
friends in the completion of my project work.

I am extremely grateful to Mrs Rose Mary Georgie for her


guidance and constant encouragement which helped me to
complete the project work successfully.

My sincere thanks to my classmates who encouraged


and supported me throughout the project with their
valuable suggestions.

2
INDEX
SL NO CONTENTS PAGE NO

1 INTRODUCTION 6-7

2 METHODOLOGY 8-10

3 TABLE STRUCTURE 11-13

4 DATA FLOW DIAGRAM 14

5 USER DEFINED FUNCTION 16-19

6 PROGRAM CODE AND OUTPUT 20-37

7 MERITS AND DEMERITS 38

8 CONCLUSION 40

9 BIBLIOGRAPHY 42

3
4
INTRODUCTION

5
Software Requirements:

● Python: Programming language for game logic and database handling.


● MySQL Database: Stores categories and words, providing dynamic data for
gameplay.
● Libraries:
○ mysql.connector: Facilitates MySQL connection.
○ random time: Adds randomness and timing effects.
○ colorama: Provides color and style options for text in the console.
○ os: Used for clearing the screen based on the OS.

Project Idea: Hangman Game with Database


Objective: To create an interactive and educational Hangman game using Python
and MySQL, providing users with an engaging experience through database-driven
word categories.

The Hangman game code begins by establishing a connection to a MySQL


database to access words categorized by topics, enabling players to select from
different word categories. It retrieves a random word from the chosen category,
using functions designed to fetch categories and specific words from the database.

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.

A colorful background pattern, introductory animation, and loading dots improve


the visual and interactive experience. The game includes a difficulty selection
feature that lets players adjust the number of allowed attempts (easy, medium, or
hard), providing tailored levels of challenge. At the start of each game, the console
clears for smooth screen transitions, and if the player decides to replay, the screen
resets, and the game restarts.

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.

Finally, this Hangman game demonstrates a methodical approach to game design


using Python, MySQL, and console aesthetics. By merging database integration
with Python-driven visuals, the game offers a modern, interactive twist on the
classic Hangman game while maintaining a user-friendly and engaging interface.

9
TABLE
STRUCTURE

10
The table structure for the Hangman game in MySQL is as follows:

Database: `hangman_game`

1. Table: `categories`

- Stores different word categories that players can choose from.

COLUMN DATA TYPE DESCRIPTION


‘id’ INT
Primary key, unique
identifier for each
category
(auto-increment)

‘name’ VARCHAR(50)
Name of the category,
e.g., 'Animals', 'Fruits',
'Countries'

11
2. Table: `words`

- Stores individual words associated with categories

COLUMN DATA TYPE DESCRIPTION


‘id’ INT
Primary key, unique
identifier for each word
(auto-increment)

‘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

A user-defined function is a function provided by the user of a program or


environment, in a context where the usual assumption is that functions are built
into the program or environment. A user defined function is a programmed routine
that has its parameters set by the user of the system. User defined functions often
are seen as programming shortcuts as they define functions that perform specific
tasks within a larger system.

In the Hangman game code, the following are the user-defined functions:

● Database Interaction Functions:


1. create_connection(): Establishes a connection to a MySQL database using
provided credentials. It handles database connection errors and returns a
connection object on success.
2. get_categories(): Fetches a list of unique categories from the database to
provide players with options for word selection. It returns an empty list if no
categories are found or an error occurs.
3. get_word(category_id): Retrieves a random word from the specified
category in the database. It ensures that the selected word is appropriate for
the game and returns the word if successful, or None otherwise.
● Game Display Functions:
1. display_guessed_letters(guessed_letters): Visually displays the letters that
the player has already guessed, providing a clear overview of progress and
incorrect guesses.
2. provide_hint(word): Generates a hint by randomly selecting a letter from the
word and presenting it to the player, aiding them in solving the puzzle.

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.

-Initializing the game state (guessed letters, attempts remaining).

-Continuously prompting the user for a letter guess.

-Validating the guess and updating the game state.

-Displaying the current game state (hangman figure, guessed letters, and
partially revealed word).

-Checking for win or lose conditions.


17
-Providing hints and handling game over scenarios.

-Asks the user if they want to play again.

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

Python is a widely used general-purpose, high level programming language.


It was initially designed by Guido van Rossum in 1991 and developed by
Python Software Foundation. It was mainly developed for emphasis on code
readability, and its syntax allows programmers to express concepts in fewer
lines of code. Python is a programming language that lets you work quickly
and
integrate systems more efficiently

It is used for :

● web development (server-side),


● software development,
● mathematics,
● system scripting.

What can Python do?

● Python can be used on a server to create web applications. ●


Python can be used alongside software to create workflows.

● Python can connect to database systems. It can also read and


modify files.
● Python can be used to handle big data and perform complex
mathematics.
● Python can be used for rapid prototyping, or for production ready
software development.

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 Syntax compared to other programming languages

Python was designed for readability, and has some similarities to the
English language with influence from mathematics.

Python uses new lines to complete a command, as opposed to other


programming languages which often use semicolons or Parentheses.

Python relies on indentation, using whitespace, to define scope; such


as the scope of loops, functions and classes. Other programming
languages often use curly-brackets for this purpose.

21
INTRODUCTION TO MYSQL

MySQL is a relational database management system (RDBMS). MySQL is fast,


reliable, flexible and easy to use. MySQL was developed by Michael Widenius and
David Axmark in 1994. MySQL is presently developed, distributed, and supported
by Oracle Corporation.

● MySQL is a database system used for developing web-based software


applications, and used for both small and large applications.
● MySQL is a relational database management system (RDBMS).
● MySQL is fast, reliable, flexible and easy to use.
● MySQL supports standard SQL (Structured Query Language).
● MySQL is free to download and use.

Main Features of MySQL

● MySQL server design is multi-layered with independent modules.


● MySQL provides transactional and non-transactional storage engines.
● MySQL supports in-memory heap tables.
● MySQL Handles large databases.
● MySQL Server works in client/server or embedded systems.
● MySQL Works on many different platforms.

22
VISUAL STUDIO CODE

Visual Studio Code (VS Code) to be an excellent choice for developing my


Hangman game code due to its powerful features and user-friendly interface. As a
lightweight yet robust code editor, VS Code supports multiple programming
languages and offers extensive customization options through its rich extensions
marketplace. This flexibility allows me to tailor the development environment to
my specific needs, whether I'm working with Python, JavaScript, or any other
language I choose for my game. The built-in IntelliSense feature provides smart
code completions and suggestions, making it easier for me to write and debug my
code efficiently.

Additionally, VS Code's integrated terminal and debugging capabilities streamline


my workflow, enabling me to run commands and troubleshoot issues without
switching between different applications. Its Git integration simplifies version
control, allowing me to track changes and collaborate effectively if I'm working
with others. With features like real-time collaboration through Live Share, I can
engage with peers for code reviews or pair programming. Overall, using Visual
Studio Code for my Hangman project not only enhances my productivity but also
provides a supportive environment for learning and growth in my programming
journey.

23
PROGRAM

CREATE DATABASE hangman_game;


USE hangman_game;

CREATE TABLE categories (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50)
);

CREATE TABLE words (


id INT AUTO_INCREMENT PRIMARY KEY,
category_id INT,
word VARCHAR(50),
FOREIGN KEY (category_id) REFERENCES categories(id)
);

-- 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

# Fetch unique categories from the database


def get_categories():
conn = create_connection()
if conn is None:
return [] # Return empty list if connection fails
cursor = conn.cursor()
cursor.execute("SELECT DISTINCT * FROM categories")
categories = cursor.fetchall()
cursor.close()
conn.close()
return categories

# Get a random word from the selected category


def get_word(category_id):
conn = create_connection()
if conn is None:
return None # Return None if connection fails
cursor = conn.cursor()
cursor.execute("SELECT word FROM words WHERE category_id = %s",
(category_id,))
words = cursor.fetchall()

25
cursor.close()
conn.close()
return random.choice(words)[0] if words else None

# Display previously guessed letters


def display_guessed_letters(guessed_letters):
if guessed_letters:
print(Fore.YELLOW + "Previously guessed letters: " + ',
'.join(guessed_letters))
else:
print(Fore.YELLOW + "No letters guessed yet.")

# Provide a hint after a certain number of incorrect guesses


def provide_hint(word):
hint = random.choice(word) # Randomly select a letter from the word
return f"Hint: One of the letters is '{hint}'"

# Hangman graphic representation


def display_hangman(attempts):
stages = [
'''
------
| |
| O
| /|\\
| / \\
|
''',
'''
------
| |
| O
| /|\\
| /
|
''',

26
'''
------
| |
| O
| /|\\
|
|
''',
'''
------
| |
| O
| /
|
|
''',
'''
------
| |
| O
|
|
|
''',
'''
------
|
|
|
|
|
''',
'''
------
|
|

27
|
|
|
'''
]

# Ensure attempts is within the bounds of stages


attempts = max(0, min(attempts, len(stages) - 1))
print(Back.BLUE + stages[attempts])

# Light aesthetic background with ASCII art


def print_background():
pattern = """
. * . * . * . * . * . * .
* . * . * . * . * . * .
. * . * . * . * . * . * .
* . * . * . * . * . * .
"""
print(Fore.MAGENTA + pattern * 4) # Repeat the pattern to simulate aesthetic
background

# Function to introduce a short delay with dots (animation)


def delay_with_dots(text, delay=0.5):
print(Fore.CYAN + text, end="", flush=True)
for _ in range(3):
print(Fore.CYAN + ".", end="", flush=True)
time.sleep(delay)
print()

# Clear the console screen


def clear_screen():
if os.name == 'nt': # For Windows
os.system('cls')
else: # For Mac and Linux
os.system('clear')

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()

# Difficulty level selection


def select_difficulty():
print(Fore.CYAN + "Select Difficulty Level:")
print(Fore.CYAN + "1. Easy (8 attempts)")
print(Fore.CYAN + "2. Medium (6 attempts)")
print(Fore.CYAN + "3. Hard (4 attempts)")
while True:
choice = input("Enter 1, 2, or 3: ")
if choice == '1':
return 8
elif choice == '2':
return 6
elif choice == '3':
return 4
else:
print(Fore.RED + "Invalid choice. Please select a valid difficulty level.")

# Play the game function with additional graphics and interactivity


def play_game():
print_background()
hangman_intro()
print(Fore.CYAN + "Welcome to Hangman!")

categories = get_categories()
if not categories:
print(Fore.RED + "No categories found or database connection failed.")
return

print(Fore.CYAN + "Choose a category:")


for category in categories:
print(f"{category[0]}: {category[1]}")

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 = []

attempts = select_difficulty() # Set attempts based on selected difficulty


score = 0

print(Fore.YELLOW + f"The word has {len(word)} letters.")

while attempts > 0 and "_" in guessed:


display_hangman(attempts)
print(Fore.YELLOW + "\nCurrent word: " + guessed)
display_guessed_letters(guessed_letters)

guess = input("Guess a letter: ").upper()

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))

if "_" not in guessed:


print(Fore.GREEN + f"You won! The word was: {word}")
score += 1
else:
print(Fore.RED + f"You lost! The word was: {word}")

print(Fore.YELLOW + f"Your current score is: {score}")

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

The Hangman game project successfully demonstrates the integration of


programming concepts, database management, and user interface design. By
utilizing a MySQL database to store categories and words, the game allows
for dynamic content selection, enhancing replayability and user engagement.
The inclusion of a user-friendly interface, colorful outputs, and a hint system
contributes to an enjoyable gaming experience.

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

1. MySQL Documentation. “MySQL 8.0 Reference Manual.” MySQL,


Oracle Corporation, https://dev.mysql.com/doc/refman/8.0/en/.
2. Python Software Foundation. “Python 3 Documentation.”
https://docs.python.org/3/.
3. Colorama Documentation. “Colorama: Simple Cross-Platform API to
Print Colored Text.” GitHub, https://github.com/tartley/colorama.
4. Corey Schafer. “Python MySQL Tutorial.” YouTube,
https://www.youtube.com/watch?v=OK_JCtrrv-c.
5. MySQL Connector/Python Developer Guide. MySQL, Oracle
Corporation, https://dev.mysql.com/doc/connector-python/en/.

42

You might also like