Exemple #1
0
def test_clear_shelf():
    banker = Banker()
    banker.shelf(100)
    banker.bank()
    banker.shelf(50)
    banker.clear_shelf()
    assert banker.balance == 100
    assert banker.shelved == 0
Exemple #2
0
class Game:
    """Class for Game of Greed application
    """
    def __init__(self, num_rounds=20):
        self.banker = Banker()
        self.logic = GameLogic()
        self.num_rounds = num_rounds
        self._roller = GameLogic.roll_dice
        self.round_num = 0

    def play(self, roller=None):
        """Entry point for playing (or declining) a game
        Args:
            roller (function, optional): Allows passing in a custom dice roller function.
                Defaults to None.
        """

        self.round_num = 0

        self._roller = roller or GameLogic.roll_dice

        print("Welcome to Game of Greed")

        print("(y)es to play or (n)o to decline")

        response = input("> ")

        if response == "y" or response == "yes":
            self.start_game()
        else:
            self.decline_game()

    def decline_game(self):
        print("OK. Maybe another time")

    def new_roll(self, remaining_die):
        print(f"Rolling {remaining_die} dice...")
        die_roll = self._roller(remaining_die)
        string_roll = [str(num) for num in die_roll]
        return (die_roll, string_roll)

    def check_validity(self, die_roll, string_roll):
        cheated = True
        while cheated:
            cheated = False
            print(f'*** {" ".join(string_roll)} ***')
            round_points = self.logic.calculate_score(die_roll)
            if round_points == 0:
                return 'Zilch'
            print("Enter dice to keep, or (q)uit:")
            kept_die = input("> ")
            saved_die = list(kept_die)
            if kept_die == "q":
                print(
                    f"Thanks for playing. You earned {self.banker.total} points"
                )
                sys.exit()

            good_input = True
            for value in saved_die:
                try:
                    int(value)
                except:
                    saved_die.remove(value)

            user_selection = tuple(int(char) for char in saved_die)
            no_cheats = self.logic.validate_keepers(die_roll, user_selection)
            if not no_cheats:
                cheated = True
                print('Cheater!!! Or possibly made a typo...')
        return user_selection

    def round_decisions(self, remaining_die):
        print(
            f"You have {self.banker.shelved} unbanked points and {remaining_die} dice remaining"
        )
        print("(r)oll again, (b)ank your points or (q)uit:")
        round_choice = input("> ")
        if round_choice == "q":
            print(f"Thanks for playing. You earned {self.banker.total} points")
            sys.exit()
        elif round_choice == "b":
            round_points = self.banker.bank()
            remaining_die = 6
            print(
                f"You banked {round_points} points in round {self.round_num}")
        elif round_choice == "r":
            if remaining_die == 0:
                remaining_die = 6
            self.full_roll(remaining_die)

    def full_roll(self, remaining_die):

        (die_roll, string_roll) = self.new_roll(remaining_die)
        user_selection = self.check_validity(die_roll, string_roll)

        if user_selection == 'Zilch':
            self.banker.clear_shelf()
            print(
                '****************************************\n**        Zilch!!! Round over         **\n****************************************'
            )
            print(f"You banked 0 points in round {self.round_num}")
        else:
            remaining_die -= len(user_selection)
            self.banker.shelf(self.logic.calculate_score(user_selection))
            self.round_decisions(remaining_die)

    def start_game(self):
        remaining_die = 6

        while self.round_num < self.num_rounds:
            self.round_num += 1
            print(f"Starting round {self.round_num}")
            self.full_roll(remaining_die)
            print(f"Total score is {self.banker.total} points")

        print(f"Thanks for playing. You earned {self.banker.total} points")
        sys.exit()
Exemple #3
0
class Game:
    """Class for Game of Greed application
    """
    def __init__(self, roller=None, num_rounds=20):

        self._roller = roller or GameLogic.roll_dice
        self.banker = Banker()
        self.num_rounds = num_rounds
        self.round_num = 0

    def play(self):
        """
        Entry point for playing (or/not) a game
        """

        print("Welcome to Game of Greed")

        prompt = "Wanna play?"

        self.choice(prompt.strip(), self.start_game, self.decline_game)

    def choice(self, prompt, accept, decline):

        response = input(prompt)

        if response == "y" or response == "yes":

            accept()

        else:

            decline()

    def decline_game(self):
        print("OK. Maybe another time")

    def start_game(self):

        self.round_num = 1

        while self.round_num <= self.num_rounds:

            self.start_round(self.round_num)

            self.round_num += 1

            print(f"Total score is {self.banker.balance} points")

        self.quit_game()

    def quit_game(self):

        print(f"Thanks for playing. You earned {self.banker.balance} points")

        sys.exit()

    def start_round(self, round, num_dice=6):

        print(f"Starting round {round}")

        round_score = 0

        while True:

            roll = self.roll_dice(num_dice)

            if self.got_zilch(roll):
                break

            keepers = self.handle_keepers(roll)

            roll_again_response = input(
                "(r)oll again, (b)ank your points or (q)uit ")

            if roll_again_response == "q":

                self.quit_game()

                return

            elif roll_again_response == "b":

                round_score = self.banker.bank()

                break

            else:

                num_dice -= len(keepers)

                if num_dice == 0:

                    num_dice = 6

        print(f"You banked {str(round_score)} points in round {round}")

    def handle_keepers(self, roll):

        while True:
            keeper_string = input(
                "Enter dice to keep (no spaces), or (q)uit: ")

            if keeper_string.startswith("q"):
                self.quit_game()

            keepers = self.gather_keepers(roll, keeper_string)

            roll_score = self.calculate_score(keepers)

            if roll_score == 0:
                print("Must keep at least one scoring dice")
            else:
                break

        self.banker.shelf(roll_score)

        print(
            f"You have {self.banker.shelved} unbanked points and {len(roll) - len(keepers)} dice remaining"
        )

        return keepers

    def roll_dice(self, num):

        print(f"Rolling {num} dice...")

        roll = self._roller(num)

        print(",".join([str(i) for i in roll]))

        return roll

    def got_zilch(self, roll):

        initial_score = self.calculate_score(roll)

        if initial_score == 0:

            print("Zilch!!! Round over")

            self.banker.clear_shelf()

            return True

        return False

    def calculate_score(self, roll):
        return GameLogic.calculate_score(roll)

    def keep_scorers(self, roll):
        return GameLogic.get_scorers(roll)

    def gather_keepers(self, roll, keeper_string):

        keepers = [int(ch) for ch in keeper_string]

        while not GameLogic.validate_keepers(roll, keepers):
            print("Cheater!!! Or possibly made a typo...")
            print(",".join([str(i) for i in roll]))
            keeper_string = input(
                "Enter dice to keep (no spaces), or (q)uit: ")
            if keeper_string.startswith("q"):
                self.quit_game()

            keepers = [int(ch) for ch in keeper_string]

        return keepers
Exemple #4
0
class Game:
    """Class for Game of Greed application
    """
    def __init__(self, num_rounds=20):
        self.banker = Banker()
        self.num_rounds = num_rounds

    def play(self, roller=None):
        """Entry point for playing (or declining) a game
        Args:
            roller (function, optional): Allows passing in a custom dice roller function.
                Defaults to None.
        """

        self.round_num = 0

        self._roller = roller or GameLogic.roll_dice

        print("Welcome to Game of Greed")

        print("(y)es to play or (n)o to decline")

        response = input("> ")

        if response == "y" or response == "yes":
            self.start_game()
        else:
            self.decline_game()

    def decline_game(self):
        print("OK. Maybe another time")

    def quit_game(self, score=0):
        print(f"Thanks for playing. You earned {self.banker.balance} points")
        sys.exit()

    def start_game(self):
        self.round_num += 1
        self.start_round(self.round_num)

    def start_round(self, round_num, number=6):
        print(f"Starting round {round_num}")
        current_round_score = 0
        while True:
            roll = self.rolling_dice(number)
            if self.farkle(roll):
                self.start_round
                # break
            selection = self.handle_selection(roll)
            print("(r)oll again, (b)ank your points or (q)uit:")
            response = input("> ")
            if response == "q":
                self.quit_game()
                return
            elif response == "b":
                current_round_score = self.banker.bank()
                print(
                    f"You banked {str(current_round_score)} points in round {round_num}"
                )
                print(f'Total score is {self.banker.balance} points')
                self.start_game()
                # break
            else:
                number -= len(selection)
                if number == 0:
                    number = 6

    def handle_selection(self, roll):
        while True:
            print("Enter dice to keep, or (q)uit:")
            response = input("> ")
            if response == 'q':
                self.quit_game()
            saved_dice = self.saved_dice(roll, response)
            tup = tuple([int(i) for i in response])
            score = GameLogic.calculate_score(tup)
            break
        self.banker.shelf(score)
        print(
            f'You have {self.banker.shelved} unbanked points and {len(roll) - len(saved_dice)} dice remaining'
        )
        return saved_dice

    def rolling_dice(self, number):
        print(f"Rolling {number} dice...")
        roll = self._roller(number)
        var = ' '
        for i in range(0, len(roll)):
            var += f'{roll[i]} '
        print(f"***{var}***")
        return roll

    def check_cheater(self, response, roll):
        tup = tuple([int(i) for i in response])
        for x in tup:
            if x not in roll:
                return False
        return True

    def saved_dice(self, roll, response):
        tup = tuple([int(i) for i in response])
        check = self.check_cheater(response, roll)
        if check == 0:
            print("Cheater!!! Or possibly made a typo...")
            var = ' '
            for i in range(0, len(roll)):
                var += f'{roll[i]} '
                if response == "q":
                    sys.exit()
            print(f"***{var}***")
            tup = tuple([int(i) for i in response])
            # print("Enter dice to keep, or (q)uit:")
            # response = input("> ")
        return tup

    def farkle(self, roll):
        score = GameLogic.calculate_score(roll)
        if score == 0:
            print(f"""****************************************
**        Zilch!!! Round over         **
****************************************""")
            self.banker.clear_shelf()