Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Interactive Tower of Hanoi Game #1005

Merged
merged 2 commits into from
Nov 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions Game_Development/Tower of Hanoi/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Tower of Hanoi Game

An interactive Tower of Hanoi game built with Python using `pygame` for the graphical interface and `colorama` for colorful console messages. This classic puzzle game challenges players to move all disks from one rod to another while following specific rules.

## Game Overview

In the Tower of Hanoi puzzle:
- You have three rods and several disks of different sizes.
- The goal is to move all the disks from the first rod to the third rod.
- Disks must be stacked in decreasing order of size on the destination rod.
- You can only move one disk at a time, and a larger disk cannot be placed on a smaller disk.

This game implements these rules and includes visual feedback, vibrant colors, and drag-and-drop controls.

## Features

- **Interactive gameplay**: Click and drag disks between rods to move them.
- **Colorful Console Instructions**: Using `colorama`, the game provides color-coded messages in the console, guiding players and alerting them of invalid moves.
- **Customizable settings**: Adjust the number of disks for different levels of difficulty.

## Setup Instructions

### Requirements

- Python 3.x
- `pygame` library for graphics
- `colorama` library for colored console feedback

### Installation

1. Install dependencies:

```bash
pip install pygame colorama
```

2. Run the game:

```bash
python game.py
```

## How to Play

1. Launch the game by running `game.py`.
2. Follow the console instructions to understand the game rules:
- Move one disk at a time.
- Only place smaller disks on larger ones.
3. Click on a disk to pick it up, then click on another rod to drop it there.
4. Try to move all disks from the first rod to the third rod with the fewest moves.

## Console Guide

The console provides feedback:
- **Instructions**: Game rules and objectives.
- **Invalid Move Alert**: If you try to place a larger disk on a smaller disk, you’ll see an error message in red.

## Customization

You can adjust the following settings in `game.py`:
- **Number of disks**: Change `num_disks` for different difficulty levels.
- **Colors**: Modify `DISK_COLORS` and `BACKGROUND_COLOR` to customize the look and feel.


## Acknowledgments

Thanks to the `pygame` and `colorama` communities for their libraries, which make this interactive Python game possible!
92 changes: 92 additions & 0 deletions Game_Development/Tower of Hanoi/game.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import pygame
from colorama import init, Fore, Style

# Initialize Pygame and Colorama
pygame.init()
init(autoreset=True)

# Screen settings
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Tower of Hanoi")

# Colors
BACKGROUND_COLOR = (30, 30, 60)
ROD_COLOR = (220, 220, 220)
DISK_COLORS = [(240, 128, 128), (250, 200, 200), (100, 149, 237), (152, 251, 152), (255, 105, 180)]

# Font
font = pygame.font.Font(None, 36)

# Rod positions and disk settings
rod_x_positions = [WIDTH // 4, WIDTH // 2, 3 * WIDTH // 4]
rod_y_position = HEIGHT - 50
rod_width, rod_height = 10, 250
disk_height = 20
disks = []

# Game settings
num_disks = 5
rods = [[], [], []]
for i in range(num_disks, 0, -1):
disks.append({
'width': i * 30,
'color': DISK_COLORS[i % len(DISK_COLORS)],
'position': (rod_x_positions[0], rod_y_position - disk_height * len(rods[0]))
})
rods[0].append(disks[-1])

# Draw rods and disks
def draw_rods_and_disks():
screen.fill(BACKGROUND_COLOR)
for i, x in enumerate(rod_x_positions):
pygame.draw.rect(screen, ROD_COLOR, (x - rod_width // 2, rod_y_position - rod_height, rod_width, rod_height))
for j, disk in enumerate(rods[i]):
disk_x = x - disk['width'] // 2
disk_y = rod_y_position - disk_height * (j + 1)
pygame.draw.rect(screen, disk['color'], (disk_x, disk_y, disk['width'], disk_height))

# Console instructions
print(Fore.CYAN + "Welcome to the Tower of Hanoi Game!" + Style.RESET_ALL)
print(Fore.YELLOW + "Move all disks from the first rod to the third rod following the rules:")
print("- Move one disk at a time.")
print("- Only smaller disks can be placed on larger disks.\n" + Style.RESET_ALL)

# Main game loop
running = True
selected_disk = None
selected_rod = None

while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = event.pos
for i, rod in enumerate(rods):
if rod and (rod_x_positions[i] - rod[0]['width'] // 2 < mouse_x < rod_x_positions[i] + rod[0]['width'] // 2):
selected_disk = rod.pop()
selected_rod = i
break
elif event.type == pygame.MOUSEBUTTONUP and selected_disk:
mouse_x, mouse_y = event.pos
for i, x in enumerate(rod_x_positions):
if abs(mouse_x - x) < 50: # Drop zone for rods
if not rods[i] or selected_disk['width'] < rods[i][-1]['width']:
rods[i].append(selected_disk)
selected_disk = None
break
else:
print(Fore.RED + "Invalid move! You can't place a larger disk on a smaller one." + Style.RESET_ALL)
rods[selected_rod].append(selected_disk)
selected_disk = None
break
if selected_disk:
rods[selected_rod].append(selected_disk)
selected_disk = None

draw_rods_and_disks()
pygame.display.flip()

# Exit
pygame.quit()
2 changes: 2 additions & 0 deletions Project-Structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,8 @@
* [Main](Game_Development/Text-Based%20Adventure/main.py)
* Tic Tac Toe
* [Tic Tac Toe](Game_Development/Tic_Tac_Toe/tic_tac_toe.py)
* Tower Of Hanoi
* [Game](Game_Development/Tower%20of%20Hanoi/game.py)
* Trivia
* [Trivia](Game_Development/Trivia/Trivia.py)
* Turtle Collection Game
Expand Down