Skip to content
Open
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
239 changes: 77 additions & 162 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,191 +1,106 @@
# Towers Puzzle Game - 4 Greedy Strategies
# Towers Puzzle Game

A competitive implementation of the classic Towers puzzle (also known as Skyscrapers) where you play against CPU using different strategic approaches.
A competitive implementation of the classic Towers (Skyscrapers) logic puzzle with CPU opponents using different strategic approaches.

## Game Overview
## About

Towers is a logic puzzle where you fill a 4×4 grid with numbers 1-4, ensuring:
- Each number appears exactly once per row
- Each number appears exactly once per column
- The clues around the edges indicate how many "towers" are visible from that direction (taller towers hide shorter ones behind them)
Towers is a 4×4 logic puzzle where players must place numbers 1-4 in each cell following specific rules. This version adds turn-based competitive gameplay where you face off against a CPU opponent that can switch between four different decision-making strategies.

## Game Mechanics
## Rules

The puzzle follows standard Towers constraints:
- Each row contains numbers 1-4 exactly once
- Each column contains numbers 1-4 exactly once
- Edge clues show how many towers are visible from that direction (taller towers block shorter ones)

### Scoring System
- **Valid Move**: +1 point, +5 lives
- **Completing a Row/Column**: +2 bonus points per completion
- **Invalid Move**: -5 points, -10 lives

### Win Conditions
The game ends when:
1. The board is full
2. Either player runs out of lives (≤0)
3. No valid moves remain

**Winner is determined by:**
1. If one player has 0 lives → other player wins
2. Highest score
3. If tied on score → most lives remaining
4. If still tied → declared a TIE

## 🤖 AI Strategies

The CPU opponent can use four different greedy strategies, each with its own color-coded heat map:

### 1. **SCORE-GREEDY** (Blue Heat Map) 🔵
**Goal**: Maximize immediate points
- **Formula**: `Utility = 2.0 × deltaPoints + 0.5 × deltaLives`
- **Strategy**: Prioritizes moves that complete rows/columns for bonus points
- **When to use**: When ahead in lives and want to build a point lead
- **Weakness**: May sacrifice survival for points

### 2. **LIVES-GREEDY** (Green Heat Map) 🟢
**Goal**: Maximize survival/longevity
- **Formula**: `Utility = 0.5 × deltaPoints + 2.0 × deltaLives`
- **Strategy**: Prioritizes staying alive over scoring
- **When to use**: When low on lives and need to last longer
- **Weakness**: May fall behind in score

### 3. **CONSTRAINT-GREEDY** (Purple Heat Map) 🟣
**Goal**: Solve most constrained cells first (MCV Heuristic)
- **Formula**: `Score = (10.0 / validOptions) × 15.0 + basePoints × 5.0`
- **Strategy**: Tackles cells with fewer valid options before they become impossible
- **When to use**: Complex board states requiring systematic solving
- **Weakness**: May not optimize for score or lives
- **Logic**: "If a cell has only 1 valid option, solve it NOW before it becomes impossible"

### 4. **COMPLETION-GREEDY** (Red Heat Map) 🔴
**Goal**: Complete rows/columns fastest (Aggressive)
- **Formula**: `Score = (10.0/emptyInRow + 10.0/emptyInCol) × 12.0 + basePoints × 8.0`
- **Strategy**: Prioritizes nearly-complete lines to finish them quickly
- **When to use**: For fast visible progress and reducing search space
- **Weakness**: May create difficult constraints elsewhere
- **Logic**: "If a row has 1 empty cell left, filling it completes the row"

## Heat Map Visualization

Each strategy displays a **color-coded heat map** showing which cells the AI values most:
- **Darker/More Saturated** = Higher priority for AI
- **Lighter/Less Saturated** = Lower priority for AI
- **White** = No valid moves or filled cells

The heat map updates dynamically and animates when the CPU is thinking, giving you insight into the AI's decision-making process.

## HOW TO PLAY

1. **Your Turn**:
- Click any empty cell
- Select a value (1-4) from the popup
- Only valid moves are enabled

2. **CPU Turn**:
- Watch the heat map animate (if enabled)
- CPU selects its move based on chosen strategy
- Status updates show the move result

3. **Strategy Selection**:
- Change CPU strategy anytime using the dropdown
- Heat map colors update to match strategy
- Toggle heat map visibility with checkbox

## Running the Game

### Prerequisites
- Correct placement: +10 points
- Complete a row/column: +20 bonus
- Invalid move: -5 lives
- Each player starts with 100 lives

### Victory Conditions
The game ends when the board is complete or a player runs out of lives. The winner is determined by:
1. Lives remaining (player alive wins)
2. Higher score
3. If tied, it's a draw

## CPU Strategies

The CPU can use four different approaches:

**Lives-Greedy (Survival)** - Focuses on safe moves to preserve lives. Prefers cells with fewer possible values to minimize risk.

**Completion-Greedy (Rusher)** - Prioritizes finishing nearly-complete rows and columns quickly.

**Score-Greedy (Gambler)** - Goes for high-scoring opportunities even if riskier.

**Constraint-Greedy (MRV)** - Uses the Minimum Remaining Values heuristic to tackle the most constrained cells first.

Each strategy shows a different colored heat map indicating which cells it considers high-priority.

## Features

- Real-time heat map showing CPU decision process
- Switch strategies mid-game to change AI behavior
- Clean dark-themed interface
- Move validation with visual feedback
- Reasoning panel explaining CPU moves

## Running the Game

### Requirements
- Java JDK 8 or higher
- Java Swing (included in standard JDK)

### Compilation
```bash
javac TowersGameGUI.java
javac game/*.java
```

### Execution
```bash
java TowersGameGUI
java game.TowersssGameGUI
```

## 🏗️ Project Structure

## Project Structure
```
TowersGameGUI.java
├── Game State Management
│ ├── grid[][] # 4×4 board
│ ├── rowUsed[][] # Track used values per row
│ └── colUsed[][] # Track used values per column
├── UI Components
│ ├── cellButtons[][] # Grid cells
│ ├── valueButtons[] # Value selection (1-4)
│ ├── strategyCombo # Strategy dropdown
│ └── heatMapToggle # Heat map visibility
├── Core Game Logic
│ ├── canPlace() # Validate moves
│ ├── checkRow() # Verify row constraints
│ ├── checkCol() # Verify column constraints
│ └── placeValue() # Execute moves
├── AI System
│ ├── getBest() # Find optimal move
│ ├── eval() # Strategy dispatcher
│ ├── evalScore() # Score-Greedy
│ ├── evalLives() # Lives-Greedy
│ ├── evalConstraint() # Constraint-Greedy
│ └── evalCompletion() # Completion-Greedy
└── Visualization
├── updateHeatMap() # Calculate heat values
├── animateHeatMap() # Animate visualization
└── getHeatColor() # Strategy-specific colors
game/
├── TowersssGameGUI.java # Main game window and controls
├── GameState.java # Game logic and validation
├── PuzzleGenerator.java # Creates valid puzzle configurations
├── StrategyLives.java # Survival strategy
├── StrategyCompletion.java # Completion strategy
├── StrategyScore.java # Score-maximizing strategy
└── StrategyMRV.java # Constraint-based strategy
```

## Learning Outcomes

This project demonstrates:
- **Graph Representation**: The puzzle as a constraint satisfaction problem
- **Greedy Algorithms**: Four different heuristic approaches
- **Game Theory**: Competitive two-player dynamics
- **UI/UX Design**: Real-time visualization of AI decision-making
- **Java Swing**: Event-driven GUI programming
## How to Play

## 🔧 Technical Features
1. Click any empty cell on your turn
2. Select a value from the popup (grayed out values are invalid)
3. Watch the CPU analyze the board with the heat map
4. Try to outscore and outlast the CPU

- **Constraint Validation**: Real-time checking of Towers puzzle rules
- **Dynamic Heat Maps**: Visual feedback on AI priorities
- **Animated Transitions**: Smooth cell-by-cell heat map animation
- **Strategy Comparison**: Switch strategies mid-game to compare
- **Score/Lives System**: Adds competitive pressure beyond puzzle-solving
You can change the CPU strategy anytime using the dropdown menu. The heat map can be toggled on/off.

## Strategy Comparison
## Understanding Greedy Algorithms and Their Limitations

| Strategy | Best For | Weakness | Complexity |
|----------|----------|----------|------------|
| Score-Greedy | Aggressive scoring | Risky with lives | Low |
| Lives-Greedy | Defensive play | Falls behind in points | Low |
| Constraint-Greedy | Complex boards | Not score-optimized | Medium |
| Completion-Greedy | Fast progress | May create dead ends | Medium |
Greedy algorithms select the locally optimal choice at each step without considering future consequences. In the Towers puzzle, each strategy evaluates available moves and immediately commits to the highest-scoring option. While computationally efficient, this approach does not guarantee optimal solutions. For example, Completion-Greedy may rush to finish a row that violates visibility rules, incurring penalties, while Lives-Greedy may play too conservatively and score minimal points. These limitations arise because greedy algorithms cannot reconsider decisions or anticipate downstream effects of current choices.

## Known Issues
## Greedy Algorithms as Practical Heuristics

- Value buttons may not always properly disable for invalid moves (validation still works)
- Heat map animation delay is fixed at 120ms per cell
- No undo functionality

## Future Enhancements

- [ ] Minimax or Monte Carlo Tree Search AI
- [ ] Multiple difficulty levels (3×3, 5×5, 6×6 grids)
- [ ] Hint system for players
- [ ] Move history and replay
- [ ] Tournament mode (best of N games)
- [ ] Custom puzzle input
- [ ] Save/Load game state
In this project, greedy algorithms function as heuristics that provide reasonable solutions quickly rather than guaranteed optimal outcomes. The four strategies demonstrate varied problem-solving approaches suitable for real-time gameplay. Achieving truly optimal solutions would require exhaustive methods like backtracking that explore all possible sequences. Greedy heuristics offer a practical trade-off between solution quality and speed, making them valuable for interactive applications. This implementation effectively demonstrates how greedy approaches address constraint satisfaction problems while maintaining the distinction between heuristic adequacy and mathematical optimality.

## Limitations

## 👨‍💻 Author

Created as a demonstration of greedy algorithms and competitive AI strategies in puzzle-solving.
- Fixed 4×4 board size
- No undo functionality
- Heat map animation speed cannot be adjusted

---
## Possible Improvements

**Enjoy the game and may the best strategy win! 🏆**
- Larger grid options (5×5, 6×6)
- Hint system for difficult moves
- Move history tracking
- Minimax or alpha-beta pruning strategies
- Multiplayer network mode