Game Theory

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

1)Prisoner's diemma

code:

import numpy as np

def prisoner_dilemma(player1_action, player2_action):

if player1_action == 'cooperate' and player2_action == 'cooperate':

return (3, 3) # Both players cooperate, they both receive a moderate payoff

elif player1_action == 'cooperate' and player2_action == 'betray':

return (0, 5) # Player 1 is betrayed, Player 2 gets a high payoff

elif player1_action == 'betray' and player2_action == 'cooperate':

return (5, 0) # Player 2 is betrayed, Player 1 gets a high payoff

elif player1_action == 'betray' and player2_action == 'betray':

return (1, 1) # Both players betray, they both receive a low payoff

player1_action = np.random.choice(['cooperate', 'betray'])

player2_action = np.random.choice(['cooperate', 'betray'])

payoff_player1, payoff_player2 = prisoner_dilemma(player1_action, player2_action)

print(f"Player 1 chose: {player1_action}")

print(f"Player 2 chose: {player2_action}")

print(f"Payoff for Player 1: {payoff_player1}")

print(f"Payoff for Player 2: {payoff_player2}")

o/p:

Player 1 chose: cooperate

Player 2 chose: betray

Payoff for Player 1: 0

Payoff for Player 2: 5


2)Pure Strategy Nash Equilibrium

code:

!pip install scipy

import numpy as np

from scipy.optimize import linprog

payoff_matrix_player1 = np.array([[3, 1], [0, 2]])

payoff_matrix_player2 = np.array([[3, 0], [1, 2]])

c = [-1, -1] # Coefficients for the objective function (maximize)

A_eq = np.array([[1, -1]]) # Coefficients for equality constraints

b_eq = np.array([0]) # Right-hand side of equality constraints

result = linprog(c, A_eq=A_eq, b_eq=b_eq, bounds=[(0, None), (0, None)])

if result.success:

optimal_strategy_player1 = result.x[0]

optimal_strategy_player2 = result.x[1]

else:

print("The linear programming problem is infeasible.")

if result.success:

print("Pure Strategy Nash Equilibrium:")

print(f"Player 1's optimal strategy: {optimal_strategy_player1}")

print(f"Player 2's optimal strategy: {optimal_strategy_player2}")

print(result)

o/P:

The linear programming problem is infeasible.

message: The problem is unbounded. (HiGHS Status 10: model_status is Unbounded;


primal_status is At upper bound)

success: False

status: 3

fun: None

x: None
nit: 1

lower: residual: None

marginals: None

upper: residual: None

marginals: None

eqlin: residual: None

marginals: None

ineqlin: residual: None

marginals: None

3)Extensive Form-Graphs and Trees, Game Trees

Code:

from graphviz import Digraph

def create_game_tree():

game_tree = Digraph('GameTree')

game_tree.node('A', label='Player A', shape='ellipse')

game_tree.node('B', label='Player B', shape='ellipse')

game_tree.node('C', label='Outcome C', shape='box')

game_tree.node('D', label='Outcome D', shape='box')

game_tree.edge('A', 'B', label='Action 1')

game_tree.edge('A', 'C', label='Action 2')

game_tree.edge('B', 'D', label='Action 3')

return game_tree

game_tree = create_game_tree()

game_tree.render('game_tree', format='png', cleanup=True, view=True)

o/p

game_tree.png
4)Strategic Form-Elimination of dominant strategy

code:

import numpy as np

game_matrix = np.array([[3, 2, 5],

[1, 4, 6],

[0, 3, 2]])

def eliminate_dominant_strategy(matrix):

rows, cols = matrix.shape

for row in range(rows):

for other_row in range(rows):

if all(matrix[row, col] >= matrix[other_row, col] for col in range(cols)) and row != other_row:

matrix = np.delete(matrix, other_row, axis=0)

rows -= 1

return eliminate_dominant_strategy(matrix)

for col in range(cols):

for other_col in range(cols):

if all(matrix[row, col] >= matrix[row, other_col] for row in range(rows)) and col != other_col:

matrix = np.delete(matrix, other_col, axis=1)

cols -= 1

return eliminate_dominant_strategy(matrix)

return matrix

result_matrix = eliminate_dominant_strategy(game_matrix)

print("Original Game Matrix:")

print(game_matrix)

print("\nAfter Eliminating Dominant Strategies:")

print(result_matrix)
o/p

Original Game Matrix:

[[3 2 5]

[1 4 6]

[0 3 2]]

After Eliminating Dominant Strategies:

[[6]]

5)Minimax theorem, minimax strategies

code:

import numpy as np

def find_minimax_strategy(game_matrix):

row_minima = np.min(game_matrix, axis=1)

max_of_minima = np.max(row_minima)

minimax_strategy_indices = np.where(row_minima == max_of_minima)[0]

minimax_strategy = np.zeros(len(row_minima))

minimax_strategy[minimax_strategy_indices] = 1 / len(minimax_strategy_indices)

return minimax_strategy

game_matrix = np.array([[3, 2],

[1, 4]])

minimax_strategy = find_minimax_strategy(game_matrix)

print("Game Matrix:")

print(game_matrix)

print("\nMinimax Strategy:")

print(minimax_strategy)
o/p

Game Matrix:

[[3 2]

[1 4]]

Minimax Strategy:

[1. 0.]

6)Perfect information games, trees, players assigned to nodes, payoffs, backward Induction,
subgame perfect equilibrium.

code:

pip install nashpy graphviz

import nashpy as nash

import numpy as np

import graphviz

game_matrix = np.array([[4, 3], [1, 2]])

game = nash.Game(game_matrix)

equilibria = game.support_enumeration()

equilibrium = list(equilibria)[0]

print("Nash Equilibrium:")

print(equilibrium)

def create_game_tree():

dot = graphviz.Digraph('GameTree', node_attr={'shape': 'ellipse'})

dot.node('A', label='Player 1')

dot.node('B', label='Player 2')


dot.edge('A', 'B', label=f'{equilibrium[0][0]}\n{equilibrium[1][0]}')

dot.edge('A', 'B', label=f'{equilibrium[0][1]}\n{equilibrium[1][1]}')

return dot

game_tree = create_game_tree()

game_tree.render('game_tree', format='png', cleanup=True, view=True)

o/p

Nash Equilibrium:

(array([1., 0.]), array([0., 1.]))

game_tree.png

7) imperfect-information games Mixed Strategy Nash Equilibrium Finding mixed-strategy Nash


equilibria for zero sum games, mixed versus behavioral strategies.

code:

!pip install nashpy

import nashpy as nash

a=2

b=1

c=0

d=3

A = np.array([[a, b],

[c, d]])

B = -np.transpose(A)

game = nash.Game(A, B)
equilibria = game.support_enumeration()

print("Mixed Strategy Nash Equilibrium:")

for eq in equilibria:

player1_strategy, player2_strategy = eq

print("Player 1's mixed strategy:", player1_strategy)

print("Player 2's mixed strategy:", player2_strategy)

print()

o/p

Mixed Strategy Nash Equilibrium:

Player 1's mixed strategy: [0.5 0.5]

Player 2's mixed strategy: [0.5 0.5]

8)Repeated Games

import numpy as np

def prisoner_dilemma(player1_action, player2_action):

if player1_action == 'cooperate' and player2_action == 'cooperate':

return (3, 3) # Both players cooperate, they both receive a moderate payoff

elif player1_action == 'cooperate' and player2_action == 'betray':

return (0, 5) # Player 1 is betrayed, Player 2 gets a high payoff

elif player1_action == 'betray' and player2_action == 'cooperate':

return (5, 0) # Player 2 is betrayed, Player 1 gets a high payoff

elif player1_action == 'betray' and player2_action == 'betray':

return (1, 1) # Both players betray, they both receive a low payoff

def play_repeated_game(num_rounds):

total_payoff_player1 = 0

total_payoff_player2 = 0
for _ in range(num_rounds):

player1_action = np.random.choice(['cooperate', 'betray'])

player2_action = np.random.choice(['cooperate', 'betray'])

payoff_player1, payoff_player2 = prisoner_dilemma(player1_action, player2_action)

total_payoff_player1 += payoff_player1

total_payoff_player2 += payoff_player2

average_payoff_player1 = total_payoff_player1 / num_rounds

average_payoff_player2 = total_payoff_player2 / num_rounds

return average_payoff_player1, average_payoff_player2

num_rounds = 10

average_payoff_player1, average_payoff_player2 = play_repeated_game(num_rounds)

print(f"Average Payoff for Player 1 over {num_rounds} rounds: {average_payoff_player1}")

print(f"Average Payoff for Player 2 over {num_rounds} rounds: {average_payoff_player2}")

o/p

Average Payoff for Player 1 over 10 rounds: 2.3

Average Payoff for Player 2 over 10 rounds: 2.8


9)Bayesian Nash equilibrium

code:

import numpy as np

from scipy.optimize import minimize

def player1_utility(x, y):

return -x**2 - y**2

def player2_utility(x, y):

return -2*x**2 - y**2

def joint_utility(x, y):

return player1_utility(x, y) + player2_utility(x, y)

def neg_joint_utility(params):

return -joint_utility(params[0], params[1])

initial_guess = np.array([0, 0])

result = minimize(neg_joint_utility, initial_guess, method='SLSQP')

equilibrium = result.x

print("Bayesian Nash Equilibrium:", equilibrium)

o/p

Bayesian Nash Equilibrium: [0. 0.]

You might also like