Here's the code for my blackjack game that uses PySimpleGUI.
# import PySimpleGUI as sg
import random
import PySimpleGUI as sg
import time
sg.theme('DarkAmber')
player_money = 1500
player_cards = []
player_value = 0
computer_cards = []
computer_value = 0
bet = 0
count = 0
end = 0
# Function to calculate quadratic equation properties
def get_card():
global player_cards
card = random.randint(1, 13)
if card == 1:
card = 11
elif card == 11 or card == 12 or card == 13:
card = 10
return card
def start_game():
global player_cards
global computer_cards
global player_value
global computer_value
player_value = 0
computer_value = 0
player_cards = []
computer_cards = []
for i in range(4):
card = get_card()
if i % 2 == 0:
player_cards.append(card)
player_value += card
else:
computer_cards.append(card)
computer_value += card
# if player_value >= 21:
# stand()
def check_value(list):
count = 0
for i in list:
count += i
return count
def print_cards():
print(F"player cards: {player_cards}")
print(F"your cards add up to {check_value(player_cards)}.")
print(F"computer cards: [{computer_cards[0]}, ---]")
def deal():
global player_cards
global player_value
card = get_card()
player_cards.append(card)
player_value += card
def comp_deal():
global computer_cards
global computer_value
card = get_card()
computer_cards.append(card)
computer_value += card
def button_swap(list, e1, e2):
list[e1].update(visible=False)
list[e1].update(disabled=True)
list[e2].update(visible=True)
list[e2].update(disabled=False)
def show_comp():
global window
global computer_cards
global computer_value
window["cc"].update(F"Dealer cards: {computer_cards}")
window["cv"].update(F"The value of the dealers cards: {computer_value}")
def check_win():
global player_value
if player_value >= 21:
stand()
def results():
global player_value
global computer_value
global window
global player_money
global bet
global count
global event
global end
end = 0
bet = int(bet)
if player_value > 21:
player_money -= bet
window['results'].update(F"You lost ${bet} and now have {player_money}.")
elif computer_value > 21:
player_money += bet
window['results'].update(F"You won ${bet} and now have {player_money}!")
else:
if player_value > computer_value:
player_money += bet
window['results'].update(F"You won ${bet} and now have {player_money}!")
elif player_value == computer_value:
window['results'].update("You tied, so you got your bet back.")
else:
player_money -= bet
window['results'].update(F"You lost ${bet} and now have {player_money}.")
window['Deal'].update(disabled=True) # Disable the "Deal" button
window['Stand'].update(disabled=True) # Disable the "Stand" button
# if player_money == 0:
# window["restart"].update("You're out of money. Bye!")
# button_swap(window, "Deal", "Quit")
# window["Stand"].update(visible=False)
# else:
window["restart"].update("Play again?")
button_swap(window, "Deal", "Yes")
button_swap(window, "Stand", "No")
window["intro"].update(F"Your current money: ${player_money}")
def end_game():
global player_value
global computer_value
global window
global player_money
global bet
global count
show_comp()
results()
count += 1
print(count)
def stand():
global player_value
global computer_value
global window
global player_money
global bet
global count
if player_value <= 21:
while computer_value < player_value:
comp_deal()
end_game()
start_game()
layout1 = [
[sg.Text("Welcome to blackjack!")],
[sg.Text(F"Your cards: {player_cards}", key='pc')],
[sg.Text(F"The value of your cards: {player_value}", key='pv')],
[sg.Text(F"Dealer cards: [{computer_cards[0]}, ---]", key="cc")],
[sg.Text("", key="cv")],
[sg.Text("", key="results")],
[sg.Text("", key="restart")],
[sg.Button("Deal"), sg.Button("Stand"),
sg.Button("Yes", visible=False, disabled=False), sg.Button("No", visible=False, disabled=False)]
]
def update_layout():
global window
window['pc'].update(F"Your cards: {player_cards}")
window['pv'].update(F"The value of your cards: {player_value}")
window['cc'].update(F"Dealer cards: [{computer_cards[0]}, ---]")
window['cv'].update("")
window['results'].update("")
window["restart"].update('')
button_swap(window, "Yes", "Deal")
button_swap(window, "No", "Stand")
def error_trap(num):
global window
global player_money
result = True
try:
int(num)
except ValueError:
window["error"].update("Number not entered. Please try again.")
return False
if int(num) > player_money:
window["error"].update("You don't have that much money. Please try again.")
result = False
elif int(num) <= 0:
window["error"].update("Please input actual money.")
return result
layout2 = [
[sg.Text(F"Your current money: ${player_money}", key="intro")],
[sg.Text("How much would you like to bet on this round?")],
[sg.InputText("50", key="money")],
[sg.Text("", key="error")],
[sg.Button("Start"), sg.Button("Quit")]
]
layout = [[sg.Column(layout1, visible=False, key="-COL1-"), sg.Column(layout2, visible=True, key="-COL2-")]]
window = sg.Window("the box", layout)
while True:
event, values = window.read()
check_win()
if event == "Deal":
deal()
window['pc'].update(F"Your cards: {player_cards}")
window['pv'].update(F"The value of your cards: {player_value}")
check_win()
elif event == "Stand":
stand()
elif event == "Yes":
window['-COL1-'].update(visible=False)
window['-COL2-'].update(visible=True)
elif event == "Start":
bet = window["money"].get()
i = error_trap(bet)
if i == True:
window['-COL2-'].update(visible=False)
window['-COL1-'].update(visible=True)
if count != 0:
start_game()
update_layout()
window.close()
I can't seem to figure out why if the player wins, they win their money twice, or if they lose, they lose their money twice. The second charge happens whenever the player says 'yes' or 'no' to play again.
In the main loop, You call
check_win()
unconditionally. You also callstand()
to handle an event. However, one of the main thingscheck_win()
does is to also callstand()
.The method
stand()
callsend_game()
which callsresults()
. The methodresults()
then updatesplayer_money
.The net effect is that there are situations where there are ultimately multiple calls to the method that updates the player ballance.