Hangman Game using Python and
MySQL
Introduction
This project is a command-line implementation of the classic Hangman game using Python
and MySQL. it uses database connectivity to fetch words and store player results.
Features
- Random word selected from MySQL database
- One starting letter is revealed to the player
- Player can ask for one additional hint during the game
- Game results (Win/Lose, Wrong Attempts) are saved in MySQL
- Player can replay the game without restarting the script
Technologies Used
- Python 3.x
- MySQL
- mysql-connector-python
MySQL Setup
Execute the following commands in your MySQL shell to set up the database and tables:
CREATE DATABASE IF NOT EXISTS hangman_game;
USE hangman_game;
CREATE TABLE words (
id INT AUTO_INCREMENT PRIMARY KEY,
word VARCHAR(50) NOT NULL
);
INSERT INTO words (word) VALUES
('python'), ('mysql'), ('computer'), ('network'), ('hangman');
CREATE TABLE results (
id INT AUTO_INCREMENT PRIMARY KEY,
player_name VARCHAR(50),
word VARCHAR(50),
result VARCHAR(10),
wrong_attempts INT
);
Python Code Overview
The main Python script connects to the database, retrieves a word, and initiates the
Hangman game. One letter is pre-revealed to help the player. Players can also request a
single additional hint. Results are saved to the database and the last 5 results are displayed
after each game. The user is prompted to play again or exit after each round.
Key Functions
- connect_db(): Connects to the MySQL database
- get_random_word(): Fetches a random word from the 'words' table
- give_hint(): Reveals one unguessed letter as a hint
- play_game(): Runs one complete session of Hangman
- A loop allows multiple rounds with replay functionality
Sample Output
Enter your name: Vedansh
🎁 Hint! The letter 'o' is revealed.
Word: _ o _ _ _ _
Guessed letters: o
Guess a letter: p
Correct guess!
Word: p o _ _ _ _
Guess a letter: hint
💡 Hint used! Letter 'y' revealed.
Word: p o _ _ _ _
Guess a letter: t
Correct guess!
...
🎉 You WON! The word was: python
📊 Game Results So Far:
Vedansh | Word: python | Result: Win | Wrong Attempts: 1
Conclusion
This Hangman game project demonstrates the integration of Python and MySQL in a fun and
educational way. It covers important syllabus concepts like loops, conditionals, lists, and
database connectivity without using file-based storage.
Full Python Code
Below is the complete Python script for the Hangman game:
import mysql.connector
import random
def connect_db():
return mysql.connector.connect(
host="localhost",
user="root",
password="your_mysql_password", # Change this
database="hangman_game"
)
def get_random_word(cursor):
cursor.execute("SELECT word FROM words")
words = cursor.fetchall()
return random.choice(words)[0] if words else None
def give_hint(secret_word, display_word, guessed_letters):
available_letters = [ch for ch in secret_word if ch not in guessed_letters]
if not available_letters:
print("No hints available.")
return None
return random.choice(available_letters)
def play_game():
conn = connect_db()
cursor = conn.cursor()
secret_word = get_random_word(cursor)
if not secret_word:
print("No words found in database.")
return
player_name = input("\nEnter your name: ")
max_attempts = 6
wrong_attempts = 0
hint_used = False
pre_revealed = random.choice(secret_word)
guessed_letters = [pre_revealed]
display_word = [ch if ch == pre_revealed else '_' for ch in secret_word]
print(f"\n🎁 Hint! The letter '{pre_revealed}' is revealed.\n")
while wrong_attempts < max_attempts and "_" in display_word:
print("Word:", " ".join(display_word))
print("Guessed letters:", ", ".join(guessed_letters))
guess = input("Guess a letter (or type 'hint' once): ").lower()
if guess == "hint":
if not hint_used:
hint_letter = give_hint(secret_word, display_word,
guessed_letters)
if hint_letter:
guessed_letters.append(hint_letter)
for i in range(len(secret_word)):
if secret_word[i] == hint_letter:
display_word[i] = hint_letter
print(f"💡 Hint used! Letter '{hint_letter}' revealed.")
hint_used = True
continue
else:
print("You have already used your hint.")
continue
if len(guess) != 1 or not guess.isalpha():
print("Please enter a valid single letter.")
continue
if guess in guessed_letters:
print("You already guessed that letter.")
continue
guessed_letters.append(guess)
if guess in secret_word:
for i in range(len(secret_word)):
if secret_word[i] == guess:
display_word[i] = guess
print("✅ Correct!")
else:
wrong_attempts += 1
print(f"❌ Wrong! Attempts left: {max_attempts - wrong_attempts}")
# End result
if "_" not in display_word:
print(f"\n🎉 You WON! The word was: {secret_word}")
result = "Win"
else:
print(f"\n😢 You LOST! The word was: {secret_word}")
result = "Lose"
# Save result
cursor.execute(
"INSERT INTO results (player_name, word, result, wrong_attempts) VALUES
(%s, %s, %s, %s)",
(player_name, secret_word, result, wrong_attempts)
)
conn.commit()
# Show last 5 scores
print("\n📊 Game Results So Far:")
cursor.execute("SELECT player_name, word, result, wrong_attempts FROM
results ORDER BY id DESC LIMIT 5")
for row in cursor.fetchall():
print(f"{row[0]} | Word: {row[1]} | Result: {row[2]} | Wrong Attempts:
{row[3]}")
cursor.close()
conn.close()
# 🔁 Game loop for replay
while True:
play_game()
again = input("\nDo you want to play again? (yes/no): ").lower()
if again != "yes":
print("Thank you for playing!")
break