9 boxes
= {'human?': False}
10 for b
in range(1, INITIAL_GAME_SIZE
+1):
11 box
= collections
.Counter()
12 for i
in range(1, MAX_TAKE
+1):
14 box
[i
] = INITIAL_BEAD_COUNT
19 return random
.choice(list(box
.elements()))
22 return {'human?': True}
26 print('Opponent took', game
['history'][-1]['move'], 'pieces.')
28 print('You play first.')
29 print('There are', game
['tokens'], 'pieces left.')
31 max_move
= min(MAX_TAKE
, game
['tokens'])
34 while not valid_input
:
35 user_input
= input('Your move (1-{})? '.format(max_move
))
36 if user_input
.isnumeric():
37 move
= int(user_input
)
38 if move
in range(1, max_move
+1):
41 print('Number not a valid move.')
43 print('Please enter a number.')
46 def new_game(player1
, player2
):
47 return {'tokens': INITIAL_GAME_SIZE
,
50 'player1_active': True,
53 def game_finished(game
):
54 return game
['tokens'] == 0
57 if game
['history'][-1]['player1?']:
58 return game
['player2']
60 return game
['player1']
63 if game
['history'][-1]['player1?']:
64 return game
['player1']
66 return game
['player2']
70 if game
['player1_active']:
71 active
= game
['player1']
73 active
= game
['player2']
75 move
= human_move(game
)
77 move
= menace_move(active
[game
['tokens']])
78 game
['history'] += [{'player1?': game
['player1_active'], 'move': move
, 'tokens': game
['tokens']}]
79 game
['tokens'] -= move
80 game
['player1_active'] = not game
['player1_active']
83 while not game_finished(game
):
86 def winning_moves(game
):
88 player1_won
= game
['history'][-1]['player1?']
89 for m
in game
['history']:
90 if m
['player1?'] != player1_won
:
94 def losing_moves(game
):
96 player1_won
= game
['history'][-1]['player1?']
97 for m
in game
['history']:
98 if m
['player1?'] == player1_won
:
102 def update_winner(game
):
103 player
= winner(game
)
104 moves
= winning_moves(game
)
106 player
[m
['tokens']][m
['move']] += 1
108 def update_loser(game
, allow_drop_move
=False):
110 moves
= losing_moves(game
)
113 if len(list(player
[m
['tokens']].elements())) > 1:
114 player
[m
['tokens']][m
['move']] -= 1
116 if player
[m
['tokens']][m
['move']] > 1:
117 player
[m
['tokens']][m
['move']] -= 1
120 def game_with_players(p1
, p2
, report_result_for
=None):
121 if random
.choice([True, False]):
126 if report_result_for
:
127 if winner(g
) == report_result_for
:
133 def train_players(p1
, p2
, rounds
=10000, allow_drop_move
=False):
134 for _
in range(rounds
):
135 g
= game_with_players(p1
, p2
)
137 update_loser(g
, allow_drop_move
=allow_drop_move
)