Skip to content

Instantly share code, notes, and snippets.

@romovpa
Last active September 5, 2017 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romovpa/a96b2d2622a3a4a014ea2fb6256445ab to your computer and use it in GitHub Desktop.
Save romovpa/a96b2d2622a3a4a014ea2fb6256445ab to your computer and use it in GitHub Desktop.
Запуск серии игр агента против 8 random-ботов
#!/usr/bin/env python
import sys
if __name__ == '__main__':
while True:
line = sys.stdin.readline().rstrip()
if not line:
break
event_type, data = line.split('\t', 1)
if event_type == 'declare_action':
sys.stdout.write('fold\t0\n')
sys.stdout.flush()
import os
import sys
import json
import subprocess
import datetime
import random
from pypokerengine.players import BasePokerPlayer
from pypokerengine.api.game import setup_config, start_poker
from pypokerengine.utils.card_utils import gen_cards, estimate_hole_card_win_rate
class RandomPlayer(BasePokerPlayer):
def __init__(self):
self.fold_ratio = self.call_ratio = raise_ratio = 1.0 / 3
def set_action_ratio(self, fold_ratio, call_ratio, raise_ratio):
ratio = [fold_ratio, call_ratio, raise_ratio]
scaled_ratio = [1.0 * num / sum(ratio) for num in ratio]
self.fold_ratio, self.call_ratio, self.raise_ratio = scaled_ratio
def declare_action(self, valid_actions, hole_card, round_state):
choice = self.__choice_action(valid_actions)
action = choice["action"]
amount = choice["amount"]
if action == "raise":
amount = random.randrange(amount["min"], max(amount["min"], amount["max"]) + 1)
return action, amount
def __choice_action(self, valid_actions):
r = random.random()
if r <= self.fold_ratio:
return valid_actions[0]
elif r <= self.call_ratio:
return valid_actions[1]
else:
return valid_actions[2]
def receive_game_start_message(self, game_info):
pass
def receive_round_start_message(self, round_count, hole_card, seats):
pass
def receive_street_start_message(self, street, round_state):
pass
def receive_game_update_message(self, new_action, round_state):
pass
def receive_round_result_message(self, winners, hand_info, round_state):
pass
class ExternalExecutablePlayer(BasePokerPlayer):
def __init__(self, cmd):
self.process = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
self.executable_input = self.process.stdin
self.executable_output = self.process.stdout
def _read_answer(self):
answer_line = self.executable_output.readline().decode('utf8')
answer_parts = answer_line.rstrip().split('\t')
return answer_parts
def _write_event(self, event_type, data):
event_line = '{event_type}\t{data}\n'.format(
event_type=event_type,
data=json.dumps(data),
)
self.executable_input.write(event_line.encode('utf8'))
self.executable_input.flush()
def declare_action(self, valid_actions, hole_card, round_state):
data = {
'valid_actions': valid_actions,
'hole_card': hole_card,
'round_state': round_state,
}
self._write_event('declare_action', data)
answer_parts = self._read_answer()
if len(answer_parts) != 2:
raise RuntimeError('Bad executable declare_action answer')
action, amount = answer_parts
amount = int(amount)
return action, amount
def receive_game_start_message(self, game_info):
game_info['uuid'] = self.uuid
self._write_event('game_start', game_info)
def receive_round_start_message(self, round_count, hole_card, seats):
data = {
'round_count': round_count,
'hole_card': hole_card,
'seats': seats,
}
self._write_event('round_start', data)
def receive_street_start_message(self, street, round_state):
data = {
'street': street,
'round_state': round_state,
}
self._write_event('street_start', data)
def receive_game_update_message(self, new_action, round_state):
data = {
'new_action': new_action,
'round_state': round_state,
}
self._write_event('game_update', data)
def receive_round_result_message(self, winners, hand_info, round_state):
data = {
'winners': winners,
'hand_info': hand_info,
'round_state': round_state,
}
self._write_event('round_result', data)
if __name__ == '__main__':
start_time = datetime.datetime.now()
# choose here your strategy
player = ExternalExecutablePlayer('python external_agent.py')
config = setup_config(max_round=50, initial_stack=1500, small_blind_amount=15)
config.register_player(name='Participant', algorithm=player)
for i in range(8):
config.register_player(name='Random {}'.format(i), algorithm=RandomPlayer())
num_games = 30
game_scores = []
for game_no in range(num_games):
game_result = start_poker(config, verbose=0)
participant_result = game_result['players'][0]
game_scores.append(participant_result['stack'])
print('Game #{}: stack={}, state={}'.format(
game_no,
participant_result['stack'],
participant_result['state'],
))
print('Elapsed time: {}'.format(datetime.datetime.now() - start_time))
print('Score: {}'.format(sum(game_scores) / num_games))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment