示例#1
0
def main():
    players = []
    player_csv = "FantasyPros_2020_Draft_Overall_Rankings.csv"
    position = 6
    name = "vinny"
    n_rosters = 8
    with open("user_cfg.cfg",'r') as f:
        for line in f:
            if line.startswith("CSVFILE"):
                player_csv = line.split("=", 1)[1].strip()
            elif line.startswith("PORT"):
                port = int(line.split("=", 1)[1], 10)
            elif line.startswith("DRAFTPOSITION"):
                position = int(line.split("=", 1)[1], 10)
            elif line.startswith("N_TEAMS"):
                n_rosters = int(line.split("=", 1)[1], 10)
            elif line.startswith("TEAM_NAME"):
                name = line.split("=", 1)[1].strip()
            elif line.startswith("SERVER_ADDRESS"):
                ip = line.split("=", 1)[1].split(",", 1)[0].strip()
                send_port = int(line.split("=", 1)[1].split(",", 1)[1], 10)
                send_address = (ip, send_port)

    with open(player_csv,'r') as f:
        f.__next__()
        for line in f:
            player = player_generate_fromcsv(line)
            if player != None:
                players.append(player)

    draft = Draft(position, name, players, n_rosters, player_csv)
    txqueue = Queue()
    keyboard_rxqueue = Queue()
    threadpool = []

    server_thr = ServerThread(port, keyboard_rxqueue, txqueue, draft, send_address)

    threadpool.append(server_thr)
    key_thr = KeyboardThread(draft, txqueue, keyboard_rxqueue)
    timer_thr = TimerThread(draft)

    threadpool.append(key_thr)
    threadpool.append(timer_thr)

    for t in threadpool:
        t.start()
    alive = True
    try:
        while alive:
            for t in threadpool:
                if not t.is_alive():
                    try:
                        print(t.name + " has died! Exiting.")
                    except:
                        _exit(1)
                    _exit(1)
                    alive = False
    except KeyboardInterrupt:
        _exit(1)
    return
示例#2
0
async def init_ihl_draft(message, client):
    if message.channel.id not in DRAFT_TO_MISC:
        return

    await message.delete()

    content = message.content.split(',')
    guild = message.guild

    captain1 = guild.get_member(int(content[1]))
    captain2 = guild.get_member(int(content[2]))

    if not captain1.dm_channel:
        await captain1.create_dm()
    if not captain2.dm_channel:
        await captain2.create_dm()

    # check if already in a draft
    if captain1.id in CAPTAINS or captain2.id in CAPTAINS:
        await captain1.dm_channel.send(
            'Unable to create draft because one of the captains is already in a draft, exit with `!exit`'
        )
        await captain2.dm_channel.send(
            'Unable to create draft because one of the captains is already in a draft, exit with `!exit`'
        )
        return

    draft = Draft(captain1, captain2)
    draft.id = content[0]
    draft.ihl = True
    draft.ihl_channel_id = DRAFT_TO_MISC[message.channel.id]
    for champ in content[3:]:
        draft.banned_champs.append(champ.lower())

    CAPTAINS[int(content[1])] = draft.id
    CAPTAINS[int(content[2])] = draft.id
    SESSIONS[draft.id] = draft

    await init_draft(draft, client)
示例#3
0
async def draft(ctx):
    """
  Creates a new draft. 
  Only one draft can be active in a server
  Creates a new text channel for the draft.
  """
    if ctx.guild.id not in drafts:
        channel = await ctx.guild.create_text_channel('DRAFT-CHANNEL')
        draft = Draft(channel.id)
        drafts[ctx.guild.id] = draft
        messagesToDelete[draft] = []
        response = ctx.author.mention + ' has started a draft!\n'
        response += 'Please use {} for future commands and updates.'.format(
            channel.mention)
        rulesEmbed = discord.Embed(
            title="MTGDraftBot Guide",
            description=
            "MTGDraftBot uses discord messages and commands to simulate a live MTG Draft."
        )
        rulesEmbed.set_author(name="Elwyn Cruz")
        rulesEmbed.add_field(
            name="Getting Started",
            value=
            """After creating a draft, users can !join to put themselves in the draft.
               Once everyone has joined, use !start to begin. You can check the status
               of the draft (pick order, time left, who has not picked) in this channel.""",
            inline=False)
        rulesEmbed.add_field(
            name="Drafting",
            value=
            """Once you start the draft, MTGDraftBot will DM each player individually.
               After you get all of your picks, you can react to any of them to select it.
               You will have until the timer runs out or until everyone has selected a card
               to change your pick.""",
            inline=False)
        rulesEmbed.add_field(
            name="Useful Commands",
            value="""!join : join the draft. Use this in this channel.
               !start : start the draft. Use this in this channel.
               !players : list the players in the draft. Use this in this channel.
               !picks <timeout> : see your picks. They will expire after <timeout> 
               seconds to ensure that it doesn't clutter up the draft. Use this in 
               your DM Channel with MTGDraftBot.
                """,
            inline=False)
        await ctx.send(response, delete_after=30)
        await channel.send(embed=rulesEmbed)
    else:
        ctx.send("There is already a draft going on!", delete_after=30)
示例#4
0
def main():
    players = []
    player_csv = "FantasyPros_2020_Draft_Overall_Rankings.csv"
    with open(player_csv, 'r') as f:
        f.__next__()
        for line in f:
            player = player_generate_fromcsv(line)
            if player != None:
                players.append(player)
    try:
        # position = int(input("Welcome to Vince's Mock Draft. Please Enter your position:"), 10)
        # name = input("Welcome to Vince's Mock Draft. Please Enter your team name:")
        # n_rosters = int(input("Welcome to Vince's Mock Draft. Please Enter the number of players in the draft: "), 10)
        position = 6
        name = "vinny"
        n_rosters = 8
    except ValueError:
        print("Invalid position. Exiting...")
        sys.exit(2)
    if position > n_rosters or position < 0:
        print("Invalid position. Exiting...")
        sys.exit(2)
    draft = Draft(position, name, players, n_rosters, player_csv)
    draft.draft()
示例#5
0
async def start_draft(args, author, client):
    channel = author.dm_channel

    if args:
        await channel.send('Too many arguments provided, try **just** `!draft`'
                           )
        return

    if author.id in CAPTAINS:
        await channel.send('You are already in a draft, exit with `!exit`')
        return

    draft = Draft(author)
    CAPTAINS[author.id] = draft.id
    SESSIONS[draft.id] = draft

    await channel.send('Share **Draft ID** with Opposing Captain\t>>>\t`' +
                       draft.id + '`')
示例#6
0
    def __render_movie_from_sequence(self, inFile):
        import fileseq
        from draft import Draft

        codec = "H264"
        quality = 80

        lut = Draft.LUT.CreateRec709()

        fs = fileseq.findSequencesOnDisk(inFile)[0]

        output_path = os.path.join(fs.dirname(),
                                   "{}.mov".format(fs.basename()[:-1]))

        if not os.path.exists(output_path):
            firstFrame = fs.frame(fs.start())
            firstFrame = Draft.Image.ReadFromFile(firstFrame)

            check_beauty = False
            if firstFrame.HasChannel('Beauty.blue'):
                channels = {
                    'Beauty.blue': 'B',
                    'Beauty.green': 'G',
                    'Beauty.red': 'R'
                }
                check_beauty = True

            inputWidth = firstFrame.width
            inputHeight = firstFrame.height

            encoder = Draft.VideoEncoder(output_path,
                                         width=inputWidth,
                                         height=inputHeight,
                                         quality=quality,
                                         codec=codec)

            progressCounter = 0
            for currFrame in range(fs.start(), fs.end()):

                currFile = fs.frame(currFrame)
                frame = Draft.Image.ReadFromFile(currFile)

                if check_beauty:
                    imgLayer = Draft.Image.CreateImage(frame.width,
                                                       frame.height,
                                                       channels.keys())
                    imgLayer.Copy(frame, channels=channels.keys())
                    for ch in channels:
                        imgLayer.RenameChannel(ch, channels[ch])
                else:
                    imgLayer = frame

                lut.Apply(imgLayer)

                encoder.EncodeNextFrame(imgLayer)

                progressCounter = progressCounter + 1
                progress = progressCounter * 100 / (fs.end() - fs.start())
                print("Progress: %i%%" % progress)

            encoder.FinalizeEncoding()

        return {'path': output_path, 'first_frame': fs.start()}
示例#7
0
    def __init__(self, team, champ_ids = get_champion_ids(), num_positions = 5, draft = Draft('default')):
        #TODO (Devin): This should make sure that numChampions >= num_positions
        self.num_champions = len(champ_ids)
        self.num_positions = num_positions
        self.num_actions = (self.num_positions+1)*self.num_champions
        self.state_index_to_champ_id = {i:k for i,k in zip(range(self.num_champions),champ_ids)}
        self.champ_id_to_state_index = {k:i for i,k in zip(range(self.num_champions),champ_ids)}
        self.state = np.zeros((self.num_champions, self.num_positions+2), dtype=bool)
        self.picks = []
        self.bans = []
        self.selected_pos = []

        self.team = team
        self.draft_structure = draft
        # Get phase information from draft
        self.BAN_PHASE_LENGTHS = self.draft_structure.PHASE_LENGTHS[DraftState.BAN_PHASE]
        self.PICK_PHASE_LENGTHS = self.draft_structure.PHASE_LENGTHS[DraftState.PICK_PHASE]

        # The dicts pos_to_pos_index and pos_index_to_pos contain the mapping
        # from position labels to indices to the state matrix and vice versa.
        self.positions = [i-1 for i in range(num_positions+2)]
        self.pos_indices = [1,0]
        self.pos_indices.extend(range(2,num_positions+2))
        self.pos_to_pos_index = dict(zip(self.positions,self.pos_indices))
        self.pos_index_to_pos = dict(zip(self.pos_indices,self.positions))
示例#8
0
文件: test.py 项目: muriloime/kata
 def test_abtraction(self):
     self.assertRaises(NotImplementedError, lambda: Draft())
示例#9
0
import os
import json

# Needs to run before Draft import
os.chdir("/Users/Patrick/PycharmProjects/git-nfl-groupme-bot/NFL_Groupme_Bot")

from draft import Draft

with open("tests/users.json", "r") as json_file:
    users = json.load(json_file)

draft_instance = Draft(users)
print(draft_instance.init_draft())

# Get current user
current_user = None
for user in users:
    if user["user_id"] == draft_instance.current_user:
        current_user = user
        break

print(draft_instance.make_selection(current_user, "draft Kansas City Chiefs"))
示例#10
0
async def on_message(message):
    global drafts
    global cubes

    global messagestring

    #Ignores the bots own messages.
    if message.author == client.user:
        return

    if '!joindraft' in message.content.lower():
        #Makes sure there is both a draft in this channel, that draft hasnt started yet, and that the player isnt already in a draft.
        #Might want to split that up for serpeate error messages for the user.
        currentlyPlaying = []
        for draft in drafts:
            for player in drafts[draft].players:
                if not player.user in currentlyPlaying:
                    currentlyPlaying.append(player.user)
        if message.channel in drafts and drafts[
                message.
                channel].currentPack == 0 and message.author not in currentlyPlaying:
            drafts[message.channel].players.append(
                Player(message.author, drafts[message.channel]))
            await message.channel.send(message.author.name +
                                       ' has joined the draft!')
        else:
            await message.channel.send(
                "The draft is already running or you are already in another draft. Try !leavedraft in the channel where you previously drafted."
            )

    #de-registers a player
    if ('!leavedraft') in message.content.lower():
        if message.channel in drafts:
            for player in drafts[message.channel].players:
                if message.author == player.user:
                    drafts[message.channel].kick(player)
                    await message.channel.send('So sorry to see you leave, ' +
                                               message.author.name +
                                               '. Catch you for the next one!')

    #Sends the name of all registered players.
    if ('!currentplayers') in message.content.lower():
        if message.channel in drafts:
            await message.channel.send([
                player.user.name for player in drafts[message.channel].players
            ])
        else:
            await message.channel.send(
                'There is no draft in this channel currently.')

    if ('!!createdraft') in message.content.lower():
        if 'Admin' in str(message.author.roles) or 'Moderator' in str(
                message.author.roles) or 'Host' in str(
                    message.author.roles
                ):  #Only admins, mods or draft hosts can do this command
            for key in cubes.keys():
                if len(message.content.lower().split()
                       ) > 1 and key == message.content.lower().split()[1]:
                    drafts[message.channel] = Draft(cubes[key],
                                                    message.channel)
                    await message.channel.send(
                        'Draft created. Players can now join.')
                    messagestring = message.content.lower()
                    return
            await message.channel.send(
                'Cube not found, please enter one from this list next time:\n'
                + str(list(cubes.keys())))

    if ('!!startdraft') in message.content.lower():
        if 'Admin' in str(message.author.roles) or 'Moderator' in str(
                message.author.roles) or 'Host' in str(
                    message.author.roles
                ):  #Only admins, mods or draft hosts can do this command
            #Confirms there is a unstarted draft in the channel.
            if message.channel in drafts and drafts[
                    message.channel].currentPack == 0:
                await message.channel.send(
                    'The draft is starting! All players have received their first pack. Good luck!'
                )
                drafts[message.channel].startDraft()
        else:
            await message.channel.send(
                'Only admins or moderators can start the draft')

    if ('!cubemetric' in message.content.lower()):
        if 'Admin' in str(
                message.author.roles):  #Only admins can do this command
            for key in cubes.keys():
                if len(message.content.lower().split()
                       ) > 1 and key == message.content.lower().split()[1]:
                    CardList = cubes[key]
                    if ('attr' in message.content.lower()):
                        asyncio.create_task(
                            message.channel.send(
                                createAttributeDictionary(CardList)))
                    elif ('type' in message.content.lower()):
                        asyncio.create_task(
                            message.channel.send(
                                createTypeDictionary(CardList)))
                    elif ('level' in message.content.lower()):
                        asyncio.create_task(
                            message.channel.send(
                                createLevelDictionary(CardList)))
                    elif ('tuner' in message.content.lower()):
                        asyncio.create_task(
                            message.channel.send(
                                createTunerDictionary(CardList)))
                    elif ('extra' in message.content.lower()):
                        asyncio.create_task(
                            message.channel.send(createExtraMessage(CardList)))
                    else:
                        asyncio.create_task(
                            message.channel.send(
                                createSpreadDictionary(CardList)))
                    return
            await message.channel.send(
                'Cube not found, please enter one from this list next time:\n'
                + str(list(cubes.keys())))

    if ('!mypool' in message.content.lower()):
        for draft in drafts:
            for player in drafts[draft].players:
                if player.user == message.author:
                    temppool = player.pool[:]
                    if ('attr' in message.content.lower()):
                        await message.channel.send(
                            createAttributeDictionary(temppool))
                    elif ('type' in message.content.lower()):
                        await message.channel.send(
                            createTypeDictionary(temppool))
                    elif ('level' in message.content.lower()):
                        await message.channel.send(
                            createLevelDictionary(temppool))
                    elif ('tuner' in message.content.lower()):
                        await message.channel.send(
                            createTunerDictionary(temppool))
                    elif ('extra' in message.content.lower()):
                        await message.channel.send(createExtraMessage(temppool)
                                                   )
                    elif ('list' in message.content.lower()):
                        await message.author.send(temppool)
                    else:
                        monsters = [
                            card for card in temppool
                            if 'monster' in card.cardType.lower()
                            and 'synchro' not in card.cardType.lower()
                            and 'xyz' not in card.cardType.lower()
                        ]
                        if (len(monsters) > 0):
                            #Async so they dont stall the other messages waiting for the response from the server
                            asyncio.create_task(
                                message.channel.send("**Monsters (" +
                                                     str(len(monsters)) +
                                                     "):** " + str(monsters)))
                        spells = [
                            card for card in temppool
                            if 'spell' in card.cardType.lower()
                        ]
                        if (len(spells) > 0):
                            asyncio.create_task(
                                message.channel.send("**Spells (" +
                                                     str(len(spells)) +
                                                     "):** " + str(spells)))
                        traps = [
                            card for card in temppool
                            if 'trap' in card.cardType.lower()
                        ]
                        if (len(traps) > 0):
                            asyncio.create_task(
                                message.channel.send("**Traps (" +
                                                     str(len(traps)) +
                                                     "):** " + str(traps)))
                        extra = [
                            card for card in temppool
                            if 'xyz' in card.cardType.lower()
                            or 'synchro' in card.cardType.lower()
                        ]
                        if (len(extra) > 0):
                            asyncio.create_task(
                                message.channel.send("**Extra Deck (" +
                                                     str(len(extra)) +
                                                     "):** " + str(extra)))

    #Lists all cards in all pools and says who has each card. Could be useful for detecting cheating if necessary
    if ('!totalpool') in message.content.lower():
        if 'Admin' in str(
                message.author.roles):  #Only admins can do this command
            pooltosend = ''
            for draft in drafts:
                for player in drafts[draft].players:
                    pooltosend += '\n\n' + player.user.name
                    for thing in player.pool:
                        pooltosend += '%s\n' % thing
            asyncio.create_task(
                message.author.send(file=discord.File(
                    fp=StringIO(pooltosend), filename="OverallPool.ydk")))
        else:
            asyncio.create_task(message.channel.send('Admins only'))

    #Removes people from the draft. Does not use @. For example, !remove fspluver, not !remove @fspluver
    if message.content.lower().strip().startswith('!remove'):
        if (
                'Admin' in str(message.author.roles)
                or 'Moderator' in str(message.author.roles)
                or 'Host' in str(message.author.roles)
        ) and message.channel in drafts:  #Only admins, mods or draft hosts can do this command and makes sure there is a draft in this channel
            for player in drafts[message.channel].players:
                if player.user.name in message.content:
                    drafts[message.channel].kick(player)
                    await message.channel.send(
                        'That player has been removed from the draft.')
        else:
            await message.channel.send(
                'Only admins or moderators can remove players from the draft. If you yourself would like to leave, use !leavedraft.'
            )

    if ('!grabdata' in message.content.lower()):
        pickdata.append(messagestring)
        file = open('pick_data_file.csv', 'w+', newline='')
        with file:
            write = csv.writer(file)
            write.writerows(pickdata)

        asyncio.create_task(
            message.author.send(file=discord.File(r'pick_data_file.csv')))

    if ('!ydk' in message.content.lower()):
        for draft in drafts:
            for player in drafts[draft].players:
                if player.user == message.author:
                    tempidpoolnoextra = []
                    tempidpoolextra = []
                    tempidpoolside = []
                    overflow_counter = 0

                    for card in player.pool:
                        if (card.cardType != ("Synchro Monster") or
                            ("Synchro Tuner Monster")) and (card.cardType !=
                                                            "XYZ Monster"):
                            tempidpoolnoextra.append(
                                card.id
                            )  #puts the ids of the main deck cards in a list
                        if ('xyz' in card.cardType.lower()
                                or 'synchro' in card.cardType.lower() and
                            (overflow_counter < 14)):
                            tempidpoolextra.append(
                                card.id
                            )  #puts the ids of the extra deck cards in a list
                            overflow_counter = overflow_counter + 1
                        if ('xyz' in card.cardType.lower()
                                or 'synchro' in card.cardType.lower()) and (
                                    overflow_counter > 13):
                            tempidpoolside.append(
                                card.id
                            )  #puts the ids of the extra deck cards in an overflow side list

                    #This whole block formats their cards for the .ydk format
                    ydkString = ""
                    ydkstuff = ["#created by ...", "#main"]
                    for listitem in ydkstuff:  #puts in the necessary ydk stuff
                        ydkString += '%s\n' % listitem
                    for listitem in tempidpoolnoextra:
                        ydkString += (
                            '%s\n' % listitem
                        )  #should put main deck cards in the ydk file
                    ydkextraline = ["#extra"]
                    for listitem in ydkextraline:  #Stuff after this gets put in the extra deck (until side)
                        ydkString += '%s\n' % listitem
                    for listitem in tempidpoolextra:
                        ydkString += '%s\n' % listitem
                    ydksidestuff = ["!side"
                                    ]  #Stuff after this gets put in the side
                    for listitem in ydksidestuff:
                        ydkString += '%s\n' % listitem
                    for listitem in tempidpoolside:
                        ydkString += '%s\n' % listitem

                    asyncio.create_task(
                        message.author.send(
                            file=discord.File(fp=StringIO(ydkString),
                                              filename="YourDraftPool.ydk")))

    if ('!draftdone') in message.content.lower():
        if 'Admin' in str(message.author.roles) or 'Moderator' in str(
                message.author.roles) or 'Host' in str(
                    message.author.roles
                ):  #Only admins, mods or draft hosts can do this command
            await message.channel.send(
                'The draft has concluded! Type "!mypool" to see your cardpool, and !ydk to get an export of your list. Good luck in your duels!'
            )
示例#11
0
from player import Player
from player import Players
from teamroster import TeamRoster
from draft import Draft
from team import Teams

#max year should be current -1
minYear = 2010
maxYear = 2020
keeperDraftDate = "2021-09-19"

playerList = Players()
teamRoster = TeamRoster()
draftPick = Draft()
#teams = Teams()

#min 2007, max 2017
# should get season 2017-2018 to 2008-2009
# should get draft 2008
for currentYear in range(maxYear, minYear, -1):
    season = str(currentYear) + "" + str(currentYear + 1)
    draft = str(currentYear + 1)
    print("Season : " + season + "   draft: " + str(draft))
    teamRoster.getTeamRoster(season, keeperDraftDate, playerList)
    draftPick.getDraftPlayers(draft, keeperDraftDate, playerList)

playerListFile = ".\playerList.txt"
open(playerListFile, 'w').close()
playerList.writePlayerList(playerListFile)
print("Done")
示例#12
0
def main():
    players = []
    player_csv = "FantasyPros_2020_Draft_Overall_Rankings.csv"
    position = 6
    user_name = "vinny"
    n_rosters = 8
    names = []
    for i in range(0, 14):
        names.append("comp{0}".format(i))
    with open("server_cfg.cfg", 'r') as f:
        for line in f:
            if line.startswith("CSVFILE"):
                player_csv = line.split("=", 1)[1].strip()
            elif line.startswith("PORT"):
                port = int(line.split("=", 1)[1], 10)
            elif line.startswith("DRAFTPOSITION"):
                position = int(line.split("=", 1)[1], 10)
            elif line.startswith("N_TEAMS"):
                n_rosters = int(line.split("=", 1)[1], 10)
            elif line.startswith("USER_NAME"):
                user_name = line.split("=", 1)[1].strip()
            elif line.startswith("TEAM_NAME"):
                stuff = line.split("=", 1)[1].strip()
                roster_position = int(stuff.split(",", 1)[0], 10)
                name = stuff.split(",", 1)[1]
                names[roster_position] = name
            elif line.startswith("SERVER_ADDRESS"):
                ip = line.split("=", 1)[1].split(",", 1)[0].strip()
                send_port = int(line.split("=", 1)[1].split(",", 1)[1], 10)
                send_address = (ip, send_port)

    with open(player_csv, 'r') as f:
        f.__next__()
        for line in f:
            player = player_generate_fromcsv(line)
            if player != None:
                players.append(player)

    draft = Draft(position, user_name, players, n_rosters, player_csv)
    for i in range(0, draft.n_rosters):
        if i != draft.user_pos:
            draft.roster[i].name = names[i]

    keyboard_rxqueue = Queue()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(5)
    sock.bind(('', port))
    sock.listen(1)

    key_thr = KeyboardThread(draft, keyboard_rxqueue)
    timer_thread = TimerThread(draft)

    key_thr.start()
    timer_thread.start()
    while True:
        try:
            conn, addr = sock.accept()
            draft.logger.logg("New conn! addr:{0}".format(addr), 1)
            q = Queue()
            conn.settimeout(5)
            new_thread = ClientThread(conn, keyboard_rxqueue, q, draft, addr,
                                      len(conn_threads))
            new_thread.start()

            conn_threads.append(new_thread)
        except socket.timeout:
            pass
        i = 0
        deleted = 0

        while (i < len(conn_threads)):
            if (conn_threads[i].is_alive() == False):
                draft.logger.logg("Dead Thread {0}".format(addr), 1)
                conn_threads[i].sock.close()
                conn_threads.pop(i)
            i += 1
        if deleted:
            i = 0
            while (i < len(conn_threads)):
                conn_threads[i].index = i
        if (key_thr.is_alive() == False):
            print("Keyboard Thread Died!!")
            _exit(1)

        time.sleep(1)

    _exit(1)
    return