Skip to content

Instantly share code, notes, and snippets.

@Zwiebelkopf
Forked from jenslauterbach/dota2-random-hero.py
Last active December 10, 2015 23:38
Show Gist options
  • Save Zwiebelkopf/4511160 to your computer and use it in GitHub Desktop.
Save Zwiebelkopf/4511160 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import random
# heroes.txt file format: One hero per line
# Comments in players.txt & heroes.txt with # at first position
# players.txt file format: One player per line.
# <player_name>: <banned_hero_1>, <banned_hero_2>, ..., <banned_hero_n>
# global list of heroes and players
heroes = list()
players = dict()
def main():
""" Main method. Calls all the important methods. """
read_heroes_file()
read_players_file()
pick_heroes()
display_result()
def read_heroes_file():
""" Reads the heroes file and saves its content to the heroes list. """
with open('heroes.txt', 'r') as heroes_file:
for hero in heroes_file:
if hero[0:1] != "#":
heroes.append(hero.strip())
def read_players_file():
""" Reads the players file and saves its contet to the players list. """
with open('players.txt', 'r') as players_file:
for player in players_file:
if player[0:1] != "#":
player_name, banned_heroes_list = player.split(':')
banned_heroes = banned_heroes_list.split(',')
banned_heroes = [hero.strip() for hero in banned_heroes]
players[player_name] = {
'heroes': list(),
'banned_heroes': banned_heroes
}
def pick_heroes():
""" Picks two heroes for every player. """
# Randomize all player names. That way it's more fair.
player_names = players.keys()
random.shuffle(player_names)
# First round of drawings. Start at the front and iterate to the end.
for player_name in player_names:
pick_hero(player_name)
# Second round. This time iterate in reverse.
for player_name in reversed(player_names):
pick_hero(player_name)
def display_result():
""" Displays result on stdout. """
for player in players:
print "%s: %s" % (player, ', '.join(players[player]['heroes']))
def pick_hero(player_name):
""" Picks hero for the given player. Banned heroes are considered. """
while True: # iterate until a non-banned hero is found
hero = random.choice(heroes)
if hero not in players[player_name]['banned_heroes']:
# Hero is not banned by the player. Add him to his hero list
players[player_name]['heroes'].append(hero)
# Delete hero from the global hero list so it can't be drawn again.
del heroes[heroes.index(hero)]
break;
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment