Demo entry 6336870

21 (commented)

   

Submitted by Jamie Land on Dec 08, 2016 at 13:38
Language: Python 3. Code size: 10.2 kB.

###########
# Imports #
###########
import random
import sys
import time

###########
# Globals #
###########
# This is a list of all possible cards, '11' = the Ace, meaning it can be 1 or 11.
# I will get the game to automatically do this if the person has 1 ace or more and if they are over the amount,
#  the ace will become 1.
CARD_LOOKUP = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]

############
# Routines #
############
def menu():
    # Initialises variable 'runs' which can be changed to see how many players have gone.
    runs = 0
    print("What would you like to do?")
    print("1) Play against the computer\n2) Play against a human\n3) Quit")
    answer = input("\nChoose your selection. ")
    # Exception handling as the program will crash if they have written in the answer wrong.
    try:
        answer = int(answer)
    # Checks for TypeError as a string with letters cannot be turned into an integer.
    # Checks for ValueError too.
    except(TypeError, ValueError):
        print("Please type in 1, 2 or 3.")
        menu()
    # If statement to define the variables
    if answer == 1 or answer == 2:
        # Initialises the player and the computer's hands
        # The points that they will gain
        # And flags for if they are in bust or not.
        # Including the mode
        player1Hand = []
        player2Hand = []
        player1Points = 0
        player2Points = 0
        player1Bust = False
        player2Bust = False
    # If statement to get the correct mode.
        if answer == 1:
            # Computer game
            mode = "computer"
        elif answer == 2:
            # Human game
            mode = "human"
        # Send the user to the main game loop where it will play through all of the game.
        play_loop(player1Hand, player2Hand, mode, runs, player1Points, player2Points, player1Bust, player2Bust)
    elif answer == 3:
        print("\nThank you for playing my game.")
        sys.exit()
    else:
        print("\nPlease type in 1, 2 or 3.")
        menu()

# This is the function that I will call that will add together the player's total points.
# It will also change itself based on the aces that they have drawn to accord for the 1/11 game rule.
def adder(hand):
    # Adds all of the numbers in the hand together.
    points = sum(hand)
    # Gives back the amount of aces that the player has.
    aces = hand.count(11)
    # The user has busted, but they have an ace.
    if points > 21 and aces >= 1:
        # This is turing the ace from 11 points to 1 point.
        points -= 10
        # Since the ace has been used, to make sure it can't be used again, I make it seem like it doesn't exist.
        aces -= 1
    # Gives the points back to where it came from: working out the points.
    return points

def play_loop(hand, hand2, mode, runs, pPoints, p2Points, pBust, p2Bust):
    runs += 1
    # This is the game loop so that each player can play.
    while True:
        # The name of the player is set here for the print statement below.
        if runs == 1 and mode == "human":
            player = "first player"
        elif runs == 2 and mode == "human":
            player = "second player"
        elif runs == 1 and mode == "computer":
            player = "player"
        elif runs == 2 and mode == "computer":
            player = "computer"
        # random.choice() will look through all of the cards in the 'cardLookup' list and draw one.
        # It will then append that card to the player's hand.
        hand.append(random.choice(CARD_LOOKUP))
        hand.append(random.choice(CARD_LOOKUP))
        # Loop for the player's hand to be drawn and for them to play.
        while True:
            # Sends to the 'adder' routine with the hand and gives back the current points.
            current = adder(hand)
            # Sorts the list in number order.
            hand.sort()
            print("\nThe %s has the %s cards, with a total of %d points." % (player, hand, current))
            if current == 21:
                print("%s: Blackjack!" % player)
                if runs == 1:
                    # If it is the first player who just played.
                    # It gives control to the second player, swapping the parameters around.
                    play_loop(hand2, hand, mode, runs, p2Points, current, p2Bust, pBust)
                else:
                    # Otherwise, if it is the second player who has just played.
                    # Send to the final screen.
                    win(hand2, hand, p2Points, current, p2Bust, pBust, "first player", "second player")
            # If their current has gone over 21.
            elif current > 21:
                # They go into bust.
                print("%s went bust!\n" % player)
                # Sets the flag to true to show in the 'win' routine.
                pBust = True
                if runs == 1:
                    play_loop(hand2, hand, mode, runs, current, pPoints, p2Bust, pBust)
                else:
                    win(hand2, hand, p2Points, current, p2Bust, pBust, "first player", "second player")
            # This is where they gain control again.
            # If they are playing the human vs human game mode, it will tell them to Hit, or Stand.
            # Otherwise, it will tell only the human to Hit or Stand
            # Otherwise it will make it so the computer will play.
            else:
                if mode == "human" or (mode == "computer" and runs == 1):
                    nextPlay = input("1) Hit\n2) Stand\n\nWhat is your choice? ")
                    try:
                        nextPlay = int(nextPlay)
                    except(TypeError, ValueError):
                        print("Please type in 1 or 2.\n")
                    if nextPlay == 1:
                        hand.append(random.choice(CARD_LOOKUP))
                    elif nextPlay == 2:
                        print("%s: Standing at %d" % (player, current))
                        if runs == 1:
                            time.sleep(2)
                            play_loop(hand2, hand, mode, runs, p2Points, current, pBust, p2Bust)
                        else:
                            if mode == "computer":
                                time.sleep(2)
                                win(hand2, hand, p2Points, current, p2Bust, pBust, "player", "computer")
                            else:
                                time.sleep(2)
                                win(hand2, hand, p2Points, current, p2Bust, pBust, "first player", "second player")
                    else:
                        print("Please type in 1 or 2.")
                elif mode == "computer" and runs == 2:
                    # In real blackjack, the dealer (the computer) will stand at 18.
                    # If they have less than 18, they will take another card.
                    if current < 18:
                        hand.append(random.choice(CARD_LOOKUP))
                        time.sleep(2)
                    else:
                        print("%s: Standing at %d" % (player, current))
                        time.sleep(2)
                        win(hand2, hand, p2Points, current, p2Bust, pBust, "player", "computer")

def win(p1Hand, p2Hand, p1Points, p2Points, p1Bust, p2Bust, p1Player, p2Player):
    # In the case of a draw...
    if p1Points == p2Points:
        # In the case that either player got a two-card blackjack.
        if (p1Hand.count(11) == 1 and p1Hand.count(10) == 1) and (p2Hand.count(11) == 1 and p2Hand.count(10) == 1):
            print("It's a draw!\n")
            menu()
        elif p1Hand.count(11) == 1 and p1Hand.count(10) == 1:
            print("%s wins with a Two-Card Blackjack!" % p1Player)
        elif p2Hand.count(11) == 1 and p2Hand.count(10) == 1:
            print("%s wins with a Two-Card Blackjack!" % p2Player)
        else:
            print("It's a draw!\n")
            menu()
    # In the case that player one has more points than player 2...
    elif p1Points > p2Points:
        # If player one has more because of a bust.
        if p1Bust:
            print("%s went bust! %s wins with %s in their hand, making %d points." % (p1Player, p2Player, p2Hand,
                                                                                      p2Points))
        elif p2Bust:
            print("Both players went bust!")
        else:  # The first player has more points than the second and has not gone bust.
            print("%s win with %s in their hand, making %d points" % (p1Player, p1Hand, p1Points))
            print("%s loses with %s in their hand, making %d points" % (p2Player, p2Hand, p2Points))
    # In the case that the second player has more points than player 1...
    elif p1Points < p2Points:
        if p2Bust:
            print("%s went bust! %s wins with %s in their hand, making %d points." % (p2Player, p1Player, p1Hand,
                                                                                      p1Points))
        elif p1Bust:
            print("Both players went bust!")
        else:  # The second player has more points than the first and has not gone bust.
            print("%s win with %s in their hand, making %d points" % (p2Player, p2Hand, p2Points))
            print("%s loses with %s in their hand, making %d points" % (p1Player, p1Hand, p1Points))
    # Opens up a new text file to save the results in. It creates the text file based on an input from the user.
    fileName = input("\nWhat is the file name that you would like to store the game under? ")
    with open(fileName + ".txt", "w") as file:
        file.write("---- Game: %s ----\n" % fileName)
        file.write("%s - Hand: %s, Points: %d, Bust? %s\n" % (p1Player, p1Hand, p1Points, p1Bust))
        file.write("%s - Hand: %s, Points: %d, Bust? %s" % (p2Player, p2Hand, p2Points, p2Bust))
    time.sleep(4)
    sys.exit()

#############
# Game Loop #
#############
menu()

This snippet took 0.02 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).