tpemartin / 112-2-programming-for-economic-modeling

MIT License
0 stars 1 forks source link

Exercise Another Game User Interface #15

Open tpemartin opened 1 year ago

tpemartin commented 1 year ago

For the following 2-player normal form game,

C D
C -1, -1 -3, 0
D 0, -3 -2, -2

We want to usage interface as

payoffMatrix1 = [[-1, -3],[0, -2]]
payoffMatrix2 = [[-1, 0],[-3, -2]]

player1 = Player("Alice", ['C', 'D'])
player2 = Player("Bob", ['C', 'D'])

game = Game([player1, player2], [payoffMatrix1, payoffMatrix2])

player1.play('C')
player2.play('D')
game.payoff()

Design Game and Player Class accordingly

aryhsg commented 1 year ago
class Player:
    def __init__(self, player, strategy):
        self.player = player
        self.strategy = strategy
        self.played_strategy = None

    def play(self, played_strategy):
        play_funtion(self, played_strategy)

def play_funtion(player, played_strategy):
    player.played_strategy = played_strategy

class Game:
    def __init__(self, players: list, player_matrix: list):
        self.players = players
        self.player_matrix = player_matrix

    def payoff(self):
        strategy_indices = {'C': 0, 'D': 1}
        p1_payoff = strategy_indices[self.players[0].played_strategy]
        p2_payoff = strategy_indices[self.players[1].played_strategy]

        payoff = (payoffMatrix1[p1_payoff][p2_payoff], payoffMatrix2[p1_payoff][p2_payoff])
        return payoff

player1 = Player("Alice", ['C', 'D'])
player2 = Player("Bob", ['C', 'D'])

payoffMatrix1 = [[-1, -3],[0, -2]]
payoffMatrix2 = [[-1, 0],[-3, -2]]

game = Game([player1, player2], [payoffMatrix1, payoffMatrix2])
player1.play('D')
player2.play('C')
print(game.payoff())
tpemartin commented 1 year ago
class Game:
    def __init__(self, players: list, player_matrix: list):
        self.players = players
        self.player_matrix = player_matrix

    def payoff(self):
        strategy_indices = {'C': 0, 'D': 1}
        p1_payoff = strategy_indices[self.players[0].played_strategy]
        p2_payoff = strategy_indices[self.players[1].played_strategy]
        payoffMatrix1 = self.player_matrix[0]
        payoffMatrix2 = self.player_matrix[1]
        payoff = (payoffMatrix1[p1_payoff][p2_payoff], payoffMatrix2[p1_payoff][p2_payoff])
        return payoff