Chuvico / MyProject

0 stars 0 forks source link

FULL GAME BLACKJACK #4

Open Chuvico opened 3 months ago

Chuvico commented 3 months ago

# PSP Assignment 2 - Provided file (blackjack.py). high_scores.txt import random

def play_blackjack(): total_score = 0

play_game = 'y'
while play_game == 'y':
    print("-"*21,"START GAME","-"*21)

    dealer_hand = random.randint(1, 10)
    print("| Dealer hand:", dealer_hand)

    player_total = deal_players_hand()
    print("| Player hand:", player_total)

    dealer_total = deal_dealers_hand(dealer_hand)
    print("| Dealer hand:", dealer_total)

    result = determine_winner(player_total, dealer_total)
    print("|","Dealer hand:",dealer_total,"Player hand:",player_total,get_winner_message(result))

    total_score += result

    print("-"*21,"END GAME","-"*21)
    play_game = input("Your score: " + str(total_score) + " - Play again [y|n]?: ")
    while play_game != 'y' and play_game != 'n':
        print("Please enter y or n.")
        play_game = input("Play again [y|n]?: ")

return total_score

def deal_players_hand(): die1 = random.randint(1, 10) die2 = random.randint(1, 10) player_total = die1 + die2 choice = "h"

if die1 == 1 or die2 == 1:
    player_total += 10

print("| Player hand:", die1, "+", die2, "=", player_total)

while player_total < 21 and choice != "s":
    choice = get_choice()
    if choice == 'h':
        new_die = random.randint(1, 10)
        print("| Player hand:", player_total, "+", new_die, "=", player_total + new_die)
        player_total += new_die

        if new_die == 1 and player_total > 21:
            player_total -= 10

        if player_total > 21:
            print("| PLAYER BUSTS!")

    elif choice == 's':
        if player_total < 15:
            print("| Cannot stand on value less than 15!")
            new_die = random.randint(1, 10)
            print("| Player hand:", player_total, "+", new_die, "=", player_total + new_die)
            player_total += new_die
            choice = "h"

return player_total

def deal_dealers_hand(die_value): die2 = random.randint(1, 10) dealer_total = die_value + die2

if die2 == 1 and dealer_total > 21:
    dealer_total -= 10

print("| Dealer hand:", die_value, "+", die2, "=", dealer_total)

while dealer_total < 17:
    new_die = random.randint(1, 10)

    if new_die == 1 and dealer_total + 11 <= 21:
        new_die = 11
    print("| Dealer hand:", dealer_total, "+", new_die, "=", dealer_total + new_die)
    dealer_total += new_die

    if dealer_total > 21:
        print("| DEALER BUSTS!")
        # return dealer_total

return dealer_total

def determine_winner(player_total, dealer_total):

# Case 1: Player busted and dealer busted - Dealer wins
if player_total > 21 and dealer_total > 21:
    return 0

# Case 2: Dealer busted player not busted - Player wins
elif player_total <= 21 and dealer_total > 21:
    return 3

# Case 4: Dealer not busted player busted - Dealer wins
elif dealer_total <= 21 and player_total > 21:
    return 0
elif player_total <= 21 and dealer_total < player_total:
    return 3
elif player_total <= 21 and player_total < dealer_total:
    return 0

Case 5: They are draw

else:
    return 1

def get_winner_message(result): if result == 0: return " Dealer Wins! " elif result == 1: return " Push - no winners. " elif result == 3: return " Player Wins! "

def get_choice(): choice = input("| Please choose to hit or stand (h/s): ") while choice != 'h' and choice != 's': choice = input("| Please choose to hit or stand (h/s): ") return choice

Call function play_blackjack() - plays Blackjack against the computer

score = play_blackjack()

Display score to the screen

print("\nYour score:", score)

# PSP Assignment 2 - Provided file (highscores.py). import dincy016_blackjack

This function takes a file name and reads the contents of that file into

the player_name and player_scores lists passed as a parameter into the

function.

#

The function returns the number of players read in from the file.

You should make sure that you do not exceed the size of the lists (i.e. size

of 5). The player_names and player_scores lists should not exceed 5 elements.

def read_file(filename, player_names, player_scores): file = open(filename, "r") lines = file.readlines() file.close()

index = 0
for line in lines:

    parts = line.strip("\n").split(" ")

if len(parts) == 2 and num_players < max_players:

    name = parts[0] + " " + parts[1]
    score = int(parts[2])
    player_names[index] = name
    player_scores[index] = score
    index += 1

return index

This function will output the contents of the player_names and player_scores

lists to a file in the same format as the input file.

#

The file will need to be opened for writing in this function (and of course

closed once all writing has been done).

#

The function accepts the filename of the file to write to, the player_names

and player_scores lists.

def write_to_file(filename, player_names, player_scores): with open(filename, "w", encoding="utf-8") as outfile: for i in range(len(player_names)): line = player_names[i] + " " + str(player_scores[i]) + "\n" outfile.write(line)

This function will take the player_names list and the player_scores list

as parameters and will output the contents of the lists to the screen.

#

This function displays the information to the screen in the format

specified in the assignment specifications under the section - 'Screen Format'.

def display_high_scores(player_names, player_scores): print(sep = "\n\n\n") print("" 53) print("" 18,format("Blackjack","^17s"),"" 18, sep = "") print("" 18,format("HIGH SCORES","^17s"),"" 18,sep = "") print("" 53) print(" ") print(format("","<7s"), format("Player Name","<33s"),format("Score","<12s"),"", sep="") print("" 53)

for i in range(len(player_names)):
    player_name = player_names[i]
    player_score = player_scores[i]
    if player_name != "":
        print(format("*","<7s"), format(player_name,"<33s"),format(str(player_score),"<12s"),"*", sep="")
        print("*---------------------------------------------------*")
    else:
        print(format("*","<7s"), format("?"*8,"<33s"),format(str(player_score),"<12s"),"*", sep="")
        print("*---------------------------------------------------*")

print("*" * 53)

print("*" * 53)

This function will take the player's name as input along with the player_names

list and will return the

position (index) of the player found in the player_names list. You must not

use list methods in your solution.

#

If more than one player exists with the same name, return the position

of the player who has the highest score (i.e. first match found).

#

If the player is not found, the function returns -1.

def find_player(player_names, name): for i in range(len(player_names)): if player_names[i] == name: return i return -1

This function takes a player's score, and the player_scores list

as input and determines whether the player is to be added to the

high scores lists (player_names and player_scores).

If the player is to be added, the insertion position is returned from this function.

#

If the player does not qualify to have their name recorded in the high scores lists,

the function returns -1.

def is_high_score(player_scores, new_score): if len(player_scores) < 5: return len(player_scores)

for i in range(5):
    if new_score > player_scores[i]:
        return i

return -1

This function takes the high scores lists (player_names and player_scores),

the player's name and score and the position to insert the player into the lists.

#

The player is added to the high scores lists at the insert position.

The high scores lists (player_names and player_scores) must be maintained in

descending order of total score. Where two players have the same total score,

the new player being added should appear first.

#

(Hint: when inserting a player, simply shift all elements one position down the lists.

You must make sure you are not exceeding list bounds and that your lists do not contain

more than five elements). You must not use list methods in your solution.

#

The function returns the number of high scores stored in the lists.

old = [10,8,6,1,0] new = [0,0,0,0,0] def add_player(player_names, player_scores, new_name, new_score, insert_position): new_names = ["","","","",""] new_scores = [0,0,0,0,0]

# If insert position is at beginning
if insert_position == 0:
    index_of_new = 1
    index_of_old = insert_position
    new_scores[0] = new_score
    new_names[0] = new_name
    for index in range(len(player_scores)-1):
        new_scores[index_of_new] = player_scores[index]
        new_names[index_of_new] = player_names[index]
        index_of_new += 1

player_scores[index] = player_scores[index - 1]

player_names[index] = player_names[index - 1]

print(new_names)

print(new_scores)

    # Copy values from temp list to official lists
    for index in range(len(new_names)):
        player_names[index] = new_names[index]
        player_scores[index] = new_scores[index]

# Insert position is at end   
elif insert_position == 4:
    player_names[4] = new_name
    player_scores[4] = new_score

# Insert position is between (but not including first and last position)    
else:

index_of_new = insert_position

    index_of_old = insert_position

    # Copy all values upto but not including the insert value at insert pos
    # to new lists
    for index in range(insert_position):
        new_scores[index] = player_scores[index]
        new_names[index] = player_names[index]

    new_scores[insert_position] = new_score
    new_names[insert_position] = new_name

    # Copy all the values from insert position over to new lists
    for index in range(insert_position+1, len(new_names)):
        new_scores[index] = player_scores[index_of_old]
        new_names[index] = player_names[index_of_old]
        index_of_old+=1

    # Copy values from temp list to official lists    
    for index in range(len(new_names)):
        player_names[index] = new_names[index]
        player_scores[index] = new_scores[index]

for index in range(insert_position):

player_scores[index] = player_scores[index - 1]

player_names[index] = player_names[index - 1]

player_scores[insert_position] = new_score

player_names[insert_position] = new_name

print(player_scores)

MAX_SCORES = 5

def main(): valid_choices = ["scores", "search", "play", "quit"]

# Create empty lists to store player names and scores
player_names = [""] * MAX_SCORES
player_scores = [0] * MAX_SCORES

read_file("high_scores.txt", player_names, player_scores)

# Main loop for processing commands
choice = ""
rounds_played = 0  # Track the number of rounds played

while choice != "quit":
    choice = input("Please enter command [scores, search, play, quit]: ")

    while choice not in valid_choices:
        print("Not a valid command - please try again.")
        choice = input("Please enter command [scores, search, play, quit]: ")

    if choice == "scores":
        # Display high scores
        display_high_scores(player_names, player_scores)
    elif choice == "search":
        # Ask user for a name and display the score for the player
        name_to_search = input("Please enter the name to search for: ")
        position = find_player(player_names, name_to_search)
        if position == -1:
            print(f"{name_to_search} does not have a high score entry.")
        else:
            print(f"{name_to_search} has a high score of {player_scores[position]}")
    elif choice == "play":
        # Play blackjack and calculate score
        score = dincy016_blackjack.play_blackjack()
        rounds_played += 1  # Increment rounds played

        # Check if the score is a high score
        insert_position = is_high_score(player_scores, score)
        if insert_position != -1:
            # Ask for the player's name and add them to high scores
            new_name = input("Congratulations! You achieved a high score. Enter your name: ")
            add_player(player_names, player_scores, new_name, score, insert_position)
            print(f"{new_name} has been added to the high scores list.")
    elif choice == "quit":
        if rounds_played == 0:
            print("Goodbye!")
            print("See You In Hell", u"\U0001F608")
            print("       _              _     ")
            print("      | |            | |    ")
            print("      | |            | |    ")
            print("      | |            | |    ")
            print("      | |            | |    ")
            print("      | |            | |    ")
            print("      | |            | |    ")
            print(" _  _ | | _     _  _ | | _  ")
            print("/ \/ \| |/ \   / \/ \| |/ \ ")
        else:
            print("Goodbye - thanks for playing!")
            display_high_scores(player_names, player_scores)

# Write scores to a file before exiting
write_to_file("new_scores.txt", player_names, player_scores)

main()