Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
from __future__ import print_function
from itertools import chain
import random
R = random.Random('the game')
def run_game(players, turns, rounds, starting_clones):
# in the game function, players are represented by their index in
# the players list.
population = list(range(len(players))) * starting_clones
for i in range(rounds):
# in a round, run each pair
scores = [0]*len(players)
for player_a_index in population:
for player_b_index in population:
score_a, score_b = run_pairing(
scores[player_a_index] += score_a
scores[player_b_index] += score_b
print_round_info(players, scores, population, i)
# rebalance population
n = len(population)
all_score = sum(scores)
if 1 == len(set(population)):
# could have pop changes due to rounding by truncation
new_counts = [(n*scores[i])//all_score for i in range(len(players))]
population = [i for i in range(len(players)) for _ in range(new_counts[i])]
def print_round_info(players, scores, population, round):
print("round%5d player score score%% count" % round)
for i in range(len(players)):
print(" %15s%15d%9.2f%10d" % (
players[i].__name__, scores[i], 100 * scores[i] / sum(scores),
def run_pairing(player_a, player_b, turns):
points_a = 0
points_b = 0
history_a = []
history_b = []
# play the games and create the history of moves
for round in range(turns):
history_a.append(player_a(history_a, history_b))
history_b.append(player_b(history_b, history_a))
# return (score_a, score_b)
return (player_score(history_a, history_b),
player_score(history_b, history_a))
def player_score(player_moves, opponent_moves):
ans = 0
for i in range(len(player_moves)):
if 5 >= (player_moves[i] + opponent_moves[i]):
ans += player_moves[i]
return ans
# a player functions takes 2 arguments, lists of integers with the
# same length
# - your moves history
# - their moves history
def random0to5(a, b):
return R.randint(0,5)
def random2to3(a, b):
return R.randint(2,3)
def meanie(a, b):
return 5
def weakling(a, b):
return 0
the_players = [
the_turns = 100
the_rounds = 100
the_starting_clones = 50
run_game(the_players, the_turns, the_rounds, the_starting_clones)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.