Skip to content

devxnshsharma/slot-machine-game

Repository files navigation

Slot Machine Game - Production Edition

Python License Code Style

A production-grade slot machine game built with Python and Tkinter, featuring comprehensive error handling, security measures, data persistence, logging, and unit tests.

Features

🎮 Core Gameplay

  • Realistic Slot Machine: Three spinning reels with emoji symbols
  • Dynamic Payouts: Different multipliers for each symbol
  • Balance Management: Track winnings and losses
  • Game Persistence: Auto-save game state to resume later

🔒 Security Features

  • Input Validation: Comprehensive validation against injection attacks
  • Path Traversal Prevention: Secure file handling
  • Type Safety: Full type hints throughout codebase
  • Integer Overflow Protection: Safe integer arithmetic
  • Session Timeout: Configurable session management

📊 Production Features

  • Structured Logging: File and console logging with rotation
  • Configuration Management: Environment-based settings
  • State Persistence: JSON-based game state storage
  • Error Handling: Comprehensive exception hierarchy
  • Audio System: Optional sound effects with graceful degradation
  • Statistics Tracking: Track spins, wins, losses, and win rates

🧪 Quality Assurance

  • Unit Tests: 20+ test cases covering core functionality
  • Type Checking: Full type hints (Python 3.8+ compatible)
  • Modular Architecture: Clean separation of concerns
  • Error Recovery: Graceful handling of missing resources

Project Structure

slot-machine-game/
├── src/
│   ├── __init__.py
│   ├── config/
│   │   ├── __init__.py
│   │   └── settings.py           # Configuration management
│   ├── game/
│   │   ├── __init__.py           # GameEngine
│   │   ├── controller.py         # Game orchestration
│   │   └── persistence.py        # State management
│   ├── ui/
│   │   └── __init__.py           # GUI components
│   ├── audio/
│   │   └── __init__.py           # Sound management
│   └── utils/
│       ├── logger.py             # Logging setup
│       ├── validators.py         # Input validation
│       ├── exceptions.py         # Custom exceptions
│       └── resource_manager.py   # Resource handling
├── tests/
│   └── test_game.py              # Unit tests
├── logs/                         # Application logs
├── data/                         # Game state persistence
├── main.py                       # Entry point
├── requirements.txt              # Dependencies
├── setup.py                      # Package setup
└── README.md                     # Documentation

Installation

Prerequisites

  • Python 3.8 or higher
  • pip package manager

From Source

# Clone repository
git clone https://github.com/yourusername/slot-machine-game.git
cd slot-machine-game

# Create virtual environment
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Run the game
python main.py

As a Package

pip install .
slot-machine

Usage

Running the Game

python main.py

Environment Variables

Configure the game behavior using environment variables:

# Enable debug mode
export DEBUG_MODE=true

# Set game environment
export GAME_ENVIRONMENT=development  # or testing, production

# Control audio
export ENABLE_AUDIO=true

# Set logging level
export LOG_LEVEL=DEBUG  # DEBUG, INFO, WARNING, ERROR, CRITICAL

Running Tests

# Run all tests
python -m pytest tests/ -v

# Or using unittest
python tests/test_game.py

# With coverage report
python -m pytest tests/ --cov=src

Configuration

GameConfig

Edit configuration in src/config/settings.py:

config = GameConfig(
    INITIAL_BALANCE=100,
    MIN_BET=1,
    MAX_BET=1000,
    SYMBOLS=['🍒', '🍉', '🍋', '🔔', '⭐'],
    PAYOUTS={
        '🍒': 2.0,
        '🍉': 4.0,
        '🍋': 6.0,
        '🔔': 8.0,
        '⭐': 20.0,
    },
    ENABLE_AUDIO=True,
    SAVE_GAME_STATE=True,
)

Security

Input Validation

  • All user inputs validated against injection attacks
  • Bet amounts checked for valid range
  • Filename paths validated for traversal attacks

Data Integrity

  • Game state validated before saving/loading
  • Type checking prevents unexpected conversions
  • Integer overflow protection

Logging & Auditing

  • All game events logged with timestamps
  • Security-relevant events recorded
  • Log rotation to prevent disk space issues

Architecture

MVC Pattern

  • Model: GameEngine - Core game logic
  • View: SlotMachineGUI - User interface
  • Controller: GameController - Orchestration

Separation of Concerns

  • Game Logic: Isolated in GameEngine
  • UI: Decoupled in SlotMachineGUI
  • Persistence: Abstracted in GameStatePersistence
  • Audio: Encapsulated in SoundManager

Error Handling

Comprehensive exception hierarchy:

GameException (base)
├── ValidationError
├── AudioError
├── InsufficientFundsError
├── InvalidBetError
└── GameStateError

All operations have try-catch blocks with proper logging.

Logging

Log Levels

  • DEBUG: Detailed diagnostic information
  • INFO: General informational messages
  • WARNING: Warning messages for recoverable issues
  • ERROR: Error messages for failures
  • CRITICAL: Critical system failures

Log Output

  • Console output (colored)
  • File output with rotation
  • Default log file: logs/slot_machine.log
  • Max size: 10MB with 5 backup files

Game Mechanics

Winning Conditions

  • All three reels show the same symbol
  • Different symbols have different payouts

Payout Table

🍒 = 2x bet
🍉 = 4x bet
🍋 = 6x bet
🔔 = 8x bet
⭐ = 20x bet (jackpot)

Performance

  • Efficient animation rendering using tkinter's after() method
  • Graceful audio degradation if sound system unavailable
  • Smart state persistence with JSON format
  • Minimal memory footprint

Development

Code Quality

  • PEP 8 compliant code
  • Type hints throughout
  • Comprehensive docstrings
  • Modular architecture

Testing

  • Unit tests for core logic
  • Mock-based testing for dependencies
  • Edge case coverage
  • 80%+ code coverage target

CI/CD Ready

  • Clean exit codes
  • Structured logging for monitoring
  • Configuration from environment
  • Unit test integration

Known Limitations

  • Audio files not included (place in assets/audio/)
  • Tkinter UI is single-threaded (intentional for simplicity)
  • No network/multiplayer features
  • Local persistence only (no cloud sync)

Future Enhancements

  • Web interface using Flask/FastAPI
  • Multiplayer functionality
  • Leaderboards and achievements
  • Advanced statistics and analytics
  • Theme customization
  • Mobile app version
  • Progressive web app (PWA)

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new features
  4. Ensure all tests pass
  5. Submit a pull request

License

MIT License - See LICENSE file for details

Author

Created as a portfolio project showcasing production-grade Python development practices.

Support

For issues and questions:

  • Open an issue on GitHub
  • Check documentation in docs/
  • Review test cases in tests/

Changelog

Version 1.0.0 (2024)

  • Initial production release
  • Full security features
  • Comprehensive testing
  • Complete documentation

Built with best practices for production-ready applications 🚀

About

python tkinter gui slot machine game

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages