Empirical
PayoffMatrix.h
Go to the documentation of this file.
1 // This file is part of Empirical, https://github.com/devosoft/Empirical
2 // Copyright (C) Michigan State University, 2016-2017.
3 // Released under the MIT Software license; see doc/LICENSE
4 //
5 //
6 // A simple game theory payoff matrix.
7 
8 
9 #ifndef EMP_GAME_PAYOFF_MATRIX_H
10 #define EMP_GAME_PAYOFF_MATRIX_H
11 
12 #include "../base/array.h"
13 
14 namespace emp {
15 
16  // A simple payoff matrix for a symmetric two-player game.
17  class PayoffMatrix {
18  private:
19  emp::vector<double> payoff;
20  size_t num_moves;
21 
22  constexpr size_t to_index(size_t A, size_t B) const { return A * num_moves + B; }
23  public:
24  PayoffMatrix(size_t _moves=2) : num_moves(_moves) {
25  const size_t combos = num_moves * num_moves;
26  payoff.resize(combos);
27  }
28 
29  using move_t = size_t;
30 
31  void Reset() { ; } // No history...
32 
33  void SetVal(size_t self, size_t other, double value) { payoff[to_index(self,other)] = value; }
34  double & operator()(size_t A, size_t B) { return payoff[to_index(A,B)]; }
35  double operator()(size_t A, size_t B) const { return payoff[to_index(A,B)]; }
36 
37  // Setup a Prisoner's Dilema Payoff Matrix
38  void SetupPD(double u) {
39  payoff[to_index(0,0)] = u; // Both defect
40  payoff[to_index(0,1)] = 1.0 + u; // Player defects, other cooperates
41  payoff[to_index(1,0)] = 0.0; // Player cooperates, other defects
42  payoff[to_index(1,1)] = 1.0; // Both cooperate
43  }
44 
45  void SetupSnowdrift(double cost) {
46  payoff[to_index(0,0)] = 0; // Both defect -- trapped in snowdrift
47  payoff[to_index(0,1)] = 1.0; // Player defects, other digs out alone.
48  payoff[to_index(1,0)] = 1.0 - cost; // Player digs out by themself.
49  payoff[to_index(1,1)] = 1.0 - cost/2; // Both dig out together and share cost.
50  }
51 
52  std::unordered_map<int, double> AsInput(size_t player_id) const {
53  std::unordered_map<int, double> out_map;
54  out_map[-1] = num_moves;
55  for (size_t i = 0; i < payoff.size(); i++) {
56  out_map[i] = payoff[i];
57  }
58  return out_map;
59  }
60 
61  };
62 
63 }
64 
65 #endif
std::unordered_map< int, double > AsInput(size_t player_id) const
Definition: PayoffMatrix.h:52
void SetupPD(double u)
Definition: PayoffMatrix.h:38
double operator()(size_t A, size_t B) const
Definition: PayoffMatrix.h:35
void SetVal(size_t self, size_t other, double value)
Definition: PayoffMatrix.h:33
Definition: PayoffMatrix.h:17
size_t size() const
Definition: vector.h:151
void Reset()
Definition: PayoffMatrix.h:31
void SetupSnowdrift(double cost)
Definition: PayoffMatrix.h:45
void resize(size_t new_size)
Definition: vector.h:161
double & operator()(size_t A, size_t B)
Definition: PayoffMatrix.h:34
If we are in emscripten, make sure to include the header.
Definition: array.h:37
PayoffMatrix(size_t _moves=2)
Definition: PayoffMatrix.h:24
size_t move_t
Definition: PayoffMatrix.h:29