PROject Python | Blackjack (#extremely.cool.it’s.kinda.unbelieveable,just.saying)

Quote of AWESOMENESS: “Thinking is already a conversation” ~ Paul Pangaro

 

Hey there!

I know it’s been awhile but here I am with another Python project. Today, you will be learning the code for blackjack! Just put it out on your editor, study the code, and explore the game on your terminal. It was quite some challenge getting toward the end of finishing up the game. And, at some point, problems and bugs constantly came up that I didn’t that it would actually get done. BUT, nevertheless, it’s finally hereeee!!

*ahem, drum rollllllllll*

*cricket sounds*

*Umm….. DRUMMM ROLLLL!!!……. please?*

*DRUM ROLLLLLLLLLL (in the background, finally)*

TADA!!!!:

#import the random library from python
from random import *


#Function Definitions 
def deal_from_deck(deck):
    if len(deck)<1:
         create_deck(deck)
         shuffle_deck(deck)
         deal_cards()

def deal_cards(deck):
    return deck.pop(0)

def define_cards(n):
    rank_string = ("ace", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen","king")
    suit_string = ("clubs", "diamonds", "hearts", "spades")
    cards = []

    for suit in range(4):
        for rank in range(13):
            card_string = rank_string[rank] + " of " + suit_string[suit]
            cards.append(card_string)
    return cards[n]

def create_deck(deck):
    for i in range(52):
        deck.append(i)
    return

def shuffle_deck(deck):
    shuffle(deck)
    return

def card_value(n):
    vals = (11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10)
    card_vals = []

    for s in range(4):
        for r in range(13):
            card_vals.append(vals[r])
    return card_vals[n]

def card_display(n):
    name = define_cards(n)
    val = card_value(n)
    print (name + " : " + str(val))

def show_cards(hand):
    for card in hand:
        card_display(card)


def hand_val(hand):
    list = []
    for card in hand:
        list.append(card_value(card))
    if sum(list) > 21:
        for i in range(len(list)):
            if list[i] == 11:
                list[i] = 1
    return sum(list)





# Initializing
drawn_hands = 0
player_wins = 0
dealer_win = 0
deck = []
player_hand = []
dealer_hand = []
playing = True


#Processing
create_deck(deck)
shuffle_deck(deck)

for i in range(2):
    card = deal_cards(deck)
    card2 = deal_cards(deck)
    player_hand.append(card)
    dealer_hand.append(card2)


# put in a loop for player hand
print()
print("--------------------")
print("Dealer shows: ")
card_display(dealer_hand[0])
print("--------------------")

while playing == True:
    player_val = hand_val(player_hand)
    print()
    print()
    print("* * * * * * * * * * *")
    print("Your current hand is...")
    show_cards(player_hand)
    print(hand_val(player_hand))
    print("* * * * * * * * * * *")
    print()
    print()
    if player_val < 22:
        response = input("Would you like another card?")
        if response == "yes":
            player_hand.append(deal_cards(deck))
        else:
            playing = False
    else:
        playing = False
        print("sorry you busted")
        print("Thanks for playing")
        exit()

# check if it is higher than 21, if yes then end program, dealer hand wins
show_cards(dealer_hand)

playing = True
while playing == True:
    if hand_val(dealer_hand) < 17:
        dealer_hand.append(deal_cards(deck))
    else:
        playing = False

print()
print()
print("****************")
print("Dealer has:")
print(show_cards(dealer_hand))
print("****************")
print()
print()

if hand_val(dealer_hand) > 21:
    print("The dealer busted")
    show_cards(dealer_hand)
    print("You win!")
    exit()
elif hand_val(dealer_hand) > hand_val(player_hand):
    print("Dealer wins")
    show_cards(dealer_hand)
    exit()
elif hand_val(player_hand) > hand_val(dealer_hand):
    print("You win!")
    show_cards(player_hand)
    exit()
else:
    print("It's a draw")
    exit()

 

don’t forget to smile & be awesome 🙂

Yours truly, 

L.O.A.S.H

 


 © Elizabeth Anne Villoria

PROject Python: Hangman Game!

Quote of AWESOMENESS: “First, solve the problem. Then, write the code.” ~ John Johnson

Yup, I know, this is like the fourth blog in a row that relates to Python. BUT, it’s okay! This one is really fun. The program we will be making today is Hangman. The code is shown below:


import random

def print_game_rules(max_incorrect,word_len):
    print("This game we will be playing hangman!")

def display_figure(bad_guesses):
    gallows = (
        """
            +----------+
            |
            |
            |
            |
            |
        ================
        """,
        """
            +----------+
            |          o
            |
            |
            |
            |
        ================
        """,
        """
            +----------+
            |          o
            |          +---
            |
            |
            |
        ================
        """,
        """
            +----------+
            |          o
            |       ---+---
            |
            |
            |
        ================
        """,
        """
            +----------+
            |          o
            |       ---+---
            |          |
            |
            |
        ================
        """,
        """
            +----------+
            |          o
            |       ---+---
            |          |
            |         /
            |        /
        ================
        """,
        """
            +----------+
            |          o
            |       ---+---
            |          |
            |         / \
            |        /   \
        ================
        """
    )
    print(gallows[bad_guesses])
    return()

def prompt_for_letter():
    print("")
    player_guess = str(input("Guess a letter in the mystery word: "))
    player_guess = player_guess.strip()
    player_guess = player_guess.lower()
    print("")
    return(player_guess)

animal_words = ("horse", "mall", "desktop", "apple", "earth", "tree", "sun", "can", "love", "dog", "door", "house", "mansion", "beach", "computer", "window", "keyboard", "airplane", "hotel", "cat")
theword = random.choice(animal_words)
word_len = len(theword)
letterguess = word_len * ["_"]
max_incorrect = 6
alphabet = ("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z")
letters_tried = []
number_guesses = 0
letters_correct = 0
incorrect_guesses = 0
###############################
# PROCESSING SECTION
# Branching code: if/else
# Looping code: for-loop, while-loop
###############################

print("This game is hangman.")
while (incorrect_guesses != max_incorrect) and (letters_correct != word_len):
    letter = prompt_for_letter()
    if letter in alphabet:
        if letter in letters_tried:
            print("You already picked", letter)
        else:
            letters_tried.append(letter)
            if theword.find(letter) == -1:
                print("the letter", letter,"is not in the word")
                incorrect_guesses += 1
                print("***********************")
                print(incorrect_guesses)
            else:
                print("the letter", letter,"is in the word")
                for i in range(word_len):
                    if letter == theword[i]:
                        letterguess[i] = letter
                        letters_correct += 1
                    else:
                        pass
    else:
        print("Please guess a single letter in the alphabet.")


    x = ""
    print(x.join(letterguess))
    a = ""
    print("Letters tried so far: ", a.join(letters_tried))
    if incorrect_guesses == max_incorrect:
        print("Sorry, too many incorrect guesses. You are hanged.")
        print("The word was", theword)
    if letters_correct == word_len:
        print("You guessed all the letters in the word!")
        print("The word was", theword)



    display_figure(incorrect_guesses)

 

Honestly, this was a challenging project at the start and I had quite a few obstacles that were highly annoying but eventually here we are!

 

Pssst, don’t forget to be awesome today.

Yours truly, 

L.O.A.S.H

 


 © Elizabeth Anne Villoria 

 

 

PROject Python: Making a function

Quote of AWESOMENESS: “The function of leadership is to produce more leaders, not more followers” ~ Ralph Leader

Hiii!

Functions are so useful and cool at the same time and right now I’m going to teach just how to make one!

But, before we go there, what exactly is a function? It’s somewhat like a pre-made command that you get to customize yourself. For example, you wanted to make five circles, imagine you would have to make each circle repeating how big you wanted it to be, the color, locations, and others. But, if you had a function, you would make it so much simpler in just adding the code and copy-pasting the function.

Here’s the code for a function:

[rememberWHITESPACE is very important in Python]

# This hastag is a comment and won't affect the code
# We start making function by defining it with the word def
# The thing written inside the parenthesis is called the argument
# Remember to put the colon then the indentation will be proper, too

def list(alist):
    # Here, I'm setting the variable a to number 0
    a = 0

    # This is a for-loop and the i just stands for index 
    for i in alist:
        if i > 0:
            a += 1
        else:
            pass
    print(a)


# Here is the actual function in action!
# Test section
mylist = [2,-4,5,-16,-20]
mylist2 = [2,6,8,-4]
mylist3 = [-5,-6,-7,-8,10]


list(mylist)
list(mylist2)
list(mylist3)

This is just a simple example of what you can make of a function. Try it out! 

 

Don’t forget to be awesome!

Yours truly, 

L.O.A.S.H

 


 © Elizabeth Anne Villoria 

 

L.O.A.S.H’s Guide to (nearly) Everything: Arduino Color Lamp Mixer!

Quote of awesomeness: “Is not about creating an object. It is about creating a perspective.” ~ Albert Paley

Level of hardness: intermediate (You can do this!)

Heyyy!!!! Here’s another Arduino project for you!

For this project, you will need the following:

  • 1x Arduino UNO Board
  • 1x USB Cable Type A/B
  • 1x Breadboard
  • 1x RGB LED 
  • 3x 220-Ohm Resistor
  • 3x 10k-Ohm Resistor
  • 3x Photoresistors
  • 13x Jumper Wires

 

Step 1:

0-02-01-25a0a6f9debabdd212fbc3c05acd2fcf5f1c439705c879adf26fea2d27db35df_full.jpg

The first step is two connect your breadboard to your Arduino and it should look something like the photo above. Then, add your RGB LED to your breadboard. 

Step 2:

0-02-01-ce8d12da04188f7a9054ea5aa04a72e5ac576232bc208167812c08ec3ba18cfe_full

 

Next, you need to grab another wire and connect the other positive lane of the breadboard to the negative lane on the other side of the breadboard.

 

Step 3:

0-02-01-9bde85f3c5437a50c6a476f15138e6c5858ce46a700364835db6ee8e53447d2f_full

In this step, we will be placing the three 220-Ohm Resistors to three of the legs of the RGB LED. You will only be placing the resistors on the R, G and B of the RGB LED, this will leave you with one leg unconnected.

 

Step 4:

0-02-01-dbc63a13ab6f50466eb8dd3465af30d65b8f5e7967920a87645ee225ffaa44ea_full.jpg

For this step, you will be needing four wires. Remember I told you that you were left with one leg of the RGB LED which isn’t connected? Well, it’s time to connect it now! Place one end of the wire to the remaining leg of the RGB LED then place the other end to the negative lane of the board. In the photo, the wire which I used for this connection is white.

0-02-01-61ac8f02b55daa224f1962b3e828047ead0580414fcee62ded86ee5ad453523a_full.jpg

With the other three wires, connect it to each of the 220-ohm resistors. Then, connect the other end of the wires to the Arduino 9, 19, and 11.

 

Step 5:

0-02-01-9f2cb7be6b6ebbcc06aaf7b34dfd409e332e34965665efa0386c1a48cf6d16fb_full.jpg

Let’s place the photo-resistors on the breadboard so that they cross the center divide from one side to the other. 

 

Step 6:

0-02-01-c45f2f455156cfbfb4d1aee3c77926f4c5d55503f0796170018956fc0281a57a_full.jpg

Now, connect the 10k-Ohm resistors to one side of the photo-resistors and the other side to the negative lane of the breadboard.

 

Step 7:

0-02-01-3e1c74c9aa8f84a2158daa0ca5b528a6e2785236e0f532f18c1820533a1aa4a9_full.jpg

Taking three other wires, connect it between the photo-resistor and the 10k-Ohm resistor then connect the other end to the Analog In pins 0, 1, and 2 on the Arduino.

 

Step 8:

0-02-01-b946dc989126c65408412e7a570d06c10c28d9cfba450fc3cdc3bf12acca7b91_full.jpg

Going on the other side of the photo-resistor, connect each leg to the positive lane of the Arduino with three wires.

0-02-01-1733d59664a66910bba653033a94e1427937448a2a20dee06bab915fa06fac0f_full.jpg

Your result should look something like this!

 

Step 9:

This is the final step! Connect your Arduino to your computer, fire up your Arduino and copy paste in the following code:

const int greenLEDPin = 9;
const int redLEDPin = 11;
const int blueLEDPin = 10;

const int redSensorPin = A0;
const int greenSensorPin = A1;
const int blueSensorPin = A2;

int redValue = 0;
int greenValue = 0;
int blueValue = 0;

int redSensorValue = 0;
int greenSensorValue = 0;
int blueSensorValue = 0;

void setup() {
Serial.begin(9600);

pinMode(greenLEDPin, OUTPUT);
pinMode(redLEDPin, OUTPUT);
pinMode(blueLEDPin, OUTPUT);

}

void loop() {
redSensorValue = analogRead(redSensorPin);
delay(5);
greenSensorValue = analogRead(greenSensorPin);
delay(5);
blueSensorValue = analogRead(blueSensorPin);

Serial.print(“Raw Sensor Value \t Red: “);
Serial.print(redSensorValue);
Serial.print(“\t Green: “);
Serial.print(greenSensorValue);
Serial.print(“\t Blue: “);
Serial.print(blueSensorValue);

redValue = redSensorValue/4;
greenValue = greenSensorValue/4;
blueValue = blueSensorValue/4;

Serial.print(“Mapped Sensor Values \t Red: “);
Serial.print(redValue);
Serial.print(“\t Green: “);
Serial.print(greenValue);
Serial.print(“\t Blue: “);
Serial.println(blueValue);

analogWrite(redLEDPin, redValue);
analogWrite(greenLEDPin, greenValue);
analogWrite(blueLEDPin, blueValue);
}

 

Then watch as your RGD LED comes to life! It should change, mix and fade in different colours as the light around it changes, too! Awesome, right?? Yeah, it totally is.

Yours truly,

L.O.A.S.H

 


 © Elizabeth Anne Villoria 

 

What is eBay?

Quote of awesomeness: “Creating a life that reflects your values and satisfies your soul is a rare achievement.” ~ Bill Watterson

In 1995, eBay was created by Pierre Omidyar in his living room as this idea went to him. In the beginning, this site was first called AuctionWeb. The main goal of the website created was for people to have the ability to post and sell on auctions. At first, when Omidyar launched his website, no one was going to his site because the link to his site wasn’t known to anyone else but himself. So then, he started creating ads which showed things about what his site could do. Omidyar created eBay “dedicated to bringing together buyers and sellers in an honest and open marketplace.”

Did you know that the first thing that was listed and sold was a broken laser pointer which was bought by Mark Fraser? Yeah. It was. And, one of the most amazing things that I found was that just in the second year of release (in 1996, around June), $7.2 million was the total value of the merchandise sold on AuctionWeb.  Then in October 1996, eBay got their first office in a small suite at 1025 Hamilton Avenue in San Jose, CA. At this time, Omidyar has had his first employee and has paired up with his longtime friend, Jeff Skoll making him the president, who he knew had an excellent skill at business.

A myth went around for a while that Omidyar created AuctionWeb (now eBay) to help his wife to sell Pez, but this was later found false. 

 It was in September 1997 when AuctionWeb was officially renamed into eBay!

Remember in Transformers when Sam Witwicky was trying to sell some of his great-great-grandfather’s stuff? That’s right! He did that on eBay. 

From 1995 to the present time, eBay has reached so many people everywhere and has even funded charities and helped nonprofit organizations. With eBay, it has been able to create this community where people trust each other more. Imagine how ideas could turn into something so much more and help so much more. This is exactly what eBay is, an amazing concept turned into reality. And, one thing that I believe we could really use here is: Trust.

Yours truly,

L.O.A.S.H

 


 © Elizabeth Anne Villoria