#100DaysOfCode - Day 4

Random & Lists

·

5 min read

This morning was a slower pace for me. Working with the random library and lists. I didn't want to dig too deep as the weekend was hard going and I ended if with pulling a muscle in my shoulder.

Today was handling two things, using a couple of methods from the random library and lists or more a list of lists.
The small projects that led up to the main project this morning were interesting and certainly gave me some time to look over a couple of libraries I had only used a little. I had used random before and seeded it to get consistent results but this time I went with the flow.
Heads or Tails
This is an excellent introduction to random, or more to the point random.randint. Using 0 and 1 and labelling one value 'heads' and the other 'tails'.

from random import randint

x = randint(0, 2)

if x == 1:
    print("Heads")
else:
    print("Tails")

Next up Bill payer
The game of chance that decides who is paying for everyone's meal at the table. Constructing a list of players from a single string, (I just created the string rather than play the game each time.) then pick out one name at random.
The random number is decided from the rang of zero to one less than the number of players. The chosen number is then used to select the item from the list of players that is at that ordinal.

# who_pays_the_bill.py

from random import randint
from os import system

def bill_payer():
    system("cls")
    # names_string = input("Give me everybody's names, separated by a comma. ")
    names_string = "Bill,Ben,John,Paul,Peter"
    names = names_string.split(",")  # Removed the space used in the splitter
    # Number of names in list
    length_of_names = len(names)

    print("All the names are:")
    for x in range(0, length_of_names):
        print(names[x])

    random_choice = randint(0, (length_of_names - 1))  # Remember the minus one here
    print(f"The bill payer this time is {names[random_choice]}")

if __name__ == "__main__":
    bill_payer()

Another variation on selecting an item from a list was in treasure map, and this was a choice from within a list of lists. The list of lists is used to generate a 3 by 3 square where the user inputs a value for the row and column for the 'treasure' to be buried and the console log shows the map with an 'x' at those co-ordinates. It was interesting as again you have to compensate for humans starting to count from 1 and computers start to count from 0.

def x_spot():
    system("cls")
    row1 = ["⬜️", "⬜️", "⬜️"]
    row2 = ["⬜️", "⬜️", "⬜️"]
    row3 = ["⬜️", "⬜️", "⬜️"]
    map = [row1, row2, row3]
    print(f"{row1}\n{row2}\n{row3}")
    print("Where do you want to put the treasure?")

    the_row = (
        int(input("Choose the row: \n1,2 or 3 \n")) - 1
    )  # Minus one saves using 0 - 2 as locations.
    the_column = (
        int(input("Choose the column \n1,2 or 3 \n")) - 1
    )  # Minus one saves using 0 - 2 as locations.
    system("cls")

    # X Marks the Spot
    map[the_row][the_column] = "X"

    print(f"{row1}\n{row2}\n{row3}")

if __name__ == "__main__":
    x_spot()

Rock, Paper, Scissors The major project of the day. To keep in line with using lists and a list of lists, an ascii art list was used to represent each of the options and all the options were placed into another list. Now it was a user v computer game, with the user choosing first. The lesson would simply state 1 is rock, 2 is paper...
I prefer to use the highlighted letter option, it is a little more work but I think it makes for a nicer experience. So I have to run two variables for each of the user options, but that is not a hardship for the size of this game. The first variable would hold the ascii art list and the second the position of said list in the list of lists. This does remove the need for the '-1' change as used in the previous small project. For the computer choice use of random.randint allows for random choice of a list from the list of lists holding rock, paper & scissors.
Now it is the turn of the if/elif/else statement to handle the various combination of choices from the user and the computer. Printing out the result.
Having the ascii art allows for a nice representation of the choices made, rather than just text, and a result.

from os import system
from random import randint


# images
rock = '''
    _______
---'   ____)
      (_______)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ______)
          ______)
          _______)
         ________)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ________)
       __________)
      (____)
---.__(___)
'''


# As this is a lists lessons, create a list with the above images

choices_list = [rock, paper, scissors]


system('cls')
user_selects = (input('Make your choice! \nI won\'t tell the PC \n(R)ock, (P)aper or (S)cissors \n')).lower()
if user_selects == 'r':
    user_selects = choices_list[0]
    user_value = 0
elif user_selects == 'p':
    user_selects = choices_list[1]
    user_value = 1
elif user_selects == 's':
    user_selects = choices_list[2]
    user_value = 2
else:
    user_value = 100
    print('That wasn\'t an option. \nYou Lose!\n')
    exit()


computer_value = randint(0,2)
computer_selects = choices_list[computer_value]

# Print out Images
system('cls')
print(f'User Selects')
print(user_selects)
print('Computer Selects')
print(computer_selects)

if user_value >= 3 or user_value < 0: 
    print("You typed an invalid entry, you lose!") 
elif user_value == 0 and computer_value == 2:
    print("You win!")
elif computer_value == 0 and user_value == 2:
    print("You lose")
elif computer_value > user_value:
    print("You lose")
elif user_value > computer_value:
    print("You win!")
elif computer_value == user_value:
    print("It's a draw")