示例#1
0
def get_upcoming():
    """ similar to get_score but this time we are searching for upcoming live
        match info"""
    utils.log("Fetching URL: ".format(config.SCORE_URL))
    response = urllib2.urlopen(config.SCORE_URL)
    tree = ET.fromstring(response.read())
    listing = []

    for elem in tree.findall("Day"):
        for subelem in elem.findall("Game"):
            if subelem.find('PercentComplete').text == '0':
                g = classes.game()
                home = subelem.find('HomeTeam').attrib['FullName']
                away = subelem.find('AwayTeam').attrib['FullName']
                timestamp = subelem.find('Timestamp').text
                #convert zulu to local time
                delta = (time.mktime(time.localtime()) -
                         time.mktime(time.gmtime())) / 3600
                ts = datetime.datetime.fromtimestamp(
                    time.mktime(
                        time.strptime(timestamp[:-1], "%Y-%m-%dT%H:%M:%S")))
                ts += datetime.timedelta(hours=delta)
                airTime = ts.strftime("%A @ %I:%M %p")
                returnString = ('[COLOR red]Upcoming:[COLOR] '
                                '{0} v {1} - [COLOR yellow]{2}[/COLOR]')
                g.title = returnString.format(home, away, airTime)
                g.dummy = True
                listing.append(g)
    return listing
def get_upcoming():
    """
    similar to get_score but this time we are searching for upcoming live
    match info
    """
    data = fetch_url(config.SCORE_URL)
    tree = ET.fromstring(data)
    listing = []

    for elem in tree.findall("Day"):
        for subelem in elem.findall("Game"):
            if subelem.find('GameState').text == 'Full Time':
                continue
            g = classes.game()
            home = subelem.find('HomeTeam').attrib['FullName']
            away = subelem.find('AwayTeam').attrib['FullName']
            timestamp = subelem.find('Timestamp').text
            # convert zulu to local time
            airtime = get_airtime(timestamp)
            title = ('[COLOR red]Upcoming:[/COLOR] '
                     '{0} v {1} - [COLOR yellow]{2}[/COLOR]')
            g.title = title.format(home, away, airtime)
            g.dummy = True
            listing.append(g)
    return listing
示例#3
0
def evaluate_generation(genomes, players_number, repetitions):
    generation_score = 0
    for i in range(len(genomes)):
        for n in range(repetitions):
            g = game()
            g.deal_cards(players_number, genomes[i])
            g, score, lost = launch_game_genetic(g, False)
            generation_score += score
    generation_score /= (repetitions * len(genomes))

    return generation_score
示例#4
0
def select_parents(genomes, players_number, repetitions):
    scores = [0] * len(genomes)

    for i in range(len(genomes)):
        mean_score = 0
        for n in range(repetitions):
            g = game()
            g.deal_cards(players_number, genomes[i])
            g, score, lost = launch_game_genetic(g, False)
            mean_score += score
        mean_score /= repetitions

        scores[i] = mean_score

    parents_genomes = genomes[np.argpartition(scores, int(
        -len(genomes) / 2))[int(-len(genomes) / 2):]]

    return parents_genomes
示例#5
0
def saved_launch_game(players_number, display):
    g = game()
    g.deal_cards(players_number)
    data_game = [deepcopy(g)]

    first_player = randrange(players_number)
    current_player = first_player

    end_game = False
    no_draw_pile_counter = 0
    if display:
        turn_number = 0
        print(g)
        print("turn number :", turn_number)
        print("first player :", first_player)
        print("__________________________________________________________")

    while not (end_game):
        turn_player(g, g.players[current_player])
        data_game += [deepcopy(g)]
        if display:
            turn_number += 1
            if turn_number < 100:
                print(g)
                print("")
                print("turn_number :", turn_number)
                print("current player :", current_player)
                print(
                    "__________________________________________________________"
                )
        end_game, no_draw_pile_counter = check_end_game(
            g, no_draw_pile_counter)

        current_player = (current_player + 1) % players_number

    # Results display
    if g.error_tokens == 0:
        lost = True
        if display:
            print("game lost")
    else:
        lost = False

    return data_game, first_player, sum(g.fireworks.values()), lost
示例#6
0
def launch_game(players_number, display):
    # use a constant seed for the tests
    #seed(123)
    g = game()
    g.deal_cards(players_number)

    first_player = randrange(players_number)
    current_player = first_player

    end_game = False
    no_draw_pile_counter = 0
    if display:
        turn_number = 0
        print(g)
        print("turn number :", turn_number)
        print("first player :", first_player)
        print("__________________________________________________________")

    while not (end_game):
        turn_player(g, g.players[current_player])
        if display:
            turn_number += 1
            if turn_number < 100:
                print(g)
                print("")
                print("turn_number :", turn_number)
                print("current player :", current_player)
                print(
                    "__________________________________________________________"
                )
        end_game, no_draw_pile_counter = check_end_game(
            g, no_draw_pile_counter)

        current_player = (current_player + 1) % players_number

    # Results display
    if g.error_tokens == 0:
        lost = True
        if display:
            print("game lost")
    else:
        lost = False

    return g, sum(g.fireworks.values()), lost, g.error_tokens
示例#7
0
def list_matches(params, live=False):
    """ go through our xml file and retrive all we need to pass to kodi"""
    data = get_url(params, live)
    tree = ET.fromstring(data)
    listing = []
    for elem in tree.findall("MediaSection"):
        for gm in elem.findall('Item'):
            # remove items with no video eg. news articles
            if not gm.attrib['Type'] == 'V':
                continue
            g = classes.game()
            g.title = gm.find('Title').text.encode('ascii', 'replace')
            if gm.find('Description') is not None:
                g.desc = gm.find('Description').text.encode('ascii', 'replace')
            # remove PSA videos
            if g.title.startswith('Better Choices'):
                continue
            g.video_id = gm.find('Video').attrib['Id']
            g.live = gm.find('LiveNow').text
            # keep live videos out of other submenus and vice versa
            if not live and g.live == 'true':
                continue
            if live and g.live == 'false':
                continue
            g.thumb = gm.find('FullImageUrl').text
            game_date = utils.ensure_ascii(gm.find('Date').text)
            g.time = game_date[game_date.find('  ') + 2:]
            # add game start time and current score to live match entries
            if g.live:
                # only use live videos that are actual matches
                if gm.find('NavigateUrl') is not None:
                    id_string = gm.find('NavigateUrl').text
                    start = id_string.find('=') + 1
                    end = id_string.find('&')
                    g.match_id = id_string[start:end]
                    g.score = get_score(g.match_id)
                    title = '[COLOR green][LIVE NOW:][/COLOR] {0} {1}'
                    g.title = title.format(g.title.replace(' LIVE', ''),
                                           g.score)
            listing.append(g)
    return listing
def list_live_matches():
    """
    go through list of xml objects and return listing of game objects
    """
    tree_list = find_live_matches()
    listing = []
    for tree in tree_list:
        g = classes.game()
        home = tree.find('HomeTeam').attrib['FullName']
        away = tree.find('AwayTeam').attrib['FullName']
        match_id = tree.find('Id').text
        score = get_score(match_id)
        title = '[COLOR green][LIVE NOW][/COLOR] {0} v {1} {2}'
        g.title = title.format(home, away, score)
        media_url = tree.find('WatchButton').find('URL').text
        video_id = media_url[media_url.find('Id=') + 3:]
        media_tree = get_media_tree(video_id)
        g.video_id = media_tree.find('Video').attrib['Id']
        g.live = 'true'
        listing.append(g)
    return listing
示例#9
0
def get_upcoming():
    """ similar to get_score but this time we are searching for upcoming live
        match info"""
    utils.log("Fetching URL: {0}".format(config.SCORE_URL))
    response = urllib2.urlopen(config.SCORE_URL)
    tree = ET.fromstring(response.read())
    listing = []

    for elem in tree.findall("Day"):
        for subelem in elem.findall("Game"):
            if subelem.find('PercentComplete').text == '0':
                g = classes.game()
                home = subelem.find('HomeTeam').attrib['Name']
                away = subelem.find('AwayTeam').attrib['Name']
                timestamp = subelem.find('Timestamp').text
                # convert zulu to local time
                airtime = utils.get_airtime(timestamp)
                title = ('[COLOR red]Upcoming:[/COLOR] '
                         '{0} v {1} - [COLOR yellow]{2}[/COLOR]')
                g.title = title.format(home, away, airtime)
                g.dummy = True
                listing.append(g)
    return listing
示例#10
0
def new_game():
    screen.blit(images.normal_background,(0,0))
    text = classes.text("Add Your Name:",40,color.Chocolate4,"font/Crimes-Times-Six-1.ttf")
    screen.blit(text.getImage(),(400,300))
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        elif event.type == KEYDOWN:
            global name
            if event.key == K_RETURN:
                text = classes.text("OK",40,color.white,"font/Crimes-Times-Six-1.ttf")
                screen.blit(text.getImage(),(500,500))
                global user
                user = classes.game(name)
                time.sleep(2)
                global md
                md = 2
            elif event.key == K_BACKSPACE:
                name = name[:-1]
            else:
                name += chr(event.key)
    text = classes.text(name,40,color.white,"font/Crimes-Times-Six-1.ttf")
    x = 540 - len(name)*10
    screen.blit(text.getImage(),(x,450))
def list_matches(params, live=False):
    """
    go through our xml file and retrive all we need to pass to kodi
    """
    if live:
        return list_live_matches()
    if params['category'] == 'MatchReplays':
        url = config.REPLAY_URL
    else:
        url = config.XML_URL
    data = fetch_url(url)
    tree = ET.fromstring(data)
    listing = []
    for elem in tree.findall("MediaSection"):
        for gm in elem.findall('Item'):
            # remove items with no video eg. news articles
            if not gm.attrib['Type'] == 'V':
                continue
            # filter videos by category
            for metadata in gm.find('Metadata').findall('Data'):
                key = metadata.attrib['Key']
                if key == 'contentType':
                    content_type = metadata.attrib['Value']
            if content_type != params['category']:
                continue

            g = classes.game()
            g.title = gm.find('Title').text.encode('ascii', 'replace')
            if gm.find('Description') is not None:
                g.desc = gm.find('Description').text.encode('ascii', 'replace')
            g.video_id = gm.find('Video').attrib['Id']
            g.live = gm.find('LiveNow').text
            g.thumb = gm.find('FullImageUrl').text
            g.time = utils.ensure_ascii(gm.find('Date').text)
            listing.append(g)
    return listing
示例#12
0
def defineGameFromID(gameid):
  localobject=classes.game(gameid)
  globals()["game"+gameid]=localobject
示例#13
0
def launch_game_nn(players_number, display, model):

    # use a constant seed for the tests
    #seed(123)
    g = game()
    g.deal_cards(players_number)

    first_player = randrange(players_number)
    current_player = first_player

    ## create the game state dataframe
    colors_list = ['blue', 'red', 'green', 'yellow', 'white']
    values_list = [1, 2, 3, 4, 5]
    cards_in_deck_indexes = [0, 1, 2, 3]
    next_players_indexes = range(1, players_number)
    # general game information
    game_state = pd.DataFrame(columns=[
        'info_tokens', 'error_tokens', 'blue_firework', 'red_firework',
        'green_firework', 'yellow_firework', 'white_firework'
    ])
    # discard pile composition
    for color in colors_list:
        for value in values_list:
            game_state[str(value) + " " + color +
                       " in the discard pile"] = None
    # player deck
    for card in cards_in_deck_indexes:
        for color in colors_list:
            game_state["info : card " + str(card) + " is " + color] = None
        for value in values_list:
            game_state["info : card " + str(card) + " is " + str(value)] = None
    # next players' decks
    for player in next_players_indexes:
        for card in cards_in_deck_indexes:
            for color in colors_list:
                game_state["player " + str(player) + " turn(s) after : card " +
                           str(card) + " is " + color] = None
            for value in values_list:
                game_state["player " + str(player) + " turn(s) after : card " +
                           str(card) + " is " + str(value)] = None
    # next players' deck information
    for player in next_players_indexes:
        for card in cards_in_deck_indexes:
            for color in colors_list:
                game_state["player " + str(player) +
                           " turn(s) after : info : card " + str(card) +
                           " is " + color] = None
            for value in values_list:
                game_state["player " + str(player) +
                           " turn(s) after : info : card " + str(card) +
                           " is " + str(value)] = None
    # choices
    for card in cards_in_deck_indexes:
        game_state["play card " + str(card)] = None
        game_state["discard card " + str(card)] = None
    for player in next_players_indexes:
        for color in colors_list:
            game_state["say to player " + str(player) + " the " + color] = None
        for value in values_list:
            game_state["say to player " + str(player) + " the " +
                       str(value)] = None
    game_state.loc[0] = 0

    end_game = False
    no_draw_pile_counter = 0
    if display:
        turn_number = 0
        print(g)
        print("turn number :", turn_number)
        print("first player :", first_player)
        print("__________________________________________________________")

    # the game starts from here
    while not (end_game):
        neural_network_predictions(g, g.players[current_player],
                                   players_number, game_state, model)
        if display:
            turn_number += 1
            if turn_number < 100:
                print(g)
                print("")
                print("turn_number :", turn_number)
                print("current player :", current_player)
                print(
                    "__________________________________________________________"
                )
        end_game, no_draw_pile_counter = check_end_game(
            g, no_draw_pile_counter)

        current_player = (current_player + 1) % players_number

    # Results display
    if g.error_tokens == 0:
        lost = True
        if display:
            print("game lost")
    else:
        lost = False

    return g, sum(g.fireworks.values()), lost
def add_data_with_one_game(data, players_number, index):

    g = game()
    g.deal_cards(players_number)

    first_player = randrange(players_number)
    current_player = first_player

    end_game = False
    no_draw_pile_counter = 0

    starting_index = index

    turn_type = 'first'

    #    # display
    #    turn_number = 0
    #    print(g)
    #    print("")
    #    print("turn_number :", turn_number)
    #    print("first player :", first_player)
    #    print("__________________________________________________________")

    while not (end_game):
        data = turn_player_data_neural_network(g, players_number,
                                               g.players[current_player], data,
                                               turn_type, index)
        turn_type = 'regular'
        index += 1

        #        turn_number += 1
        #        if turn_number < 17:
        #            print(g)
        #            print("")
        #            print("turn_number :", turn_number)
        #            print("current player :", current_player)
        #            print("next player :", (current_player + 1) % players_number)
        #            print("__________________________________________________________")

        end_game, no_draw_pile_counter = check_end_game(
            g, no_draw_pile_counter)

        current_player = (current_player + 1) % players_number

    # update the game results
    data.loc[starting_index:index - 1,
             'final_score'] = sum(g.fireworks.values())
    data.loc[starting_index:index - 1, 'game_lost'] = int(g.error_tokens == 0)

    # update the "turn+5" features
    for i in range(index - players_number):
        data.loc[i, 'score_evolution_turn+5'] = sum(
            data.loc[i:i + 4, 'score_evolution_turn+1'])
        data.loc[i, 'errors_turn+5'] = sum(data.loc[i:i + 4, 'error'])
    for i in range(index - players_number, index):
        data.loc[i, 'score_evolution_turn+5'] = sum(
            data.loc[i:index - 1, 'score_evolution_turn+1'])
        data.loc[i, 'errors_turn+5'] = sum(data.loc[i:index - 1, 'error'])

    # clear the last row, that is altered by this game but is actually for the next game
    data.loc[index] = 0

    return data, index
示例#15
0
import classes
import pandas as pd
import numpy as np
import copy

df = pd.read_csv('out.csv')
players = []
for index, row in df.iterrows():
    players.append(
        classes.player(
            row['Name'], row['Team'], row['Position'], row['Price'],
            [row['1'], row['2'], row['3'], row['4'], row['5'], row['6']]))

model = classes.game(players)

teamList = []

gkpCount = 0
fwdCount = 0
midCount = 0
defCount = 0
totalCount = 0
for i in model.nextQ[0]:

    if i.position == 'Goalkeeper' and gkpCount < 2:
        gkpCount += 1
        teamList.append(copy.copy(i))
        totalCount += 1

    elif i.position == 'Defender' and defCount < 5:
        defCount += 1