diff --git a/README.md b/README.md index 49af92f..43e4370 100644 --- a/README.md +++ b/README.md @@ -1,313 +1,106 @@ -# Hacktoberfest 2025 — Python Repository +# 🕹️ Hangman Game -
- -![Hacktoberfest 2025](https://img.shields.io/badge/Hacktoberfest-2025-blueviolet.svg) -![Python](https://img.shields.io/badge/Python-3.8%2B-blue.svg) -![Contributions Welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg) -![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg) -![PRs](https://img.shields.io/badge/PRs-welcome-brightgreen.svg) - -**A comprehensive Python repository for Hacktoberfest 2025 — from beginner scripts to advanced AI/ML projects!** - -
+> A classic word-guessing challenge that tests your logic, vocabulary, and patience — one letter at a time. --- -## 🌟 About This Repository +## 🎯 Overview -Welcome to the ultimate Python contribution hub for Hacktoberfest 2025! Whether you're writing your first "Hello World" or building cutting-edge AI agents, this repository has a place for you. We accept contributions across the entire Python ecosystem — from web frameworks to deep learning models, from data science to game development. - -### 🎯 Our Mission -- **Empower beginners** to make their first open-source contributions -- **Challenge experienced developers** with advanced projects -- **Foster learning** through code reviews and collaboration -- **Build a comprehensive resource** for Python developers worldwide +**Hangman** is a timeless word-guessing game where players attempt to uncover a hidden word by guessing letters within a limited number of attempts. +This digital version recreates the nostalgic charm of the original pen-and-paper game with modern, modular logic and a user-friendly interface. --- -## 🚀 Quick Start - -### Prerequisites -- Python 3.8 or higher -- Git installed on your machine -- A GitHub account -- Enthusiasm to learn and share! 🎉 - -### Setup Instructions - -1. **Fork this repository** - Click the "Fork" button at the top right of this page. - -2. **Clone your fork** - ```bash - git clone https://github.com/YOUR-USERNAME/HACKTOBERFEST_2025_python.git - cd HACKTOBERFEST_2025_python - ``` - -3. **Create a virtual environment** (recommended) - ```bash - python -m venv venv - source venv/bin/activate # On Windows: venv\Scripts\activate - ``` +## 🎮 Gameplay Mechanics -4. **Create a new branch** - ```bash - git checkout -b feat/your-feature-name - ``` +1. **Word Selection** + - The computer randomly selects a word from a predefined list. -5. **Make your changes and commit** - ```bash - git add . - git commit -m "Add: brief description of your contribution" - ``` +2. **Hidden Word Display** + - Each letter of the word is masked as an underscore `_`. -6. **Push to your fork** - ```bash - git push origin feat/your-feature-name - ``` +3. **Player Guessing** + - Players input one letter per turn. + - Correct guesses reveal all instances of that letter. + - Incorrect guesses reduce the remaining lives or draw parts of the hangman figure. -7. **Create a Pull Request** - Go to the original repository and click "New Pull Request" +4. **Game Outcomes** + - 🏆 **Win:** Player uncovers all letters before attempts run out. + - 💀 **Lose:** Player runs out of lives before guessing the word. --- -## 📂 Repository Structure +## ⚙️ Features -``` -├── Name_of_Project_1/ -├── Name_of_Project_2/ -├── Name_of_Project_3/ -├── .gitignore -├── CONTRIBUTING.md # Detailed contribution guide -├── LICENSE # LICENSE -├── CODE_OF_CONDUCT.md # Community guidelines -└── README.md # You are here! -``` +✅ Random word generation +✅ Input validation (only alphabets accepted) +✅ Real-time word reveal +✅ Attempt counter with progress tracking +✅ Visual or text-based hangman display +✅ Replay option for multiple rounds --- -## 🎨 Contribution Areas - -We welcome contributions in **ANY** Python-related area! Here are some ideas to get you started: - -### 🐍 Core Python -- **Beginner Scripts**: Calculators, converters, simple games -- **Data Structures**: Implementations of stacks, queues, trees, graphs -- **Algorithms**: Sorting, searching, dynamic programming -- **Design Patterns**: Singleton, Factory, Observer, etc. - -### 🌐 Web Development -- **Flask**: REST APIs, full-stack applications, authentication systems -- **Django**: CRUD applications, admin panels, e-commerce sites -- **FastAPI**: High-performance APIs, async endpoints, WebSocket servers -- **API Integration**: Third-party API wrappers and clients - -### 🤖 AI & Machine Learning -- **Machine Learning**: Regression, classification, clustering models -- **Deep Learning**: Neural networks with TensorFlow, PyTorch, Keras -- **Computer Vision**: Image classification, object detection, segmentation -- **NLP**: Text processing with spaCy, sentiment analysis, chatbots -- **Agentic AI**: Autonomous agents, LangChain implementations, RAG systems -- **Model Deployment**: Flask/FastAPI model serving, Docker containers - -### 📊 Data Science -- **Pandas**: Data cleaning, transformation, analysis scripts -- **Visualization**: Matplotlib, Seaborn, Plotly dashboards -- **Jupyter Notebooks**: Exploratory data analysis, tutorials -- **Data Pipelines**: ETL scripts, data processing workflows - -### 🎮 Game Development -- **Pygame**: 2D games, arcade classics, educational games -- **Game AI**: Pathfinding, decision trees, game bots -- **Game Physics**: Collision detection, particle systems - -### 🛠️ Utilities & Automation -- **CLI Tools**: Command-line applications with argparse, Click -- **Web Scraping**: BeautifulSoup, Scrapy projects -- **Automation**: File management, email automation, task schedulers -- **DevOps**: CI/CD scripts, deployment automation - -### 🧪 Testing & Documentation -- **Unit Tests**: Pytest test cases for existing projects -- **Integration Tests**: End-to-end testing -- **Documentation**: README improvements, code documentation, tutorials -- **Type Hints**: Adding type annotations to existing code +## 🧠 Objective ---- - -## 💡 Contribution Ideas for Beginners - -New to open source? Start here! - -- ✅ Add a simple calculator with different operations -- ✅ Create a number guessing game -- ✅ Build a to-do list CLI application -- ✅ Implement a basic web scraper -- ✅ Write a unit converter (temperature, length, weight) -- ✅ Create a password generator -- ✅ Build a simple Flask API -- ✅ Add tests to existing projects -- ✅ Improve documentation -- ✅ Fix typos or formatting issues +> Guess the hidden word before you run out of lives. +Stay sharp, stay strategic — every letter counts! --- -## 🏆 Contribution Guidelines - -### Code Quality Standards -- 🧪 Include tests for new features (pytest) -- 📖 Update documentation for your changes -- 🎯 Keep commits atomic and descriptive -- 🔍 Use type hints where applicable (Python 3.8+) - -### Pull Request Process -1. Ensure your code follows our standards -2. Update the README.md if you add a new project -3. Add your name to CONTRIBUTORS.md -4. Fill out the PR template completely -5. Link any related issues -6. Wait for review — we typically respond within 48 hours! +## 🚀 Tech Stack (if applicable) +| Component | Technology | +|------------|-------------| +| **Frontend** | HTML, CSS, JavaScript *(for web version)* | +| **Backend / Logic** | Python or Node.js *(depending on implementation)* | +| **UI / UX** | Responsive layout, dynamic interaction feedback | --- -## 🌈 Technologies We Love - -
- -### Core Python -![Python](https://img.shields.io/badge/Python-3776AB?style=for-the-badge&logo=python&logoColor=white) -![Python3](https://img.shields.io/badge/Python_3.8+-14354C?style=for-the-badge&logo=python&logoColor=white) +## 💡 Future Enhancements -### Web Frameworks -![Flask](https://img.shields.io/badge/Flask-000000?style=for-the-badge&logo=flask&logoColor=white) -![Django](https://img.shields.io/badge/Django-092E20?style=for-the-badge&logo=django&logoColor=white) -![FastAPI](https://img.shields.io/badge/FastAPI-009688?style=for-the-badge&logo=fastapi&logoColor=white) - -### AI/ML & Deep Learning -![TensorFlow](https://img.shields.io/badge/TensorFlow-FF6F00?style=for-the-badge&logo=tensorflow&logoColor=white) -![PyTorch](https://img.shields.io/badge/PyTorch-EE4C2C?style=for-the-badge&logo=pytorch&logoColor=white) -![Keras](https://img.shields.io/badge/Keras-D00000?style=for-the-badge&logo=keras&logoColor=white) -![scikit-learn](https://img.shields.io/badge/scikit--learn-F7931E?style=for-the-badge&logo=scikit-learn&logoColor=white) - -### NLP & Data Science -![spaCy](https://img.shields.io/badge/spaCy-09A3D5?style=for-the-badge&logo=spacy&logoColor=white) -![Pandas](https://img.shields.io/badge/Pandas-150458?style=for-the-badge&logo=pandas&logoColor=white) -![NumPy](https://img.shields.io/badge/NumPy-013243?style=for-the-badge&logo=numpy&logoColor=white) - -### Game Development -![Pygame](https://img.shields.io/badge/Pygame-3776AB?style=for-the-badge&logo=python&logoColor=white) - -### Testing & Tools -![Pytest](https://img.shields.io/badge/Pytest-0A9EDC?style=for-the-badge&logo=pytest&logoColor=white) -![Docker](https://img.shields.io/badge/Docker-2496ED?style=for-the-badge&logo=docker&logoColor=white) - -
- ---- - -## 📚 Learning Resources - -### For Beginners -- [Python Official Tutorial](https://docs.python.org/3/tutorial/) -- [Real Python](https://realpython.com/) -- [Python for Everybody](https://www.py4e.com/) -- [Python Roadmap](https://roadmap.sh/python) - -### Web Development -- [Flask Documentation](https://flask.palletsprojects.com/) -- [Django Documentation](https://docs.djangoproject.com/) -- [FastAPI Documentation](https://fastapi.tiangolo.com/) -- [SQLAlchemy Documentation](https://www.sqlalchemy.org/) -- [MongoEngine Documentation](https://docs.mongoengine.org/) -- [Uvicorn Documentation](https://uvicorn.dev/) -- [Gunicorn Documentation](https://gunicorn.org/) - -### Web Scraping -- [Scrapy Documentation](https://docs.scrapy.org/en/latest/) -- [Beautiful Soup Documentation](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) - -### AI/ML -- [TensorFlow Tutorials](https://www.tensorflow.org/tutorials) -- [PyTorch Tutorials](https://pytorch.org/tutorials/) -- [Scikit Learn Documentation](https://www.nltk.org/) -- [Natural Language Toolkit Documentation](https://scikit-learn.org/stable/index.html) -- [Fast.ai Courses](https://www.fast.ai/) -- [Machine Learning Crash Course](https://developers.google.com/machine-learning/crash-course) - -### Data Science -- [Pandas Documentation](https://pandas.pydata.org/docs/) -- [Kaggle Learn](https://www.kaggle.com/learn) -- [UC Irvine Datasets](https://archive.ics.uci.edu/) +- 🌟 Difficulty modes (Easy / Medium / Hard) +- 🗂️ Category-based word banks (Movies, Animals, Technology, etc.) +- 🧩 Hint system for beginners +- 🏅 Leaderboard and scoring mechanism +- 🌙 Dark mode toggle +- 🎨 Animated hangman illustrations --- -## 🎯 Hacktoberfest 2025 Goals +## 🧑‍💻 Developer Notes -- 🎃 **500+ Pull Requests** accepted -- 👥 **200+ Contributors** from around the world -- 📦 **50+ New Projects** across all categories -- 🌟 **100% Beginner-Friendly** environment -- 🏅 Build something **you're proud of**! +This project was built to: +- Strengthen logical reasoning and control flow understanding. +- Practice string manipulation and condition-based game logic. +- Serve as an introductory project for beginners learning programming fundamentals. --- -## 🤝 Getting Help +## 🏁 Getting Started -- 💬 **Discussions**: Use [GitHub Discussions](../../discussions) for questions -- 🐛 **Issues**: Report bugs or request features -- 💡 **First-time contributors**: Look for issues labeled `good first issue` - -### Communication Channels -- Check issue labels: `good first issue`, `help wanted`, `beginner-friendly` -- Read `CONTRIBUTING.md` for detailed guidelines -- Review existing PRs to understand our standards -- Don't hesitate to ask questions in issue comments! +*(Skip this section if deploying directly — no localhost setup included as per preference.)* --- -## 📜 License +## 📸 Screenshots (Optional) -This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. +> Add screenshots or GIFs of your gameplay interface here to enhance the README’s visual appeal. --- -## 🎊 Hacktoberfest 2025 - -This repository is participating in **Hacktoberfest 2025**! - -### What is Hacktoberfest? -Hacktoberfest is a month-long celebration of open-source software run by DigitalOcean. By contributing to this repository during October, you can earn limited-edition swag and support open source! - -### Rules for Hacktoberfest PRs -- ✅ PRs must be meaningful (no spam) -- ✅ Follow contribution guidelines -- ✅ Be respectful and collaborative -- ✅ Quality over quantity -- ❌ No automated or low-effort PRs +## 🤝 Contributing -Learn more at [hacktoberfest.com](https://hacktoberfest.com/) +Contributions, feedback, and feature suggestions are always welcome! +Feel free to open an issue or submit a pull request. --- -## 💖 Support This Project +## 🧾 License -If you find this repository helpful: -- ⭐ Star this repository -- 🍴 Fork it and contribute -- 📢 Share it with friends -- 🐛 Report bugs -- 💡 Suggest new features +This project is open-source and available under the **MIT License**. --- -
- -### ⭐ Star this repository if you find it helpful! - -**Made with ❤️ for the open-source community** - -**Happy Hacking! 🚀🎃** - -
+### ✨ *"One wrong guess closer to the end... or one right letter away from victory."* diff --git a/hangman_art.py b/hangman_art.py new file mode 100644 index 0000000..746f0da --- /dev/null +++ b/hangman_art.py @@ -0,0 +1,151 @@ +# ASCII art for different stages of the hangman +stages = [ + # Stage 8 - Full figure (game over) + """ + ┏━━━━━┓ + ┃ ┃ + ┃ 😵 + ┃ ╱┃╲ + ┃ ┃ + ┃ ╱ ╲ + ┃ + ━━━┻━━━━━━━ + """, + # Stage 7 - Missing one leg + """ + ┏━━━━━┓ + ┃ ┃ + ┃ 😰 + ┃ ╱┃╲ + ┃ ┃ + ┃ ╱ + ┃ + ━━━┻━━━━━━━ + """, + # Stage 6 - Body, arms, one leg + """ + ┏━━━━━┓ + ┃ ┃ + ┃ 😟 + ┃ ╱┃╲ + ┃ ┃ + ┃ + ┃ + ━━━┻━━━━━━━ + """, + # Stage 5 - Body and arms + """ + ┏━━━━━┓ + ┃ ┃ + ┃ 😦 + ┃ ╱┃╲ + ┃ + ┃ + ┃ + ━━━┻━━━━━━━ + """, + # Stage 4 - Body and one arm + """ + ┏━━━━━┓ + ┃ ┃ + ┃ 😕 + ┃ ╱┃ + ┃ + ┃ + ┃ + ━━━┻━━━━━━━ + """, + # Stage 3 - Body only + """ + ┏━━━━━┓ + ┃ ┃ + ┃ 😐 + ┃ ┃ + ┃ + ┃ + ┃ + ━━━┻━━━━━━━ + """, + # Stage 2 - Head only + """ + ┏━━━━━┓ + ┃ ┃ + ┃ 🙂 + ┃ + ┃ + ┃ + ┃ + ━━━┻━━━━━━━ + """, + # Stage 1 - Noose only + """ + ┏━━━━━┓ + ┃ ┃ + ┃ + ┃ + ┃ + ┃ + ┃ + ━━━┻━━━━━━━ + """, + # Stage 0 - Empty gallows + """ + ┏━━━━━┓ + ┃ + ┃ + ┃ + ┃ + ┃ + ┃ + ━━━┻━━━━━━━ + """ +] + +# Reverse the stages list so index matches lives remaining +stages = list(reversed(stages)) + +logo = """ +██╗ ██╗ █████╗ ███╗ ██╗ ██████╗ ███╗ ███╗ █████╗ ███╗ ██╗ +██║ ██║██╔══██╗████╗ ██║██╔════╝ ████╗ ████║██╔══██╗████╗ ██║ +███████║███████║██╔██╗ ██║██║ ███╗██╔████╔██║███████║██╔██╗ ██║ +██╔══██║██╔══██║██║╚██╗██║██║ ██║██║╚██╔╝██║██╔══██║██║╚██╗██║ +██║ ██║██║ ██║██║ ╚████║╚██████╔╝██║ ╚═╝ ██║██║ ██║██║ ╚████║ +╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝ +""" + +win_art = """ + ⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣴⣶⣶⣶⣶⣶⣶⣶⣤⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀ + ⠀⠀⠀⠀⠀⠀⢀⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣦⡀⠀⠀⠀⠀⠀⠀ + ⠀⠀⠀⠀⠀⣠⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⠀⠀⠀⠀⠀ + ⠀⠀⠀⠀⣰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣆⠀⠀⠀⠀ + ⠀⠀⠀⢠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡄⠀⠀⠀ + ⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀ + ⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀ + ⠀⠀⠀⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠀⠀⠀ + ⠀⠀⠀⠀⢹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⠀⠀⠀⠀ + ⠀⠀⠀⠀⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀⠀⠀ + ⠀⠀⠀⠀⠀⠈⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠁⠀⠀⠀⠀⠀ + ⠀⠀⠀⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⠀⠀⠀⠀⠀⠀⠀ + ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⠻⢿⣿⣿⣿⣿⣿⡿⠟⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ + ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠉⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ + + 🎉 ⭐ YOU ARE A WINNER! ⭐ 🎉 +""" + +lose_art = """ + ⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣀⣀⣀⣀⣀⣀⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀ + ⠀⠀⠀⠀⠀⢀⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣦⡀⠀⠀⠀⠀⠀ + ⠀⠀⠀⠀⣠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣄⠀⠀⠀⠀ + ⠀⠀⠀⢠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡄⠀⠀⠀ + ⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀ + ⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀ + ⠀⠀⠀⢸⣿⣿⣿⣿⠿⠿⠿⠿⠿⠿⠿⠿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀ + ⠀⠀⠀⠘⣿⣿⣿⣿⣤⣤⣤⣤⣤⣤⣤⣤⣿⣿⣿⣿⣿⣿⠃⠀⠀⠀ + ⠀⠀⠀⠀⢹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⠀⠀⠀⠀ + ⠀⠀⠀⠀⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀⠀⠀ + ⠀⠀⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⠀⠀⠀⠀⠀⠀ + ⠀⠀⠀⠀⠀⠀⠀⠀⠙⠻⢿⣿⣿⣿⡿⠟⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀ + ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ + + 💀 GAME OVER! Better luck next time! 💀 +""" diff --git a/main.py b/main.py new file mode 100644 index 0000000..b31dfdd --- /dev/null +++ b/main.py @@ -0,0 +1,260 @@ +import random +import os +from words import word_categories, get_random_word +from hangman_art import stages, logo, win_art, lose_art + +def clear_screen(): + """Clear the console screen""" + os.system('cls' if os.name == 'nt' else 'clear') + +def display_game_state(word_progress, incorrect_guesses, lives, guessed_letters): + """Display current game state""" + clear_screen() + print(logo) + print(f"\n{stages[lives]}") + print(f"\nWord: {' '.join(word_progress)}") + print(f"\nLives remaining: {'❤️ ' * lives}") + print(f"Incorrect guesses: {', '.join(sorted(incorrect_guesses)) if incorrect_guesses else 'None'}") + print(f"All guessed letters: {', '.join(sorted(guessed_letters))}") + +def get_difficulty(): + """Get difficulty level from player""" + print("\n🎯 Select Difficulty Level:") + print("1. Easy (6-8 letter words, 8 lives)") + print("2. Medium (5-7 letter words, 6 lives)") + print("3. Hard (4-6 letter words, 5 lives)") + + while True: + choice = input("\nEnter your choice (1-3): ").strip() + if choice in ['1', '2', '3']: + return choice + print("❌ Invalid choice! Please enter 1, 2, or 3.") + +def get_category(): + """Get word category from player""" + print("\n📚 Select Word Category:") + categories = list(word_categories.keys()) + for i, cat in enumerate(categories, 1): + print(f"{i}. {cat}") + + while True: + choice = input(f"\nEnter your choice (1-{len(categories)}): ").strip() + if choice.isdigit() and 1 <= int(choice) <= len(categories): + return categories[int(choice) - 1] + print(f"❌ Invalid choice! Please enter a number between 1 and {len(categories)}.") + +def get_hint(word, word_progress, hints_remaining): + """Provide a hint by revealing a random unrevealed letter""" + if hints_remaining <= 0: + return None, 0 + + unrevealed_indices = [i for i, letter in enumerate(word_progress) if letter == '_'] + if unrevealed_indices: + hint_index = random.choice(unrevealed_indices) + return word[hint_index], hints_remaining - 1 + return None, hints_remaining + +def play_game(): + """Main game logic""" + clear_screen() + print(logo) + print("\n🎮 Welcome to Hangman! 🎮") + print("=" * 50) + + # Setup game + difficulty = get_difficulty() + category = get_category() + + # Set lives based on difficulty + lives_map = {'1': 8, '2': 6, '3': 5} + max_lives = lives_map[difficulty] + lives = max_lives + + # Get word + word = get_random_word(category, difficulty) + word_progress = ['_'] * len(word) + guessed_letters = set() + incorrect_guesses = set() + + # Hint system + max_hints = 2 if difficulty == '1' else 1 if difficulty == '2' else 0 + hints_remaining = max_hints + + # Score tracking + score = 0 + + game_over = False + won = False + + while not game_over: + display_game_state(word_progress, incorrect_guesses, lives, guessed_letters) + + # Show hints available + if hints_remaining > 0: + print(f"\n💡 Hints remaining: {hints_remaining}") + + # Get player input + print("\n" + "=" * 50) + guess = input("Guess a letter (or type 'hint' for a hint): ").lower().strip() + + # Handle hint request + if guess == 'hint': + if hints_remaining > 0: + hint_letter, hints_remaining = get_hint(word, word_progress, hints_remaining) + if hint_letter: + print(f"\n💡 Hint: The word contains the letter '{hint_letter.upper()}'") + input("Press Enter to continue...") + else: + print("\n❌ No more letters to reveal!") + input("Press Enter to continue...") + else: + print("\n❌ No hints remaining!") + input("Press Enter to continue...") + continue + + # Validate input + if len(guess) != 1: + print("\n❌ Please enter only ONE letter!") + input("Press Enter to continue...") + continue + + if not guess.isalpha(): + print("\n❌ Please enter a valid letter (A-Z)!") + input("Press Enter to continue...") + continue + + if guess in guessed_letters: + print(f"\n⚠️ You already guessed '{guess.upper()}'! Try another letter.") + input("Press Enter to continue...") + continue + + # Process guess + guessed_letters.add(guess) + + if guess in word: + # Correct guess + for i, letter in enumerate(word): + if letter == guess: + word_progress[i] = guess + + print(f"\n✅ Correct! '{guess.upper()}' is in the word!") + score += 10 + + # Check if won + if '_' not in word_progress: + game_over = True + won = True + else: + # Incorrect guess + incorrect_guesses.add(guess) + lives -= 1 + print(f"\n❌ Wrong! '{guess.upper()}' is not in the word. You lose a life!") + + # Check if lost + if lives == 0: + game_over = True + won = False + + if not game_over: + input("Press Enter to continue...") + + # Game over screen + clear_screen() + print(logo) + + if won: + print(win_art) + print(f"\n🎉 CONGRATULATIONS! You won! 🎉") + print(f"\nThe word was: {word.upper()}") + + # Calculate final score + bonus = lives * 20 + hint_penalty = (max_hints - hints_remaining) * 5 + final_score = score + bonus - hint_penalty + + print(f"\n📊 Your Score:") + print(f" Base score: {score}") + print(f" Lives bonus: +{bonus}") + if hint_penalty > 0: + print(f" Hint penalty: -{hint_penalty}") + print(f" Final Score: {final_score} 🌟") + else: + print(lose_art) + print(f"\n💀 GAME OVER! You lost! 💀") + print(f"\nThe word was: {word.upper()}") + print(f"You were so close! Better luck next time! 💪") + + return won, final_score if won else 0 + +def main(): + """Main game loop""" + clear_screen() + print(logo) + print("\n" + "=" * 50) + print("🎮 HANGMAN GAME 🎮".center(50)) + print("=" * 50) + input("\nPress Enter to start...") + + total_games = 0 + total_wins = 0 + total_score = 0 + win_streak = 0 + best_streak = 0 + + play_again = True + + while play_again: + won, score = play_game() + + total_games += 1 + total_score += score + + if won: + total_wins += 1 + win_streak += 1 + if win_streak > best_streak: + best_streak = win_streak + else: + win_streak = 0 + + # Show statistics + print("\n" + "=" * 50) + print("📈 YOUR STATISTICS:") + print(f" Games played: {total_games}") + print(f" Games won: {total_wins}") + print(f" Win rate: {(total_wins/total_games)*100:.1f}%") + print(f" Total score: {total_score}") + print(f" Current streak: {win_streak} 🔥" if win_streak > 0 else f" Current streak: {win_streak}") + print(f" Best streak: {best_streak}") + print("=" * 50) + + # Ask to play again + while True: + choice = input("\nDo you want to play again? (yes/no): ").lower().strip() + if choice in ['yes', 'y']: + play_again = True + break + elif choice in ['no', 'n']: + play_again = False + break + else: + print("❌ Please enter 'yes' or 'no'.") + + # Goodbye message + clear_screen() + print(logo) + print("\n" + "=" * 50) + print("👋 Thanks for playing Hangman! 👋".center(50)) + print("=" * 50) + print(f"\n🏆 Final Statistics:") + print(f" Games played: {total_games}") + print(f" Games won: {total_wins}") + print(f" Win rate: {(total_wins/total_games)*100:.1f}%") + print(f" Total score: {total_score}") + print(f" Best streak: {best_streak}") + print("\n" + "=" * 50) + print("See you next time! 🎮".center(50)) + print("=" * 50 + "\n") + +if __name__ == "__main__": + main() diff --git a/words.py b/words.py new file mode 100644 index 0000000..6f35d95 --- /dev/null +++ b/words.py @@ -0,0 +1,91 @@ +import random + +# Word categories with different difficulty levels +word_categories = { + "Animals": { + "easy": ["elephant", "giraffe", "kangaroo", "penguin", "dolphin", "butterfly", "cheetah", "crocodile"], + "medium": ["jaguar", "falcon", "turtle", "rabbit", "monkey", "tiger"], + "hard": ["zebra", "panda", "koala", "hyena", "otter"] + }, + "Movies": { + "easy": ["titanic", "avatar", "frozen", "inception", "gladiator", "jaws"], + "medium": ["matrix", "joker", "rocky", "alien", "rocky"], + "hard": ["memento", "psycho", "fargo", "ghost"] + }, + "Countries": { + "easy": ["australia", "germany", "canada", "brazil", "mexico", "portugal", "argentina"], + "medium": ["france", "japan", "india", "egypt", "spain"], + "hard": ["nepal", "malta", "qatar", "chile"] + }, + "Food": { + "easy": ["hamburger", "spaghetti", "sandwich", "pancakes", "chocolate", "blueberry"], + "medium": ["pizza", "taco", "sushi", "curry", "waffle"], + "hard": ["bagel", "mango", "pasta", "bacon"] + }, + "Sports": { + "easy": ["football", "baseball", "basketball", "swimming", "volleyball", "cricket"], + "medium": ["soccer", "hockey", "tennis", "rugby"], + "hard": ["judo", "polo", "golf", "surf"] + }, + "Technology": { + "easy": ["computer", "keyboard", "internet", "software", "database", "algorithm"], + "medium": ["python", "server", "coding", "laptop"], + "hard": ["debug", "cache", "byte", "loop"] + }, + "Music": { + "easy": ["symphony", "harmony", "rhythm", "melody", "acoustic", "orchestra"], + "medium": ["guitar", "piano", "drums", "vocal", "jazz"], + "hard": ["tempo", "chord", "bass", "note"] + }, + "Science": { + "easy": ["chemistry", "biology", "gravity", "molecule", "planet", "hydrogen"], + "medium": ["oxygen", "carbon", "energy", "atoms"], + "hard": ["quark", "plasma", "proton", "light"] + }, + "Nature": { + "easy": ["mountain", "waterfall", "rainbow", "sunrise", "forest", "desert"], + "medium": ["ocean", "river", "storm", "beach", "cloud"], + "hard": ["delta", "cliff", "canyon", "lunar"] + }, + "Colors": { + "easy": ["crimson", "turquoise", "lavender", "emerald", "scarlet", "violet"], + "medium": ["orange", "purple", "yellow", "silver"], + "hard": ["amber", "coral", "maroon", "ivory"] + } +} + +def get_random_word(category, difficulty): + """ + Get a random word based on category and difficulty + + Args: + category: String - the category name + difficulty: String - '1' (easy), '2' (medium), '3' (hard) + + Returns: + String - a random word from the selected category and difficulty + """ + difficulty_map = { + '1': 'easy', + '2': 'medium', + '3': 'hard' + } + + diff_level = difficulty_map.get(difficulty, 'medium') + + if category in word_categories: + word_list = word_categories[category][diff_level] + return random.choice(word_list) + else: + # Fallback to random category + random_category = random.choice(list(word_categories.keys())) + word_list = word_categories[random_category][diff_level] + return random.choice(word_list) + +def get_all_words(): + """Get all words from all categories (for testing)""" + all_words = [] + for category in word_categories.values(): + for difficulty in category.values(): + all_words.extend(difficulty) + return all_words