Example #1
0
    def play_hand(self, i):
        """Play a hand."""
        # Print player's hand
        utils.print_separator()
        print("Player's hand #" + str(i) + ":\n")
        self.print_player_hand()

        # Check if the hand is a BlackJack
        if self.player.hand.is_blackJack():
            self.player.hand.status = "blackjack"
            print("Congratulations! You got a Blackjack!\n")

        else:
            while self.player.hand.status == "active":
                # Ask for player's next move
                action = utils.multiple_choice_question("[H]it or [S]tand? (H/S): ", ["h", "s"])
                utils.print_separator()
                # If he stands
                if action == "s":
                    # Finish the current hand
                    self.player.hand.status = "finished"

                    # If he hits
                elif action == "h":
                    # Hit
                    self.player.hit()
                    self.print_player_hand()

                    # Check if player is busted
                    if self.player.is_busted():
                        self.player.hand.status = "busted"
                        print("You bust!\n")
Example #2
0
    def split_step(self):
        """If player's hand is a pair, he has to choose whether he wants to split it or not."""
        for i in range(len(self.player.hands)):
            self.player.hand = self.player.hands[i]
            # Check if player's hand is splittable (Player can play a maximum of 4 hands at the same time)
            if self.player.hand.is_splittable() and len(self.player.hands) < 4:

                # Print player's hand
                utils.print_separator()
                print("Player's hand #" + str(i) + ":\n")
                self.print_player_hand()

                # Ask player whether he wants to split the hand or not
                do_split = utils.read_boolean("Do you want to split? (Y/N)")

                if do_split:
                    # Check if player has enough chips to split
                    if self.player.can_split():

                        # Split the hand
                        self.player.split()

                        # Recursive call of split_bet to check if the new hands can also be split
                        self.split_step()
                        break

                    else:
                        print("Sorry, you don't have enough chips to split!")
Example #3
0
    def display_results(self):
        """Compute player's gain and display results at the end of the round."""
        gain = 0

        # Check if dealer is busted
        if self.dealer.is_busted():
            print("Dealer is busted!\n")

            # Compute player's gain. Loop through player's hands
            for hand in self.player.hands:
                if hand.is_blackJack():
                    gain += 2.5 * self.player.get_bet()
                elif hand.status == "finished":
                    gain += 2 * self.player.get_bet()

                    # Dealer got a BlackJack
        elif self.dealer.hand.is_blackJack():
            print("Dealer got a BlackJack!\n")

            # Compute player's gain. Loop through player's hands
            for hand in self.player.hands:
                if hand.is_blackJack():
                    gain += self.player.get_bet()

                    # Dealer has neither busted nor got a BlackJack
        else:
            # Compute player's gain. Loop through player's hands
            for hand in self.player.hands:
                if hand.is_blackJack():
                    gain += 2.5 * self.player.get_bet()
                elif hand.status == "finished":
                    if hand.get_value() > self.dealer.hand.get_value():
                        gain += 2 * self.player.get_bet()
                    elif hand.get_value() == self.dealer.hand.get_value():
                        gain += self.player.get_bet()

                        # Add gain to player's account
        self.player.bankroll += gain

        # Player wins chips
        if gain > 0:
            print(
                "You won " + str(gain) + " chip(s)! Your new bankroll is: " + str(self.player.get_bankroll())
            ) + " chips."

            # Player loses chips
        else:
            loss = len(self.player.hands) * self.player.get_bet()
            print(
                "You lost " + str(loss) + " chip(s)... Your new bankroll is: " + str(self.player.get_bankroll())
            ) + " chips."
        utils.print_separator()
        utils.print_separator()
Example #4
0
    def start(self):
        """Starts the game. A game ends when the player has no more chips."""
        # Print game's title
        asciiArts.print_title()
        utils.print_separator()

        # While the player has enough money to play
        while self.player.get_bankroll() > 0:
            # Display player's bankroll
            print("Your current bankroll is: " + str(self.player.get_bankroll())) + " chips."

            # Play a game
            self.play()

            # End
            self.end()

        print("Thank you for playing pyBlackJack!")
Example #5
0
    def display_header_infos_in_directory(self, path):
        print("Scanning directory {}...".format(path))
        num_audio_files = 0
        for current_dir, subdirs, files in os.walk(path):
            for file in files:
                full_path = os.path.join(current_dir, file)
                is_wave_file = self.is_wave_file(full_path)
                is_aiff_file = self.is_aiff_file(full_path)
                if is_wave_file or is_aiff_file:
                    if is_wave_file:
                        self.analyze_wave_header(full_path)
                    else:
                        self.analyze_aiff_header(full_path)

                    print_separator()
                    num_audio_files += 1
                else:
                    print(
                        "Unrecognized file extension, skipping file {}".format(
                            full_path))
        print("Total Number of Audio Files:", num_audio_files)
Example #6
0
    def play(self):
        """Play a round. The player first bets and then play his hand(s)."""
        # Clear player's and dealer's hand
        self.player.clear()
        self.dealer.clear()

        #################
        # Ask for a bet #
        #################
        bet = self.bet_step()

        # Register player's bet
        self.player.bet(bet)

        ##############
        # Deal cards #
        ##############

        # If the dealer has dealt 75% of the cards, then shuffle a new deck
        if self.deck.get_number_of_cards_left() < 78:
            self.deck = Deck(6)

        print("Dealing...")
        self.dealer.deal()
        utils.print_separator()
        self.print_dealer_hand(False)

        #########
        # Split #
        #########
        self.split_step()

        ##############
        # Play Hands #
        ##############
        for i in range(len(self.player.hands)):
            self.player.hand = self.player.hands[i]
            self.play_hand(i)
Example #7
0
    def repair_audio_file_headers_in_directory(self, source_path,
                                               destination_path, sample_rate,
                                               bits_per_sample, num_channels):
        if not os.path.exists(destination_path):
            print("Creating destination directory {}...".format(
                destination_path))
            os.mkdir(destination_path)
        else:
            if not os.path.isdir(destination_path):
                print_error(
                    "File at destination path already exists but is not a directory."
                )
                return

        print("Scanning directory {}...".format(source_path))
        print_separator()
        num_repaired_audio_files = 0
        for current_dir, subdirs, files in os.walk(source_path):
            for file in files:
                full_path = os.path.join(current_dir, file)
                is_wave_file = self.is_wave_file(full_path)
                is_aiff_file = self.is_aiff_file(full_path)
                if is_wave_file or is_aiff_file:
                    found_error = False

                    # we print an analysis notification here because nothing is displayed during analysis due the display=False flag
                    if is_wave_file:
                        print("Analyzing WAVE file {}".format(full_path))
                        found_error = self.analyze_wave_header(
                            full_path, False)
                    else:
                        print("Analyzing AIFF file {}".format(full_path))
                        found_error = self.analyze_aiff_header(
                            full_path, False)

                    if found_error:
                        print("Found errors in file {}, trying to restore...".
                              format(full_path))
                        full_destination_path = os.path.join(
                            destination_path, file)

                        if os.path.exists(full_destination_path):
                            if not self.ask_user_to_overwrite_destination_file(
                                    full_destination_path):
                                continue

                        repair_result = False
                        if is_wave_file:
                            repair_result = self.repair_wave_file_header(
                                full_path, full_destination_path, sample_rate,
                                bits_per_sample, num_channels)
                        else:
                            repair_result = self.repair_aiff_file_header(
                                full_path, full_destination_path, sample_rate,
                                bits_per_sample, num_channels)

                        if repair_result:
                            num_repaired_audio_files += 1

                        print_separator()
                else:
                    print(
                        "Unrecognized file extension, skipping file {}".format(
                            full_path))

        print("Total Number of Repaired Audio Files:",
              num_repaired_audio_files)
Example #8
0
    def repair_audio_file_headers_in_directory(self, source_path,
                                               destination_path, sample_rate,
                                               bits_per_sample, num_channels,
                                               force):
        if not os.path.exists(destination_path):
            print("Creating destination directory {}...".format(
                destination_path))
            os.mkdir(destination_path)
        else:
            if not os.path.isdir(destination_path):
                print_error(
                    "File at destination path already exists but is not a directory."
                )
                return

        print("Scanning directory {}...".format(source_path))
        print_separator()
        num_repaired_audio_files = 0
        for current_dir, subdirs, files in os.walk(source_path):
            for file in files:
                full_path = os.path.join(current_dir, file)
                is_wave_file = self.is_wave_file(full_path)
                is_aiff_file = self.is_aiff_file(full_path)

                if is_wave_file or is_aiff_file:
                    found_error = False

                    if force:
                        print(
                            "Skipping check of file {} because restore is enforced."
                            .format(full_path))
                    else:
                        found_error = self.check_file_for_errors(
                            full_path, is_wave_file)
                        if found_error:
                            print(
                                "Found errors in file {}, trying to restore..."
                                .format(full_path))
                        else:
                            print(
                                "Skipping file {} because no errors were found."
                                .format(full_path))

                    if force or found_error:
                        full_destination_path = os.path.join(
                            destination_path, file)

                        if os.path.exists(full_destination_path):
                            if not self.ask_user_to_overwrite_destination_file(
                                    full_destination_path):
                                continue

                        repair_result = False
                        if is_wave_file:
                            repair_result = self.repair_wave_file_header(
                                full_path, full_destination_path, sample_rate,
                                bits_per_sample, num_channels)
                        else:
                            repair_result = self.repair_aiff_file_header(
                                full_path, full_destination_path, sample_rate,
                                bits_per_sample, num_channels)

                        if repair_result:
                            num_repaired_audio_files += 1

                        print_separator()
                else:
                    print(
                        "Unrecognized file extension, skipping file {}".format(
                            full_path))

        print("Total Number of Repaired Audio Files:",
              num_repaired_audio_files)
Example #9
0
def main():
    if utils.DATA['version'] != VERSION:
        print('Your version of Launchcraft ({}) does not match the minimum version of Launchcraft ({}). Please update.'.format(VERSION, utils.DATA['version']))
        utils.exit()

    print('This script will ask you yes or no questions.')
    print('Any answers in square brackets (e.g. [1.7.10]), or that are capitalized (e.g. [Y/n]) are the default answers, and will be selected when you press enter.')
    utils.print_separator()

    version = raw_input('Which version of Minecraft would you like to use? [1.7.10]: ').lower()
    if version == '':
        version = '1.7.10'

    if version not in utils.DATA['versions']:
        print("Invalid version selected.")
        utils.exit()

    utils.MODS = utils.DATA['versions'][version]

    JAR_DIR = os.path.join(VERSIONS_DIR, version)

    FORGE_VERSION = '{}-Forge{}'.format(version, utils.MODS['mods']['forge']['version'])
    FORGE_DIR = os.path.join(VERSIONS_DIR, FORGE_VERSION)

    print('Entering directory "{}".'.format(MINECRAFT_DIR))
    try:
        os.chdir(MINECRAFT_DIR)
    except:
        print('Failed to enter minecraft directory, please install minecraft first.')
        utils.exit()
    utils.print_separator()

    # Set the directory to which the custom profile will be installed.
    profile_name = raw_input('What would you like to call the profile being created? [launchcraft]: ').lower()
    if profile_name == '':
        profile_name = 'launchcraft'
    PROFILE_DIR = os.path.join(VERSIONS_DIR, profile_name)
    print('Creating profile {}'.format(profile_name))

    # Delete the old profile directory so we can start from scratch.
    try:
        shutil.rmtree(PROFILE_DIR)
        print('Removed old profile directory.')
    except OSError as ex:
        if ex.errno == errno.ENOENT:
            print('No old profile directory found.')
        else:
            print(ex)
            print('Failed to remove old profile directory, exiting...')
            utils.exit()
    utils.print_separator()

    forge = utils.query_yes_no('Would you like to use Forge?', default='no')
    if forge:
        if os.path.exists(FORGE_DIR):
            print('The required Forge version has been detected on your system.')
            message = 'reinstall'
        else:
            print('The required Forge version has not been detected on your system.')
            message = 'install'
        # Ask the user whether or not they need Forge.
        if utils.query_yes_no('Do you need to {} Forge?'.format(message), default='no'):
            forge = utils.MODS['mods']['forge']
            name = forge['name']
            version = forge['version']
            jarName = 'forge.jar'

            if sys.platform == 'win32' or sys.platform == 'cygwin':
                os.chdir(BASE_DIR)

            # Download the Forge installer.
            print('Downloading {} version {}'.format(name, version))
            utils.downloadFile(forge['url'], jarName)

            if sys.platform == 'win32' or sys.platform == 'cygwin':
                print('You must now run the {} that has been downloaded to your Launchcraft directory.'.format(jarName))
                utils.exit()
            else:
                # Run the installer so the user can install Forge.
                print('You will now be asked to install Forge version {}.'.format(version))
                with open(os.devnull, 'w') as devnull:
                    subprocess.call('java -jar {}'.format(jarName), shell=True, stdout=devnull)

                os.remove(jarName)
    utils.print_separator()

    JAR_FILE = os.path.join(PROFILE_DIR, '{}.jar'.format(profile_name))
    JSON_FILE = os.path.join(PROFILE_DIR, '{}.json'.format(profile_name))

    if forge:
        print('Using Forge {} as the base for the profile'.format(utils.MODS['mods']['forge']['version']))
        if not os.path.exists(MOD_DIR):
            os.makedirs(MOD_DIR)

        utils.INSTALLED_MODS.append('forge')
        JAR_DIR = FORGE_DIR
        print('Creating new profile directory.')
        shutil.copytree(FORGE_DIR, PROFILE_DIR)
        print('Renaming Forge jar.')
        shutil.move(os.path.join(PROFILE_DIR, '{}.jar'.format(FORGE_VERSION)), JAR_FILE)
        SOURCE_JSON_FILE = '{}.json'.format(FORGE_VERSION)

        print('Entering newly created profile directory.')
        os.chdir(PROFILE_DIR)
    else:
        print('Using Minecraft {} as the base for the profile'.format(version))
        # Create the profile directory.
        try:
            print('Creating new profile directory.')
            os.makedirs(PROFILE_DIR)
        except OSError as ex:
            print(ex)
            print('Failed to create new profile directory, exiting...')
            utils.exit()

        print('Entering newly created profile directory.')
        os.chdir(PROFILE_DIR)

        print('Downloading "{0}.jar" and "{0}.json".'.format(version))
        utils.downloadFile('https://s3.amazonaws.com/Minecraft.Download/versions/{0}/{0}.jar'.format(version), '{}.jar'.format(profile_name))
        utils.downloadFile('https://s3.amazonaws.com/Minecraft.Download/versions/{0}/{0}.json'.format(version), '{}.json'.format(version))
        SOURCE_JSON_FILE = '{}.json'.format(version)

    print('Creating "{}.json".'.format(profile_name))
    with open('{}'.format(SOURCE_JSON_FILE), "r") as file:
        data = json.load(file)
    data['id'] = profile_name
    with open(JSON_FILE, "w") as file:
        json.dump(data, file, indent=4)

    print('Deleting "{}".'.format(SOURCE_JSON_FILE))
    os.remove(SOURCE_JSON_FILE)
    utils.print_separator()

    if utils.query_yes_no('Do you want to install mods?', default='no'):
        print('Which mods would you like to install?')
        toInstall = utils.printAskOptions(utils.MODS['mods'])
        print('Installing mods.')
        print('')
        for mod in toInstall:
            modData = utils.MODS['mods'][mod]
            skip = False

            conflicts = [i for i in modData['conflicts'] if i in utils.INSTALLED_MODS]

            if mod == 'forge':
                continue

            # Do not install forge-dependant mods if Forge is not installed.
            if 'forge' in modData['deps'] and 'forge' not in utils.INSTALLED_MODS:
                print('Skipping {} due to missing Forge'.format(modData['name']))
                skip = True
            # Skip conflicting mods
            elif conflicts:
                conflicting_mods = ""
                for i in conflicts:
                    conflicting_mods += utils.MODS['mods'][i]['name'] + ", "
                print('Skipping {} because it conflicts with {}'.format(modData['name'], conflicting_mods[:-2]))
                skip = True

            if skip:
                print('')
                continue

            utils.installDep(mod, JAR_FILE)
            print('')

    utils.removeMETAINF(JAR_FILE)
    utils.print_separator()

    if utils.query_yes_no('Do you want to install texture packs?', default='no'):
        if not os.path.exists(RESOURCEPACK_DIR):
            os.makedirs(RESOURCEPACK_DIR)
        print("What texture packs would you like to install?")
        toInstall = utils.printAskOptions(utils.MODS['resourcepacks'])
        print('Installing resourcepacks.')
        print('')
        for pack in toInstall:
            packData = utils.MODS['resourcepacks'][pack]

            utils.installResourcePack(pack)
            print('')
    utils.print_separator()

    if utils.query_yes_no('Do you want to install shader packs?', default='no'):
        if not os.path.exists(SHADERPACK_DIR):
            os.makedirs(SHADERPACK_DIR)
        print("What shader packs would you like to install?")
        toInstall = utils.printAskOptions(utils.MODS['shaderpacks'])
        print('Installing shaderpacks.')
        print('')
        for pack in toInstall:
            packData = utils.MODS['shaderpacks'][pack]

            utils.installShaderPack(pack)
            print('')
    utils.print_separator()

    print('Completed successfully!')
    utils.exit()

    try:
        input('Press any key to exit...')
    except:
        pass