Friday, January 22, 2021

Python - Project - Higher or Lower game (Day 14)

This is a 100 Days challenge to learn a new language (Python). 100 Days of Code - The Complete Python Pro Bootcamp 

I will post some notes to motivate myself to finish this challenge.


Higher or Lower Game



Build a simple higher or lower game such as Reference.

    * Pick up accounts randomly
    * Format the account information
    * Ask user for a guess
    * Once user guess correctly, make account position b (compare B) 
       become position a (Compare A) on next game
    * Score keeping

Ex: 
game_data.py

data = [
    {
        'name': 'Instagram',
        'follower_count': 346,
        'description': 'Social media platform',
        'country': 'United States'
    },
...
]


main.py
import random
from game_data import data


def getAccountInfo(account):
    return account["name"] + ", " + account["description"] + ", " +
account["country"]


def getRandomAccount():
    return random.choice(data)


def setupAccountB(compare):
    compare["B"] = getRandomAccount()
    while compare["B"] == compare["A"]:
        compare["B"] = getRandomAccount()

    return compare


def game():
    score = 0

    # Init Compare Dictionary
    compare = {
        "A": getRandomAccount(),
    }

    game_end = False

    while not game_end:
        # Update compare dictionary by randomly picking company B
# from accounts
        compare = setupAccountB(compare)

        print(f"Compare A: { getAccountInfo(compare['A'])}")
        print("V.S.")
        print(f"Compare B: { getAccountInfo(compare['B'])}")

        # Ask user input
        guess = input("Who has more followers? Type 'A' or 'B': ")

        # Right Guess
        if (
            guess == "A"
            and compare["A"]["follower_count"] >
compare["B"]["follower_count"]
        ) or (
            guess == "B"
            and compare["B"]["follower_count"] >
compare["A"]["follower_count"]
        ):
            score += 1
            print(f"You're right! Current score: { score }.\n")

            # This is an requirement to make B to be a Compare A on
# next run
            compare["A"] = compare["B"]

            continue

        # Wrong Guess, and then terminate this game
        game_end = True

    print(f"Sorry, that's wrong. Final score: { score}")


game()


No comments:

Post a Comment