<s> '''<STR_LIT>''' <EOL> from mesa import Agent , Model <EOL> from mesa . datacollection import DataCollector <EOL> from mesa . time import BaseScheduler , RandomActivation , SimultaneousActivation <EOL> from mesa . space import SingleGrid <EOL> import random <EOL> class PD_Agent ( Agent ) : <EOL> def __init__ ( self , pos , starting_move = None ) : <EOL> '''<STR_LIT>''' <EOL> self . pos = pos <EOL> self . score = <NUM_LIT:0> <EOL> if starting_move : <EOL> self . move = starting_move <EOL> else : <EOL> self . move = random . choice ( [ "<STR_LIT:C>" , "<STR_LIT:D>" ] ) <EOL> self . next_move = None <EOL> def step ( self , model ) : <EOL> '''<STR_LIT>''' <EOL> neighbors = model . grid . get_neighbors ( self . pos , True , <EOL> include_center = True ) <EOL> best_neighbor = max ( neighbors , key = lambda a : a . score ) <EOL> self . next_move = best_neighbor . move <EOL> if model . schedule_type != "<STR_LIT>" : <EOL> self . advance ( model ) <EOL> def advance ( self , model ) : <EOL> self . move = self . next_move <EOL> self . score += self . increment_score ( model ) <EOL> def increment_score ( self , model ) : <EOL> neighbors = model . grid . get_neighbors ( self . pos , True ) <EOL> if model . schedule_type == "<STR_LIT>" : <EOL> moves = [ neighbor . next_move for neighbor in neighbors ] <EOL> else : <EOL> moves = [ neighbor . move for neighbor in neighbors ] <EOL> return sum ( model . payoff [ ( self . move , move ) ] for move in moves ) <EOL> class PD_Model ( Model ) : <EOL> '''<STR_LIT>''' <EOL> schedule_types = { "<STR_LIT>" : BaseScheduler , <EOL> "<STR_LIT>" : RandomActivation , <EOL> "<STR_LIT>" : SimultaneousActivation } <EOL> payoff = { ( "<STR_LIT:C>" , "<STR_LIT:C>" ) : <NUM_LIT:1> , <EOL> ( "<STR_LIT:C>" , "<STR_LIT:D>" ) : <NUM_LIT:0> , <EOL> ( "<STR_LIT:D>" , "<STR_LIT:C>" ) : <NUM_LIT> , <EOL> ( "<STR_LIT:D>" , "<STR_LIT:D>" ) : <NUM_LIT:0> } <EOL> def __init__ ( self , height , width , schedule_type , payoffs = None ) : <EOL> '''<STR_LIT>''' <EOL> self . running = True <EOL> self . grid = SingleGrid ( height , width , torus = True ) <EOL> self . schedule_type = schedule_type <EOL> self . schedule = self . schedule_types [ self . schedule_type ] ( self ) <EOL> for x in range ( width ) : <EOL> for y in range ( height ) : <EOL> agent = PD_Agent ( ( x , y ) ) <EOL> self . grid . place_agent ( agent , ( x , y ) ) <EOL> self . schedule . add ( agent ) <EOL> self . datacollector = DataCollector ( { "<STR_LIT>" : <EOL> lambda m : len ( [ a for a in m . schedule . agents if a . move == "<STR_LIT:C>" ] ) } ) <EOL> def step ( self ) : <EOL> self . datacollector . collect ( self ) <EOL> self . schedule . step ( ) <EOL> def run ( self , n ) : <EOL> '''<STR_LIT>''' <EOL> for _ in range ( n ) : <EOL> self . step ( ) </s>
