Day 3 assignment – Apostrophe’s

Today’s exercise is a simple text based adventure. Dr Angela Yu of the Udemy Course 100 Days of Code: The Complete Python Pro Bootcamp for 2022 provided the basic framework. I just need to copy the text, embellish it a bit, and add in the flow control to navigate through the game, resulting in a dead player, or escape the labyrinth. There are no hints on how to navigate the game to win, you need to read the code, or look at the example below.

What is the difference between ‘ and ’ one is an ascii single quote that is used by code to indicate encapsulated text is a string, and the second one is punctuation. It is common to use the single quote. The evil Dr Yu provide the ascii single quote throughout the examples provided. I fortunately have played this game of mismatched single quotes before and converted them first thing.

At this rate I might get through 100 days of code in a couple years, but I’m not in a hurry, and I like the slower pace. I’m also working on blogging. Having something to write everyday is a nice way to practice blog writing.

print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.") 

#https://www.draw.io/?lightbox=1&highlight=0000ff&edit=_blank&layers=1&nav=1&title=Treasure%20Island%20Conditional.drawio#Uhttps%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1oDe4ehjWZipYRsVfeAx2HyB7LCQ8_Fvi%26export%3Ddownload

#Write your code below this line 👇
user_input = ""
print('You’re at a crossroad. Where do you want to go?' )
while user_input.lower() != "left":
  user_input = input('Type "left" or "right"')
  if (user_input.lower() == "right"):
    print("You hear a painful cry like a little fluffy cute animal calling out for help, you jump into actual and run to the right, but you should look where you are going because you fell into a deep hole and died dead.")

print('You’re come to a lake. There is an island in the middle of the lake.')
while user_input.lower() != "wait":
  user_input = input('Type "wait" to wait for a boat. Type "swim" to swim across.')
  if (user_input.lower() == 'swim'):
    print("You drowned, and now you're dead")
  

print("You arrive at the island unharmed. There is a house with 3 doors. One red, one yellow and one blue.")
while user_input.lower() != 'yellow': 
  user_input = input('Which colour do you choose?')
  if user_input.lower() == 'red':
    print("It’s a room full of fire. Game Over.")
  elif user_input.lower() == "yellow":    
    print("You found the treasure! You Win!")
  elif user_input.lower() == "blue":
    print("You get attacked by an angry trout. Game Over.")
  else:
    print("You chose a door that doesn’t exist. Game Over.")

This is a successful run through looks like:

Welcome to Treasure Island.
Your mission is to find the treasure.
You’re at a crossroad. Where do you want to go?
Type "left" or "right"left
You’re come to a lake. There is an island in the middle of the lake.
Type "wait" to wait for a boat. Type "swim" to swim across.wait
You arrive at the island unharmed. There is a house with 3 doors. One red, one yellow and one blue.
Which colour do you choose?yellow
You found the treasure! You Win!

This is what happens when you enter incorrect directions:

Welcome to Treasure Island.
Your mission is to find the treasure.
You’re at a crossroad. Where do you want to go?
Type "left" or "right" tom
Type "left" or "right" ;et
Type "left" or "right" lft
Type "left" or "right" left
You’re come to a lake. There is an island in the middle of the lake.
Type "wait" to wait for a boat. Type "swim" to swim across. swm
Type "wait" to wait for a boat. Type "swim" to swim across. swam
Type "wait" to wait for a boat. Type "swim" to swim across. sum
Type "wait" to wait for a boat. Type "swim" to swim across. swim
You drowned, and now you're dead
>

When life gets fast… slow it down

Yeah, I’m dragging my butt through the #100daysofcode program. A warning signal is going off in my head, this is not how you create a new habit. But also, you should not kill yourself to force a new habit. You need it to be easy, otherwise if it becomes hard then you hit resistance, and resistance is a brutal killer of new habits. So if you need to take an extra day to continue on your habit that is okay, but be sure to do the minimum you can everyday. Lets look at what I’ve been working on over the last weekend.

Day 3 – Leap Year

Write a program that works out whether if a given year is a leap year. A normal year has 365 days, leap years have 366, with an extra day in February.

Dr Angela Yu. 100 Days of Code: The Complete Python Pro Bootcamp for 2022

I spent extra time to document the process of figuring this out. When the code gets topsy turvy like this I like to write it out in english, it helps tease out the flaws in my logic. I made Several bugs writing this, like not setting the flag false if it is not divisible by 4. I removed an extra if statement and moved the assumption statement to be prominent at the top.

The last line 25 is a bit of trick, rather than use if then else to print the statement I used the position in the array to print out the right statement. There are two results. False = 0 and True = 1. So I used the positions 0 and 1 in the Array to store the values. When I print the result I use the True/False variable to select which statement to use.

Day 3 – Pizza Shop

Another if else test. I didn’t use elif. I could have used elif for the pizza size, but didn’t feel it needed it to make it better.
What I like about code like this is I can simulate the process. And holy shit this is an epiphany! I should use this to document my processes at work! Let’s stay on task though, I’ll write about that next. Back to why I like this, the person who is taking an order needs to understand that additional pepperoni is a different charge for the size of pizza. So that logic needs to be trained to the new employee. But something like this is never mentioned during training. It’s always added when someone realizes the total is not right, then they go back and tell the new employee about the different rates of pepperoni charges.

I feel like coding is a way to document this better than with a flow chart. I find flow charts are cumbersome to illustrate.

# 🚨 Don't change the code below 👇
print("Welcome to Python Pizza Deliveries!")
size = input("What size pizza do you want? S, M, or L ")
add_pepperoni = input("Do you want pepperoni? Y or N ")
extra_cheese = input("Do you want extra cheese? Y or N ")
# 🚨 Don't change the code above 👆

#Write your code below this line 👇
price_small_pizza    = 15
price_medium_pizza   = 20
price_large_pizza    = 25
ad_pepperoni_small   = 2
ad_pepperoni_medplus = 3
ad_ex_cheese         = 1

total_price = 0
if size == 'S' or size == 's' :
    total_price += price_small_pizza
    if add_pepperoni == 'Y' :
        total_price += ad_pepperoni_small
if size == 'M' :
    total_price += price_medium_pizza
    if add_pepperoni == 'Y' :
        total_price += ad_pepperoni_medplus
if size == 'L' :
    total_price += price_large_pizza
    if add_pepperoni == 'Y' :
        total_price += ad_pepperoni_medplus
if extra_cheese == 'Y' :
    total_price += ad_ex_cheese

print(f'Your final bill is: ${total_price}.')

Code as documentation brain spill

I don’t like documentation to explain processes. The usual process is that I need to write documentation, then I share it around. People usually look it over but don’t take time to read it and process it. I end up having to verbally explain nuances in a meeting and people look at me weird, then agree it’s fine, and the documentation is never brought up again, until someone needs it. Then we may update it. The greater problem with this is it is not a suitable documentation method. If I wrote a simple javascript program in an HTML page then people could simulate the process.
I’m thinking the ticketing process for new laptops. I could create a text based adventure game for creating a new laptop request, and simulate it through to the end. I could write a simulator for the whole process. Cool!

So I tried to write a simple demo, but there is overhead of interacting with the end user. So I found a terminal emulator library here:
https://terminal.jcubic.pl/#demo
I’ll take a look at this to see if I can use it…

Day 3 Love Calculator

Another day IRL has passed. Meanwhile I’m still on day three of the python programming course. Aside from not feeling well, I enjoy taking the time to play with the code somewhat. For this lab I mixed up what I was supposed to be tallying. So I needed to add in some debug messages.

print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")

lower_names = [name1.lower(), name2.lower()]
test_words = ["true","love"]
match_res = []
total_score = 0
##### Test how many times each letter in the test word matches in a name
for aword in test_words:                           # Cycle through the test words
    letter_hits = 0                                # Reset the word hit counter
    for aname in lower_names:                      # Cycle through the names
        for wletter in aword:                      # Cycle through the letters of word
            countres = aname.count(wletter)        # Count instances of letter
            letter_hits += countres                # Add it to tally
            #print("{} finds {} of {}".format(aname,countres,wletter))  # Debug Print
    match_res.append(letter_hits)                  # Save count of the hits in names
    #print("{} tested with word {} result is {}".format(aname,aword,letter_hits))  # debug

#funky Love test rule combine the numbers as strings to makeup new number
match_score = int( str(match_res[0]) + str(match_res[1]) )

if match_score < 10 or match_score > 90:
    print("Your score is {}, you go together like coke and mentos.".format(match_score))
elif match_score < 50 and match_score > 40:
    print("Your score is {}, you are alright together.".format(match_score))
else:
    print("Your score is {}.".format(match_score))

Tanya and I score 54. I take it that is good, otherwise…

Welcome to the Love Calculator!
What is your name? 
Billy Baker
What is their name? 
Tanya Baker

Python basics in 100 days of code

At work a funny thing happens. I love working with computers, I think I’m a lucky guy. At work though I have so many distractions that I can’t get work done. For every distraction it drains my attention on what I’m doing, and when it exceeds a certain level then I’m not very useful.

When I go home and rest for a while, I’m drained, I don’t want to do much, it would be so easy to turn on the TV. Sometimes I go for a walk, but I’ll drag along, it’s been a long day and I just want to rest.

The funny thing that happens, is that I go sit at the computer and do something as simple as work on some basic Python challenges and I find it rejuvenating. I find following along a good course like Dr Angela Yu’s 100 projects in Python is a perfect blend of guided meditation and problem solving that it gets me out of that slump. Weird.

Here are my notes from the day:

Day 2 – Data Types

June 22, 2022 – Coding Rooms Exercises Day 2 (Lessons 1,2,3) Day 3 (1,2)
BMI-calculator.py

We played around with strings. Numbers as strings. Typecasting strings to integers or floats.

To declare a variable as a data type use:

varname = int(5)
But this will be overwritten when a new assignment
varname = input("New Value:")
Will change the data type back to a string, even if a number is entered.
So I need to validate the data type after an input.
varname = int(varname)

Formatting strings

I thought I would be able to use printf style formatting, there is a Python way using the .format() method and there is a printf method. Kinda weird either way.

age = input("What is your current age?")
age = int(age)
years_till_90 = 90 - age
age_in_months = years_till_90 * 12
age_in_weeks  = years_till_90 * 52
age_in_days   = years_till_90 * 365

These next lines produce the same result. The python way and the old printf way. The Python way is a bit more friendly for type conversion.

print('You have {} days, {} weeks, and {} months left.'.format(age_in_days, age_in_weeks, age_in_months))

print('You have %d days, %d weeks, and %d months left.' % (age_in_days, age_in_weeks, age_in_months))

print(f'You have {age_in_days} days, {age_in_weeks} weeks, and {age_in_months} months left.')  
// this one is the most readable and likely the new standard.  (Note the 'f' )

Operators

The standard operators apply: + – / * == != < <= >= >
Logic operators are words: and, or

maths

Standard operators built into python
rounding numbers round(23.2552, 2) will round two decimal places
modulo operator % 4 % 2 will result in 0. No remainder dividing 4 by 2. 5 % 2 will result 1
For more advanced commands like ceil, or floor, import the math module

Day 2 Assignment 3 – BMI Calculator 2

I struggled to pass the tests at first, due to my spelling of slightly vs slighty, and almost invisible difference in the code when you are looking for syntax differences.

Day 0 of 100 days of code

I’m looking for something to do when I’m tired after a long day of work. Usually I’m exhausted, and after making dinner for the family I struggle to do something productive. At work I need a language skill, and I really don’t want to rely on PowerShell.

When I’m looking to learn a new tech skill I like to check out courses on Udemy. Today I found 100 days of Python by Dr Angela Yu.

What I liked about this course is that I should be able to commit to 1 hour per day. The trick to developing a new habit is to make it easy on yourself. I can spend a little time while at work to look over the days material and think about how to solve the problems. After dinner I can give another 30 minutes to finish up the days work.

The first day I solved some python syntax puzzles for the print and input commands. Concatenating strings with the + operator. Type casting with int() and str() commands.

When I sat down this evening I didn’t think I could muster the energy. But listening to music and starting something new is the easy part. Doing a daily exercise is going to be tougher. To keep myself accountable, I’m posting to my WordPress blog. They recommend Twitter, but that is to much of a distraction. My sosh media game is at level zero, my blogging level is at least a 2. I will try with this course to interact with other 100 days of coders, but that is extra. First let’s get through a week of lessons.

WordPress Godot Web Game Plugin

Godot Game Engine is a free and open platform for making games. Some people use unity to make 3d and 2d games. Other people like me are learning Godot. Find out more at https://godotengine.org

I want to host games I create on my WordPress blog. I know I could add a static page and load the game that way, and it would be easier. I do want to eventually make an income from my games and having the game integrated into WordPress would allow for more control over who plays and how they play my games.

Why do I want control?
* to present the game with navigation buttons to browse the site
* observe who is playing the games
* receive feedback on games in the comments section
* protect my game assets
* create communication channel with players
* potentially make this plugin available to other indie game developers

I will make a demo available if/when I have one. For now this will be a space to record my progress.


Proudly powered by WordPress | Theme: Baskerville 2 by Anders Noren.

Up ↑