Пример #1
0
    def make_dice(self, sides):
        fair_dice = dice.make_fair_dice(sides)

        def gui_dice():
            """Roll fair_dice and add a corresponding image to self.dice."""
            result = fair_dice()
            img = HogGUI.IMAGES[result]
            self.dice[self.dice_count].config(image=img).pack(side=LEFT)
            self.dice_count += 1
            return result

        return gui_dice
Пример #2
0
    def test_run_experiments(self):
        """Run a series of strategy experiments and report results."""
        if True:  # Change to False when done finding max_scoring_num_rolls
            six_sided_max = max_scoring_num_rolls(make_fair_dice(6),1000)
            print('Max scoring num rolls for six-sided dice:', six_sided_max)

        if True:  # Change to False when done finding max_scoring_num_rolls
            four_sided_max = max_scoring_num_rolls(make_fair_dice(4),1000)
            print('Max scoring num rolls for four-sided dice:', four_sided_max)

        if True:  # Change to True to test always_roll(3)
            print('always_roll(3) win rate:', average_win_rate(always_roll(3)))

        if True:  # Change to True to test always_roll(4)
            print('always_roll(4) win rate:', average_win_rate(always_roll(4)))


        if True:  # Change to True to test always_roll(5)
            print('always_roll(5) win rate:', average_win_rate(always_roll(5)))

        if True:  # Change to True to test always_roll(6)
            print('always_roll(6) win rate:', average_win_rate(always_roll(6)))

        if True:  # Change to True to test always_roll(7)
            print('always_roll(7) win rate:', average_win_rate(always_roll(7)))


        if True:  # Change to True to test always_roll(8)
            print('always_roll(8) win rate:', average_win_rate(always_roll(8)))



        if True:  # Change to True to test bacon_strategy
            print('bacon_strategy win rate:', average_win_rate(bacon_strategy))

        if True:  # Change to True to test swap_strategy
            print('swap_strategy win rate:', average_win_rate(swap_strategy))

        if True:  # Change to True to test final_strategy
            print('final_strategy win rate:', average_win_rate(final_strategy))
Пример #3
0
    def make_dice(self, sides):
        """Creates a dice function that hooks to the GUI and wraps
        dice.make_fair_dice.

        sides -- number of sides for the die
        """
        fair_dice = dice.make_fair_dice(sides)
        def gui_dice():
            """Roll fair_dice and add a corresponding image to self.dice."""
            result = fair_dice()
            img = HogGUI.IMAGES[result]
            self.dice[self.dice_count].config(image=img).pack(side=LEFT)
            self.dice_count += 1
            return result
        return gui_dice
Пример #4
0
    def make_dice(self, sides):
        """Создаёт функцию dice с GUI-хуками и обёртывает dice.make_fair_dice.

        sides — количество сторон у кости
        """
        fair_dice = dice.make_fair_dice(sides)
        def gui_dice():
            """Делает бросок fair_dice и выставляет соответствующее изображение
            в self.dice."""
            result = fair_dice()
            img = HogGUI.IMAGES[result]
            self.dice[self.dice_count].config(image=img).pack(side=LEFT)
            self.dice_count += 1
            return result
        return gui_dice
Пример #5
0
    def make_dice(self, sides):
        """Creates a dice function that hooks to the GUI and wraps
        dice.make_fair_dice.

        sides -- number of sides for the die
        """
        fair_dice = dice.make_fair_dice(sides)
        def gui_dice():
            """Roll fair_dice and add a corresponding image to self.dice."""
            result = fair_dice()
            img = HogGUI.IMAGES[result]
            self.dice[self.dice_count].config(image=img).pack(side=LEFT)
            self.dice_count += 1
            return result
        return gui_dice
Пример #6
0
def take_turn(prev_rolls, move_history, goal, game_rules):
    fair_dice = dice.make_fair_dice(6)
    dice_results = []

    feral_hogs = game_rules["Feral Hogs"]
    swine_swap = game_rules["Swine Swap"]

    if not swine_swap:
        old_is_swap, hog.is_swap = hog.is_swap, lambda score0, score1: False

    def logged_dice():
        if len(dice_results) < len(prev_rolls):
            out = prev_rolls[len(dice_results)]
        else:
            out = fair_dice()
        dice_results.append(out)
        return out

    final_scores = None
    final_message = None

    commentary = hog.both(
        hog.announce_highest(0),
        hog.both(hog.announce_highest(1), hog.announce_lead_changes()),
    )

    def log(*logged_scores):
        nonlocal final_message, commentary
        f = io.StringIO()
        with redirect_stdout(f):
            # commentary = commentary(*logged_scores)
            print("OO")
        final_message = f.getvalue()
        return log

    move_cnt = 0

    def strategy(*scores):
        nonlocal final_scores, move_cnt
        final_scores = scores
        if move_cnt % 2:
            final_scores = final_scores[::-1]
        if move_cnt == len(move_history):
            raise HogLoggingException()
        move = move_history[move_cnt]
        move_cnt += 1
        return move

    game_over = False

    try:
        final_scores = trace_play(hog.play,
                                  strategy,
                                  strategy,
                                  0,
                                  0,
                                  dice=logged_dice,
                                  say=log,
                                  goal=goal,
                                  feral_hogs=feral_hogs)[:2]
    except HogLoggingException:
        pass
    else:
        game_over = True

    if not swine_swap:
        hog.is_swap = old_is_swap

    return {
        "rolls": dice_results,
        "finalScores": final_scores,
        "message": final_message,
        "gameOver": game_over,
    }
Пример #7
0
def take_turn(prev_rolls, move_history, goal, game_rules):
    """Simulate the whole game up to the current turn."""
    fair_dice = dice.make_fair_dice(6)
    dice_results = []

    swine_align = game_rules["Swine Align"]
    pig_pass = game_rules["Pig Pass"]

    try:
        if not swine_align:
            old_swine_align, hog.swine_align = hog.swine_align, lambda score0, score1: False

        if not pig_pass:
            old_pig_pass, hog.pig_pass = hog.pig_pass, lambda score0, score1: False

        def logged_dice():
            if len(dice_results) < len(prev_rolls):
                out = prev_rolls[len(dice_results)]
            else:
                out = fair_dice()
            dice_results.append(out)
            return out

        final_scores = None
        final_message = None
        who = 0

        commentary = hog.both(
            hog.announce_highest(0),
            hog.both(hog.announce_highest(1), hog.announce_lead_changes()),
        )

        def log(*logged_scores):
            nonlocal final_message, commentary
            f = io.StringIO()
            with redirect_stdout(f):
                commentary = commentary(*logged_scores)
            final_message = f.getvalue()
            return log

        move_cnt = 0

        def strategy_for(player):
            def strategy(*scores):
                nonlocal final_scores, move_cnt, who
                final_scores = scores
                if player:
                    final_scores = final_scores[::-1]
                who = player
                if move_cnt == len(move_history):
                    raise HogLoggingException()
                move = move_history[move_cnt]
                move_cnt += 1
                return move

            return strategy

        game_over = False

        try:
            final_scores = trace_play(hog.play,
                                      strategy_for(0),
                                      strategy_for(1),
                                      0,
                                      0,
                                      dice=logged_dice,
                                      say=log,
                                      goal=goal)[:2]
        except HogLoggingException:
            pass
        else:
            game_over = True
    finally:
        if not swine_align:
            hog.swine_align = old_swine_align
        if not pig_pass:
            hog.pig_pass = old_pig_pass

    return {
        "rolls": dice_results,
        "finalScores": final_scores,
        "message": final_message,
        "gameOver": game_over,
        "who": who,
    }
def test(strategy0, strategy1, score0 = 0, score1 = 0, goal = 100, startWho = 0, canPrint = True):
    who = startWho #math.floor(random.random() * 2.0)  # Who is about to take a turn, 0 (first) or 1 (second)
    eight_sided_dice = diceLib.make_fair_dice(8)
    six_sided = diceLib.make_fair_dice(6)
    dice = six_sided

    overallTurnNum = 0

    # BEGIN PROBLEM 5
    while score0 < goal and score1 < goal:
        if who == 0:
            isPlayerPlaying = True
            turnNum = 0
            
            isMoreBoar = False
            isTimeTrot = False
            
            while isPlayerPlaying and score0 < goal:
                if canPrint:
                    print("--------------------------")
                    print('score',score0,score1)
                    print('player',0,'turn',turnNum)
                if VIEW_STEP_BY_STEP:
                    time.sleep(2)
                if(turnNum == 0):
                    dice = six_sided
                else:
                    dice = eight_sided_dice
                
                if strategy0 == final_strategy_train.final_strategy and not(final_strategy_train.final_strategy.producing_actual_result):
                    final_strategy_train.feedHitData(False,turnNum,overallTurnNum,score0,score1,1.0)

                final_strategy_train.MATCH_CURRENT_TURN_NUM = turnNum
                final_strategy_train.MATCH_LAST_EXTRA = turnNum>=1
                final_strategy_train.MATCH_OVERALL_TURN_NUM = overallTurnNum
                
                strategyThisRound = strategy0(score0,score1)
                scoreAdditionThisRound = gamecalc.take_turn(strategyThisRound,score1,dice,goal)
                score0 += scoreAdditionThisRound
                isMoreBoar = gamecalc.more_boar(score0,score1)
                isTimeTrot = gamecalc.time_trot(overallTurnNum,strategyThisRound,turnNum>=1)
                isPlayerPlaying = isMoreBoar or isTimeTrot

                if canPrint:
                    print("rolling", strategyThisRound, 'with a score increase of',scoreAdditionThisRound)
                    if(isMoreBoar):
                        print("MoreBoar!")
                    elif(isTimeTrot):
                        print("TimeTrot!")
                turnNum += 1
                overallTurnNum += 1
                
            who = 1
        else: #if who == 1
            isPlayerPlaying = True
            turnNum = 0

            isMoreBoar = False
            isTimeTrot = False
            
            while isPlayerPlaying and score1 < goal:
                if canPrint:
                    print("--------------------------")
                    print('score',score0,score1)
                    print('player',1,'turn',turnNum)
                if VIEW_STEP_BY_STEP:
                    time.sleep(2)
                if(turnNum == 0):
                    dice = six_sided
                else:
                    dice = eight_sided_dice

                if strategy1 == final_strategy_train.final_strategy and not(final_strategy_train.final_strategy.producing_actual_result):
                    final_strategy_train.feedHitData(False,turnNum,overallTurnNum,score1,score0,1.0)

                final_strategy_train.MATCH_CURRENT_TURN_NUM = turnNum
                final_strategy_train.MATCH_LAST_EXTRA = turnNum >= 1
                final_strategy_train.MATCH_OVERALL_TURN_NUM = overallTurnNum

                strategyThisRound = strategy1(score1,score0)
                scoreAdditionThisRound = gamecalc.take_turn(strategyThisRound,score0,dice,goal)
                score1 += scoreAdditionThisRound
                isMoreBoar =  gamecalc.more_boar(score1,score0)
                isTimeTrot = gamecalc.time_trot(overallTurnNum,strategyThisRound,turnNum >= 1)
                isPlayerPlaying = isMoreBoar or isTimeTrot

                if canPrint:
                    print("rolling", strategyThisRound, 'with a score increase of',scoreAdditionThisRound)
                    if(isMoreBoar):
                        print("MoreBoar!")
                    elif(isTimeTrot):
                        print("TimeTrot!")
                turnNum += 1
                overallTurnNum += 1
            who = 0
    
    # END PROBLEM 5
    # (note that the indentation for the problem 6 prompt (***YOUR CODE HERE***) might be misleading)
    # BEGIN PROBLEM 6
    "Finished in PROBLEM 5 parts"
    # END PROBLEM 6
    return score0, score1
Пример #9
0
def take_turn(prev_rolls, move_history, goal):
    fair_dice = dice.make_fair_dice(6)
    dice_results = []

    def logged_dice():
        if len(dice_results) < len(prev_rolls):
            out = prev_rolls[len(dice_results)]
        else:
            out = fair_dice()
        dice_results.append(out)
        return out

    final_scores = None
    final_message = None

    commentary = hog.both(
        hog.announce_highest(0),
        hog.both(hog.announce_highest(1), hog.announce_lead_changes()),
    )

    def log(*logged_scores):
        nonlocal final_scores, final_message, commentary
        final_scores = logged_scores
        f = io.StringIO()
        with redirect_stdout(f):
            commentary = commentary(*logged_scores)
        final_message = f.getvalue()
        return log

    move_cnt = 0

    def strategy(*args):
        nonlocal move_cnt
        if move_cnt == len(move_history):
            raise HogLoggingException()
        move = move_history[move_cnt]
        move_cnt += 1
        return move

    game_over = False

    try:
        trace_play(hog.play,
                   strategy,
                   strategy,
                   0,
                   0,
                   dice=logged_dice,
                   say=log,
                   goal=goal,
                   feral_hogs=True)
    except HogLoggingException:
        pass
    else:
        game_over = True

    return {
        "rolls": dice_results,
        "finalScores": final_scores,
        "message": final_message,
        "gameOver": game_over,
    }