Game Theory - CSU083 | Shoolini University

Game Theory

1. Prerequisites

Before diving into game theory, it's essential to understand the following concepts:

2. What is Game Theory?

Game theory is the mathematical study of strategic interactions where multiple decision-makers (players) influence outcomes.

2.1 Key Components

2.2 Types of Games

3. Why Does Game Theory Exist?

Game theory models strategic decision-making in competitive and cooperative environments.

3.1 Economics & Business

3.2 Politics & Social Sciences

3.3 Cybersecurity

3.4 Artificial Intelligence

4. When Should You Use Game Theory?

Game theory is most effective when:

5. How Does Game Theory Compare to Alternatives?

5.1 Strengths

5.2 Weaknesses

5.3 Alternative Approaches

6. Basic Implementation

Let's implement a basic game theory example using the Prisoner's Dilemma in Python.

6.1 Prisoner's Dilemma

Two prisoners are caught and interrogated separately. Each prisoner can either Cooperate (C) or Defect (D). The payoff matrix is as follows:

"
Prisoner A / Prisoner B Cooperate (C) Defect (D)
Cooperate (C) (-1, -1) (-3, 0)
Defect (D) (0, -3) (-2, -2)

We simulate the game for two players deciding randomly between Cooperate or Defect.

import random

# Payoff Matrix (A, B)
payoff_matrix = {
    ('C', 'C'): (-1, -1),
    ('C', 'D'): (-3, 0),
    ('D', 'C'): (0, -3),
    ('D', 'D'): (-2, -2)
}

# Players' possible actions
actions = ['C', 'D']

# Simulating a round of the Prisoner's Dilemma
def play_prisoners_dilemma():
    player_A = random.choice(actions)
    player_B = random.choice(actions)
    payoff = payoff_matrix[(player_A, player_B)]
    
    print(f"Player A chooses: {player_A}")
    print(f"Player B chooses: {player_B}")
    print(f"Payoff: Player A = {payoff[0]}, Player B = {payoff[1]}")

# Run the simulation
play_prisoners_dilemma()

7. Dry Run

7.1 Input and Initialization

7.2 Step-by-Step Execution

Let's assume the following random choices:

7.3 Variable Tracking

"
Step Variable Value Explanation
1 player_A 'C' Random choice for Player A
2 player_B 'D' Random choice for Player B
3 payoff (-3, 0) Fetched from payoff_matrix based on (C, D)
4 Output Player A = -3, Player B = 0 Final result displayed

7.4 Example Output


Player A chooses: C
Player B chooses: D
Payoff: Player A = -3, Player B = 0

This dry run illustrates how payoffs are determined dynamically using game theory logic.

8. Time & Space Complexity Analysis

Analyzing the complexity of Game Theory algorithms depends on the type of game and the approach used. Let's analyze the complexity of a basic game simulation, like the Prisoner's Dilemma and extend it to more complex scenarios.

8.1 Time Complexity

For the Prisoner's Dilemma:

Overall Complexity: O(1) (constant time), since the number of players and choices are fixed.

For N-player strategic games (e.g., Nash Equilibrium in general games):

8.2 Best, Worst, and Average Case

9. Space Complexity Analysis

Space consumption varies depending on how the game is represented:

9.1 Space Complexity for Prisoner’s Dilemma

9.2 Space Complexity for N-Player Games

Trade-off: As N increases, storing possible game states becomes infeasible, requiring approximation techniques.

10. Trade-offs in Game Theory Computation

Choosing the right game theory approach depends on:

10.1 Time vs. Accuracy Trade-off

10.2 Space vs. Performance Trade-off

10.3 Computation Feasibility

Understanding these trade-offs helps optimize game theory models for real-world decision-making.

11. Optimizations & Variants

Game theory algorithms can be computationally expensive. Optimizations help reduce complexity and improve performance.

11.1 Common Optimizations

11.2 Variants of Game Theory Algorithms

12. Iterative vs. Recursive Implementations (Efficiency Comparison)

Game Theory problems, especially those solved using the Minimax Algorithm, can be implemented using both recursion and iteration.

12.1 Recursive Minimax Algorithm

A recursive implementation is easier to write but can be inefficient due to deep recursive calls.

def minimax(depth, is_maximizing, scores):
    if depth == len(scores):  # Base case
        return scores[depth - 1]

    if is_maximizing:
        return max(minimax(depth + 1, False, scores), minimax(depth + 1, False, scores))
    else:
        return min(minimax(depth + 1, True, scores), minimax(depth + 1, True, scores))

# Example usage
scores = [3, 5, 2, 9]  # Terminal node values
result = minimax(0, True, scores)
print(result)

12.2 Iterative Minimax Algorithm

By using explicit stacks, we avoid deep recursion.

def iterative_minimax(scores):
    while len(scores) > 1:
        scores = [max(scores[i], scores[i+1]) if i % 2 == 0 else min(scores[i], scores[i+1]) for i in range(0, len(scores)-1, 2)]
    return scores[0]

scores = [3, 5, 2, 9]
print(iterative_minimax(scores))

12.3 Comparison

"
Aspect Recursive Iterative
Time Complexity O(2^N) (Exponential) O(N) (Linear)
Space Complexity O(N) (Stack Depth) O(1) (Constant)
Performance Slower due to repeated evaluations Faster due to in-place modifications
Ease of Implementation Easier to understand Requires explicit stack handling

12.4 When to Use Each?

13. Edge Cases & Failure Handling

Game theory models rely on assumptions that can fail in real-world scenarios. Identifying edge cases and handling failures ensures robustness.

13.1 Common Edge Cases

13.2 Failure Handling Mechanisms

14. Test Cases to Verify Correctness

We validate a game theory implementation by testing key scenarios.

14.1 Test Cases for Prisoner's Dilemma


import unittest
import random

# Sample Prisoner's Dilemma Function
def get_payoff(action_A, action_B):
    payoff_matrix = {
        ('C', 'C'): (-1, -1),
        ('C', 'D'): (-3, 0),
        ('D', 'C'): (0, -3),
        ('D', 'D'): (-2, -2)
    }
    return payoff_matrix.get((action_A, action_B), None)

class TestGameTheory(unittest.TestCase):
    
    def test_valid_payoff(self):
        self.assertEqual(get_payoff('C', 'C'), (-1, -1))
        self.assertEqual(get_payoff('C', 'D'), (-3, 0))
        self.assertEqual(get_payoff('D', 'C'), (0, -3))
        self.assertEqual(get_payoff('D', 'D'), (-2, -2))
        
    def test_invalid_inputs(self):
        self.assertIsNone(get_payoff('X', 'D'))  # Invalid action
        self.assertIsNone(get_payoff('C', 'X'))  # Invalid action
    
    def test_randomized_actions(self):
        actions = ['C', 'D']
        action_A = random.choice(actions)
        action_B = random.choice(actions)
        self.assertIn(get_payoff(action_A, action_B), [(-1, -1), (-3, 0), (0, -3), (-2, -2)])

if __name__ == "__main__":
    unittest.main()

This test suite ensures:

15. Understanding Real-World Failure Scenarios

Despite theoretical robustness, game theory models can fail in real-world applications.

15.1 Real-World Failure Scenarios

15.2 Handling Failures

Understanding these failure scenarios ensures game theory is applied effectively in real-world decision-making.

16. Real-World Applications & Industry Use Cases

Game theory is widely used in various industries to optimize decision-making in competitive and cooperative environments.

16.1 Economics & Business

16.2 Cybersecurity

16.3 Artificial Intelligence & Machine Learning

16.4 Healthcare & Medicine

16.5 Politics & Military Strategy

17. Open-Source Implementations

Several open-source libraries provide game theory algorithms:

17.1 Open-Source Python Libraries

17.2 Example: Nashpy for Nash Equilibrium

Nashpy is a simple library for finding Nash Equilibrium in two-player games.


import nashpy as nash
import numpy as np

# Define payoff matrices for two players
A = np.array([[3, 1], [5, 2]])  # Player A
B = np.array([[3, 5], [1, 2]])  # Player B

# Create the game
game = nash.Game(A, B)

# Compute Nash Equilibria
equilibria = game.support_enumeration()
for eq in equilibria:
    print(f"Nash Equilibrium: {eq}")

18. Practical Project: Game Theory-Based Auction System

Let's implement a simplified auction system where multiple bidders compete for an item.

18.1 Project Overview

This auction system follows a sealed-bid, first-price auction model where the highest bidder wins.

18.2 Implementation


import random

class Auction:
    def __init__(self, players, reserve_price):
        self.players = players  # List of players
        self.reserve_price = reserve_price  # Minimum acceptable bid

    def run_auction(self):
        bids = {player: random.randint(1, 100) for player in self.players}
        print(f"Bids: {bids}")

        # Determine winner
        highest_bidder = max(bids, key=bids.get)
        highest_bid = bids[highest_bidder]

        if highest_bid >= self.reserve_price:
            print(f"Winner: {highest_bidder} with bid {highest_bid}")
        else:
            print("No winner: All bids were below reserve price.")

# Run the auction
players = ["Alice", "Bob", "Charlie", "David"]
auction = Auction(players, reserve_price=50)
auction.run_auction()

18.3 Explanation

18.4 Example Output


Bids: {'Alice': 45, 'Bob': 72, 'Charlie': 60, 'David': 50}
Winner: Bob with bid 72

This simple project showcases how game theory principles apply to real-world auctions.

19. Competitive Programming & System Design Integration

19.1 Game Theory in Competitive Programming

Game theory-based problems frequently appear in programming contests like Codeforces, LeetCode, and CodeChef. Common patterns include:

19.2 System Design Use Cases

Game theory is crucial in system design, especially in:

Example: Google's PageRank algorithm has elements of game theory in determining how webpages interact strategically for ranking.

20. Assignments

20.1 Solve at Least 10 Problems Using Game Theory

Try solving these problems on competitive programming platforms:

  1. Game of Nim (Grundy Numbers).
  2. Optimal Tic-Tac-Toe Strategy (Minimax).
  3. Winning at a Coin Game (Dynamic Programming).
  4. Chess AI Move Predictor (Alpha-Beta Pruning).
  5. Rock-Paper-Scissors Nash Equilibrium.
  6. First-Price Auction Bidding Strategy.
  7. Two-Player Turn-Based Game.
  8. Zero-Sum Game Optimal Play.
  9. Monte Carlo Tree Search for a Simple Game.
  10. Network Attack-Defense Strategy Model.

20.2 Use Game Theory in a System Design Problem

Design a system that uses game theory principles. Some example projects:

20.3 Practice Implementing It Under Time Constraints

To improve speed in competitive programming, follow these steps:

Mastering game theory in competitive programming and system design will help in real-world problem-solving and interviews.