def equip(x):
global bag_sword
global bag_chest
global bag_gloves
global bag_helmet
while x == "iron sword" and "iron sword" in bag:
if bag_sword:
print "You can't have 2 weapons equipped!"
x = ""
print "\nYou equip the iron sword.\n"
bag.remove("iron sword")
bag_sword.append("iron sword")
When I run this the first time, it works fine, but when I run it a second time nothing happens.
bag_sword is a list
test code:
bag.append("iron sword")
if input1[:5] == "equip":
print input1[:5]
equip(input1[6:])
print input1[6:]
I type into the console 'equip iron sword'
I've tried using a variable in place of the input[]
(It isn't syntax)
Here is how you can make the function work as described:
bag_sword = []
def equip(x):
global bag_sword
if x == "iron sword":
if "iron sword" in bag_sword:
print "You can't have 2 weapons equipped!"
else:
bag_sword.append("iron sword")
print bag_sword # Prints "[]".
equip("iron sword") # Prints nothing. Puts the string "iron sword" in bag_sword.
print bag_sword # Prints "['iron sword']".
equip("iron sword") # Prints "You can't have 2 weapons equipped!". bag_sword is unchanged.
You can make nwk's solution more general (also try to get rid of global variables):
def equip(item, bag):
if item in bag:
print "You can't have 2 {}s equipped!".format(item)
else:
bag.append(item)
def main():
bag_sword = []
print bag_sword
equip("iron sword", bag_sword)
print bag_sword
equip("iron sword", bag_sword)
if __name__ == '__main__':
main()
It also seems to me that a dictionary or class would be a better alternative than several bag lists:
def equip(item, slot, inventory):
if inventory[slot] == item:
print 'Already equipped.'
else:
inventory[slot] = item
print item.capitalize(), 'equipped.'
def main():
inventory = {
'weapon': None,
'gloves': None,
}
equip('iron sword', 'weapon', inventory)
print inventory
equip('iron sword', 'weapon', inventory)
if __name__ == '__main__':
main()
Related
What i am trying to do is write my first program on my own. i don't want the answer but just some guidance its been two days and i haven't made any real progress. I'm a newbie so go easy on me.
Four co-workers carpool to work each day. A driver is selected randomly for the drive to work and again randomly for the drive home. Each of the drivers has a lead foot, and each has a chance of being ticketed for speeding. Driver A has a 10 percent chance of getting a ticket each time he drives, Driver B a 15 percent chance, Driver C a 20 percent chance, and Driver D a 25 percent chance. The state will immediately revoke the license of a driver after his or her third ticket, and a driver will stop driving in the carpool once his license is revoked. Since there is only one police officer on the carpool route, a maximum of one ticket will be issued per morning and a max of one per evening
import random
day_counter = 0
alan_tickets = 0
betty_tickets = 0
charles_tickets = 0
diana_tickets = 0
drivers = ["Alan", "Betty", "Charles", "Diana"]
#def head_to_work(): is the driver selection process when heading to work.
def head_to_work():
if random.choice(drivers) == "Alan":
print "Alan it's your turn."
global alan_tickets
if alan_tickets == 3:
print "i cant"
head_to_work()
else:
return alan_drives_tw()
elif random.choice(drivers) == "Betty":
print "Betty it's your turn."
global betty_tickets
if betty_tickets == 3:
print "nope"
head_to_work()
else:
return betty_drives_tw()
elif random.choice(drivers) == "Charles":
print "Charles it's your turn."
global charles_tickets
if charles_tickets == 3:
print "no way"
head_to_work()
else:
return charles_drives_tw()
elif random.choice(drivers) == "Diana":
print "Diana it's your turn."
global diana_tickets
if diana_tickets == 3:
print "sorry guys"
head_to_work()
else:
return diana_drives_tw()
else:
print "All drivers have their Licenses suspended."
print "Take the Bus."
# driver alan is heading to work he has a 10% chance of getting a ticket
def alan_drives_tw():
global alan_tickets
print "Yo i'm driving"
print "..."
print "Now driving"
print "..."
print "your getting pulled over"
if random.random <= 0.10:
print "your getting a ticket"
alan_tickets += 1
print "i got a ticket, but we have arrived at work"
head_home()
else:
print "just a warning today"
print "we have arrived at work"
head_home()
# driver betty is heading to work she has a 15% chance of getting a ticket
def betty_drives_tw():
global betty_tickets
print "Hi i'll drive"
print "..."
print "we outta here"
print "your getting pulled over"
if random.random() <= 0.15:
print "your getting a ticket"
betty_tickets += 1
print "i got a ticket but, made it to work"
head_home()
else:
print "just a warning today"
print "made it to work"
head_home()
#driver charles is heading to work he has a 20% chance of getting a ticket
def charles_drives_tw():
global charles_tickets
print "I'll take the wheel"
print "..."
print "lets roll out"
print "your getting pulled over"
if random.random() <= 0.20:
print "your getting a ticket"
charles_tickets += 1
print "i got a ticket but, made it to work"
head_home()
else:
print "just a warning today"
print "made it to work"
head_home()
#driver charles is heading to work she has a 25% chance of getting a ticket
def diana_drives_tw():
global diana_tickets
print "I got it today"
print "..."
print "whippin it"
print "your getting pulled over"
if random.random() <= 0.25:
print "its ticket time"
diana_tickets += 1
print "i got a ticket but, were here at work"
else:
print "just a warning today"
print "were here at work"
return head_home()
#def head_home(): is the driver selection process when heading home
def head_home():
if random.choice(drivers) == "Alan":
print "Alan it's your turn"
global alan_tickets
if alan_tickets == 3:
print "i cant"
return head_home()
else:
return alan_drives_h()
elif random.choice(drivers) == "Betty":
print "Betty it's your turn"
global betty_tickets
if betty_tickets == 3:
print "nope"
return head_home()
else:
return betty_drives_h()
elif random.choice(drivers) == "Charles":
print "Charles it's your turn"
global charles_tickets
if charles_tickets == 3:
print "no way"
return head_home()
else:
return charles_drives_h()
elif random.choice(drivers) == "Diana":
print "Diana it's your turn"
global diana_tickets
if diana_tickets == 3:
print "sorry guys"
return head_home()
else:
return diana_drives_h()
else:
print "Drivers are not eligible to drive"
# driver alan is heading to work he has a 10% chance of getting a ticket
def alan_drives_h():
global alan_tickets
global day_counter
print "Yo i'm driving"
print "..."
print "Now driving"
print "your getting pulled over"
if random.random <= 0.10:
print "your getting a ticket"
alan_tickets += 1
else:
print "just a warning today"
print "were home"
day_counter += 1
head_to_work()
# driver betty is heading to work she has a 15% chance of getting a ticket
def betty_drives_h():
global betty_tickets
global day_counter
print "Hi i'll drive"
print "..."
print "we outta here"
print "your getting pulled over"
if random.random() <= 0.15:
print "your getting a ticket"
betty_tickets += 1
else:
print "just a warning today"
print "made it home"
day_counter += 1
head_to_work()
# driver charles is heading to work he has a 20% chance of getting a ticket
def charles_drives_h():
global charles_tickets
global day_counter
print "I'll take the wheel"
print "..."
print "lets roll out"
print "your getting pulled over"
if random.random() <= 0.20:
print "your getting a ticket"
charles_tickets += 1
else:
print "just a warning today"
print "made it home guys"
day_counter += 1
head_to_work()
# driver diana is heading to work she has a 25% chance of getting a ticket
def diana_drives_h():
global diana_tickets
global day_counter
print "I got it today"
print "..."
print "whippin it"
print "your getting pulled over"
if random.random() <= 0.25:
print "its ticket time"
else:
print "just a warning today"
print "were home everyone"
day_counter += 1
head_to_work()
print head_to_work()
print "Alan %d tikets." % (alan_tickets)
print "Betty %d tickets." % (betty_tickets)
print "Charles %d tickets." % (charles_tickets)
print "Diana %d tickets." % (diana_tickets)
print "%d days has passed." % (day_counter)
there are several problems that i come across.
get the code to keep running till everyone has 3 tickets
sometimes it stops after 1,2,3, or 4 days max and i have no idea why
thanks in advance remember no answers just clues and guidance
When you are selecting a random item from a list, and comparing it to multiple values, you should only make a random selection once.
if random.choice(drivers) == "Alan":
...
elif random.choice(drivers) == "Betty":
This selects a random driver and compares it to 'Alan'. If it IS Alan, the if block runs correctly. If it fails, it now calls the random.choice function again, and selects a NEW random driver to compare to 'Betty'. But, that random driver could be Alan (or anyone).
You want something more like this:
driver = random.choice(drivers)
if driver == 'Alan':
...
elif driver == 'Betty':
...
Some other quick thoughts:
Print statements are a good way to debug a program - but that's virtually impossible with as much print spam as you have. Comment most of that out until the program works - and add print statements to show you what variables are at different times.
You have several typos such as random.random instead of random.random() and functions where you forget to update counters. This is due primarily to having so many very similar functions. As you keep writing programs, you're going to want to learn how to make a single function that can handle any of the four drivers for a single trip. It will be easier to program, and reduce some of the typo errors.
You have a fundamental flaw in your code. In your head_to_work function random.choice(drivers) is present in each of if elif clause that is where unpredictability lies. You should improve upon by like this.
drivers = ["Alan", "Betty", "Charles", "Diana"]
available_drivers=drivers[:]
def head_to_work():
if available_drivers:
selected_driver=random.choice(available_drivers)
else:
selected_driver= None
if selected_driver == "Alan":
print "Alan it's your turn."
global alan_tickets
if alan_tickets == 3:
available_drivers.remove("Alan")
print "i cant"
head_to_work()
else:
return alan_drives_tw()
#Similiarly for the other three.
else:
print "All drivers have their Licenses suspended."
print "Take the Bus."
What we did here is removed the unnecessary random choices. Solved the unpredictability. Also maintaining a avaliable_drivers list helps in finding the non-ticketed drivers which is the essential condition for the else clause in head_to_work function to work.Since when all drivers get ticketed random.choice will get an empty list. And this will work until all the drivers will get ticketed.
I'm new to coding, especially in python. I started learning python using codeacademy about 1 day ago and I have progressed quickly. After reaching the end of the battleship unit, it challenged me to challenge myself by seeing what I can do. So, I set out to make the game two-player. However, after finishing the program, it tells me that the column variable on the second player's ship is not defined. Why?
Here is the code:
board1 = []
board2 = []
for i in range(5):
board1.append(["O"] * 5)
board2.append(["O"] * 5)
# Creates 2 boards, one for each player to view
def printboard(board):
for row in board:
print " ".join(row)
# Prints one of the boards, depending on which player is meant to see it
def boardset1():
print "Player 1, set your coordinates!"
ship_col1 = int(raw_input("X:"))
ship_row1 = int(raw_input("Y:"))
if ship_col1 not in range(1,6) or ship_row1 not in range(1,6):
print "Invalid coordinates!"
boardset1()
else:
ship_col1 = abs(ship_col1 - 5)
ship_row1 = abs(ship_row1 - 5)
for i in range(10):
print ""
print "Coordinates set!"
def boardset2():
print "Player 2, set your coordinates!"
ship_col2 = int(raw_input("X:"))
ship_row2 = int(raw_input("Y:"))
if ship_col2 not in range(1,6) or ship_row2 not in range(1,6): #< Issue is here, I think
print "Invalid coordinates!"
boardset2()
else:
ship_col2 = abs(ship_col2 - 5) #< Might be here
ship_row2 = abs(ship_row2 - 5)
for i in range(10):
print ""
print "Coordinates set!"
# 2 above functions set coordinates based on player input
def play1():
printboard(board1)
print "Player 1: Where is the opponent's ship?"
guess_col1 = int(raw_input("X:"))
guess_row1 = int(raw_input("X:"))
if guess_col1 not in range(1,6) or guess_row1 not in range(1,6):
print "Invalid coordinates!"
play1()
else:
guess_col1 = abs(guess_col1 - 5)
guess_row1 = abs(guess_row1 - 5)
if board1[guess_col1][guess_row1] == "X":
print "You already guessed here!"
play1()
elif guess_col1 == ship_col2 and guess_row1 == ship_row2:
win = True
print "You have won!"
else:
board1[guess_col1][guess_row1] = "X"
print "You have missed!"
def play2():
if win == False:
printboard(board2)
print "Player 2: Where is the opponent's ship?"
guess_col2 = int(raw_input("X:"))
guess_row2 = int(raw_input("X:"))
if guess_col2 not in range(1,6) or guess_row2 not in range(1,6):
print "Invalid coordinates!"
play2()
else:
guess_col2 = abs(guess_col2 - 5)
guess_row2 = abs(guess_row2 - 5)
if board2[guess_col2][guess_row2] == "X":
print "You already guessed here!"
play2()
elif guess_col2 == ship_col1 and guess_row2 == ship_row1:
win = True
print "You have won!"
else:
board2[guess_col2][guess_row2] = "X"
print "You have missed!"
# Play functions are for gameplay
win = False
boardset1()
boardset2()
for i in range(25):
if win == False:
play1()
play2()
else:
break
Immediately after player 1 makes a guess, this error occurs:
Traceback (most recent call last):
File "python", line 97, in <module>
File "python", line 59, in play1
NameError: global name 'ship_col2' is not defined
Any advice or solution is welcome. The more detailed, the better, as I am still learning.
Thanks!
Your problem is that the variable ship_col2 is defined within a function. That means that it only exists until that function is done running, and then it is deleted. In order to make it available outside that function and in other functions, you must declare it as a global variable, which you can do by defining it with a default value under board1 and board2 at the top of the file. You must define all variables that you want to use in multiple functions like that.
Here is some further reading that might help you understand better: http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html
I'm really stuck on this simple user input game I created. It's an exercise from learn python the hard way. I've been trying for over a week to figure it out on my own and finally caved in to asking for help. I think the problem point in my code is the Engine() class. Anyway here's the code:
from sys import exit
from random import randint
class Island(object):
def enter(self):
pass
class Engine(object):
def __init__(self, island_map):
self.island_map = island_map
def play(self):
current_island = island_map.opening_island()
last_island = self.island_map.next_island('Tropical')
while current_island != last_island:
next_island_name = current_island.enter()
current_island = self.island_map.next_island(next_island_name)
current_island.enter()
class Loser(Island):
snippets = ["Welcome to loser Island",
"Can't win them all",
"There's always next time"]
def enter(self):
print "Game over"
print Loser.snippets[randint(0,len(self.snippets)-1)]
exit(1)
class Jungle(Island):
def enter(self):
print "Welcome to the Jungle!"
print "You must fight the monkey to pass!"
print "Choose your weapon..."
weapons = ['stick', 'fly swatter', 'banana']
print weapons
fighter_weapon = raw_input("Choose from a a weapon above...")
if fighter_weapon == 'stick':
print "Stick can't beat a monkey!"
print "Monkey wins"
return 'Loser'
elif fighter_weapon == 'fly swatter':
print "The monkey steals your fly swatter"
print "Monkey wins"
return 'Loser'
elif fighter_weapon == 'banana':
print "The monkey is hypnotized by the banana"
print "You continue to the next island..."
return 'Frozen'
else:
print "What? Doesn't make sense"
return 'Jungle'
class Frozen(Island):
#add green, blue circle, and black diamond
def enter(self):
print "This is snow land"
print "Here's your snowboard, choose your path"
print "([[[[[[[[[)"
runs = ["green", "blue", "black"]
print runs
run_choice = raw_input(" >")
if run_choice == 'green':
print "Easy way out?"
print "No good"
print "Wrong"
return 'Loser'
elif run_choice == 'blue':
print "okay, at least not the easiest way"
print "You have some guts, I'll let you choose one more time"
return 'Frozen'
elif run_choice == 'black':
print "I like your style"
print "Going for the hard choice shows courage"
print "Continue to the next island"
return 'Tropical'
else:
print "Say whaaat?!"
return 'Frozen'
class Tropical(Island):
def enter(self):
print "You made it to the final Island!"
print "Look here's the treasure chest!"
print " All that's left to do is guess the code on the chest"
print "Be smart, you only get five guesses..."
t_key = "1234"
chest_guess = raw_input("What do you think it is?")
guesses = 0
while chest_guess != t_key and guesses < 4:
print "Guess again"
guesses += 1
chest_guess = raw_input(" ?")
if chest_guess == t_key:
print "You guessed right!"
print "You won"
else:
print "Sorry"
return 'Loser'
class Map(object):
islands = {
'Loser': Loser(),
'Jungle': Jungle(),
'Frozen': Frozen(),
'Tropical': Tropical(),
}
def __init__(self, start_island):
self.start_island = start_island
def next_island(self, island):
val = Map.islands.get(island)
return val
def opening_island(self):
return self.next_island(self.start_island)
mj_map = Map('Jungle')
mj_game = Engine(mj_map)
mj_game.play()
Right now I'm stuck on an error that states "island_map" is not defined in my Engine class. Which I don't understand because to me it looks like it is defined. Any input would be appreciated.
def play(self):
current_island = island_map.opening_island()
needs to be changed to
def play(self):
current_island = self.island_map.opening_island()
as it is apart of that instance
Ok I going through LPTHW and writing a game. We are supposed to section the game up into different scripts to see how importing them works. I have 4 scripts: ex45.py executes the main code, Engine45.py is the engine, Locations45.py is the list of locations, and Maps45.py is what holds the map values and moves through locations.
The error I get when running is:
Traceback (most recent call last):
File "ex45.py", line 2, in
import Maps45
File "C:\Users\Raistlin\Python\Maps45.py", line 1, in
import Locations45
File "C:\Users\Raistlin\Python\Locations45.py", line 4, in
class Map(object):
File "C:\Users\Raistlin\Python\Locations45.py", line 6, in Map
'Gold_gym' : Gold_gym(),
NameError: name 'Gold_gym' is not defined
I don't understand why I am getting a Gold_gym is not defined when it is defined in Locations45.py.
Code blocks below:
ex45.py
import Engine45
import Maps45
import Locations45
a_map = Map('Gold_gym')
a_game = Engine(a_map)
a_game.run()
Engine45.py
class Engine(object):
def __init__(self, location_map):
print "Engine __init__ has location_map", location_map
self.location_map = location_map
def run(self):
current_location = self.location_map.opening_location()
print "Play's first scene", current_location
while True:
print "\n"('-' * 20)
next_location_name = current_location.use()
print "next location", next_location_name
current_location = self.location_map.next_location(next_location_name)
print "map returns new location", current_location
Locations45.py
from random import randint
from sys import exit
class Location(object):
def use(self):
print "This is not configured."
exit(1)
class Loser_gym(Location):
quips = [
'You are worthless, goodbye.'
'Thanks for trying noob.'
'Sex and candy, not today.'
]
def use(self):
print Loser_gym.quips[randint(0, len(self.quips)-1)]
exit(1)
class Gold_gym(Location):
def use(self):
print "Welcome to the Gold Gym. This gym will test your physical prowess."
print "Before you there is a large pool of water with a center platform."
print "On your person is a satchel, a whip, a hat, and a gun."
print "Your goal is to find the way out of the gym."
print "Acceptable inputs are satchel, whip, hat, or gun."
print "Good Luck."
action = raw_input("What do you do:> ")
if action == 'satchel':
print "You throw your satchel towards the center platform."
print "It does absolutely nothing. Try again."
return 'Gold_gym'
elif action == 'whip':
print "You use your whip somewhat akin to Indiana Jones."
print "You swing from a pipe and land squarely on the center platform."
print "You have survived this turmoil."
return 'Sapphire_gym'
elif action == 'hat':
print "You valiantly toss your hat toward the center platform."
print "Your hat is caught by a gust of wind and blows away."
print "You cannot survive without your hat."
return 'Loser_gym'
elif action == 'gun':
print "You shoot your about wildly in the air."
print "A ricochet hits you in the head and you die."
return 'Loser_gym'
else:
print "DOES NOT COMPUTE, TRY AGAIN."
return 'Gold_gym'
class Sapphire_gym(Location):
def use(self):
print "Welcome to the Sapphire gym, here your cognitive ability will be tested."
print "Just kidding there is no way to figure this out consistently."
print "Before you stands a door, the door has a small keypad on it."
print "Below the keypad is what appears to be a smart card reader."
print "On your way to the location you picked up two smartcards off the ground."
print "One is red and one is green."
print "Clearly you will need to use a smartcard and guess a code(3-digits)."
card = raw_input('Which card do you choose:> ')
if card == 'red':
print "A laser beam comes out of the door and cauterizes your brain."
return 'Loser_gym'
elif card == 'green':
code = '%d%d%d' % (randint(0,9), randint(0,9), randint(0,9))
guess = raw_input('What code do you enter:> ')
guesses = 0
while guess != code and guesses < 20 and guess != '123':
print "INCORRECT!"
guesses += 1
guess = raw_input('What code do you enter:> ')
if guess == code or guess == '123':
print "Nice guess noob! You may press onward."
return 'Cerulean_gym'
else:
print "WRONG! TOO MANY GUESSES! DIE INFERIOR BEING!"
return 'Loser_gym'
class Cerulean_gym(Location):
def use(self):
print "Welcome to the final gym, the Cerulean Gym!"
print "Before you is a 3x3 platform, your job is to cross the platform."
print "Be warned that each tile can trigger a trap."
print "Good luck!"
correct_square = ['3', '1', '2']
jump = raw_input("Square 1, 2, or 3?:> ")
jumps = 0
while jumps < 3:
if jump == correct_square:
print "Nice job! You picked the correct square!"
jump += 1
correct_square = correct_square[0+jump]
jump = raw_input("Square 1, 2, or 3?:> ")
jumps += 1
else:
print "YOU FAIL! Goodbye you puny infidel."
return 'Loser_gym'
print 'NICE JOB. YOU WIN ALL THE BASE!'
Maps45.py
import Locations45
class Map(object):
locations = {
'Gold_gym' : Gold_gym(),
'Sapphire_gym' : Sapphire_gym(),
'Cerulean_gym' : Cerulean_gym(),
'Loser_gym' : Loser_gym()
}
def __init__(self, start_location):
self.start_location = start_location
print "start_location in __init__", self.start_location
def next_location(self, location_name):
print "start_location in next_location"
val = Map.locations.get(location_name)
print "next_location returns", val
return val
def opening_location(self):
return self.next_location(self.start_location)
Help please?
When you:
import Locations45
that module is imported under the namespace Locations45
So when you call
Gold_gym()
It looks in Maps45 for that object, never knowing to look in Locations45.
Change the line to read:
locations = {
'Gold_gym' : Locations45.Gold_gym(),
'Sapphire_gym' : Locations45.Sapphire_gym(),
'Cerulean_gym' : Locations45.Cerulean_gym(),
'Loser_gym' : Locations45.Loser_gym()
If you just do import Locations45, it doesn't import each of the names - instead, it imports it as a group. You can refer to individual things within the group using a period:
'Gold_gym': Locations45.Gold_gym(),
'Sapphire_gym': Locations45.Sapphire_gym(),
'Cerulean_gym': Locations45.Cerulean_gym(),
'Loser_gym': Locations45.Loser_gym()
Alternatively, you could import all of the names specifically:
from Locations45 import Gold_gym, Sapphire_gym, Cerulean_gym, Loser_gym
which would make those names available without needing to use the prefix.
Here's the current code for my Black Jack game:
import random
def showMenu():
userInput = raw_input("Welcome to the game of Black Jack! Please choose an option from the following: \n - Start Game \n - Rules \n - Exit")
if userInput == "Start Game":
return maingame()
def maingame():
done = False
return cardGenerator()
print "{0:>4} {01:>18} {02:>20} {03:>18}".format("Player Money", (cards[0], cards[1]), "CPU Cards", "CPU Money")
def getInitialMoney():
initialdough = 5000
def cardGenerator():
#Assign a random suit
suit_card = ["Hearts", "Spades", "Clubs", "Diamond"]
from random import choice
#Assign a random number between 1-13 (Ace to King)
number_card = random.randrange(1,14)
cards = choice(suit_card), (number_card)
def getDecision():
getDecision = raw_input("What will you do? \n - Hit \n - Stand")
if getDecision == "Hit":
return hit()
elif getDecision == "Stand":
return stand()
def hit():
return cardGenerator()
def stand():
return opponentphase()
def raise_bet():
raise_amount = input("How much will you bet?")
total_pot = 0 + raise_amount
def main():
maingame()
main()
The problem is in maingame(). is return cardGenerator effectively calling the function? Not sure why I can't index a value from a list in the string formatting, when I run as of now it doesn't return anything.
Sorry if things are unclear, I'm really bad at articulating what I'm trying to explain
In the method maingame(), you are returning the result of cardGenerator()(which is None because it is not returning anything), so your method maingame() never reaches the print statement. I think you could do these modifications:
def maingame():
done = False
cards = cardGenerator()
print "{0:>4} {01:>18} {02:>20} {03:>18}".format("Player Money", (cards[0], cards[1]), "CPU Cards", "CPU Money")
and return cards in cardGenerator(), so you can use it in maingame()
def cardGenerator():
#Assign a random suit
suit_card = ["Hearts", "Spades", "Clubs", "Diamond"]
from random import choice
#Assign a random number between 1-13 (Ace to King)
number_card = random.randrange(1, 14)
cards = choice(suit_card), (number_card)
return cards
Note that you have never declared opponentphase() method (at least it is not in the code you posted).