Example #1
0
    def test_point_won_by(self):
        player_one = Player(PLAYER_NAME_ONE)
        player_two = Player(PLAYER_NAME_TWO)
        match = Match(player_one, player_two)
        match.point_won_by(PLAYER_NAME_TWO)

        self.assertEqual(match.score, '0 - 0, 0 - 15')
Example #2
0
    def test_match_winner_set_one(self):
        player_one = Player(PLAYER_NAME_ONE)
        player_two = Player(PLAYER_NAME_TWO)
        match = Match(player_one, player_two)
        game_points = 4
        set_points = 6

        for index in range(game_points * set_points):
            match.point_won_by(PLAYER_NAME_TWO)

        self.assertEqual(match.score,
                         f'Winner {PLAYER_NAME_TWO} Set: 0 - 1 | Game: 0 - 6')
Example #3
0
def test_parse_match_with_tie():
    match_url = "https://www.over.gg/11948/ldn-vs-shd-overwatch-league-2019-season-play-in-sf"

    fields = overggparser.parse_match(match_url)
    match = Match(id=7269,
                  start=datetime.strptime("2019-08-31 15:00:00",
                                          "%Y-%m-%d %H:%M:%S"),
                  url=match_url,
                  home=Team("London Spitfire", "US"),
                  away=Team("Shanghai Dragons", "US"))

    overggparser.merge_fields_into_match(fields, match)

    assert len(match.maps) == 8
    assert match.maps[0].name == "Busan"
    assert match.maps[0].winner == Winner.HOME
    assert match.maps[1].name == "Numbani"
    assert match.maps[1].winner == Winner.HOME
    assert match.maps[2].name == "Hanamura"
    assert match.maps[2].winner == Winner.AWAY
    assert match.maps[3].name == "Watchpoint: Gibraltar"
    assert match.maps[3].winner == Winner.HOME
    assert match.maps[4].name == "Lijiang Tower"
    assert match.maps[4].winner == Winner.AWAY
    assert match.maps[5].name == "King's Row"
    assert match.maps[5].winner == Winner.TIED
    assert match.maps[6].name == "Dorado"
    assert match.maps[6].winner == Winner.AWAY
    assert match.maps[7].name == "Ilios"
    assert match.maps[7].winner == Winner.HOME
def vote(postVars):
	
	global couchdbServer
	
	templateVars = dict()
	winnerId = postVars["winner"].value.decode("utf-8")
	loserId = postVars["loser"].value.decode("utf-8")
	
	try:
		db = couchdbServer.create("players")
	except:
		db = couchdbServer["players"]
	
	winner = Player.load(db,winnerId)
	loser = Player.load(db,loserId)

	match = Match()
	if postVars["draw"].value == "0":
		match.matchWithWinner(winner,loser)
	else:
		match.matchWithoutWinner(winner,loser)
	
	try:
		winner.store(db)
	except ResourceConflict:
		print "Unable to store winner"
	
	try:
		loser.store(db)
	except ResourceConflict:
		print "Unable to store loser"
		
		
	votesCount = classes.rankingsession.getSession("votesToFinish")
	votesCount -= 1
	votesCount = classes.rankingsession.setSession("votesToFinish", votesCount)
	
	templateVars = dict(json = json.dumps(dict()))
	return output_template("json.html", templateVars )
Example #5
0
def grabMatchesDay(date, liveornot):
    matches = []

    #Replace date in the kava.ee url
    simple_date = str(date.day) + '-' + str(date.month) + '-' + str(date.year)
    url = "https://www.kava.ee/programme/listing/football/%s?filter=sports" % (
        simple_date)

    response = urllib.urlopen(url)
    data = json.loads(response.read())
    #Adding some useless comment

    programmes = data['schedule']['programme']

    for i in range(len(programmes)):
        title = programmes[i]['title']

        #Make the description the title if the title doesn't show the teams.
        pattern = ['-', ' v ', ' - ']
        containsit = False
        for p in pattern:
            x = re.search(p, title)
            if x != None:
                containsit = True
                break
            else:
                containsit = False

        if containsit == False and programmes[i]['description'] != '':
            title = programmes[i]['description']

        start_time = datetime.datetime.fromtimestamp(
            programmes[i]['start_unix'])
        end_time = datetime.datetime.fromtimestamp(programmes[i]['stop_unix'])
        status = programmes[i]['status']
        channel = programmes[i]['channel']['name']
        id_kava = programmes[i]['id']
        match = Match(title, start_time, end_time, status, channel, id_kava)

        matches.append(match)

    if (liveornot):
        filtered_matches = []
        for i in range(len(matches)):
            if matches[i].live:
                filtered_matches.append(matches[i])

        matches = filtered_matches

    return matches
Example #6
0
def test_parse_match():
    match_url = "https://www.over.gg/12004/nyxl-vs-atl-overwatch-league-2019-season-p-offs-sf"

    fields = overggparser.parse_match(match_url)
    match = Match(id=7322,
                  start=datetime.strptime("2019-09-08 18:00:00",
                                          "%Y-%m-%d %H:%M:%S"),
                  url=match_url,
                  home=Team("New York Excelsior", "US"),
                  away=Team("Atlanta Reign", "US"))

    overggparser.merge_fields_into_match(fields, match)

    assert match.home.name == "New York Excelsior"
    assert match.away.name == "Atlanta Reign"
    assert match.state == GameState.COMPLETE
    assert match.home_score == 4
    assert match.away_score == 2
    assert match.winner == "New York Excelsior"
    assert match.competition == "Overwatch League 2019 Season"
    assert match.competition_url == "https://www.over.gg/event/266/overwatch-league-2019-season"
    assert match.stage == "Playoffs: Semifinals"

    expected_streams = [
        Stream("https://www.twitch.tv/overwatchleague", "ENG"),
        Stream("https://www.twitch.tv/overwatchleague_kr", "KR"),
        Stream("https://www.twitch.tv/overwatchleague_fr", "FR")
    ]
    for match_stream in match.streams:
        found = False
        for expected_stream in expected_streams:
            if match_stream == expected_stream and match_stream.language == expected_stream.language:
                found = True
                break
        assert found

    assert len(match.maps) == 6
    assert match.maps[0].name == "Busan"
    assert match.maps[0].winner == Winner.HOME
    assert match.maps[1].name == "King's Row"
    assert match.maps[1].winner == Winner.HOME
    assert match.maps[2].name == "Hanamura"
    assert match.maps[2].winner == Winner.AWAY
    assert match.maps[3].name == "Rialto"
    assert match.maps[3].winner == Winner.HOME
    assert match.maps[4].name == "Lijiang Tower"
    assert match.maps[4].winner == Winner.AWAY
    assert match.maps[5].name == "Numbani"
    assert match.maps[5].winner == Winner.HOME
Example #7
0
def add_new_match(db, sa, mas):
    """
    Create a new match in the database
    :param sa: `StatisticalAlgorithm` a SA obj
    :param family: `Agent` a Family object
    :param religion: `Agent` a Religion object
    :param education: `Agent` a Education object

    Usage
    >>> from velhia import Velhia
    >>> match = velhia.add_new_match(sa, family, religion, education)
    >>> print(match)

    <classes.match.Match object at 0x7fe6de3287d0>
    """

    try:
        ret = db.create(
            json.dumps({
                "begin": datetime.now().ctime(),
                "time": 0,
                "sa": {
                    "playerId": sa.id,
                    "symbol": sa.char[0]
                },
                "mas": {
                    "family": {
                        "playerId": mas.family_leader.id,
                        "symbol": mas.char[0]
                    },
                    "religion": {
                        "playerId": mas.religion_leader.id,
                        "symbol": mas.char[0]
                    },
                    "education": {
                        "playerId": mas.education_leader.id,
                        "symbol": mas.char[0]
                    }
                },
                "plays": [],
                "status": "PENDENT"
            }))

        match = Match(json.loads(ret.text))
        return match
    except:
        raise NewMatchError
Example #8
0
def get_upcoming_events(events):
    data = retry_request(static.OVER_GG_API, 5, 60)
    if data is None:
        return False

    for match_table in data['matches']:
        match = Match(id=match_table['id'],
                      start=datetime.utcfromtimestamp(
                          int(match_table['timestamp'])),
                      url=match_table['match_link'],
                      home=Team(match_table['teams'][0]['name'],
                                match_table['teams'][0]['country']),
                      away=Team(match_table['teams'][1]['name'],
                                match_table['teams'][1]['country']))

        fits_event = False
        for event in events:
            if event.match_fits(match.start, match_table['event_name'],
                                match.id):
                event.add_match(match)
                fits_event = True
                break

        if not fits_event:
            rank, competition = mappings.get_competition(
                match_table['event_name'])
            if competition is None:
                if match_table['event_name'] not in static.missing_competition:
                    static.missing_competition.add(match_table['event_name'])
                    log.warning(
                        f"Upcoming event not mapped: {match_table['event_name']} : {str(match.start)}"
                    )

            elif static.utcnow() + timedelta(hours=competition.event_build_hours_ahead) > \
              match.start > \
              static.utcnow() - timedelta(hours=10):
                log.debug(
                    f"Found new upcoming event: {match_table['event_name']} : {str(match.start)}"
                )

                event = Event(competition=competition)
                event.add_match(match)
                events.append(event)
Example #9
0
    def backup(self):
        """
        Get the lastest datas to use in rollback function

        usage
        >>> from velhia import Velhia
        >>> vlh = Velhia()
        >>> [match_backup, sa_backup, mas_backup] = vlh.backup()

        <classes.match.Match object at 0x7fe6de3287d0>
        <classes.statistical_algorithm.StatisticalAlgorithm object at 0x7fe6de328150>
        <classes.multi_agent_system.MultiAgentSystem object at 0x7fe6de34dd10>
        """

        ret = self.match_db.get(offset=0, limit=1).json()

        if len(ret) != 0:

            match_backup = Match(ret[0])

            sa_backup = StatisticalAlgorithm(self.algorithm_db.get(offset=0, limit=1).json()[0],
                                             ['X', 1], ['O', 0])

            mas_backup = MultiAgentSystem(Agent(self.family_db.get(offset=1, limit=1, sort="createdAt:desc").json()[0],
                                                ['O', 0]),
                                          Agent(self.family_db.get(offset=0, limit=1, sort="createdAt:desc").json()[0],
                                                ['O', 0]),
                                          Agent(self.education_db.get(offset=1, limit=1, sort="createdAt:desc").json()[0],
                                                ['O', 0]),
                                          Agent(self.education_db.get(offset=0, limit=1, sort="createdAt:desc").json()[0],
                                                ['O', 0]),
                                          Agent(self.religion_db.get(offset=1, limit=1, sort="createdAt:desc").json()[0],
                                                ['O', 0]),
                                          Agent(self.religion_db.get(offset=0, limit=1, sort="createdAt:desc").json()[0],
                                                ['O', 0]))

            return [match_backup, sa_backup, mas_backup]

        else:
            return [None, None, None]
Example #10
0
    def run_championship(self):
        """
        This method runs the grand championship match. Since this is a double
        elimination tourney, the lower bracket champion has to win 2 times in
        order to win the overall championship.

        Arguments:
            :param self: This tourney object
        """
        # Get champs
        upper = self.upper_bracket.player  # pylint: disable=no-member
        lower = self.lower_bracket.player  # pylint: disable=no-member

        print('Championship Match')
        print('{} v. {}'.format(upper.name, lower.name))
        print('Match 1')
        print('---------------------------------')
        cur_match = Match(upper, lower, self.wins_needed)
        results = cur_match.play_match()
        self.matches.append(cur_match)
        print('{} wins the match in {} games!\n'.format(
            results['winner'], results['games_played']))

        winner = upper if results['winner'] == upper.name else lower
        loser = lower if results['winner'] == upper.name else upper
        loser.losses += 1

        # If the upper lost, we need to play again
        if (loser.name == upper.name):
            print('\nMatch 2')
            print('---------------------------------')
            cur_match = Match(upper, lower, self.wins_needed)
            results = cur_match.play_match()
            self.matches.append(cur_match)
            print('{} wins the match in {} games!\n'.format(
                results['winner'], results['games_played']))

            winner = upper if results['winner'] == upper.name else lower
            loser = lower if results['winner'] == upper.name else upper
            loser.losses += 1

        # We can now crown the champion!
        print('\n\n')
        print('Grand Champion')
        print('---------------------------------')
        print('{}'.format(self.victory_screen(winner.name)))
Example #11
0
    def start(self):
        """
        Prepare all objects to start the game

        Usage
        >>> from velhia import Velhia
        >>> vlh = Velhia(match_db, family_db, education_db, religion_db, algorithm_db)
        >>> (match, sa, mas) = vlh.get_data()

        <classes.match.Match object at 0x7fe6de3287d0>
        <classes.statistical_algorithm.StatisticalAlgorithm object at 0x7fe6de328150>
        <classes.multi_agent_system.MultiAgentSystem object at 0x7fe6de34dd10>
        """

        last_match = self.match_db.get(
            offset=0, limit=1, sort="createdAt:desc").json()

        if len(last_match) == 0 or last_match[0]['status'] != 'PENDENT':
            sa = get_lastest_sa(self.algorithm_db)
            sa.matchs += 1

            [education_leader, education_learner] = get_latest_agent(
                self.education_db, self.match_db)
            education_leader.matchsAsLeader += 1
            education_learner.matchsAsLearner += 1

            [religion_leader, religion_learner] = get_latest_agent(
                self.religion_db, self.match_db)
            religion_leader.matchsAsLeader += 1
            religion_learner.matchsAsLearner += 1

            [family_leader, family_learner] = get_latest_agent(
                self.family_db, self.match_db)
            family_leader.matchsAsLeader += 1
            family_learner.matchsAsLearner += 1

            mas = MultiAgentSystem(family_leader, family_learner, education_leader,
                                   education_learner, religion_leader, religion_learner)

            match = add_new_match(self.match_db, sa, mas)
            add_new_memory(match, sa, mas)
            update_mas(self, mas)
            self.algorithm_db.update(sa.id, json.dumps(sa.create_object()))

        else:
            match = Match(last_match[0])

            sa = StatisticalAlgorithm(
                self.algorithm_db.get(
                    filters={"_id": match.sa['playerId']}).json()[0],
                ('X', 1), ('O', 0))

            [education_leader, education_learner] = get_latest_agent(
                self.education_db, self.match_db, match, match.mas['education'][-1])
            [religion_leader, religion_learner] = get_latest_agent(
                self.religion_db, self.match_db, match, match.mas['religion'][-1])
            [family_leader, family_learner] = get_latest_agent(
                self.family_db, self.match_db, match, match.mas['family'][-1])

            mas = MultiAgentSystem(family_leader, family_learner, education_leader,
                                   education_learner, religion_leader, religion_learner)

        return [match, sa, mas]
Example #12
0
    def validate(self, match, sa, mas):
        """
        Check if everything ran correctly
        :param match: `Match` Match obj
        :param sa: `Statistical Algorithm` Statistical Algorithm obj
        :param mas: `Multi Agent System` Multi Agent System obj

            Previous
            1. Check if the previous match has a status in ['WINNER', 'DRAW']
            2. Check if the previous players memory is the previous match
            3. Check if the previous match status is the previous environment status in the previous players memory
            4. Check if the plays in previous match obj is equals previous players memories
            5. Check if the number of players matchs is correctly (victories, defeats, draws)

            Currenty
            1. Check if the currenty match status is pendent
            2. Check if the last match of institutions leaders is equals the currenty match
            3. Check if the plays in match obj is equals players memories
            4. Check if the number of players matchs is correctly (victories, defeats, draws)

        usage
        >>> from velhia import Velhia
        >>> vlh = Velhia(match_db, family_db, education_db, religion_db, algorithm_db)
        >>> vlh.validate_previous_match()
        True or False
        """

        if len(self.match_db.get(offset=0, limit=2).json()) > 1:

            # Previous
            previous_match = Match(self.match_db.get(
                offset=1, limit=1, sort='createdAt:desc').json()[0])
            previous_sa = StatisticalAlgorithm(self.algorithm_db.get(
                filters={"_id": previous_match.sa['playerId']}).json()[0], ['X', 1], ['O', 0])
            previous_family = Agent(self.family_db.get(
                filters={"_id": previous_match.mas['family'][-1]['playerId']}).json()[0], ['O', 0])
            previous_religion = Agent(self.religion_db.get(
                filters={"_id": previous_match.mas['religion'][-1]['playerId']}).json()[0], ['O', 0])
            previous_education = Agent(self.education_db.get(
                filters={"_id": previous_match.mas['education'][-1]['playerId']}).json()[0], ['O', 0])

            check_match_status(previous_match, previous_family,
                               previous_religion, previous_education)
            check_previous_match_id(previous_match, previous_family,
                                    previous_religion, previous_education)
            game_status = self.game_status(
                previous_match, previous_sa.id)
            check_previous_match_game(game_status, previous_match, previous_family,
                                      previous_religion, previous_education)
            check_sa_matchs(previous_sa)
            [check_agent_matchs(x) for x in [previous_family,
                                             previous_religion,
                                             previous_education]]

            # Currenty
            check_match_pendent(match)
            check_currenty_match_id(match, mas.family_leader,
                                    mas.religion_leader, mas.education_leader)
            game_status = self.game_status(match, sa.id)
            check_currenty_match_game(game_status, mas.family_leader,
                                      mas.religion_leader, mas.education_leader)
            check_sa_matchs(sa)
            [check_agent_matchs(x) for x in [mas.family_leader,
                                             mas.religion_leader,
                                             mas.education_leader]]
        else:

            # Currenty
            check_match_pendent(match)
            check_currenty_match_id(match, mas.family_leader,
                                    mas.religion_leader, mas.education_leader)
            game_status = self.game_status(match, sa.id)
            check_currenty_match_game(game_status, mas.family_leader,
                                      mas.religion_leader, mas.education_leader)
            check_sa_matchs(sa)
            [check_agent_matchs(x) for x in [mas.family_leader,
                                             mas.religion_leader,
                                             mas.education_leader]]
Example #13
0
from classes.player import Player
from classes.match import Match
from helpers.constant import PLAYER_NAME_ONE, PLAYER_NAME_TWO

player_one = Player(PLAYER_NAME_ONE)
player_two = Player(PLAYER_NAME_TWO)

print('*******************************************************')
print(
    f'********* Playing a game {player_one.name} VS {player_two.name} *********'
)
print('*******************************************************')

match = Match(player_one, player_two)
players = {1: player_one.name, 2: player_two.name}

while True:
    if match.winner:
        print(match.score)
        break

    try:
        player = int(input('Who won the point Player (1) or Player (2):'))
        match.point_won_by(players[player])
    except Exception:
        continue

    print("\n======= SCORE ========")
    print(match.score)
    print("======================\n")
	def testMatchesResults(self):

		server = Server()
		try:
			db = server.create("players")
		except:
			db = server["players"]

		player0 = Player()
		player0.store(db)
		player1 = Player()
		player1.store(db)
		
		match = Match()

		match.matchWithWinner(player0, player1)
		self.assertEqual(player0.karma, 405), "Error on match"
		self.assertEqual(player0.matches, 1), "Error on match"
		self.assertEqual(player0.wins, 1), "Error on match"
		self.assertEqual(player0.losses, 0), "Error on match"
		self.assertEqual(player1.karma, 395), "Error on match"
		self.assertEqual(player1.matches, 1), "Error on match"
		self.assertEqual(player1.wins, 0), "Error on match"
		self.assertEqual(player1.losses, 1), "Error on match"
		
		match.matchWithWinner(player1, player0)
		self.assertEqual(player0.karma, 400), "Error on match"
		self.assertEqual(player0.matches, 2), "Error on match"
		self.assertEqual(player0.wins, 1), "Error on match"
		self.assertEqual(player0.losses, 1), "Error on match"
		self.assertEqual(player1.karma, 400), "Error on match"
		self.assertEqual(player1.matches, 2), "Error on match"
		self.assertEqual(player1.wins, 1), "Error on match"
		self.assertEqual(player1.losses, 1), "Error on match"

		match.matchWithWinner(player0, player1)
		self.assertEqual(player0.karma, 405), "Error on match"
		self.assertEqual(player0.matches, 3), "Error on match"
		self.assertEqual(player1.karma, 395), "Error on match"
		self.assertEqual(player1.matches, 3), "Error on match"

		match.matchWithWinner(player0,player1)
		self.assertEqual(player0.karma, 410), "Error on match"
		self.assertEqual(player0.matches, 4), "Error on match"
		self.assertEqual(player1.karma, 390), "Error on match"
		self.assertEqual(player1.matches, 4), "Error on match"

		match.matchWithWinner(player0, player1)
		self.assertEqual(player0.karma, 415), "Error on match"
		self.assertEqual(player0.matches, 5), "Error on match"
		self.assertEqual(player1.karma, 385), "Error on match"
		self.assertEqual(player1.matches, 5), "Error on match"

		match.matchWithWinner(player0, player1)
		self.assertEqual(player0.karma, 419.7), "Error on match"
		self.assertEqual(player0.matches, 6), "Error on match"
		self.assertEqual(player1.karma, 380.3), "Error on match"
		self.assertEqual(player1.matches, 6), "Error on match"

		player0.resetKarma()
		player1.resetKarma()
		match.matchWithoutWinner(player0, player1)
		self.assertEqual(player0.karma, 400), "Error on match"
		self.assertEqual(player0.matches, 1), "Error on match"
		self.assertEqual(player1.karma, 400), "Error on match"
		self.assertEqual(player1.matches, 1), "Error on match"
		self.assertEqual(player1.wins, 0), "Error on match"
		self.assertEqual(player1.losses, 0), "Error on match"

		match.matchWithWinner(player0, player1)
		self.assertEqual(player0.karma, 405), "Error on match"
		self.assertEqual(player0.matches, 2), "Error on match"
		self.assertEqual(player1.karma, 395), "Error on match"
		self.assertEqual(player1.matches, 2), "Error on match"
		
		match.matchWithoutWinner(player0, player1)
		self.assertEqual(player0.karma, 405), "Error on match"
		self.assertEqual(player0.matches, 3), "Error on match"
		self.assertEqual(player1.karma, 395), "Error on match"
		self.assertEqual(player1.matches, 3), "Error on match"

		match.matchWithoutWinner(player0, player1)
		self.assertEqual(player0.karma, 405), "Error on match"
		self.assertEqual(player0.matches, 4), "Error on match"
		self.assertEqual(player1.karma, 395), "Error on match"
		self.assertEqual(player1.matches, 4), "Error on match"
	def testExpectedResults(self):

		player0 = Player()
		player1 = Player()

		match = Match()

		self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.5), "Error estimating match result"

		player1.karma = 375
		self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.5), "Error estimating match result"
		self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player0, player1), 1), "Error estimating match result"

		player1.karma = 374
		self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.53), "Error estimating match result"
		self.assertEqual(match.getExpectedResultIndex(player0,player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result"

		player1.karma = 300
		self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.57), "Error estimating match result"
		self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result"

		player1.karma = 299 
		self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.64), "Error estimating match result"
		self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result"

		player1.karma = 249 
		self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.7), "Error estimating match result"
		self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result"

		player1.karma = 199 
		self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.76), "Error estimating match result"
		self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result"

		player1.karma = 149 
		self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.81), "Error estimating match result"
		self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result"

		player1.karma = 99 
		self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.85), "Error estimating match result"
		self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result"

		player1.karma = 49 
		self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.89), "Error estimating match result"
		self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result"

		player1.karma = 0 
		self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.92), "Error estimating match result"
		self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result"
Example #16
0
    def test_match_winner_set_one_tie_breaker(self):
        player_one = Player(PLAYER_NAME_ONE)
        player_two = Player(PLAYER_NAME_TWO)
        match = Match(player_one, player_two)
        game_points = 4
        set_points = 5

        # Player two winning 5 games
        for index in range(game_points * set_points):
            match.point_won_by(PLAYER_NAME_TWO)

        self.assertEqual(match.score, f'0 - 5, Winner {PLAYER_NAME_TWO}')

        # Player one winning 5 games
        for index in range(game_points * set_points):
            match.point_won_by(PLAYER_NAME_ONE)

        self.assertEqual(match.score, f'5 - 5, Winner {PLAYER_NAME_ONE}')

        # Player two winning 6 games
        for index in range(game_points):
            match.point_won_by(PLAYER_NAME_TWO)

        self.assertEqual(match.score, f'5 - 6, Winner {PLAYER_NAME_TWO}')

        # Player one winning 6 games
        for index in range(game_points):
            match.point_won_by(PLAYER_NAME_ONE)

        self.assertEqual(match.score, f'6 - 6, Winner {PLAYER_NAME_ONE}')

        # Tie breaker game
        for index in range(7):
            match.point_won_by(PLAYER_NAME_ONE)
            match.point_won_by(PLAYER_NAME_TWO)

        self.assertEqual(match.score, f'6 - 6, 7 - 7')

        # Tie breaker player one winner
        match.point_won_by(PLAYER_NAME_ONE)
        match.point_won_by(PLAYER_NAME_ONE)

        self.assertEqual(match.score,
                         f'Winner {PLAYER_NAME_ONE} Set: 1 - 0 | Game: 7 - 6')
Example #17
0
from classes.match import Match
from classes.user import User
from classes.com import Com
from classes.interface import Interface
from classes.api_client import ApiClient

interface = Interface()
match = Match()
user = User()
com = Com()
api_client = ApiClient()


def reset():
    """Resets wins and rounds"""
    match.reset_rounds()
    user.reset_wins()
    com.reset_wins()


def print_default():
    """Prints the default play area"""
    interface.clear_screen()
    interface.print_banner()


def start_new_round():
    """Starts a new round and sets input"""
    match.new_round()
    interface.print_input_prompt()
    user.set_play()
Example #18
0
    def run_upper_bracket(self):
        """
        This method runs through the upper bracket. This advances through each
        stage and runs all matches required. Loses are demoted to the lower
        bracket and winners continue to the next stage.

        Arguments:
            :param self: This tourney
        """
        # Run through each stage and advance the winner as needed
        stage_num = 1
        while (stage_num <= self.stages):
            print('Upper Stage {}'.format(stage_num))
            print('---------------------------\n')
            cur_stage = stage_num + 1
            # Find the parents of all children nodes that need played
            nodes = findall(self.upper_bracket,
                            filter_=lambda node: node.name in
                            ('Stage{}'.format(cur_stage)))
            num_match = 1
            for node in nodes:
                player1, player2 = (x.player for x in node.children)
                cur_match = Match(player1, player2, self.wins_needed)

                print('Match {} - {} v. {}'.format(num_match, player1.name,
                                                   player2.name))
                print('---------------------------------')
                results = cur_match.play_match()
                self.matches.append(cur_match)
                print('{} wins the match in {} games!\n'.format(
                    results['winner'], results['games_played']))

                node.contestant = results['winner']
                node.player = player1 if results[
                    'winner'] == player1.name else player2

                # Move the loser down to the loser's bracket
                loser = player2 if results[
                    'winner'] == player1.name else player1
                loser.losses += 1

                # First check to see if this is the last stage
                #if(stage_num is self.stages):
                # Since we are the last stage, we go to the minor of the previous stage
                #lower = findall(self.lower_bracket, lambda node: node.name == 'Stage{}-Minor'.format(stage_num) and node.player is None)[0]
                #lower.contestant = loser.name
                #lower.player = loser
                # If we are an odd stage, we move to the major loser branch, else the minor
                #elif(stage_num % 2 is 1):
                #lower = findall(self.lower_bracket, lambda node: node.name == 'Stage{}-Major-Sub'.format(stage_num) and node.player is None)[0]
                #lower.contestant = loser.name
                #lower.player = loser
                #else:
                #lower = findall(self.lower_bracket, lambda node: node.name == 'Stage{}-Minor'.format(stage_num) and node.player is None)[0]
                #lower.contestant = loser.name
                #lower.player = loser

                if (stage_num is 1):
                    # Since we are the last stage, we go to the minor of the previous stage
                    lower = findall(
                        self.lower_bracket,
                        lambda node: node.name == 'Stage{}-Major-Sub'.format(
                            stage_num) and node.player is None)[0]
                    lower.contestant = loser.name
                    lower.player = loser
                else:
                    lower = findall(
                        self.lower_bracket,
                        lambda node: node.name == 'Stage{}-Minor'.format(
                            stage_num) and node.player is None)[0]
                    lower.contestant = loser.name
                    lower.player = loser
                num_match += 1

            # Now that this stage is done, print the brackets!
            stage_num += 1
            self.print_upper_bracket()
        # Done! Print the bracket
        print('End of Upper Bracket')
        print('---------------------------\n')
        self.print_brackets()
Example #19
0
    def run_lower_bracket(self):
        """
        This method runs through the upper bracket. This advances through each
        stage and runs all matches required. Loses are done and winners advance
        to the next stage. The winner of the lower bracket plays in the grand
        championship.

        Arguments:
            :param self: This tourney
        """
        # Lower brackets alternate between major and minor events. If
        # applicable, we will do the minor for the stage (Stage 1 has
        # no minor), then we will do the majors
        stage_num = 1
        while (stage_num <= self.stages):
            print('Lower Stage {}'.format(stage_num))
            print('---------------------------\n')
            # If we are stage one, there is no minor
            if (stage_num is not 1):
                # Find the parents of all children nodes that need played
                nodes = findall(self.lower_bracket,
                                filter_=lambda node: node.name ==
                                'Stage{}-Major-Sub'.format(stage_num))
                num_match = 1
                for node in nodes:
                    print(node)
                    player1, player2 = (x.player for x in node.children)
                    cur_match = Match(player1, player2, self.wins_needed)

                    print('Match {} - {} v. {}'.format(num_match, player1.name,
                                                       player2.name))
                    print('---------------------------------')
                    results = cur_match.play_match()
                    self.matches.append(cur_match)
                    print('{} wins the match in {} games!\n'.format(
                        results['winner'], results['games_played']))

                    # Resolve Match
                    node.contestant = results['winner']
                    node.player = player1 if results[
                        'winner'] == player1.name else player2

                    # The loser is done! No more advancement. Move on to the minors.
                    loser = player2 if results[
                        'winner'] == player1.name else player1
                    loser.losses += 1

            # Now do the major
            # Find the parents of all children nodes that need played
            nodes = findall(self.lower_bracket,
                            filter_=lambda node: node.name in
                            ('Stage{}-Major'.format(stage_num)))
            num_match = 1
            for node in nodes:
                player1, player2 = (x.player for x in node.children)
                cur_match = Match(player1, player2, self.wins_needed)

                print('Match {} - {} v. {}'.format(num_match, player1.name,
                                                   player2.name))
                print('---------------------------------')
                results = cur_match.play_match()
                self.matches.append(cur_match)
                print('{} wins the match in {} games!\n'.format(
                    results['winner'], results['games_played']))

                # Resolve Match
                node.contestant = results['winner']
                node.player = player1 if results[
                    'winner'] == player1.name else player2

                # The loser is done! No more advancement. Move on to the minors.
                loser = player2 if results[
                    'winner'] == player1.name else player1
                loser.losses += 1

            # At the end of the stage, print the bracket
            stage_num += 1
            self.print_lower_bracket()

        # Done! Print the bracket
        print('End of Lower Bracket')
        print('---------------------------\n')
        self.print_brackets()
Example #20
0
def get_latest_agent(db,
                     match_db,
                     match=Match(
                         dict(id='',
                              begin='',
                              time='',
                              sa='',
                              mas='',
                              plays='',
                              status='')),
                     player=''):
    """
    Get the lastest agent obj in the database or create if it not exists
    If a match and player was passed, it will get the lastest agents as of a match obj in the database
    :param db: `Database` a Database object
    :param match: `Match`a Match object
    :param player: `string` a player ID

    Usage
    >>> (leader, learner) = get_lastest_agent(education_db)
    >>> print(leader, learner)

    <classes.agent.Agent object at 0x7fe6de3287d0>
    <classes.agent.Agent object at 0x7fe6de3289a2>
    """

    try:
        res = db.get(offset=0, limit=2, sort="createdAt:desc").json()

        if len(res) < 2:
            leader = Agent(
                db.create(
                    json.dumps({
                        "birth": datetime.now().ctime(),
                        "progenitor": "I'm the first one, bitch ;)",
                        "becomeLeader": datetime.now().ctime(),
                        "life": 100,
                        "memory": [],
                        "matchsAsLearner": 0,
                        "matchsAsLeader": 0,
                        "victories": 0,
                        "defeats": 0,
                        "draw": 0
                    })).json(), ('O', 0))

            learner = Agent(
                db.create(
                    json.dumps({
                        "birth": datetime.now().ctime(),
                        "progenitor": leader.id,
                        "life": 100,
                        "memory": [],
                        "matchsAsLearner": 0,
                        "matchsAsLeader": 0,
                        "victories": 0,
                        "defeats": 0,
                        "draw": 0
                    })).json(), ('O', 0))

            return [leader, learner]

        elif match.id != '' and player != '':

            if res[1]['_id'] == player['playerId']:
                [leader, learner] = check_life(db, res)

                if leader.id == player['playerId']:
                    return [leader, learner]
                else:
                    add_new_mas_player(match_db, match, player, leader)
                    return [leader, learner]

        else:
            return check_life(db, res)
    except:
        raise GetAgentError
    def __init__(self, p1_name, p2_name, model, points_played='', mixture=0, ts=False, setend=1):
        self.p1 = player.Player.get_player(p1_name)
        if self.p1.match_impact == 0:
            self.p1.calculate_impact()
        self.p2 = player.Player.get_player(p2_name)
        if self.p2.match_impact == 0:
            self.p2.calculate_impact()

        self.ts = ts

        if self.ts:
            player.Player.calculate_all_ts()

        self.points_played = points_played.split('.')

        self.match_exp = 0
        self.set_exp = {}
        self.game_exp = {}
        self.point_exp = {}

        self.calculate_exp(self.p1, self.p2, 3, self.ts)


        if mixture != 0:
            m = Match(0,0,0,0,0,0,self.points_played[0])
            p1_ingame_pct = m.match_pct.p1_serv_pct
            p2_ingame_pct = m.match_pct.p2_serv_pct

            self.match_exp.p1_pct = self.match_exp.p1_pct * (1 - mixture) + p1_ingame_pct * mixture
            self.match_exp.p2_pct = self.match_exp.p2_pct * (1 - mixture) + p2_ingame_pct * mixture

            self.set_exp['0:0'].p1_pct = self.set_exp['0:0'].p1_pct * (1 - mixture) + p1_ingame_pct * mixture
            self.set_exp['0:0'].p2_pct = self.set_exp['0:0'].p2_pct * (1 - mixture) + p2_ingame_pct * mixture

            self.set_exp['1:0'].p1_pct = self.set_exp['1:0'].p1_pct * (1 - mixture) + p1_ingame_pct * mixture
            self.set_exp['1:0'].p2_pct = self.set_exp['1:0'].p2_pct * (1 - mixture) + p2_ingame_pct * mixture

            self.set_exp['1:1'].p1_pct = self.set_exp['1:1'].p1_pct * (1 - mixture) + p1_ingame_pct * mixture
            self.set_exp['1:1'].p2_pct = self.set_exp['1:1'].p2_pct * (1 - mixture) + p2_ingame_pct * mixture

            self.set_exp['0:1'].p1_pct = self.set_exp['0:1'].p1_pct * (1 - mixture) + p1_ingame_pct * mixture
            self.set_exp['0:1'].p2_pct = self.set_exp['0:1'].p2_pct * (1 - mixture) + p2_ingame_pct * mixture

        # for set 1 end
        set1_length = self.points_played[0].split(';').__len__()
        if set1_length % 2 == 1:
            next_set_server = 2
        else:
            next_set_server = 1

        # tiebreak
        if self.points_played[0].__contains__('/'):
            if self.points_played[0].split(';')[12].split('/').__len__() % 2 == 1:
                if self.points_played[0][self.points_played[0].__len__()-1] == 'S' or self.points_played[0][self.points_played[0].__len__()-1] == 'A':
                    set_score = '1:0'
                else:
                    set_score = '0:1'
            else:
                if self.points_played[0][self.points_played[0].__len__() - 1] == 'S' or self.points_played[0][self.points_played[0].__len__() - 1] == 'A':
                    set_score = '0:1'
                else:
                    set_score = '1:0'
        else:
            if self.points_played[0].split(';').__len__() % 2 == 1:
                if self.points_played[0][self.points_played[0].__len__() - 1] == 'S' or self.points_played[0][self.points_played[0].__len__() - 1] == 'A':
                    set_score = '1:0'
                else:
                    set_score = '0:1'
            else:
                if self.points_played[0][self.points_played[0].__len__() - 1] == 'S' or self.points_played[0][self.points_played[0].__len__() - 1] == 'A':
                    set_score = '0:1'
                else:
                    set_score = '1:0'

        if model == 'set_iid_model':
            self.model = SetIIDModelSetend(self.match_exp, self.set_exp, self.game_exp, self.point_exp, set_score, next_set_server, 3)
        elif model == 'match_iid_model':
            self.model = MatchIIDModelSetend(self.match_exp, self.set_exp, self.game_exp, self.point_exp, set_score, next_set_server, 3)

        self.match_score_prob = {}
        self.match_winner_prob = {}