Example #1
0
    def main(self):
        command_helper = InputHelper(["play", "exit"])
        player_type_helper = InputHelper(
            ["player", "historian", "mostcommon", "random", "sequential"]
        )
        try:
            next_command = command_helper.get_legal_input("Please enter a command: \n")

            if next_command == "play":
                players = []
                for player_num in range(1, 3):
                    player_name = input(f"Please enter player {player_num}'s NAME: ")
                    player_type = player_type_helper.get_legal_input(
                        f"Please enter player {player_num}'s TYPE: "
                    )

                    players.append(self.__create_player(player_name, player_type))

                number_of_games = int(input("Please enter number of rounds: "))

                tournament = Tournament(players[0], players[1], number_of_games)
                tournament.arrange_tournament()
            else:
                sys.exit(0)
        except KeyboardInterrupt:
            return self.main()
 def test_new_round(self):
     players = [0, 1, 2, 3] 
     t = Tournament(players)  
     games = t.new_round()
     self.assertEqual(1, len(games)) 
     self.assertEqual(0, games[0].gameid) 
     self.assertEqual([0, 1, 2, 3], games[0].playerids) 
Example #3
0
    def play(cls, para):
        if not checkPara(para, ['uid', 'machine_id']):
            return Error.INVALID_PARAM

        uid = para['uid']
        mid = para['machine_id']

        bonus = cls(uid, mid)
        ret = bonus.doPlay()

        if ret is False:
            return Error.BONUS_NOT_EXIST

        (bet, rate, total_win, left) = ret

        user = User(uid)

        if total_win > 0:
            user.coin += total_win
            Tournament.compete(uid, mid, total_win)
            User(uid).addWinRec(total_win / bet)

        data = {'coin': user.coin, 'bet': bet, 'rate': rate, 'total_win': total_win, 'left': left}

        return data
Example #4
0
    def play(cls, para):
        if not checkPara(para, ["uid", "machine_id", "idx"]):
            return Error.INVALID_PARAM

        uid = para["uid"]
        mid = para["machine_id"]
        idx = para["idx"]

        bonus = cls(uid, mid)
        ret = bonus.doPlay(idx)

        if ret is False:
            return Error.BONUS_NOT_EXIST

        (bet, rate, total_win, left) = ret

        user = User(uid)

        if total_win > 0:
            user.coin += total_win
            Tournament.compete(uid, mid, total_win)
            User(uid).addWinRec(total_win / bet)

        data = {"coin": user.coin, "bet": bet, "rate": rate, "total_win": total_win, "left": left}

        return data
Example #5
0
def run_tournament():
    num_games = 20
    player_1 = NumWinsAgent(Agent.RED_PLAYER)
    player_2 = SmartRandomAgent(Agent.BLACK_PLAYER)
    tournament = Tournament(player_1, player_2, num_games)
    tournament.play_tournament()
    wins = tournament.get_player_wins()
    for win in wins:
        print(win)
Example #6
0
 def process_results(self, my_strategy, other_strategy):
     self.my_points += Tournament.score(Tournament, my_strategy,
                                        other_strategy)[0]
     self.other_points += Tournament.score(Tournament, my_strategy,
                                           other_strategy)[1]
     if self.my_points >= self.other_points:
         self.strat = False
     else:
         self.strat = True
def parse_directory(dirname, mode='json', reuse_html=False):

    tour = Tournament()
    tour.create_tournament_from_directory(dirname, reuse_html=reuse_html)

    tour_json_file = os.path.join(dirname, '{0} {1}.json'.format(tour.year, tour.tour_name))
    
    if mode == 'json':
        if tour.is_valid():
            json.dump(tour.to_dict(), open(tour_json_file, 'w'), indent=4)
Example #8
0
    def train(self):

        for i in range(1, self.config.num_iters + 1):
            log.info(f'Iteration #{i} ...')
            iteration_train_samples = deque([],
                                            maxlen=self.config.queue_max_len)

            # Start self-play to generate training samples
            for i in tqdm(range(self.config.num_self_play_games),
                          desc="Self Play"):
                self.mcts = MCTS(self.game, self.nnet, self.config)
                iteration_train_samples += self.start_game()

            # save the iteration examples to the history
            self.train_examples_history.append(iteration_train_samples)

            if len(self.train_examples_history
                   ) > self.config.num_iters_for_train_examples_history:
                self.train_examples_history.pop(0)

            train_examples = []
            for train_example in self.train_examples_history:
                train_examples.extend(train_example)

            self.nnet.save_checkpoint(folder=self.config.checkpoint,
                                      filename='temp_model.tar')
            self.pnet.load_checkpoint(folder=self.config.checkpoint,
                                      filename='temp_model.tar')
            p_mcts = MCTS(self.game, self.pnet, self.config)

            # shuffle examples before training
            shuffle(train_examples)

            self.nnet.train(train_examples)
            n_mcts = MCTS(self.game, self.nnet, self.config)

            log.info('Playing tournament against last iteration network')
            tournament = Tournament(p_mcts.get_action_with_high_prob,
                                    n_mcts.get_action_with_high_prob,
                                    self.game)
            p_wins, n_wins, draws = tournament.play_games(
                self.config.num_tournament_games)
            self.monitor_metrics(i, n_wins, p_wins, draws)

            # If all games are draw or if n_wins doesn't exceed threshold,
            if (p_wins + n_wins == 0) or (n_wins / float(p_wins + n_wins) <
                                          self.config.model_accept_threshold):
                log.info('Model not accepted')
                self.nnet.load_checkpoint(folder=self.config.checkpoint,
                                          filename='temp_model.tar')
            else:
                log.info('Model accepted')
                self.nnet.save_checkpoint(folder=self.config.checkpoint,
                                          filename='best_model.tar')
Example #9
0
def new_tournament():
    jsonData = simplejson.loads(request.body.read()) if request.body else {}
    tournament = False
    if jsonData:
        from Tournament import Tournament
        TournamentObj = Tournament(db)
        tournament = TournamentObj.create_new_tournament(jsonData)
    if tournament:
        return api_response(tournament=tournament)
    else:
        return api_error(message="Something went wrong, we'll figure it out")
 def test_init(self):
     players = [0, 1, 2, 3] 
     t = Tournament(players)
     self.assertNotEqual(None, t)
     table = t.get_table()
     self.assertEqual(4, len(table))
     self.assertEqual(1, table[1].playerid)
     self.assertEqual(0, table[1].games)
     self.assertEqual(0, table[1].points)
     self.assertEqual(0, table[1].goaldifference)
     
     self.assertEqual(0, len(t.get_games()))
Example #11
0
def get_tournaments():
    from Tournament import Tournament
    TournamentObj = Tournament(db)
    tournaments = TournamentObj.get_tournaments()
    from Location import Location
    LocationObj = Location(db)
    locations = LocationObj.get_locations()
    if auth.has_membership('Admin'):
        types = TournamentObj.get_tournament_types()
        return api_response(tournaments=tournaments,
                            types=types,
                            locations=locations)
    else:
        return api_response(tournaments=tournaments, locations=locations)
def main():
    tournament = Tournament()

    actual = LoadBracket("brackets/actual.bracket", tournament, 2)
    player = LoadBracket("brackets/rob.bracket", tournament)

    start, end = tournament.getRoundRange(3)
    for i in range(start, 63):
        print(player.getStrGame(i))

    # start, end = tournament.getRoundRange(1)
    # for i in range(start, end):
    # 	print(player.getStrGame(i))

    print(actual.getPoints(player))
Example #13
0
    def run_interface(self):
        """
            Main interface that a user interacts with
        """
        print("--------------------------Rock-Paper-Scissors--------------------------")

        self.get_player_types()
        self.declare_player_types()
        number_of_games = int(input("Number of games to be played: "))
        player_one = self.__players__[0]
        player_two = self.__players__[1]
        tournament = Tournament(player_one, player_two, number_of_games)
        tournament.arrange_tournament()

        print("-----------------------------------------------------------------------")
Example #14
0
 def startGame(self):
     fistPlayer = self.playerOne.text()
     secondPlayer = self.playerTwo.text()
     thridPlayer = self.playerThree.text()
     fourthPlayer = self.playerFour.text()
     self.frame = Tournament(fistPlayer, secondPlayer, thridPlayer,
                             fourthPlayer, 1)
     self.close()
Example #15
0
def main():
    tournament = Tournament()

    startingPoint = LoadBracket('brackets/actual.bracket', tournament, 2)
    player = LoadBracket("brackets/ferd.bracket", tournament)

    for i in range(50):
        # for i in range(2**(BITS - 5)):
        gen = GeneratedBracket(i, startingPoint, tournament)
        print(i, gen.probability, gen.getPoints(player))
Example #16
0
def main():
    tournament = Tournament()
    startingPoint = LoadBracket('brackets/actual.bracket', tournament, 2)

    PlayerHandler("__^__^_//*v*//", "brackets/blake.bracket", tournament)
    PlayerHandler("Little Dribble", "brackets/adam.bracket", tournament)
    PlayerHandler("winner_ganadora", "brackets/an.bracket", tournament)
    PlayerHandler("At Least No Duke", "brackets/duke.bracket", tournament)
    PlayerHandler("The 'Eyes Have It", "brackets/eyes.bracket", tournament)
    PlayerHandler("Thundering Ferd", "brackets/ferd.bracket", tournament)
    PlayerHandler("JakeSickAFBracket", "brackets/jake.bracket", tournament)
    PlayerHandler("Wackabrack", "brackets/spence.bracket", tournament)
    PlayerHandler("Steven Kerr", "brackets/steve.bracket", tournament)
    PlayerHandler("TLaw and Order", "brackets/tlaw.bracket", tournament)
    PlayerHandler("Animal Fries", "brackets/rob.bracket", tournament)

    totalProbabilty = 0.0
    # for i in range(50):
    # for i in range(2**(BITS - 5)):
    for i in range(NUM_IDS):
        gen = GeneratedBracket(i, startingPoint, tournament)

        curMax = 0

        for player in PlayerHandler.ALL:
            playerValue = gen.getPoints(player.bracket)
            if playerValue > curMax:
                maxList = [player]
                curMax = playerValue
            elif playerValue == curMax:
                maxList.append(player)

        if len(maxList) == 1:
            maxList[0].winProbablity += gen.probability
        else:
            for player in maxList:
                player.tieProbablity += gen.probability

        totalProbabilty += gen.probability

        #print to screen
        # print(f"{i},{gen.probability}", end="")
        # for player in PlayerHandler.ALL:
        # 	print(f",{gen.getPoints(player.bracket)}", end="")
        # print()

    print(totalProbabilty)
    for player in sorted(PlayerHandler.ALL,
                         key=lambda player: -player.winProbablity):
        print(player)
Example #17
0
def main():
    display_separator("=")
    display_intro()
    display_separator("=")
    while True:
        try:
            noOfPlayers = int(input("Number of players: "))
            if (noOfPlayers < 2):
                print("Not enough players. Please try again.")
            else:
                break
        except ValueError:
            print("Invalid input. Please Try again.")
    tournament = Tournament()
    playersList = players(noOfPlayers, tournament)
    display_separator("-")
    main_menu(playersList, tournament)
Example #18
0
def geneticAlgorithm():
    ratio_initial_max_mutation_numbers = 0.4
    ratio_initial_max_mutation_stars = 0.5
    ratio_max_mutation_numbers = ratio_initial_max_mutation_numbers
    ratio_max_mutation_stars = ratio_initial_max_mutation_stars
    total_fathers = 500
    total_generations = 100
    tournament_size = 5
    
    file = readFile("premios2012.txt")
    winning_combinations = fileToCombination(file)
    fathers = createFirstGeneration(total_fathers)
    
    count_generations = 0
    tournament = Tournament()
    
    while count_generations<total_generations:
        print("Generacion: " , count_generations)
        if count_generations%10==0:
            tournament_size+=1
            ratio_max_mutation_numbers -= 0.015
            ratio_max_mutation_stars -= 0.019
        count_generations+=1
        
        fathers = tournament.valueAll(fathers, winning_combinations)
        fathers = tournament.fightTournament(fathers, winning_combinations, total_fathers, tournament_size)
        sons = reproduceCombinations(fathers)
        sons = tournament.valueAll(sons, winning_combinations)
        sons = mutateCombinations(sons, ratio_max_mutation_numbers, ratio_max_mutation_stars)
        sons = tournament.valueAll(sons, winning_combinations)
        
        sons.sort(key=lambda combination: combination.value, reverse=False)
        fathers = sons
        
        best_combination = sons[len(sons)-1]
        best_combination.printInfo()
Example #19
0
    def spin(cls, para):
        if not checkPara(para, ['uid', 'machine_id', 'lines', 'bet', 'is_free']):
            return Error.INVALID_PARAM

        uid = para['uid']
        game_id = para['machine_id']
        lines = para['lines']
        bet = para['bet']
        is_free = para['is_free']

        fake_flag = 0
        if 'fakeflag' in para:
            fake_flag = int(para['fakeflag'])

        lv = User(uid).level

        #check
        if not ConfMgr.isMachineLocked(game_id, lv):
            return Error.MACHINE_LOCKED

        if not ConfMgr.isLineValid(game_id, lines):
            return Error.LINE_EXCEEDED

        if not ConfMgr.isBetValid(lv, bet):
            return Error.BET_EXCEEDED

        pay_in = 0
        user = User(uid)
        cur_coin = user.coin

        # may change wild_tune for this user
        user.addSpin()

        if not is_free:
            user.clearWinRec()

        if not is_free:
            pay_in = lines * bet
            if cur_coin < pay_in:
                Log.error('no enough coin to spin')
                return Error.NO_COIN
        else:
            # pick saved bet and lines for free spin
            free_spin = FreeSpin(uid, game_id)
            ret = free_spin.consume()

            if ret is False:
                return Error.NO_FREE_SPIN

            # override
            (lines, bet) = ret

        machine = cls(game_id)

        # ignore bonus if skip playing it
        game_type = BonusGameType.getBonusGameType(game_id)
        bonus_game = game_type(uid, game_id)
        bonus_game.remove()

        (response, win, bonus_num, spin_num) = machine.doSpin(game_id, lv, lines, bet, is_free, fake_flag)

        if bonus_num > 0:
            game_type.create(uid, game_id, bonus_num, bet)
            Log.debug('created bonus games: bonus_num=%s'%bonus_num)

        if spin_num > 0:
            free_spin = FreeSpin(uid, game_id)
            free_spin.add(spin_num, lines, bet)
            response['is_new_freespin'] = True
            Log.debug('added free spin=%s'%spin_num)

        # save for big/mega win
        user.addWinRec(win / bet)

        # Tournament update
        Tournament.compete(uid, game_id, win)

        # compose reponse
        now_coin = cur_coin - pay_in + win
        user.coin = now_coin
        response['coin'] = now_coin

        (now_exp, lv_up) = user.addExp(lines*bet)
        response['exp'] = now_exp

        response['level'] = user.level

        free_spin = FreeSpin(uid, game_id).getAll()
        if free_spin:
            response['free_spin'] = free_spin

        win_info = user.checkWinRec()
        if win_info:
            response.update(win_info)

        rank_info = Tournament.getRank({'uid': uid, 'machine_id': game_id})
        if rank_info != Error.TOUR_NOT_OPEN:
            response['rank_info'] = rank_info

        # share gift flag
        share = UserShareGift(uid)
        if '5combo' in response:
            share.setFlag(UserShareGift.TYPE_COMBO)

        # bonus may also trigger it
        if 'is_mega' in response:
            share.setFlag(UserShareGift.TYPE_MEGA)

        if lv_up:
            share.setFlag(UserShareGift.TYPE_LEVELUP)

        #only for stat
        data = {'bet': pay_in,
                'win': win,
                'spin': 1,
                'trigger_freespin': 1 if spin_num > 0 else 0,
                'trigger_bonus': 1 if bonus_num > 0 else 0,
                'free_spin': 1 if is_free else 0,
                }
        Stat().incr(data)

        return response
Example #20
0
import multiprocessing


def start_game(cellular_a):
    cellular_a.play()


def start_chat(cellular_a):
    cellular_a.read_chat()


if __name__ == "__main__":

    ## start with tournament
    tournament = "SmartCUP"
    pltournament1 = Tournament(name="ai9_pl1", tournament=tournament)
    pltournament2 = Tournament(name="ai9_pl2", tournament=tournament)
    pltournament3 = Tournament(name="ai9_pl3", tournament=tournament)
    input(
        'Finished to join in tournament correctly! Press any key to continue..'
    )
    ##start with game
    manager = multiprocessing.Manager()
    for i in range(1, 13):
        value = tournament + "-" + str(i) + "-1"
        print("Start game on: " + value)
        input('wait')
        SAME_NAME = value
        NAME_GAME = SAME_NAME  #+datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        NAME_CHAT = SAME_NAME
        debug = False
Example #21
0
#  to report the average RMSD
sum_of_RMSDs_all = 0

# keep a seperate running sum of RMSDs for the
#  top 4 teams (by input rank) for each tournament
sum_of_RMSDs_top_4 = 0

sum_of_ceiling_hits = 0

# declare eventual Tournament object outside for loop so the last tournament's values can be accessed
test_tournament = -1

for i in range(0, tournaments):
    #first_line = first_line + ',T' + str(i + 1)

    test_tournament = Tournament(teams, matches_per_team)

    while not test_tournament.create_match_schedule():
        continue

    test_tournament.run_tournament()

    # if needed, assign random TBP
    if (random_TBP):
        for t in test_tournament.teams:
            t.tp = int(random.random() * 1000)

    test_tournament.rank()

    sum_of_squared_residuals_all = 0
    sum_of_squared_residuals_top_4 = 0
from Tournament import Tournament, elo_ranks
from random import gauss, randint

players = ["Alice","Bob","Carol","David","Eve","Frank"]
skill =   [2.1,     2,    2.2,    3.5,    2,   1.7]
T = Tournament(players)

for i in range(500):
    p1 = randint(0,5)
    p2 = randint(0,5)
    
    sc1 = abs(gauss(skill[p1],.2))
    sc2 = abs(gauss(skill[p2],.2))

    
    T.update(players[p1],players[p2],sc1,sc2)
    
elo_ranks(T)

print(T.predict("Frank","David"))
Example #23
0
    combinations = [(a, b, c, d) for a in range(5) for b in range(5)
                    for c in range(5) for d in range(2)]

    for combination in combinations:
        second.VALUABLE_STARTING_MIN_REPEATABILITY = combination[0]
        second.VALUABLE_RESPONDING_MIN_REPEATABILITY = combination[1]
        second.MIN_STACK_VALUE_TO_REPEAT = combination[2]
        second.IGNORE_WINNING_WHEN_REPEATING = combination[3] == 1

        # total statistics
        n_first_won_tournaments = 0
        n_first_won_games = 0

        # play as many tournaments as needed
        for TOURNAMENT in range(N_TOTAL_TOURNAMENTS):
            tournament = Tournament(first, second, N_GAMES_IN_TOURNAMENT)
            tournament.playTournament()

            if tournament.getAbsoluteWinner() == first:
                n_first_won_tournaments += 1

            n_first_won_games += tournament.player1_stats['games_won']

        percentage = 100 * (
            (n_first_won_games / N_TOTAL_TOURNAMENTS) / N_GAMES_IN_TOURNAMENT)

        # statistics: (combination) : average percentage of games won in the tournament
        print("Combination {} : {}".format(combination, percentage))

        output.write('{};{};{};{};{}\n'.format(combination[0], combination[1],
                                               combination[2], combination[3],
Example #24
0
""" test.py -- A simple script for testing the Tournament module by simulating
a short 32-player tournament and outputting the results.
"""

from Player import Player
from Tournament import Tournament
from random import randint
from console import list_tables, list_standings

if __name__ == '__main__':
    EVENT = Tournament('Test Event')
    for x in open('player_names.txt').readlines():
        x = x.strip('\n')
        first, last = x.split(' ')
        EVENT.add_player(Player(first, last))

    for x in xrange(5):
        EVENT.start_round()
        print 'Round: ', EVENT.round

        list_tables(EVENT, showall=True)

        for match in EVENT.tables[EVENT.round]:
            y = randint(1, 100)
            if y < 25:
                match.report_match(2, 1)
            if y >= 25 and y < 50:
                match.report_match(2, 0)
            if y >= 50 and y < 75:
                match.report_match(1, 2)
            if y >= 75 and y <= 100:
Example #25
0
def main():
    print(django.get_version())
    # Create Players
    p1 = Player(uuid.uuid4(), 'Drew', 'Casner')
    p2 = Player(uuid.uuid4(), 'RJ', 'Morley')
    p3 = Player(uuid.uuid4(), 'Jesper', 'Stryen')
    p4 = Player(uuid.uuid4(), 'Austin', 'Smith')
    p5 = Player(uuid.uuid4(), 'Lucas', 'Sward')
    p6 = Player(uuid.uuid4(), 'Ben', 'Settlerquist')
    p7 = Player(uuid.uuid4(), 'Powell', 'Hinson')
    p8 = Player(uuid.uuid4(), 'Quinn', 'Mahone')
    p9 = Player(uuid.uuid4(), 'Colt', 'Wise')
    p10 = Player(uuid.uuid4(), 'Ryan', 'Becker')
    p11 = Player(uuid.uuid4(), 'Matt', 'Skogen')
    p12 = Player(uuid.uuid4(), 'Isaiah', 'Jones')
    p13 = Player(uuid.uuid4(), 'John', 'Gadbois')
    p14 = Player(uuid.uuid4(), 'Kian', 'Tanner')
    p15 = Player(uuid.uuid4(), 'Pete', 'Snowden')
    p16 = Player(uuid.uuid4(), 'Nick', 'Hearon')

    # Create Teams
    t1 = Team(uuid.uuid4(), 'The Killerz', 'Boulder', 'Colorado')
    t1.addPlayer(p1)
    t1.addPlayer(p2)
    t2 = Team(uuid.uuid4(), 'The Vikings', 'New York', 'New York')
    t2.addPlayer(p3)
    t2.addPlayer(p4)
    t3 = Team(uuid.uuid4(), 'The High Flyers', 'Austin', 'Texas')
    t3.addPlayer(p6)
    t3.addPlayer(p7)
    t4 = Team(uuid.uuid4(), 'The Ballers', 'Aurora', 'Colorado')
    t4.addPlayer(p5)
    t4.addPlayer(p8)
    t5 = Team(uuid.uuid4(), 'The Wurst', 'Boulder', 'Colorado')
    t5.addPlayer(p9)
    t5.addPlayer(p10)
    t6 = Team(uuid.uuid4(), 'Da N3rds', 'Seattle', 'Washington')
    t6.addPlayer(p11)
    t6.addPlayer(p12)
    t7 = Team(uuid.uuid4(), 'The Climbers', 'LA', 'Cali')
    t7.addPlayer(p13)
    t7.addPlayer(p14)
    t8 = Team(uuid.uuid4(), 'Rockstars', 'Summit County', 'Colorado')
    t8.addPlayer(p15)
    t8.addPlayer(p16)

    # Test Game
    g1 = Game(uuid.uuid4(), t1, t2)

    # Create Tournament
    turny1 = Tournament(uuid.uuid4(), 'Champions Club', 1, 8 * 60, 60)
    turny1.addTeam(t1, 0)
    turny1.addTeam(t2, 0)
    turny1.addTeam(t3, 0)
    turny1.addTeam(t4, 0)
    turny1.addTeam(t5, 0)
    #turny1.addTeam(t6, 0)
    #turny1.addTeam(t7, 0)
    #turny1.addTeam(t8, 0)
    turny1.start()

    # Update results
    #'''
    turny1.getGames()[2][0].setScoreHome(90)
    turny1.getGames()[2][0].setScoreAway(80)
    turny1.getGames()[2][0].gameComplete()
    print('')
    print(turny1.getGames()[2][0].getWinningTeam())
    print('')
    turny1.update()
Example #26
0
    def loadGame(self):
        tempBoard = Board()
        tempTournament = Tournament()
        MAX_COL = 9
        MAX_ROW = 8
        rowLine = 0
        strboard = [[]]
        gameboard = [[Die() for j in range(MAX_COL)] for i in range(MAX_ROW)]
        print("************************************")
        print("*         ~~ Load Game ~~          *")
        print("************************************")
        print()
        fileName = str(input("Enter File Name: "))
        fileName += ".txt"
        file = open(fileName, 'r')
        # Skip first line containing Board:
        file.readline()
        for line in file:
            line = line.split(' ')
            for i in line:
                if (i != ''):
                    strboard[rowLine].append(i)
            rowLine += 1
            if (rowLine == MAX_ROW):
                break
            strboard.append([])
        # Skip Blank
        file.readline()
        # Read computer wins string
        computerstr = file.readline()
        computerstr = computerstr.split(' ')
        computerwin = int(computerstr[2])
        # Skip Blank
        file.readline()
        humanstr = file.readline()
        humanstr = humanstr.split(' ')
        humanwin = int(humanstr[2])
        # Skip Blank
        file.readline()
        # Read Next Player
        next = file.readline()
        next = next.split(' ')
        nextPlayer = next[2]

        # Create Board
        iter = 0
        for row in range(7, -1, -1):
            for col in range(0, 9):
                tmp = strboard[row][col]
                if (tmp != "0" and tmp != "0\n"):
                    player = tmp[0]
                    topNum = int(tmp[1])
                    rightNum = int(tmp[2])
                    gameboard[iter][col] = self.board.dieSwitch(
                        topNum, rightNum, player)
            iter += 1

        # Set Objects
        tempBoard.setGameBoard(gameboard)
        tempTournament.setComputerWins(computerwin)
        tempTournament.setHumanWins(humanwin)
        self.setTournament(tempTournament)
        self.setBoard(tempBoard)
        self.startGame(nextPlayer, False)
Example #27
0
from read_input import read_input

if __name__ == "__main__":
    #Reads the name of the tournament from prompt
    if len(sys.argv) != 2: sys.exit('### ERROR: Choose a tournament')
    nfile = sys.argv[1]

    #Reads the tournament details, the groups and the teams from the input file
    [teams_and_groups, file_results, ppm] = read_input(nfile)
    allteams = []
    allgroups = []
    nallgroups = set([])
    ngroup = 'NG'
    for i in teams_and_groups:
        if i[0:4] == '': ngroup = 'NG'
        elif i[0:4] == '### ':
            ngroup = i[4:]
            nallgroups.add(ngroup)
        else:
            allteams.append(Team(i))
            allteams[-1].set_group(ngroup)
    pointspermatch = [2, 1, 0]
    for i in sorted(nallgroups):
        allgroups.append(
            Group(i, [team for team in allteams if team.group == i], ppm))

    #Creates the tournament
    tournament = Tournament(allgroups, file_results)
    tournament.update_results()
    tournament.print_groups()
Example #28
0
Player0 = 1613.0
Player1 = 1609.0
Player2 = 1477.0
Player3 = 1388.0
Player4 = 1586.0
Player5 = 1720.0

players = ["Player0", "Player1", "Player2", "Player3", "Player4", "Player5"]
ratings = [Player0, Player1, Player2, Player3, Player4, Player5]
results = [[0, 0.5, 1, 1, 0], [1, 1, 1, 1, 0], [0.5, 0, 1, 1, 0],
           [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [1, 1, 1, 1, 1]]
record = [
    "X L D W W L", "W X W W W L", "D L X W W L", "L L L X L L", "L L L W X L",
    "W W W W W X"
]

# Initialise Swiss Tournament
tournament = Tournament(ratings, results)
performance_ratings = tournament.GetPerformanceRatings()
old_ratings = ratings.copy()
tournament.UpdateEloScores()

# Print results
print("Rating:\tprev\tnew\tperformance\trecord")
for i in range(len(players)):
    print(
        players[i] +
        "\t{}\t{}\t{}".format(math.floor(old_ratings[i]), math.floor(
            ratings[i]), math.floor(performance_ratings[i])) + "\t\t" +
        record[i])
Example #29
0
        # for names of the form "Smith, John"
        rex = search("(\w+),( |)(\w+)", username)
        if rex is not None:
            firstname, lastname = rex.group(3), rex.group(1)

        # commit this stuff to the event
        if sanctioned == True:
            userpin = int(raw_input("pin  -> "))
            EVENT.add_player(Player(firstname, lastname, userpin))
        elif sanctioned == False:
            EVENT.add_player(Player(firstname, lastname))


if __name__ == "__main__":
    INFO = get_event_info()
    EVENT = Tournament(INFO[0], INFO[1])
    get_players()

    ROUNDS = number_rounds(len(EVENT.players))

    # main event-reporting loop
    while EVENT.round < ROUNDS:
        EVENT.start_round()

        ACTIVE = len(EVENT.active_tables())
        while ACTIVE > 0:
            CMD = raw_input("Round #%d (%d tables open) -> " % (EVENT.round, ACTIVE))
            if search("lp", CMD) is not None:
                list_pairings(EVENT)
                continue
            if search("ls", CMD) is not None:
Example #30
0
REVERSE_HANDS = [
    "KA", "QK", "JQ", "TK", "TQ", "TJ", "KAs", "QKs", "JQs", "TKs", "TQs",
    "TJs"
]
NOREVERSE_HANDS = [
    "AK", "AKs", "KQ", "KQs", "QJ", "QJs", "JT", "JTs", "KT", "KTs", "QT",
    "QTs", "JT", "JTs"
]

players = int(input("Enter the number of players for the tournament: "))
# name = input("Enter the tournament name: ")
# buyin = float(input("Enter the tournament buyin: "))
# speed = input("Enter the tournament speed: ")

Tourn = Tournament(players)
Main = PositionStrategy(Tourn)


def clean_cards(cards):
    cards = cards.upper()
    if 'S' in cards:
        cards = cards[:2] + cards[2:].lower()
    if cards in REVERSE_HANDS:
        if len(cards) == 2:
            cards = cards[1] + cards[0]
        else:
            cards = cards[1] + cards[0] + cards[2]
    elif cards in NOREVERSE_HANDS:
        cards = cards
    elif cards[0] < cards[1]:
Example #31
0
from Tournament import Tournament
from Ranking import Ranking
from SimulatedAnnealing import SimulatedAnnealing

tournament = Tournament(definition_file="1994_Formula_One.wmg")

initial_ranking = Ranking(order=list(range(0, len(tournament.participants))),
                          tournament=tournament)

final_ranking = tournament.get_best_ranking(initial_ranking=initial_ranking,
                                            initial_temp=300,
                                            temp_length=45,
                                            cooling_ratio=0.999,
                                            num_non_improve=100000)

print(final_ranking.get_kemeny_score(), final_ranking.get_participants())
Example #32
0
 def __init__(self):
     self.viewBoard = ViewBoard()
     self.board = Board()
     self.human = Human()
     self.computer = Computer()
     self.tournament = Tournament()
Example #33
0
import sys
import time

sys.path.append("..")
from Tournament import Tournament

if __name__ == "__main__":
    print "now:", int(time.time())
    Tournament.refresh()
Example #34
0
def main():
    Tournament().startTournament()
Example #35
0
            print("sqlite db created")
        except lite.Error as e:
            print("Could not open database file\n{}".format(e))


#==============================================================================
# running the  app
#==============================================================================
def run_App():
    if __name__ == '__main__':
        Main()
        #main.showName()


global base_path
base_path = 'null'
print("base_path : " + base_path)

if not os.path.isfile(base_path):
    main = Main()
    base_path = main.db

run_App()
print(base_path)

#db = SQL_Adapter(base_path)
from Tournament import Tournament

tournament = Tournament()
tournament.insertTournament("Default Tournament 3")
Example #36
0
File: Main.py Project: batherk/hex
elif RUNS[RUN] == "Tournament - different net structures using replay buffer":
    print("Mode: Tournament. Several players play against each other.")
    game = HexGame()
    replay_buffer = ReplayBuffer()
    net1 = Dense(hidden_layers=[(100, relu)], optimizer=Adam)
    net2 = Dense(hidden_layers=[(100, sigmoid)], optimizer=Adam)
    net3 = Dense(hidden_layers=[(100, relu)], optimizer=SGD)
    net4 = Dense(hidden_layers=[(100, sigmoid)], optimizer=SGD)
    player1 = NetBotFromTraining("Adam relu", net1, replay_buffer)
    player2 = NetBotFromTraining("Adam sig", net2, replay_buffer)
    player3 = NetBotFromTraining("SGD relu", net3, replay_buffer)
    player4 = NetBotFromTraining("SGD sig", net4, replay_buffer)

    players = [player1, player2, player3, player4]

    tournament = Tournament(game, players)
    wins = tournament.play_tournament()
elif RUNS[RUN] == "Tournament - different training amounts from loading ":
    print(
        "Mode: Trained tournament. Already trained nets play against each other."
    )
    game = HexGame()
    players = [NetBotFromLoading(name) for name in NETS_TOURNAMENT]
    tournament = Tournament(game, players)
    wins = tournament.play_tournament()
elif RUNS[RUN] == "Train net on buffer and save it":
    print("Mode: Train net on buffer and save it")
    trainer = NetTrainer(train_net_on_init=True)
    trainer.net.save("Saved_net")
else:
    print("Custom - nothing")
from Tournament import Tournament
from Jesus import Jesus
from Lucifer import Lucifer
from TitForTat import TitForTat

# Create tournament
 species = [Jesus, Lucifer, TitForTat]
tournament = Tournament(species, 200, 5)

# Run tournament
print(tournament)
while True:
    inp = input("Press Enter to start the next round")
    if inp.lower() == "done":
        break
    print("\n")
    tournament.round_robin()
    tournament.reproduce()
    tournament.repopulate()
    print("Results:")
    print(tournament)
Example #38
0
    def create_offspring(self):
        tournament = Tournament(np.random.choice(self.members, 4))
        winner = tournament.conduct()

        return winner
Example #39
0
from Inv_Judas import Inv_Judas
from Judas import Judas
from MasonPrisoner import MasonPrisoner
from Random import Random
from SchizophrenicRetribution import SchizophrenicRetribution
from TitForTat_Avg import TitForTat_Avg
from XmasTruce import XmasTruce
import time

# Create tournament
species = [
    Jesus, Lucifer, TitForTat, Telepath, BahHumbug, FelizNavidad, Inv_Judas,
    Judas, MasonPrisoner, Random, SchizophrenicRetribution, TitForTat_Avg,
    XmasTruce
]
tournament = Tournament(species, 200, 10)

# Time species
valid = True
for sp in species:
    print("")
    s1 = 0
    s2 = 0
    start = time.thread_time()
    for ii in range(1000):
        (score1, score2) = tournament.play_match(sp, sp, 1000)
        s1 += score1
        s2 += score2
    end = time.thread_time()
    print("Validating %s" % sp.__name__)
    print("Scores against self: %d, %d" % (s1, s2))