HT Games

How to Write a "Package Game" in Python: Complete Example

The term "package game" is ambiguous. It could mean a distributable Python package containing a game, a game about delivering packages, or simply a modular code structure. Below is a **complete, runnable example of a simple text-based guessing game structured as a proper Python package**.

Project Structure

package_game/
├── pyproject.toml
├── README.md
├── src/
│   └── package_game/
│       ├── __init__.py
│       ├── core.py
│       └── cli.py

Key Files

pyproject.toml (Modern packaging config)

[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[project]
name = "package-game"
version = "0.1.0"
description = "A simple number guessing game package"
readme = "README.md"
requires-python = ">=3.8"
entry-points = {
    console_scripts = ["guess-game = package_game.cli:main"]
}

src/package_game/core.py (Game Logic)

import random

def play_round(max_number: int = 100, max_attempts: int = 7) -> bool:
    """Play one round. Returns True if player wins."""
    secret = random.randint(1, max_number)
    attempts = 0
    print(f"\nGuess a number between 1 and {max_number}. You have {max_attempts} attempts.")
    while attempts < max_attempts:
        try:
            guess = int(input(f"Attempt {attempts + 1}: "))
        except ValueError:
            print("Please enter a valid integer.")
            continue
        attempts += 1
        if guess < secret:
            print("Too low!")
        elif guess > secret:
            print("Too high!")
        else:
            print(f"Correct! You won in {attempts} attempt(s).")
            return True
    print(f"Out of attempts. The number was {secret}.")
    return False

src/package_game/cli.py (Command Line Interface)

from .core import play_round

def main() -> None:
    print("=== Number Guessing Game ===")
    while True:
        play_round()
        if input("\nPlay again? (y/n): ").lower() != 'y':
            break
    print("Thanks for playing!")

if __name__ == "__main__":
    main()

src/package_game/__init__.py

"""Package Game - A simple guessing game."""
__version__ = "0.1.0"

Installation & Usage

# Install in development mode
pip install -e .

# Run from anywhere
guess-game

This structure separates logic (core.py) from I/O (cli.py), making it testable, importable, and distributable via PyPI. Adapt the core.py logic for your specific game mechanics.


https://www.htfbw.com © HT Games