I am currently creating a blackjack game using Python3 on Sublime Text. When the dealers cards are drawn one by one, you can see it being drawn one by one in the console using the after() to call on different functions, but in the actual GUI all the cards are appearing at the same time, right at the end.
Here is a portion of the code:
def d_pick_a_card():
global d_hand
global card
global deck
global d_counter
global cvpath
global cardvalue
global d_card_relx
global cv
cardvalue = 0
card = deck.pop(0)
print('Drew',card)
if card == 'J':
cardvalue = 10
cvpath = 11
elif card == 'Q':
cardvalue = 10
cvpath = 12
elif card == 'K':
cardvalue = 10
cvpath = 13
elif card == 'A':
cardvalue = 11
cvpath = 14
else:
cardvalue = card
cvpath = card
d_hand.append(cardvalue)
random.shuffle(deck)
random.shuffle(deck)
d_counter += 1
#THIS IS THE FUNCTION THAT SHOWS THE VISUAL CARD ON THE GUI
def d_pick_vis(cardvalue, d_counter):
global dealers_turn
global card_frame
card_frame = tk.Label(top, image = cv[cvpath])
card_frame.place(relx= d_card_relx[d_counter], rely=.18, anchor='center')
widgetList.append(card_frame)
def dturnfunc():
global dealersturn_img
holding_img1.pack_forget()
dealersturn_img = tk.Label(top, image = dealersturn)
dealersturn_img.img = dealersturnpath
dealersturn_img.pack()
top.after(500, dealers_turn())
def dealers_turn():
global cardvalue
global d_counter
d_pick_a_card()
d_pick_vis(cardvalue, d_counter)
print("The Dealers hand is:", sum(d_hand))
print('\n')
if sum(d_hand) <= sum(hand):
print('Dealer picks again')
top.after(500,dealers_turn_2())
elif sum(d_hand) == 21:
print('Dealer Wins')
elif sum(d_hand) >= 22:
print('You win!')
else:
print('Dealer Wins')
You are calling the functions in your calls to after(), instead do this:
top.after(500, dealers_turn) # Note: just pass in the name of the function
...
top.after(500, dealers_turn_2)
You need to pass in a reference to the function and after() will call that function after the time elapses.
When you were calling the functions yourself, you pass in the return value, which is probably None which, I'm guessing, after() ignores.
Related
im a beginner programmer and im trying to make a simple blackjack game just for exercise in Python 3.10 using PyCharm CE but I wasn't able to solve a problem. The problem is my player_draw_card() function is not drawing a card. I wanted to put the whole code in case I miss something but I also highlighted the important parts (imo) with #'s.
import random
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] #extra 10's stands for J,Q,K and 11 is Ace
player_score = 0
computer_score = 0
player_cards = []
computer_cards = []
#############################################################
def player_draw_card():
index = random.randint(0, 12) # Selecting a random index from cards for player
player_cards.append(cards[index]) # Adding the selected 1 card to player_cards
#############################################################
def computer_draw_card():
index = random.randint(0, 12) # Selecting a random index from cards for computer
computer_cards.append(cards[index]) # Adding the selected 1 card to computer_cards
def calculate_player_score(): # Calculate player's score everytime it draws a card to prevent confusion when you have multiple Aces.
player_score = sum(player_cards)
if player_score > 21 and (11 in player_cards):
index_of_11 = player_cards.index(11)
player_cards[index_of_11] = 1
player_score = sum(player_cards)
def calculate_computer_score(): # Calculate computer's score everytime it draws a card to prevent confusion when you have multiple Aces.
computer_score = sum(computer_cards)
if computer_score > 21 and (11 in computer_cards):
index_of_11 = computer_cards.index(11)
computer_cards[index_of_11] = 1
computer_score = sum(computer_cards)
#####################################################################
def blackjack():
player_lost = False
player_score = 0
computer_score = 0
player_cards = []
computer_cards = []
player_draw_card() #################
player_draw_card() #################
######################################################################
#**Problem is not beyond here most likely, cause when I run it step by step**
#**player_draw_card() function didnt add anything.**
##########################################################################
print(f"Your cards: {player_cards}")
calculate_player_score()
#####################################
computer_draw_card()
print(f"Computer's first card: {computer_cards}")
#####################################
#**My computer_draw_card() is also not working btw but they build in same way so**
#**if we can fix the player_draw_card() function, we can fix the computer_draw_card() aswell**
#######################################
calculate_computer_score()
player_wants_more = True
while player_wants_more:
y_or_n = input("Type 'y' to get another card, type 'n' to pass:").lower()
if y_or_n == "n":
player_wants_more = False
if y_or_n == "y":
player_draw_card()
calculate_player_score()
if player_score > 21:
player_lost = True
player_wants_more = False
if player_lost == True:
print("You lost!\n")
restart = input("If you want to play again type 'y' if you want to finish the game type 'n'")
if restart == "y":
blackjack()
while computer_score < 17:
computer_draw_card()
calculate_computer_score()
if computer_score < player_score:
print("You win!\n")
elif player_score < computer_score:
print("You lose")
else:
print("It's a draw!")
y_or_n = input("Type 'y' if you want to play another game and 'n' if you dont.").lower()
if y_or_n == 'y':
blackjack()
else:
print("Bye")
blackjack() ############################### This is the only function that is called
########################################### Except the ones that are called in def's
I tried looking it step by step in pythontutor.com and it seems like """player_cards.append(cards[index]) # Adding the selected 1 card to player_cards""" line of code, doesn't add anything to player_cards
What seems strange to me though is, I tried a simpler version for drawing card with following.
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
player_cards = []
import random
def player_draw_card():
index = random.randint(0, 12) # Selecting a random index from cards for player
player_cards.append(cards[index])
player_draw_card()
print(player_cards)
And it works, it adds a random number to the player_cards. What is the problem someone please help me.
Thanks in advance
You are defining the player_cards list twice. Once it is defined on line 7, and then again inside the blackjack() method on line 41.
What happens is that you are creating two differently scoped variables player_cards. When you're calling the player_draw_card() from the blackjack() method, the player_draw_card() doesn't know about the player_cards in your blackjack() method. It looks up the name player_cards in its own scope, then in its parent scope, where it is defined.
You can solve this in two ways:
Remove the player_cards declaration inside your blackjack() method. This will make all the methods use the global list.
Add a parameter to player_draw_card(player_cards: list[int]) method and pass the list from your blackjack() method. In this case you won't need the global list anymore. IMO this is over-complication for this code example.
Note: You have the same issue with the compiter_cards list.
# Import Modules
from Dice import dice
d10 = dice(10,1)
d4 = dice(4,1)
# Assign Classes
class Player_Character:
def __init__(self, hp, maxhp, ac, THAC0, Surprise_Adjustment, Initiative_Adjustment):
self.hp = int(hp)
self.maxhp = int(maxhp)
self.ac = int(ac)
self.THAC0 = int(THAC0)
self.Surprise_Adjustment = int(Surprise_Adjustment)
self.Initiative_Adjustment = int(Initiative_Adjustment)
def attack(self, goblin):
Player_Character_Damage = d10.die_roll()
goblin.hp -= Player_Character_Damage
if (goblin.hp <= 0):
print("congratulations you killed the goblin")
def flee(self):
print("you run away ")
quit()
def heal(self, Player_Character):
Player_Character.hp += d10.die_roll()
if Player_Character.hp >= Player_Character.maxhp:
Player_Character.hp = Player_Character.maxhp
class goblin:
def __init__(self, hp, maxhp, ac, THAC0, Surprise_Adjustment, Initiative_Adjustment):
self.hp = int(hp)
self.maxhp = int(maxhp)
self.ac = int(ac)
self.THAC0 = int(THAC0)
self.Surprise_Adjustment = int(Surprise_Adjustment)
self.Initiative_Adjustment = int(Initiative_Adjustment)
def attack(self, Player_Character):
goblin_damage = d4.die_roll()
Player_Character.hp -= goblin_damage
if (Player_Character.hp <= 0):
print("oh dear you have died")
del Player_Character
MrHezy = Player_Character(10, 20, 10, 15, 0, 2)
def spawn_goblin(goblin):
G1 = goblin(5, 10, 8, 18, 0, 0)
return G1
goblin1 = spawn_goblin(goblin)
def battle(goblin1):
# user input
player_initiative_adjustment = MrHezy.Initiative_Adjustment
monster_initiative_adjustment = goblin1.Initiative_Adjustment
#define while loop for the battle
battle_not_over = 'yes'
while battle_not_over == 'yes':
#use random.randint(a,b) to generate player and monster base initiative
player_base_initiative = d10.die_roll()
monster_base_initiative = d10.die_roll()
#subtract the adjustment to get player and monster initiative
player_initiative = player_base_initiative - player_initiative_adjustment
monster_initiative = monster_base_initiative - monster_initiative_adjustment
#compare the initiatives and display the results
if (player_initiative < monster_initiative):
attack_flee_heal = input("congratulations you go first. Would you like to attack, flee, or heal?")
while attack_flee_heal != 'attack' or 'flee' or 'heal':
if attack_flee_heal == 'attack':
MrHezy.attack(goblin1)
elif attack_flee_heal == 'heal':
MrHezy.heal(MrHezy)
print("the goblin attacks")
goblin1.attack(MrHezy)
break
elif attack_flee_heal == 'flee':
MrHezy.flee()
break
else:
print("uhoh, the monsters go first, they attack!")
goblin1.attack(MrHezy)
attack_flee_heal = input("Would you like to attack, flee, or heal? ")
while attack_flee_heal != 'attack' or 'flee' or 'heal':
if attack_flee_heal == 'attack':
MrHezy.attack(goblin1)
elif attack_flee_heal == 'heal':
MrHezy.heal(MrHezy)
print("the goblin attacks")
goblin1.attack(MrHezy)
break
elif attack_flee_heal == 'flee':
MrHezy.flee()
break
#main game loop
while True:
spawn_goblin(goblin)
battle(goblin1)
This is a code for a battle simulator that ive been working on. it starts by importing a module that i made which consists of a class called 'dice' which I use for randomly generating numbers. Defining classes is next, with attributes including hp, maxhp, armor class, 'to hit armor class 0', surprise adjustment, and initiative adjustment, and methods including attack which allows you to attack the monsters, flee which exits the battle, and heal which gives your character more hit points. The program moves on to define the spawn_goblin() function which spawns a goblin (this works just fine for the first iteration of the loop). Then it moves on to the battle part which is pretty simple; all it does is check who goes first and then allows you to attack, or flee, or heal yourself. Please ignore the "heal" and "flee" methods, these are working just fine. The problem occurs when I attack the goblin. Instead of killing the goblin and spawning another it creates an infinite loop saying "congratulations you killed the goblin"
while (goblin.hp <= 0):
print("congratulations you killed the goblin")
I think this part of your code is wrong. The while should be if, since you only want to check if the goblin has died, and run some code once. Once the goblin's HP becomes lesser than or equal to 0, the print statement will loop forever since the expression goblin.hp <= 0 will always return True.
EDIT: Now where I think your code is wrong is here:
while attack_flee_heal != 'attack' or 'flee' or 'heal':
if attack_flee_heal == 'attack':
MrHezy.attack(goblin1)
elif attack_flee_heal == 'heal':
MrHezy.heal(MrHezy)
...
I think you have missed the break in the first if (if attack_flee_heal == 'attack'
Also, it would be more appropriate to use an if here rather than a while, since, as I mentioned above, you only want to check once.
So, I've been trying to write a Rock, paper and scissor game with tkinter to learn python. And I have made the GUI and the bot displays different moves after each the button click. However, the changing buttons don't affect the scoreboard. I need help writing the rules since I'm new at coding.
Please take a look at the code.
# pictures on buttons
photo1 = PhotoImage(file=r"E:\ROCK.png")
photoimage = photo1.subsample(9, 9)
photo2 = PhotoImage(file=r"E:\download.png")
photoimage1 = photo2.subsample(4, 4)
photo3 = PhotoImage(file=r"E:\SCISSOR.png")
photoimage2 = photo3.subsample(4, 4)
#bot's move
global list
global choice
list = [1, 2, 3, 1, 2, 3, 1, 2, 3]
choice = random.choice(list)
global move
global imgbot
global bmove
bmove = int(choice)
#function of buttons
#function of Rock
def click():
global move, imgbot, choice, i
i = 1
move = 1
if choice == 1:
imgbot = photoimage
if choice == 2:
imgbot = photoimage1
if choice == 3:
imgbot = photoimage2
if move == 1 or move == 2 or move == 3:
choice = random.choice(list)
botmove.config(image=imgbot)
#function of paper
def click1():
global move, imgbot, choice, i
i = 2
move = 2
if choice == 1:
imgbot = photoimage
if choice == 2:
imgbot = photoimage1
if choice == 3:
imgbot = photoimage2
if move == 1 or move == 2 or move == 3:
botmove.config(image=imgbot)
choice = random.choice(list)
#function of scissor
def click2():
global move, imgbot, choice, i
i = 3
move = 3
if choice == 1:
imgbot = photoimage
if choice == 2:
imgbot = photoimage1
if choice == 3:
imgbot = photoimage2
if move == 1 or move == 2 or move == 3:
botmove.config(image=imgbot)
choice = random.choice(list)
# components
#Score board
scorep = 0
scoreb = 0
Scoreboard = Label(window, text=str("BOT- ") + str(scoreb) + str(":") + str(scorep) + str(" -YOU "))
#other components
button2 = Button(window, text="Close Game", command=close, padx=20)
botmove = Button(window, padx=20, pady=20, image=photoimage3)
prock = Button(window, image=photoimage, command=click)
ppaper = Button(window, image=photoimage1, command=click1)
pscissor = Button(window, image=photoimage2, command=click2)
I want to be able to continuously update the score as they win or lose and display "WIN", "LOSE" or "DRAW", I can do the positioning myself. I defined move as an integer so that I could write "if move-bmove = something then display win, or lose or draw". There is a global variable "i" because I was playing around with other ways of doing this but they failed so you can ignore "i". I did not include the whole code, only the important bits and necessary context.
I hope you understand my problem. Thanks for your help.
See the comments inline
import random
alternatives = ('rock', 'paper', 'scissors')
# we can emulate a 3x3 table with a nested dictionary
# the first layer is the player choice, the second is the result according to the bot choice
rules = {
'rock': # if player chooses rock
{'rock': 'draw', 'paper': 'loose', 'scissors': 'win'}, # results according to bot choice
'paper': {'rock': 'win', 'paper': 'draw', 'scissors': 'loose'},
'scissors': {'rock': 'loose', 'paper': 'win', 'scissors': 'draw'}
}
# photos = { # whenever you have a collection objects of the same type (e.g. PhotoImage instances)
# # it is a good idea to make a dictionary so you can dinamically access each item
# key: PhotoImage(file=f'E:\\{key.upper()}.png')
# for key in alternatives
# # this is called a 'dictionary comprehension' or 'dict-comprehension'
# }
# later you can get each photo with
# photos[player_move] # returns the PhotoImage object
score = [0, 0] # player, bot
# then you can create a single function to update the score, regardless of the choice
# and call it when a player makes a move
def update_score(player_choice):
''' keep in mind
score: list of [player, bot] integer scores
player_choice: string with the player's choice, provided by the button click
'''
bot_choice = random.choice(alternatives)
# `score` and `result` are mutable objects
# therefore they are accessible in main and all its dependant namespaces
# i.e. we can inspect `rules` and modify `score`
# without calling `global` / `nonlocal` inside the function
result = rules[player_choice][bot_choice]
if result == 'win':
score[0] += 1
out = 'lucky dog!'
elif result == 'loose':
score[1] += 1
out = 'what a looser...'
else:
out = 'we live to fight another day'
# notice we already updated score, so we don't need a return line
print(bot_choice, player_choice, '::', out)
Test it with
for player_choice in random.choices(population=alternatives, weights=(1, 1, 1), k=20):
update_score(player_choice)
# score_text = f'BOT {str(score[1])} : {str(score[0])} YOU'
score_text = (
'BOT ' +
' : '.join( # takes a sequence of strings and joins them into a single string
list(map(str, score[::-1])) # iterates `score` backwards and applies string to each value
) +
' YOU'
)
print(score_text)
I have been using global variables for a little text game in python and have come across a lot of articles saying that global variables are a no no in python. I have been trying to understand how to get what I have below (just a health variable and being able to change it and print it) working using classes but I am confused how I can converted something like this in a class. Any help, example, point in the right direction would be great.
Here is an example of me using variables.
import sys
import time
health = 100
b = 1
def intro():
print("You will die after two moves")
def exittro():
time.sleep(1)
print("Thanks for playing!")
sys.exit()
def move():
global health
global b
health -= 50
if health <= 51 and b >0:
print("almost dead")
b = b - 1
def death():
if health == 0 or health <= 0:
print("...")
time.sleep(1)
print("You died\n")
time.sleep(2)
print("Dont worry, this game sucks anyway\n")
exittro()
intro()
a = 1
while a == 1:
input("Press Enter to move")
move()
death()
Thank you
Edit: this is the kind of thing I have been trying to do...
class Test:
def __init__(self):
number = 100
def __call__(self):
return number
def reduceNum(self):
number -=10
def printNum(self):
print(number)
a = 1
while a == 1:
input("Enter")
Test.self.reduceNum()
Test.self.printNum()
I would avoid classes for this, as classes are generally slower. You could make the function return the new value for the health variable.
I would also suggest making a main controller function to take the return value and apply it to other functions. This prevents global variables outside of a function's scope.
import time
def intro():
print("You will die after two moves")
def outro():
time.sleep(1)
print("Thanks for playing!")
# sys.exit() # You can avoid this now by just stopping the program normally
def move(health):
health -= 50
if health <= 51:
print("almost dead")
return health # Return the new health to be stored in a variable
def death(health):
if health <= 0:
print("...")
time.sleep(1)
print("You died\n")
time.sleep(2)
print("Dont worry, this game sucks anyway\n")
return True # Died
return False # Didn't die
def main():
health = 100 # You start with 100 health
intro()
while not death(health):
# While the death function doesn't return `True` (i.e., you didn't die) ...
input("Press enter to move")
health = move(health) # `health` is the new health value
outro()
If you want to use classes, you need to actually instantiate the class (Make a new object from it) by doing instance = Test(). You also need to store variables as attributes of self (so self.number = number) as any local variables are different from each other.
class Test:
def __init__(self):
self.number = 100
def __call__(self):
return self.number
def reduceNum(self):
self.number -= 10
def printNum(self):
print(self.number)
a = 1
game = Test()
while a == 1:
input("Enter")
game.reduceNum()
game.printNum()
# Or:
print(game())
# As you've changed `__call__` to return the number as well.
Well i've seen this error occur to others aswell but i can't figure out were my mistake is.
I get this:
Traceback (most recent call last):
File "C:\Users\Bill\Desktop\Finalizing_2.1(DEVELOPING).py", line 100, in <module>
combined = list(zip(symbols,deck))
TypeError: 'str' object is not callable
Here is my code: (Python 3.x)
import random #shuffle
import os#file deleting
def shuffledDeck(deck):#shuffles ceck
random.shuffle(deck)
def dealCard(deck,participant):#deal cards , chooses between player and house with string z
participant.append(deck.pop())
if z==1:
print('\nYou got %s ' %("{} {}".format(player[len(player)-1],symbols.pop())))
else:
print('\nHouse got %s ' %("{} {}".format(house[len(house)-1],symbols.pop())))
def total(hand):#chooses between player and house with string z and displays total
y =sum(hand)
if z==1:
print('Your total now is :',y)
else:
print('House total now is :',y)
def compareHands(house, player): #compares players and house's hand totals
global wallet
global bet
global bank
if sum(house)>sum(player):
print('You Lose :(')
wallet += bet
bank -= bet
prw = False
elif sum(house)<sum(player):
print('You Win!')
wallet += bet
bank -= bet
prw = True
elif sum(house)==sum(player):
print('DRAW!')
def printHistory(history): # prints history.txt
if history=='h':
f = open('history.txt')
for l in f:
print(l,end='')
# r=0 # last game
row = 1 # times a game was played
bank = 10 # starting value
exit = False # making sure the game won't exit if the user doesn't want to
newGame = True
# defy if it is a new game or the previous had been canceled
try:
f=open('history.txt')
print('\n________________________ \nHistory File Available')
newGame=False#it is not a new game
except FileNotFoundError:
print('Creating History File..')
f=open('history.txt','w')
newGame=True#it is a new game
if newGame==False:#if it is not a new game
answer=input('Start new game (n) or continue previous game (c)?')#ask
if answer=='n':
f.close()
os.remove('history.txt')
f=open('history.txt','w')
elif answer=='c':
f=open('history.txt')
l=f.readlines()
list=l.pop()
splitlist=list.split()
row=int(splitlist[0])
bank=int(splitlist[5])
print('========================')#begining game
Done=iter([True, False])
while bank>0 and exit==False and (bank <30 or next(Done)):#if bank<0 bank looses so the loop brakes
deck=[2,2,2,2,3,3,3,3,4,4,4,4,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,11,11,11,11]
symbols=['\u2660', '\u2661', '\u2662', '\u2663','\u2660', '\u2661', '\u2662', '\u2663','\u2660', '\u2661', '\u2662', '\u2663','\u2660', '\u2661', '\u2662', '\u2663','\u2660', '\u2661', '\u2662', '\u2663','\u2660', '\u2661', '\u2662', '\u2663','\u2660', '\u2661', '\u2662', '\u2663','\u2660', '\u2661', '\u2662', '\u2663']
wallet = 0 #Money player won
prw = False #Player Won
player = []
house = []
bet = 0
z = 1 #to choose player or house in totalHand()
loop = True #Enter Houses loop
#out2=1#loopbrake2
Round = 2 #Rounds played(used in 5 cards combination)
# shuffle both deck and symbols the same way
combined = list(zip(symbols,deck))
shuffledDeck(combined)
symbols[:], deck[:] = zip(*combined)
#player
dealCard(deck,player)
bet = int(input('Place your bet: '))
while bet > bank:
print('Your bet should not be higher than bank\nplease try again >>>')
bet = int(input('Place your bet: '))
dealCard(deck,player)
total(player)
#checking
if sum(player) == 22: #double ace
print('You win (Α-Α)!!')
wallet += bet
bank -= bet
loop = False
prw = True
elif sum(player)==21:
print('You win!!')
wallet += bet
bank -= bet
loop = False
prw = True
else:
action = input('Hit (h) or stand (s)?: ')
while action == 'h' and sum(player) <= 21 and prw == False:
dealCard(deck, player)
total(player)
Round += 1 # 5 cards combination
if player[0] == 7 and player[1] == 7 and player[2] == 7:
print('You win (Σκουπα)!!')
wallet += bank
bank -= bank
loop = False
prw = True
exit = True
elif Round == 5 and sum(player) <= 21:
print('You win! (Πενταφυλλια)')
wallet += bet
bank -= bet
loop = False
prw = True
elif sum(player) == 21:
print('You win (21)!!')
wallet += bet
bank -= bet
loop = False
prw = True
elif sum(player) < 21:
action = input('Hit (h) or stand (s)?: ')
elif sum(player) > 21:
print('You Lose :( ')
wallet -= bet
bank += bet
loop = False
pwd = False
#houses turn
if loop is True:
z=0
dealCard(deck,house)
total(house)
while sum(house)<17:
dealCard(deck,house)
total(house)
#comparison
if sum(house)<=21:
if house[0] == 7 and house[1] == 7 and house[2] == 7:
print('You Lose :( (7-7-7)')
wallet = 0
bank += bet
pwd = False
exit = True
elif sum(house) == 21:
print('You Lose :( ')
wallet -= bet
bank += bet
pwd = False
else:
compareHands(house,player)
elif sum(house)>21:
print('You Win!')
wallet += bet
bank -= bet
prw = True
print("Bank's balance now is", bank)
if sum(house) == sum(player):
winner = 'DRAW'
elif prw is False:
winner = 'House'
elif prw is True:
winner = 'Player'
#updating history.txt file
if row==1:
f=open('history.txt','r+')
f.write('%-*s%-*s%-*s%-*s%-*s %-*s'% (10,'Round',15,'Bet($)',10,'Player',10,'House',15,'Winner',10,'Bank($)'))
f.close()
f=open('history.txt','a')
f.write('\n%-*s%-*s%-*s%-*s%-*s %-*s'%(10,row,15,bet,10,sum(player),10,sum(house),15,winner,10,bank))
row+=1
f.close()
else:
f=open('history.txt','a')
f.write('\n%-*s%-*s%-*s%-*s%-*s %-*s'% (10,row,15,bet,10,sum(player),10,sum(house),15,winner,10,bank))
row+=1
f.close()
#display history and other actions
history=input('\nContinue(c), print history (h) or exit game (x)?')
while history=='h':
printHistory(history)
history=input('\nContinue(c), print history (h) or exit game (x)?')
if history=='c':
exit=False
else:
exit=True
#game overview
print('Game Over')
if bank==0:
print('Player has won $10')
elif bank>10:
print('Player has lost %d$'%(bank-10))`
It is a simple blackjack game that most beginners make in python i hope that the comments on the code will help you understand it.
My mistake should be something silly as long as i am new to the language but i hope you will help me.
It runs as it should the only problem is...
When the programm asks :
Start new game (n) or continue previous game (c)?
and you give 'c' as input it gives the error.
I found this method on this site so i may not use it right:
combined = list(zip(symbols,deck))
shuffledDeck(combined)
symbols[:], deck[:] = zip(*combined)
any improvements to the code are acceptable.
Thanks in Advance!
UPDATE!
is there any way to display the letter 'A' (stands for ace) instead of 11?
eg.
You got A ♡
instead of
You got 11 ♡
You've overwritten the built-in list function with a string:
list=l.pop()
To fix this, use a different variable name, other than list. In general, you'll want to avoid shadowing built-ins when naming your variables. That is, don't name things list, map, dict, etc.
It's also good practice to name your variables after what's in them. So if you have list = ["apples", "oranges", "pears"], you might consider renaming it fruits = ["apples", "oranges", "pears"]. It really helps with code readability.
You've defined list to be a string:
list=l.pop()
So
list(zip(symbols,deck))
causes Python to complain that list is not callable.
The solution, of course, is to use descriptive variable names that do not shadow Python builtins.
This happened to me recently where I tried to call a function I had defined from within another function, but didn't notice that I also had a local variable in the calling fucntion with the same name as the function I was trying to call.
Due to the scope rules the call to the function was being interpreted as calling the local variable...hence the error message since a scalar variable of type 'str' (for example) is not callable.
So the essence of the problem is variables sharing the names of functions you need to call within their scope, whether they be functions you've defined, those included in imported modules or Python built-ins.