8000 GitHub - Plogoman/Hive-Mind · GitHub
[go: up one dir, main page]

Skip to content
8000
PlogomanPublic

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

HIVE MIND - Track B Implementation

AI Assignment 2: Grid-based Strategy Game with Swarm Intelligence


Project Files

  1. hive_mind_enhanced.py - Main simulation (Phase 1)
  2. genetic_optimization.py - Weight optimization (Phase 2 Bonus)
  3. AIAssignment2.py - Your original implementation

Game Mechanics

Objective

Hero must navigate grid, retrieve the Gem, and reach the Exit while evading coordinated Monster swarm.

Entities

Hero (Blue)

  • HP: 100
  • Ammo: 5
  • Attack Range: 3 cells (ranged)
  • Vision: 5 cells radius
  • Actions: Move, Fire, Interact

Monsters (Red)

  • Count: 3
  • Attack Range: 1 cell (melee)
  • Damage: 20 HP
  • Vision: 5 cells radius
  • Behavior: Hive mind with shared perception

Environment

  • Grid: 10x10
  • Fog of War: Only visible within hero's vision radius
  • Walls: Obstacles blocking movement
  • Gem: Must collect before exiting
  • Exit: Victory condition

AI Implementation

1. Hero Agent (Minimax with Alpha-Beta Pruning)

Algorithm:

def alpha_beta_search(state):
    for each possible action:
        v = min_value(next_state, alpha, beta, depth)
        if v > best_score:
            best_score, best_action = v, action
        alpha = max(alpha, v)
    return best_action

Evaluation Function E(s):

E(s) = w1 * objective_distance 
     + w2 * threat_proximity
     + w3 * resource_value
     + w4 * loop_penalty

Where:
- Objective: Distance to Gem (if not collected) or Exit (if collected)
- Threat: Proximity to nearest monster
- Resource: HP and Ammo values
- Loop: Penalty for revisiting positions

Key Features:

  • Depth-limited search (depth = 3)
  • Alpha-beta pruning for efficiency
  • Considers Move, Fire, and Interact actions
  • Tracks nodes explored and branches pruned

2. Monster Swarm (Hive Mind Utility System)

Shared Perception:

  • If ANY monster sees the hero, ALL monsters know hero location
  • Breaks fog of war for the swarm
  • Implements true cooperative behavior

Utility Function:

U(move) = w1 * pursuit(move) 
        + w2 * separation(move) 
        + w3 * aggression(move)

Where:
- Pursuit: -distance_to_hero (closer = higher)
- Separation: Penalties for clustering with other monsters
- Aggression: Bonus for entering attack range (1 cell)

Default Weights: [1.5, 0.8, 2.0]

Behaviors:

  1. Pursuit: Minimize distance to hero (or last known position)
  2. Separation: Avoid clustering (penalties for adjacent monsters)
  3. Aggression: Bonus for moving into melee range

3. Genetic Algorithm (Phase 2 Bonus)

Objective: Optimize utility weights to minimize turns needed to eliminate hero

Algorithm:

1. Initialize random population of weight sets
2. For each generation:
   a. Evaluate fitness (avg turns to eliminate hero)
   b. Select parents (tournament selection)
   c. Crossover (single-point)
   d. Mutate (gaussian noise)
   e. Apply elitism (keep best 2)
3. Return best weights found

Parameters:

  • Population size: 20
  • Generations: 25
  • Mutation rate: 0.15
  • Weight bounds: [0.1-5.0, 0.1-3.0, 0.1-5.0]

Evolution Tracking:

  • Best fitness per generation
  • Average fitness per generation
  • Final comparison: original vs optimized weights

How to Run

Phase 1: Basic Simulation

python hive_mind_enhanced.py

Expected Output:

  • Live matplotlib visualization with fog of war
  • Turn-by-turn console output
  • Hero actions and monster movements
  • Alpha-beta pruning statistics
  • Victory/defeat message

Phase 2: Genetic Optimization

python genetic_optimization.py

Expected Output:

  • Generation-by-generation evolution
  • Best/average fitness tracking
  • Final optimized weights
  • Performance comparison graph (ga_evolution.png)
  • Before/after testing results

Note: Takes 5-10 minutes to complete


Key Metrics

Alpha-Beta Pruning Efficiency

  • Nodes Explored: Total game states evaluated
  • Branches Pruned: States skipped due to pruning
  • Efficiency: Higher pruning = faster decisions

Genetic Algorithm Convergence

  • Best Fitness: Minimum turns to eliminate hero
  • Average Fitness: Population average performance
  • Convergence: Decreasing fitness over generations

Meeting Requirements

Phase 1 Checklist

  • Grid-based environment (10x10)
  • Hero with Minimax implementation
  • Monster swarm with cooperative behavior
  • Shared perception (hive mind)
  • Fog of war visualization
  • Resource management (HP, Ammo)
  • Combat mechanics (ranged vs melee)
  • Loop prevention
  • Matplotlib visualization
  • Distance-based utility function
  • Threat assessment
  • Separation behavior

Phase 2 Bonus Checklist

  • Genetic Algorithm implementation
  • Weight optimization
  • Fitness evaluation
  • Population evolution
  • Crossover and mutation
  • Evolution tracking
  • Performance comparison

Customization

Adjusting Difficulty

Make Hero Stronger:

HERO_MAX_HP = 150        # More survivability
HERO_START_AMMO = 10     # More firepower
HERO_ATTACK_RANGE = 4    # Better range

Make Monsters Harder:

MONSTER_ATTACK_DMG = 30  # Higher damage
monsters = [(5,5), (6,6), (7,2), (4,4)]  # More monsters

Adjust AI Depth:

hero.depth_limit = 4     # Deeper search (slower but smarter)

Modifying Weights

Manual Weight Testing:

swarm = MonsterSwarm()
swarm.weights = [2.0, 0.5, 3.0]  # [Pursuit, Separation, Aggression]

GA Parameters:

ga = GeneticAlgorithm(
    population_size=30,      # Larger population
    generations=50,          # More evolution
    mutation_rate=0.2        # Higher mutation
)

Code Structure

Classes

GameState:

  • Grid management
  • Entity positions
  • Legal move generation
  • Visibility/fog of war
  • Shared perception updates

HeroAgent:

  • Minimax search
  • Alpha-beta pruning
  • Evaluation function
  • Action simulation
  • Terminal state checking

MonsterSwarm:

  • Utility calculation
  • Move selection
  • Cooperative behavior
  • Weight-based decision making

GeneticAlgorithm:

  • Population management
  • Fitness evaluation
  • Selection operators
  • Crossover and mutation
  • Evolution tracking

Troubleshooting

Simulation freezes:

  • Reduce hero depth_limit to 2
  • Reduce monster count
  • Check for infinite loops in evaluation function

GA too slow:

  • Reduce population_size to 15
  • Reduce generations to 20
  • Reduce num_trials in fitness function to 3

Hero always loses:

  • Increase HERO_MAX_HP
  • Decrease MONSTER_ATTACK_DMG
  • Increase HERO_START_AMMO

Monsters not coordinating:

  • Check swarm_knows_hero_pos is updating
  • Verify is_visible() function
  • Test different weight combinations

Expected Results

Typical Game Outcomes

Hero Victory:

  • Turns: 15-30
  • Requires: Good positioning, ammo management
  • Strategy: Avoid combat, prioritize objectives

Hero Defeat:

  • Turns: 10-20
  • Causes: Cornered by swarm, low HP, out of ammo

GA Optimization

Original Weights: [1.5, 0.8, 2.0]

  • Avg turns to eliminate: 25-35

Optimized Weights: ~[2.5, 0.4, 3.5] (example)

  • Avg turns to eliminate: 18-25
  • Improvement: ~20-30%

Report Writing Tips

Part 1: Implementation Analysis

Search Algorithms:

  1. Explain minimax recursion (max/min alternating)
  2. Show alpha-beta pruning with example
  3. Quantify pruning efficiency (% branches cut)

Evaluation Function:

  1. Write E(s) formula with actual weights
  2. Justify each component (why valuable?)
  3. Show example calculations for different states

Part 2: Neural Shift

Data Representation:

  • Tensor shape: (batch, height, width, channels)
  • Example: (1, 10, 10, 8) for 8 feature maps
  • Channels: Hero, Monsters, Gem, Exit, Walls, HP, Ammo, Fog

Network Architecture:

  • Input: Game state tensor
  • Shared backbone: Conv layers
  • Value Head: Predicts state value (replaces E(s))
  • Policy Head: Predicts action probabilities

Learning Paradigms:

  • Supervised: Train on expert games (minimax decisions)
  • Reinforcement: Self-play with rewards (+1 win, -1 loss)
  • Credit Assignment: How to attribute long-term outcomes to actions

Part 3: Reflection

Interpretability:

  • Heuristic: Can trace why each weight matters
  • Neural: Black box, requires attention/saliency maps

Adaptability:

  • Heuristic: Manual reweighting for rule changes
  • Neural: Automatic retraining on new data

References

  • Minimax: Russell & Norvig, AIMA Ch. 5
  • Alpha-Beta Pruning: Knuth & Moore (1975)
  • Genetic Algorithms: Goldberg (1989)
  • AlphaZero: Silver et al. (2018)
  • Utility-based Agents: AIMA Ch. 16

Extra Features Implemented

  1. Visual Clarity - Clear text-based visualization
  2. Turn Counter - Track game progress
  3. Detection Status - Show when hero is spotted
  4. Pruning Metrics - Performance monitoring
  5. Evolution Graphs - GA convergence visualization
  6. Weight Comparison - Before/after analysis
  7. Status Bar - Real-time game state info

Next Steps for Your Report

540A
  1. Run both files and collect screenshots
  2. Record metrics (nodes explored, turns, etc.)
  3. Analyze GA results - did it converge?
  4. Compare weights - what changed and why?
  5. Test edge cases - what happens with extreme weights?
  6. Document findings in your report

Good luck with your project!

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0