External Exam Download Resources Web Applications Games Recycle Bin

Trader Game

simple functions.py

import random
#for colours only in IDLE:
#import sys
#colour = sys.stdout.shell

#global variables:
tradeprice = 0
stocks = 0
money = 10
hours = 12


def newTradePrice():
    global tradeprice
    tradeprice = random.randint(1,20)

def statusUpdate():
    global money, stocks, hours, tradeprice
    print("-------------------------")
    print("Your money: $" + str(money))
    print("Stocks owned:", stocks)
    print("Hours remaining:", hours)
    print("Current trade price: $" + str(tradeprice))
    print("-------------------------")
    
def getChoice():
    return input("""(B) for buy
(S) for sell
(W) for wait
-------------------------
Type letter of choice here: """).strip().upper()

def buyStocks():
    global stocks, tradeprice, money
    amount = int(input("How many stocks to buy: "))
    cost = amount * tradeprice
    if (cost <= money):
        money = money - cost
        stocks = stocks + amount
        outputText = "Bought " + str(amount) + " stocks, which cost $" + str(cost)
        print(outputText + ".\n") #colour.write(outputText + ".\n","COMMENT")
    else:
        print("Insufficient funds.\n") #colour.write("Insufficient funds.\n","BUILTIN")
    statusUpdate()

def sellStocks():
    global stocks, tradeprice, money
    amount = int(input("How many stocks to sell: "))
    if (amount <= stocks):
        profit = amount * tradeprice
        stocks = stocks - amount
        money = money + profit
        outputText = "Sold " + str(amount) + " stocks, and made $" + str(profit)
        print(outputText + ".\n") #colour.write(outputText + ".\n","STRING")
    else:
        print("You don't own that many stocks.\n") #colour.write("You don't own that many stocks.\n","BUILTIN")
    statusUpdate()

def waitHour():
    global hours
    hours -= 1
    print("An hour has passed.\n") #colour.write("An hour has passed.\n","BUILTIN")

play = True
while play:
    newTradePrice()
    statusUpdate()
    choice = getChoice()
    endTurn = False
    while not endTurn:
        if choice == "B":
            buyStocks()
            choice = getChoice()
        elif choice == "S":
            sellStocks()
            choice = getChoice()
        elif choice == "W":
            endTurn = True
        else:
            print("Invalid choice.\n") #colour.write("Invalid choice.\n","BUILTIN")
            choice = getChoice()
    waitHour()
    if hours < 1:
        outputText = "Final score: $" + str(money) 
        print(outputText + ".\n") #colour.write(outputText + ".\n","BUILTIN")
        play = False