#!/usr/bin/python3
import tkinter as tk
from tkinter import *
import random
import copy
import sys
import os
import time
#from time import sleep


#root = tk.Tk()
root = Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
if screen_height < 700 or screen_width < 1100:
    root.geometry('500x450')
    l = Label(root, text = "screen too small",font=(NONE,20, "bold"),background="brown",foreground="white") 
    l.pack(fill=BOTH, expand=True)
    root.mainloop()
    sys.exit(0)  #return(5) #quit
#root.config(cursor='circle white white')
root.geometry("1100x700")
root.resizable(False,False)


try:
    base_path = sys._MEIPASS
except Exception:
    base_path = os.path.abspath(".")
os.chdir(base_path)

def quit_now():
    global event_wait
    global quit_game
    event_wait = no
    quit_game = 1
    return

#frame1 = Frame(root, borderwidth=0,bg="brown")
frame1 = Canvas(root, borderwidth=0,bg="brown")
frame1.pack(side="top", fill="both", expand=True)
#player names
p0 = Label(frame1, text = "SOUTH",font=(NONE,20, "bold"),background="brown",foreground="white") 
p0.place(relx=0.5, rely=1.0,anchor=S) 
p1 = Label(frame1, text = "WEST",font=(NONE,20, "bold"),background="brown",foreground="white") 
p1.place(relx=0.0, rely=0.5,anchor=W) 
p2 = Label(frame1, text = "NORTH",font=(NONE,20, "bold"),background="brown",foreground="white") 
p2.place(relx=0.5, rely=0.0,anchor=N) 
p3 = Label(frame1, text = "EAST",font=(NONE,20, "bold"),background="brown",foreground="white") 
p3.place(relx=1.0, rely=0.5,anchor=E) 
#bid/meld msg
t0 = Label(frame1, text = "bid= ",font=(NONE,16, "bold"),background="brown",foreground="white")
t0.place(relx=0.5,  rely=1.0, y= -35,anchor=S) 
t1 = Label(frame1, text = "bid= ",font=(NONE,16, "bold"),background="brown",foreground="white") 
t1.place(relx=0.0, rely=0.5,y=-33,anchor=W) 
t2 = Label(frame1, text = "bid= ",font=(NONE,16, "bold"),background="brown",foreground="white") 
t2.place(relx=0.5, rely=0.0,y=35,anchor=N) 
t3 = Label(frame1, text = "bid= ",font=(NONE,16, "bold"),background="brown",foreground="white") 
t3.place(relx=1.0, rely=0.5,y=-33,anchor=E) 
#center buttons
toolbar = Frame(frame1)
button1 = Button(toolbar, text="Start",font=(NONE,13,"bold"), command=quit_now)
button1.pack(side=LEFT, padx=1, pady=4)
button2 = Button(toolbar, text="         ",font=(NONE,13,"bold"), command=quit_now)
button2.pack(side=LEFT, padx=1, pady=4)
button3 = Button(toolbar, text="         ",font=(NONE,13,"bold"), command=quit_now)
button3.pack(side=LEFT, padx=1, pady=4)
button4 = Button(toolbar, text="         ",font=(NONE,13,"bold"), command=quit_now)
button4.pack(side=LEFT, padx=1, pady=4)
toolbar.place(relx= 0.50, rely= 0.56, anchor=CENTER)
#title/center message
c1 = Label(frame1, text = "PINOCHLE",font=(NONE,24, "bold"),background="brown",foreground="white") 
c1.place(relx=0.5, rely=0.5,anchor=CENTER) 
#card frames for hands
spacing = 27
card_width = 75
card_height = 107
cframe0 = Frame(frame1, borderwidth=0, bg="brown", height = card_height+spacing, width = (spacing * 16)+75)
cframe0.place(relx=0.5,  rely=1.0, y= -70,anchor=S) 
cframe1 = Frame(frame1, borderwidth=0, bg="brown", height = card_height, width = (spacing * 11)+75)
cframe1.place(relx=0.0, rely=0.5,y=+70,anchor=W) 
cframe2 = Frame(frame1, borderwidth=0, bg="brown", height = card_height, width = (spacing * 11)+75)
cframe2.place(relx=0.5, rely=0.0,y=+70,anchor=N) 
cframe3 = Frame(frame1, borderwidth=0, bg="brown", height = card_height, width = (spacing * 8)+75)
cframe3.place(relx=1.0, rely=0.5,y=+70,anchor=E) 
#card played frames
pframe1 = Frame(frame1, borderwidth=0, bg="brown", height = card_height, width = card_width)
pframe1.place(relx=0.3, x=-18, rely=0.5,y=+70,anchor=W) 
pframe2 = Frame(frame1, borderwidth=0, bg="brown", height = card_height, width = card_width)
pframe2.place(relx=0.5, rely=0.0,y=+180,anchor=N) 
pframe3 = Frame(frame1, borderwidth=0, bg="brown", height = card_height, width = card_width)
pframe3.place(relx=0.7, x=+18,rely=0.5,y=+70,anchor=E) 

# "deck" is used to shuffle cards
#------------------
deck = [0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23]
# index to cards
# spades   0-nine 1- jack 2- queen 3- king 4- ten 5- ace
# diamonds 6-nine 7- jack 8- queen 9- king 10-ten 11-ace
# clubs   12-nine 13-jack 14-queen 15-king 16-ten 17-ace
# hearts  18-nine 19-jack 20-queen 21-king 22-ten 23-ace
south_hand = []
west_hand = []
north_hand = []
east_hand = []

s9 = PhotoImage(file = 'image/s9.gif') # 18
sj = PhotoImage(file = 'image/sj.gif') # 19
sq = PhotoImage(file = 'image/sq.gif') # 20
sk = PhotoImage(file = 'image/sk.gif') # 21
s10 = PhotoImage(file = 'image/s10.gif')#22
sa = PhotoImage(file = 'image/sa.gif') # 23
d9 = PhotoImage(file = 'image/d9.gif') # 6
dj = PhotoImage(file = 'image/dj.gif') # 7
dq = PhotoImage(file = 'image/dq.gif') # 8
dk = PhotoImage(file = 'image/dk.gif') # 9
d10 = PhotoImage(file = 'image/d10.gif')#10
da = PhotoImage(file = 'image/da.gif') # 11
c9 = PhotoImage(file = 'image/c9.gif') # 0 index
cj = PhotoImage(file = 'image/cj.gif') # 1
cq = PhotoImage(file = 'image/cq.gif') # 2
ck = PhotoImage(file = 'image/ck.gif') # 3
c10 = PhotoImage(file = 'image/c10.gif')#4
ca = PhotoImage(file = 'image/ca.gif') # 5
h9 = PhotoImage(file = 'image/h9.gif') # 12
hj = PhotoImage(file = 'image/hj.gif') # 13
hq = PhotoImage(file = 'image/hq.gif') # 14
hk = PhotoImage(file = 'image/hk.gif') # 15
h10 = PhotoImage(file = 'image/h10.gif')#16
ha = PhotoImage(file = 'image/ha.gif') # 17
back = PhotoImage(file = "image/back.gif")

cards = [s9,sj,sq,sk,s10,sa,\
         d9,dj,dq,dk,d10,da,\
         c9,cj,cq,ck,c10,ca,\
         h9,hj,hq,hk,h10,ha]

#### constants
south = 0
west = 1
north = 2
east = 3

spade = 0
diamond = 1
club = 2
heart = 3

nine = 0
jack = 1
queen = 2
king = 3
ten = 4
ace = 5

yes = 1
no = 0

#ctrl table data ----
ctrl_index = 0 #select window in ctrl
ctitle = 0
cflag = 1
copen = 2    #open screen function
cback1 = 3   #callback 1
cback2 = 4
cback3 = 5
cback4 = 6
cback1_txt = 7 #button 1 text
cback2_txt = 8
cback3_txt = 9
cback4_txt = 10
cclose = 11      #screen close

quit_game = 0## p_subs
event_wait = yes
deal_posn = 0 #0=south 1=west 2=north 3=east
Trump = 9 #9=no trump selected
score_ew = 0
score_ns = 0
shoot_moon = no
brief_status_display = yes
ns_pointers = 0
ew_pointers = 0
testing = no
slowdown = 0.4
 
### bid data
south_bid_loop = yes
bid_posn = 1 #0=south 1=west  (left of dealer)
pass_count = 0 #bidding done if = 4
high_bid = 25 #current/last bid
high_bid_player = 0
last_bid = [25,25,25,25] #clubs,diamonds,hearts,spades set non-zero 0=pass
max_bid = [0,0,0,0] #max for
trumps = [0,0,0,0] #selected trumps by info()
melds = [0,0,0,0] #meld calclations by info()

#meld data
dups = []
nodups = []
temp = []
pass_cards = []
meld_source = [] #temp list of cards in hand
meld_build = [] #cards for meld display
meld_ns = 0
meld_ew = 0

#### info data
clubranks = []  #0=9 1=jack 2=queen 3=king 4=ten 5=ace
diamondranks = []
heartranks = []
spaderanks = []
svalue = [] #sum of ranks by suit spades,diamonds,clubs,hearts
scount = [] #count of cards in each suit
runs = [] #suit list
runh = [] #suits with 4 out of 5 run cards
aces = 0 #count 0,1,2 of aces around
aceh = 0 #count 0,1,2 of 3ace holes
kings = 0
kingh = 0
queens = 0
queenh = 0
jacks = 0
jackh = 0
marriage_points = 0 #marriage points, 4 per if trump
marriages_per_suit = []  #spades,diamonds,clubs,hearts
total_aces = 0
pino = 0   #number of pinochles
pinoh = 0  #number of pinochle holes
half_pinos = 0 #1 if jack  3 if spade

trump_sel = 0 #this hands trump choice
trump_nines = 0 #
trump_aces = 0
meld_sel = 0 # this hands meld

#### cardpass data #####################
weights = [] # weight, card
selectx = 0 #1=select 1  4=select 4

##### play hand data ##################################################

current_player = 0 #0=south
current_card = 0 #card played by current player
play_count = 0 #0-4 count of cards played for one trick
top_card = -1 #current high card taking trick -1=none
top_player = 9 #current player taking trick, 9=none
trick_cards = [9,9,9,9] #one 4 card trick
cards_taken_ns = []
cards_taken_ew = []
spades_played = [0,0,0,0,0,0] #9,j,q,k,10,a  each with count of 0,1,2
diamonds_played = [0,0,0,0,0,0]
clubs_played = [0,0,0,0,0,0]
hearts_played = [0,0,0,0,0,0]
total_spades_played = 0
total_diamonds_played = 0
total_clubs_played = 0
total_hearts_played = 0
suit_led = 9 #suit of first card led for trick
player_leading = 9 #player starting trick

##### current player data ##############################################

this_hand_spades = [] #cards
this_hand_diamonds = []
this_hand_clubs = []
this_hand_hearts = []
this_hand_counters = []
this_hand_losers = [] # non counters
this_hand_top_cards = [] #possible trick taking cards if not trumped

##1 open.py ############################################################

#start game
def open00():
    global score_ew,score_ns,deal_posn,Trump
    Trump = 9                                            
    score_ew = 0
    score_ns = 0
    deal_posn = 0 #0=south 1=west 2=north 3=east
    crt_players()
    mouse_to_button()

# shuffle
def open01():
    global deck
    init_hand()
    x = int(time.time())
    random.seed(x)
    random.shuffle(deck)
    indx = int(time.time() % 46)
    while indx != 0:
        card = deck.pop(random.randint(0,46))
        deck.append(card)
        indx = indx - 1

# deal
def open02():
    global south_hand,west_hand,north_hand,east_hand
    south_hand = deck[0:12]
    west_hand = deck[12:24]
    north_hand = deck[24:36]
    east_hand = deck[36:48]
    south_hand.sort()
    west_hand.sort()
    north_hand.sort()
    east_hand.sort()

#south bid
def open03():
    global south_bid_loop,last_bid,high_bid,slowdown
    south_bid_loop = yes
    show_south_hand()
    bid = last_bid[south]
    if bid != 0:
        t0.configure(text = "bid="+str(bid),fg = "yellow")
    else:
        t0.configure(text = "bid=pass",fg = "yellow")
        slowdown = 0
    return

#west bid
def open04():
    global last_bid,slowdown
    info(west,west_hand)
    autobid(west)
    bid = last_bid[west]
    if bid != 0:
        t1.configure(text = "bid="+str(bid),fg = "yellow")
    else:
        t1.configure(text = "bid=pass",fg = "yellow")
        slowdown = 0
    return

#north bid
def open05():
    global last_bid,slowdown
    info(north,north_hand)
    autobid(north)
    bid = last_bid[north]
    if bid != 0:
        t2.configure(text = "bid="+str(bid),fg = "yellow")
    else:
        t2.configure(text = "bid=pass",fg = "yellow")
        slowdown = 0
    return

#east bid
def open06():
    global last_bid,slowdown
    info(east,east_hand)
    autobid(east)
    bid = last_bid[east]
    if bid != 0:
        t3.configure(text = "bid="+str(bid),fg = "yellow")
    else:
        t3.configure(text = "bid=pass",fg = "yellow")
        slowdown = 0
    return

#show bid winner
def open07():
    global ctrl_index,high_bid_player,Trump
#    display_hand(south_hand)
    show_south_hand()
    #set high_bid_player from last_bid
    indx = 0
    for bid in last_bid:
        if bid != 0:
            high_bid_player = indx
            break
        else:
            indx = indx + 1
    crt_players()   #show players
    if high_bid_player == west:
        c1.configure(text = "west won bid",fg="yellow")
    elif high_bid_player == east:
        c1.configure(text = "east won bid",fg="yellow")
    elif high_bid_player == north:
        c1.configure(text = "north won bid",fg="yellow")
    elif high_bid_player == south:
        c1.configure(text = "south won bid",fg="yellow")
    root.update()

#west_card exchange - open
def open08():
    global Trump,trump_sel
    Trump = trumps[west]
    card_pass(east,east_hand,west,west_hand)
    cards_back(west,west_hand,east,east_hand)
    return    

#east card exchange - open
def open09():
    global Trump,trump_sel
    Trump = trumps[east]
    card_pass(west,west_hand,east,east_hand)
    cards_back(east,east_hand,west,west_hand)
    Trump = trump_sel
    return

#north card exchange - open
def open10():
    global Trump,selectx
    Trump = trumps[north]
    selectx = 4
    if count_selects() == 4:
        button1.configure(text="submit")
        mouse_to_button()
    else:
        button1.configure(text="    ")
    if count_selects() == 0:
        mouse_to_cards()
    ## clear south hand area
    show_south_hand()
    root.update()    
    return

#south select trump - open
def open11():
    return

#south view cards from north
def open12():
    global south_hand
    ## clear south hand area 
    show_south_hand()
    #tenp code
#    display_all_hands()
    #end temp code
    return

#south select xchange cards for north
def open13():
    global north_hand,south_hand,selectx,slowdown
    slowdown = 0
    if count_selects() == 0:
        mouse_to_cards()
    selectx = 4
    if count_selects() == 4:
        button1.configure(text="submit")
        mouse_to_button()
    else:
        button1.configure(text="    ")
    show_south_hand()
    return

#meld
def open14():
    global brief_status_display,meld_ns,meld_ew
    clear_all_hand_displays()
    if high_bid_player == south:
        button3.configure(command=cback3_14)
        button3.configure(text="shoot")
    meld(south,south_hand)    
    meld(west,west_hand)        
    meld(north,north_hand)        
    meld(east,east_hand)
    meld_ns = melds[south] + melds[north]
    meld_ew = melds[east] + melds[west]
    shoot_moon_check()
    brief_status_display = no
    show_status()
    show_south_hand()
    return    

#play south
def open15():
    global south_hand,selectx,slowdown
    slowdown = 0
    show_south_hand()
    selectx = 1
    x = get_select()
    if x == -1: #check if any selects active
        mouse_to_cards()
        button1.configure(text="    ")
        return
    #we have got at least one select
    x = x - 100
    if legal_card(x) == yes:
        mouse_to_button()
        button1.configure(text="submit")
        return
    else:
        clear_all_selects()
    show_south_hand()


#west play one card
def open16():
    autoplay(west,west_hand)
    return

#north play one card
def open17():
    autoplay(north,north_hand)
    return

#east play one card
def open18():
    autoplay(east,east_hand)
    return

# card played, 
def open19():
    global select_count,cards_taken_ns,cards_taken_ew
#    clear_hand_display(south)
#    display_hand(south_hand)
    #show who won trick
    if top_player == south:
        txt = "south taking"
        cards_taken_ns.extend(trick_cards)
    elif top_player == west:
        txt = "west taking"
        cards_taken_ew.extend(trick_cards)
    elif top_player == north:
        txt = "north taking"
        cards_taken_ns.extend(trick_cards)
    elif top_player == east:
        txt = "east taking"
        cards_taken_ew.extend(trick_cards)
    c1.configure(text = txt,fg="yellow")
    root.update()
    return

#scoring one hand
def open20():
    global score_ns,score_ew,pointers,ns_pointers,ew_pointers
    ns_pointers = 0
    ew_pointers = 0
    for card in cards_taken_ns:
        if rank(card) > 2:
            ns_pointers = ns_pointers + 1
    for card in cards_taken_ew:
        if rank(card) > 2:
            ew_pointers = ew_pointers + 1
    #add extra point for last trick taken
    if top_player == north or top_player == south:
        ns_pointers = ns_pointers + 1
    else:
        ew_pointers = ew_pointers + 1
    #check if bid was made
    if high_bid_player == south or high_bid_player == north:
        if shoot_moon != 0:
            if ns_pointers == 25:
                score_ns = score_ns + meld_ns + 50
                report = "North/South hit moon"
            else:
                score_ns = score_ns - 50
                report = "North/South is Set"
        else:
            if high_bid <= (meld_ns + ns_pointers): #did ns make bid
                score_ns = score_ns + meld_ns + ns_pointers
                report = "North/South Made Bid"
            else:
                score_ns = score_ns - high_bid
                report = "North/South is Set"
        #if east/west took a trick, update score
        if ew_pointers > 0:
            score_ew = score_ew + meld_ew + ew_pointers
    if high_bid_player == west or high_bid_player == east:
        if shoot_moon != 0:
            if ew_pointers == 25:
                score_ew = score_ew + meld_ew + 50
                report = "East/West hit moon"
            else:
                score_ew = score_ew - 50
                report = "East/West is Set"
        else:
            if high_bid <= (meld_ew + ew_pointers): #did ew make bid
                score_ew = score_ew + meld_ew + ew_pointers
                report = "East/West Made Bid"
            else:
                score_ew = score_ew - high_bid
                report = "East/West is Set"
        #if North/South took a trick, update score
        if ns_pointers > 0:
            score_ns = score_ns + meld_ns + ns_pointers
    #show results of hand
    c1.configure(text = report,fg="yellow")
    show_status()
    #clear hands and show initial state
    open02()  #deal cards again
    display_all_hands()
    show_max_bids("white")


#game winner is
def open21():
    if score_ns >= 250 or score_ew >= 250:
        if score_ns >= 250:
            title1 = "North/South won game"
        elif score_ew >= 250:
            title1 = "West/East won game"
    c1.configure(text = title1,fg = "yellow")
    root.update()
    return

#new game?
def open22():
    global score_ns,score_ew
    init_hand()
    score_ns = 0
    score_ew = 0
    return
#2 close.py ###########################################################

#start up
def win00_close():
    global ctrl_index
    ctrl_index = 1

#shuffle
def win01_close():
    global ctrl_index
    ctrl_index = 2

#dealing
def win02_close():
    global ctrl_index,deal_posn,last_bid,high_bid,high_bid_player
    last_bid = [25,25,25,25]
    high_bid = 25
    if deal_posn == east:
        ctrl_index = 3
        high_bid_player = south
    else:
        ctrl_index = deal_posn + 4
        high_bid_player = deal_posn
    deal_posn = (deal_posn + 1) % 4 #update deal position for next hand
    crt_clear_players()

#south bid
def win03_close():
    global ctrl_index,pass_count
    if south_bid_loop == no:  #loop till submit button pressed
        if pass_count < 3:
            ctrl_index = 4
        else:
            ctrl_index = 7
    return

#west bid
def win04_close():
    global ctrl_index,pass_count
    ctrl_index = 5 # north bid
    if pass_count < 3:
        ctrl_index = 5
    else:
        ctrl_index = 7
    return

#north bid
def win05_close():
    global ctrl_index,pass_count
    if pass_count < 3:
        ctrl_index = 6
    else:
        ctrl_index = 7
    return

#east bid
def win06_close():
    global ctrl_index,pass_count,last_bid,high_bid,south_bid_loop
    if pass_count < 3:
        if last_bid[south] == 0:
            ctrl_index = 4
        else:
            ctrl_index = 3
            last_bid[south] = high_bid +1
            south_bid_loop = yes
    else:
        ctrl_index = 7
    return

#show bid winner - close window
def win07_close():
    global select_count,select_loop,Trump,trumps
    global ctrl_index,high_bid_player
    if high_bid_player == west:
        ctrl_index = 8
    elif high_bid_player == east:
        ctrl_index = 9
    elif high_bid_player == north:
        info(north,north_hand)
        Trump = trumps[high_bid_player]
        ctrl_index = 10
    else:
        ctrl_index = 11

#west card exchange - close
def win08_close():
    global ctrl_index
    ctrl_index = 14

#east card exchange - close
def win09_close():
    global ctrl_index
    ctrl_index = 14

#north card exchange - close
def win10_close():
    return

#south select trump - close
def win11_close():
    global ctrl_index,north_hand,south_hand
    card_pass(north,north_hand,south,south_hand)
    ##clear_hand_display(south)
    show_south_hand()
    ctrl_index = 12
    return

#south view cards from north 
def win12_close():
    global ctrl_index
    ctrl_index = 13
    return

#south exchange with north
def win13_close():
    show_south_hand()
    return

#meld - close
def win14_close():
    global ctrl_index,play_count,current_player,select_count
    ctrl_index = 15 + high_bid_player
    play_count = 0
    current_player = high_bid_player
    select_count = 0 #setup incase south next
    clear_all_hand_displays()
    clear_all_melds()
    init_trick()
    mouse_to_cards()

#play south close
def win15_close():
    return


#west play one card
def win16_close():
    global ctrl_index,play_count,current_player
    if play_count == 3:
        ctrl_index = 19
        play_count = 0
    else:
        ctrl_index = 17
        play_count = play_count + 1
        current_player = north

#north play one card
def win17_close():
    global ctrl_index,play_count,current_player
    if play_count == 3:
        ctrl_index = 19
        play_count = 0
    else:
        ctrl_index = 18
        play_count = play_count + 1
        current_player = east

#east play one card
def win18_close():
    global ctrl_index,select_count,play_count
    if play_count == 3:
        play_count = 0
        ctrl_index = 19
    else:
        ctrl_index = 15
        play_count = play_count + 1

#play loop control
def win19_close():
    global play_count,current_player,top_card,top_player,ctrl_index,select_loop
    if len(south_hand) > 0:
        play_count = 0
        if top_player == 9:
            ctrl_index = 15  #this is for testing only
            current_player = south #testing only
        else:
            current_player = top_player
            ctrl_index = top_player + 15
        top_player = 9
        top_card = -1
    else:
        ctrl_index = 20
    select_loop = yes
    clear_played_cards()
    show_south_hand()
    return

#show scoring
def win20_close():
    global ctrl_index
    mouse_to_button()
    clear_all_hand_displays()
    clear_south_hand()
    show_max_bids("brown") #clear max bid display
    #check for game done?
    if score_ns >= 250 or score_ew >= 250:
        ctrl_index = 21
    else:
        ctrl_index = 1
    return

#show game winner
def win21_close():
    global quit_game
    event_wait = no

def win22_close():
    global event_wait
    event_wait = no

##3 callback.py ########################################################
def dummy():
    return

#start game
def cback1_00():
    global event_wait
    event_wait = no
    return

#enable test mode
def testm():
    global event_wait,testing
    if testing == no:
        spacing = 22
        show_hands()
        testing = yes
    else:
        spacing = 27
        show_hands()
        testing = no
        clear_all_hand_displays()
    event_wait = no
    return

#bid south = pass
def cback1_03():
    global last_bid,event_wait,south_bid_loop,pass_count
    last_bid[south] = 0
    event_wait = no #release main loop wait
    south_bid_loop = no
    pass_count = pass_count + 1
    t0.configure(text = "bid=pass",fg = "yellow")
    return

#bid south = increase
def cback2_03():
    global last_bid,event_wait
    last_bid[south] = last_bid[south] +1
    event_wait = no #release main loop wait
    return

#bid south = decrease
def cback3_03():
    global last_bid,event_wait
    last_bid[south] = last_bid[south] -1
    event_wait = no #release main loop wait
    return

#bid south = submit
def cback4_03():
    global south_bid_loop,event_wait,high_bid,high_bid_player,last_bid
    if last_bid[south] < high_bid:
        cback1_03() #pass processing
        return
    if last_bid[south] != 0:
        high_bid = last_bid[south]
        high_bid_player = south
    south_bid_loop = no
    event_wait = no #release main loop wait
    return

#show bid winner - continue button
def cback1_07():
    global event_wait
    event_wait = no #release main loop wait

#east exchange card - callback
def cback1_08():
    global event_wait
    event_wait = no #release main loop wait

#west exchange card - callback
def cback1_09():
    global event_wait
    event_wait = no #release main loop wait

#north exchange cards - callback
def cback1_10():
    global north_hand,south_hand,ctrl_index,event_wait,selectx
    #send south selected cards to north
    while True:
        card = get_next_select(yes)  #get card and remove it
        if card == 200:
            break
        north_hand.append(card)
    #send 4 cards north to south
    card_weights(north,Trump,north_hand) #pass trump and player data
    weights.reverse()
    pass_cnt = 4
    while pass_cnt != 0:
        card = weights.pop()
        north_hand.remove(card[1])
        south_hand.append(card[1])
        pass_cnt = pass_cnt - 1
    south_hand.sort()
    north_hand.sort()
    ctrl_index = 14
    selectx = 4
    event_wait = no        

#south select clubs trump call back
def cback1_11():
    global Trump,event_wait
    Trump = club
    event_wait = no #release main loop wait
    return
#south select diamonds trump call back
def cback2_11():
    global Trump,event_wait
    Trump = diamond
    event_wait = no #release main loop wait
    return
#south select hearts trump call back
def cback3_11():
    global Trump,event_wait
    Trump = heart
    event_wait = no #release main loop wait
    return

#south select spades trump call back
def cback4_11():
    global Trump,event_wait
    Trump = spade
    event_wait = no #release main loop wait
    return

#south exchange cards callback - submit
def cback1_12():
    global event_wait
    event_wait = no #release main loop wait
    return

#south exchange cards callback - submit
def cback1_13():
    global event_wait,ctrl_index,north_hand,south_hand,selectx
    #send south selected cards to north
    while True:
        card = get_next_select(yes)  #get card and remove it
        if card == 200:
            break
        north_hand.append(card)
    south_hand.sort()
    north_hand.sort()
    selectx = 0
    ctrl_index = 14
    event_wait = no

#continue from meld show
def cback1_14():
    global event_wait
    event_wait = no #release main loop wait
    return

#meld shoot button
def cback3_14():
    global shoot_moon,event_wait
    shoot_moon = yes
    event_wait = no
    return

#play south - submit
def cback1_15():
    global south_hand,selectx
    global event_wait,current_card,ctrl_index,play_count,current_player
    current_card = get_select()  #get card, do not remove
    if current_card == -1:
        event_wait = no
        return
    if current_card > 99:
        current_card = current_card - 100
        clear_all_selects()
        play_this_card(south,south_hand,current_card)
    else:
        event_wait = no
        return
    if play_count == 3:
        ctrl_index = 19
        play_count = 0
    else:
        ctrl_index = 16
        play_count = play_count + 1
        current_player = west
    selectx = 0
    event_wait = no

#play loop control - continue
def cback1_19():
    global event_wait
    event_wait = no #release main loop wait
    return

#end of hand scoring - continue
def cback1_20():
    global event_wait
    event_wait = no #release main loop wait
    return

#game over - continue
def cback1_21():
    global event_wait,ctrl_index
    event_wait = no #release main loop wait
    ctrl_index = 22
    return

#new game? - continue
def cback1_22():
    global event_wait,ctrl_index
    event_wait = no #release main loop wait
    ctrl_index = 0
    return


### mouse
def mouse(event):
    global south_hand,selectx,event_wait
    if selectx == 0:
        return
    if len(south_hand) == 0:
        return
    x=event.x_root
    y=event.y_root
    leftx = root.winfo_x() + 550 - int((16*spacing +75)/2) + 7
    rightx = leftx + 17 * spacing
    topy = root.winfo_y() + 500
    if x < leftx or x > rightx:
        return
    if y < topy or y > topy + card_height:
        return
    x = x - leftx
    indx = int(x / spacing)
    if indx < 0:
        indx = 0
    if indx >= (len(south_hand) - 1):
        indx = len(south_hand) - 1
    #check if card selected already
    if south_hand[indx] > 99:
        south_hand[indx] = south_hand[indx] - 100 #clear select flag
    else:
        if count_selects() < selectx:
            south_hand[indx] = south_hand[indx] + 100
    event_wait = no
    return

def about():
    ab = Toplevel()
    ab.title("about")
    msg="pino 1.0.0\n\nsingle deck pinochle\nbased on rules from Hoyle\nCopyright(C) Jeff Owens <jkowens2001@gmail.com>"
    w = Label(ab, text=msg,fg="white",bg="blue",font=(None,18))
    w.pack()

##4 bid.py  ############################################################

#bidding west,north,east  returns  bid or 0 for pass
def autobid(player):
    global high_bid,high_bid_player,last_bid,pass_count,max_bid
    if max_bid[player] > high_bid:
        high_bid = high_bid +1
        high_bid_player = player
        last_bid[player] = high_bid  #update current bid
    else: #pass 
        if last_bid[player] != 0:  #already passed?
            pass_count = pass_count + 1
            last_bid[player] = 0  #pass
    return

#compute Pass weight for one card, use data from info()
def weight_comp(trump,rank,suit):
    weight = 0
    if suit == trump and rank > 0:
        weight = 10
    elif suit == trump and rank == 0:
        weight = 7
    elif rank == 5 and aces == 4:
        weight = 10
    elif rank == 5 and aces < 4:
        weight = 8
    #check for partial pinochles
    elif trump == 3 and rank == 1:
        weight = 3
    elif trump == 1 and rank == 2:
        weight = 3
    #check for queens,kings,jacks around
    elif rank == 3 and kings > 0:
        weight = 2
    elif rank == 2 and queens > 0:
        weight = 3
    elif rank == 1 and jacks > 0:
        weight = 2
    #check for marriages
    elif rank == 2 and marriages_per_suit[suit] > 0:
        weight = 1
    elif rank == 3 and marriages_per_suit[suit] > 0:
        weight = 1   
    return(weight)

#pass one card 
def pass_it(card,To,From):
    From.remove(card)
    To.append(card)

# build pass weights in pass_weights, array of  weight,suit,rank
def card_weights(player,trump,hand):
    global weights
    info(player,hand)
    Trump = trumps[high_bid_player]
    weights = []
    for card in hand:
        weight = weight_comp(trump,rank(card),suit(card))
        weights.append([weight,card])
    weights.sort()
    #put single non trump aces before dual aces
    i = 0
    for item in weights:
        if item[1] != Trump:
            if rank(item[1]) == rank(weights[i+1][1]) and rank(weights[i+2][1]) == 5:
                x = weights[i+2]
                weights[i+2] = weights[i+1]
                weights[i+1] = x
        i = i + 1
        if i > 4:
            break

#partner declared trump, pass trump and high cards
def card_pass(from_player,From,to_player,To):
    global weights
    card_weights(from_player,Trump,From) #pass trump and player data
    pass_cnt = 4
    while pass_cnt != 0:
        card = weights.pop()
        pass_it(card[1],To,From)
        pass_cnt = pass_cnt - 1
    From.sort()
    To.sort()    

# pass back worst cards
def cards_back(from_player,From,to_player,To):
    card_weights(from_player,Trump,From) #pass trump and player data
    weights.reverse()
    pass_cnt = 4
    while pass_cnt != 0:
        card = weights.pop()
        pass_it(card[1],To,From)
        pass_cnt = pass_cnt - 1
    From.sort()
    To.sort()

#partner declared trump, pass trump and high cards
def card_pass(from_player,From,to_player,To):
    global weights
    card_weights(from_player,Trump,From) #pass trump and player data
    pass_cnt = 4
    while pass_cnt != 0:
        card = weights.pop()
        pass_it(card[1],To,From)
        pass_cnt = pass_cnt - 1
    From.sort()
    To.sort()    

# pass back worst cards
def cards_back(from_player,From,to_player,To):
    card_weights(from_player,Trump,From) #pass trump and player data
    weights.reverse()
    pass_cnt = 4
    while pass_cnt != 0:
        card = weights.pop()
        pass_it(card[1],To,From)
        pass_cnt = pass_cnt - 1
    From.sort()
    To.sort()

##5 play.py ############################################################

#check card index for legality using, top_card,trick, assume play_south called "info"
def legal_card(card):
    have_trump = no
    have_led_suit = no
    have_higher_card = no
    if play_count == 0:
        return(yes)
    for cardx in south_hand:
        if cardx > 99:
            cardx = cardx - 100
        if suit(cardx) == Trump:
            have_trump = yes
        if suit(cardx) == suit_led:
            have_led_suit = yes
        if suit(cardx) == suit_led and rank(cardx) > rank(top_card):
            have_higher_card = yes
    if have_led_suit == yes and suit(card) != suit_led:
        return(no)
    if have_trump == yes and have_led_suit == no and suit(card) != Trump:
        return(no)
    if have_led_suit == yes and have_higher_card == yes and rank(card) < rank(top_card) and suit(top_card) != Trump:
        return(no)
    else:
        return(yes)

def is_top_card(card):
    #set top_card_played
    if play_count == 0:
        return(yes)
    else:
        if suit(top_card) == Trump:
            if suit(card) == Trump:
                if rank(card) > rank(top_card):
                    return(yes)
        #top card is not trump
        else:
            if suit(top_card) == suit(card):
                if rank(card) > rank(top_card):
                    return(yes)
            else:
                if suit(card) == Trump:
                    return(yes)
    return(no)
                

def play_this_card(player,hand,card):
    global top_card,top_player,suit_led,player_leading
    if card in hand:
        hand.remove(card)
    elif card + 100 in hand:
        hand.remove(card + 100)
#    else:
    if top_card == -1:
        top_card = card
        top_player = player
    else:
        result = is_top_card(card)
        if result == yes:
            top_card = card
            top_player = player
    if play_count == 0:
        suit_led = suit(card)
        player_leading = player
    save_play_stats(player,card)
    show_played_card(player,card)
    #test code follows
#    clear_hand_display(player)
#    display_hand(hand)

def check_if_top(rrank,cards_played):
    if rrank == ace:
        return(yes)
    if rrank == ten:
        if cards_played[ace] == 2:
            return(yes)
    if rrank == king:
        if cards_played[ace] < 2:
            return(no)
        if cards_played[ten] < 2:
            return(no)
        else:
            return(yes)
    if rrank == queen:
        if cards_played[ace] < 2:
            return(no)
        if cards_played[ten] < 2:
            return(no)
        if cards_played[king] < 2:
            return(no)
        else:
            return(yes)
    if rrank == jack:
        if cards_played[ace] < 2:
            return(no)
        if cards_played[ten] < 2:
            return(no)
        if cards_played[king] < 2:
            return(no)
        if cards_played[queen] < 2:
            return(no)
        else:
            return(yes)
    else:
        return(yes)


def hand_analysis(player,hand):
    init_trick()
    for card in hand:
        if suit(card) == spade:
            this_hand_spades.append(card)
        elif suit(card) == diamond:
            this_hand_diamonds.append(card)
        elif suit(card) == club:
            this_hand_clubs.append(card)
        elif suit(card) == heart:
            this_hand_hearts.append(card)
        #store counters and non -counters
        if rank(card) > queen:
            this_hand_counters.append(card)
        else:
            this_hand_losers.append(card)
        #determine which cards may take tricks
        if suit(card) == spade:
            result = check_if_top(rank(card),spades_played)
            if result == yes:
                this_hand_top_cards.append(card)
        if suit(card) == diamond:
            result = check_if_top(rank(card),diamonds_played)
            if result == yes:
                this_hand_top_cards.append(card)
        if suit(card) == club:
            result = check_if_top(rank(card),clubs_played)
            if result == yes:
                this_hand_top_cards.append(card)
        if suit(card) == heart:
            result = check_if_top(rank(card),hearts_played)
            if result == yes:
                this_hand_top_cards.append(card)
    return

def show_played_card(player,card):
    if player == south:
        return
    if player == west:
        l = Label(pframe1,image = cards[card])
        l.place(anchor = SW,  x = 0, y = card_height)
    if player == north:
        l = Label(pframe2,image = cards[card])
        l.place(anchor = SW,  x = 0, y = card_height)
    if player == east:
        l = Label(pframe3,image = cards[card])
        l.place(anchor = SW,  x = 0, y = card_height)


def clear_played_cards():
    #clear frame using a label
    l = Label(pframe1,bg="brown",fg="brown",height=card_height, width = card_width)
    l.place(anchor = NW, x=0, y=0)
    #south
    #west
    l = Label(pframe1,bg="brown",fg="brown",height=card_height, width = card_width)
    l.place(anchor = NW, x=0, y=0)
    #north
    l = Label(pframe2,bg="brown",fg="brown",height=card_height, width = card_width)
    l.place(anchor = NW, x=0, y=0)
    #east
    l = Label(pframe3,bg="brown",fg="brown",height=card_height, width = card_width)
    l.place(anchor = NW, x=0, y=0)
    return

# called from play_this_card
def save_play_stats(player,card):
    global spades_played,trick_cards,diamonds_played,clubs_played,hearts_played
    global total_spades_played,total_diamonds_played,total_clubs_played,total_hearts_played
    trick_cards[player] = card
    if suit(card) == spade:
         spades_played[rank(card)] = spades_played[rank(card)] + 1
         total_spades_played = total_spades_played + 1
    if suit(card) == diamond:
         diamonds_played[rank(card)] = diamonds_played[rank(card)] + 1
         total_diamonds_played = total_diamonds_played + 1
    if suit(card) == club:
         clubs_played[rank(card)] = clubs_played[rank(card)] + 1
         total_clubs_played = total_clubs_played + 1
    if suit(card) == heart:
         hearts_played[rank(card)] = hearts_played[rank(card)] + 1
         total_hearts_played = total_hearts_played + 1
    return

def choose_play_path(player,hand):
    global current_card
    have_trump = no
    if len(hand) == 1:
        current_card = hand[0]
        return
    if Trump == spade:
        if len(this_hand_spades) != 0:
            have_trump = yes
    if Trump == diamond:
        if len(this_hand_diamonds) != 0:
            have_trump = yes
    if Trump == club:
        if len(this_hand_clubs) != 0:
            have_trump = yes
    if Trump == heart:
        if len(this_hand_hearts) != 0:
            have_trump = yes
    if play_count == 0 and player == high_bid_player:
        leading_declarer(player,hand)
        return
    if play_count == 0:
        leading_not_declarer(player,hand)
        return
    if suit_led == spade:
        if len(this_hand_spades) != 0:
            follow_have_suit(player,hand)
            return
    if suit_led == diamond:
        if len(this_hand_diamonds) != 0:
            follow_have_suit(player,hand)
            return
    if suit_led == club:
        if len(this_hand_clubs) != 0:
            follow_have_suit(player,hand)
            return
    if suit_led == heart:
        if len(this_hand_hearts) != 0:
            follow_have_suit(player,hand)
            return
    if have_trump == yes:       
        follow_nosuit_havetrump(player,hand)
        return
    else:
        follow_nosuit_notrump(player,hand)

#set current_card = card to play
def leading_declarer(player,hand):
    global current_card
    if trump_aces != 0:
        current_card = Trump * 6 + 5
        return
    #check if trump are out and we have high trump
    if Trump == spade:
        trump_played = total_spades_played
        suit_played = spades_played
    if Trump == diamond:
        trump_played = total_diamonds_played
        suit_played = diamonds_played
    if Trump == club:
        trump_played = total_clubs_played
        suit_played = clubs_played
    if Trump == heart:
        trump_played = total_hearts_played
        suit_played = hearts_played
    trump_out = 12 - trump_played - scount[Trump]
    if trump_out > 0:
        #check if we have high trump
        for card in this_hand_top_cards:
            if suit(card) == Trump and rank(card) == ace:
                current_card = card
                return
            if suit(card) == Trump and rank(card) == ten:
                if suit_played[5] == 2: #have all aces been played?
                    current_card = card
                    return
            if suit(card) == Trump and rank(card) == king:
                if suit_played[5] == 2 and suit_played[4] == 2:
                    current_card = card
                    return
    #play aces
    for card in this_hand_top_cards:
        if rank(card) == ace:
            current_card = card
            return
    #play high cards until 2 left
    if len(this_hand_top_cards) > 2:
        for card in this_hand_top_cards:
            current_card = card
            return
    #play non-trump losers
    for card in this_hand_losers:
        if suit(card) != Trump:
            current_card = card
            return
    #play any card in hand
    current_card = hand[0]
##### temp code
#    print_stats(hand)
##### end of temp code
    return

#set current_card = card to play
def leading_not_declarer(player,hand):
    global current_card
    #play aces
    for card in this_hand_top_cards:
        if rank(card) == ace:
            current_card = card
            return
    for card in this_hand_top_cards:
        current_card = card
        return
    current_card = hand[0]
##### temp code
#    print_stats(hand)
##### end of temp code
    return

#set current_card = card to play
def follow_have_suit(player,hand):
    global current_card
    if suit_led == Trump:
        #go low if first lead of trump
        if play_count < 2:
            for card in hand:
                if suit(card) == Trump and rank(card) > rank(top_card):
                    current_card = card
                    return
        else:
            #go high if second lead of trump
            for card in this_hand_top_cards:
                if suit(card) == Trump and rank(card) > rank(top_card):
                    current_card = card
                    return
            for card in hand:
                if suit(card) == Trump:
                    current_card = card
                    return
    #trick is trumped, check who is taking
    if suit(top_card) == Trump:
        if player == north or player == south:
            if top_player == north or top_player == south:
                current_card = play_counter_have_suit()
                return
            else: 
                current_card = play_non_counter_have_suit()
                return
        if player == east or player == west:
            if top_player == east or top_player == west:
                current_card = play_counter_have_suit()
                return
            else:
                current_card = play_non_counter_have_suit()
                return
    #trick not trumped, check if we have higher card
    x = rank(top_card)

    for card in hand:
        if suit(card) == suit(top_card):
            if rank(card) > rank(top_card):
                x = rank(card)
                current_card = card
                return
    if player == north or player == south:
         if top_player == north or top_player == south:
             #play counter - have suit
             current_card = play_counter_have_suit()
             return
         else:
             #play non counter - have suit
             current_card = play_non_counter_have_suit()
             return
    if player == west or player == east:
        if top_player == west or top_player == east:
             #play counter - have suit
             current_card = play_counter_have_suit()
             return
        else:
             #play non counter - have suit
             current_card = play_non_counter_have_suit()
             return
    return

#set current_card = card to play
def follow_nosuit_havetrump(player,hand):
    global current_card
    #has this trick been trumped?
    if suit(top_card) == Trump:
        #check if we have higher trump
        for card in hand:
            if suit(card) == Trump and rank(card) > rank(top_card):
                current_card = card
                return
        #play low trump
        for card in hand:
            if suit(card) == Trump:
                current_card = card
        return
    #trick not trumped, trump it
    for card in hand:
        if suit(card) == Trump:
            current_card = card
            return
    #should never get here
    return

#set current_card = card to play
def follow_nosuit_notrump(player,hand):
    global current_card
    if player == 1 and top_player == 3:
        #play counter
        play_counter_no_suit(hand)
        return
    if player == 2 and top_player == 0:
        #play counter
        play_counter_no_suit(hand)
        return
    if player == 3 and top_player == 1:
        #play counter
        play_counter_no_suit(hand)
        return
    #play non counter
    if len(this_hand_losers) > 0:
        current_card = this_hand_losers[0]
    else:
        current_card = hand[(len(hand) - 1)]
    return

def play_counter_have_suit():
    global current_card
    if suit_led == spade:
        temp_suit = this_hand_spades
    if suit_led == diamond:
        temp_suit = this_hand_diamonds
    if suit_led == club:
        temp_suit = this_hand_clubs
    if suit_led == heart:
        temp_suit = this_hand_hearts
    aking = 100
    aten = 100
    aace = 100
    aother = 100
    for card in temp_suit:
        if rank(card) == king:
            aking = card
        if rank(card) == ten:
            aten = card
        if rank(card) == ace:
            aace = card
        if rank(card) < 3:
            aother = card
    if aking != 100:
        return(aking)
    if aten != 100:
        return(aten)
    if aother != 100:
        return(aother)
    return(aace)
            

def play_non_counter_have_suit():
    global current_card
    if suit_led == spade:
        temp_suit = this_hand_spades
    if suit_led == diamond:
        temp_suit = this_hand_diamonds
    if suit_led == club:
        temp_suit = this_hand_clubs
    if suit_led == heart:
        temp_suit = this_hand_hearts
    aking = 100
    aten = 100
    aace = 100
    aother = 100
    for card in temp_suit:
        if rank(card) == king:
            aking = card
        if rank(card) == ten:
            aten = card
        if rank(card) == ace:
            aace = card
        if rank(card) < 3:
            aother = card
    if aother != 100:
        return(aother)
    if aking != 100:
        return(aking)
    if aten != 100:
        return(aten)
    if aace != 100:
        return(aace)
#    return(temp_suit[(len(temp_suit) -1)])

def play_counter_no_suit(hand):
    global current_card
    if len(this_hand_counters) > 0:
        aking = 100
        aten = 100
        aace = 100
        aother = 100
        for card in this_hand_counters:
            if suit(card) == suit_led:
                current_card = card
                return
            if rank(card) == king:
                aking = card
            if rank(card) == ten:
                aten = card
            if rank(card) == ace:
                aace = card
            if rank(card) < 3:
                aother = card
        if aking != 100:
            current_card = aking
            return
        if aten != 100:
            current_card = aten
            return
        if aother != 100:
            current_card = aother
            return
    if len(this_hand_losers) > 0:
        current_card = this_hand_losers[0]
        return
    else:
        if len(this_hand_counters) > 0:
            current_card = this_hand_counters[0]
    return

    #play non counter
def play_loser(hand):
    global current_card
    if len(this_hand_losers) > 0:
        for card in this_hand_losers:
            if suit(card) == suit_led:
                current_card = card
                return
        current_card = this_hand_losers[0]
        return
    else:
        play_counter_no_suit(hand)
    return


def autoplay(player,hand):
    global current_card
    info(player,hand)
    hand_analysis(player,hand)
    choose_play_path(player,hand)
    play_this_card(player,hand,current_card)
#    show_south_hand()
    return

##6 status.py ##########################################################

def show_status():
    global melds_ns,melds_ew
    txt = " north/south score "+str(score_ns)+"   \n"+"east/west score "+str(score_ew)+"   "
    l = Label(frame1, text = txt,font=(NONE,18, "bold"),background="brown",foreground="white") 
    l.place(relx=0.0, rely=0.0,anchor=NW) 
    #clear area in top right
    x = 1.0
    y = 0.0
    l = Label(frame1,bg="brown",fg="brown",height=16,width=47)
    l.place(anchor = NE, relx = x , rely = y)

    if Trump != 9:
        if high_bid_player == 0:
            msg1="south"
        elif high_bid_player == 1:
            msg1="west"
        elif high_bid_player == 2:
            msg1="north"
        elif high_bid_player == 3:
            msg1="east"
    #show trump
    if Trump != 9:
        if Trump == club:
            msg2="clubs"
        elif Trump == diamond:
            msg2="diamonds"
        elif Trump == heart:
            msg2="hearts"
        elif Trump == spade:
            msg2="spades"
    #show meld
    if brief_status_display == no and Trump != 9:
#        meld_ns = melds[0] + melds[2]
#        meld_ew = melds[1] + melds[3]
        msg3 = "\nnorth/south meld="+str(meld_ns)
        msg4 = "\neast/west meld="+str(meld_ew)
        #show shoot the moon
        if shoot_moon == yes:
            msg5 = "\nMoon Shot !!"
        else:
            msg5 = ""
        #points needed by declarer
        if high_bid_player == north or high_bid_player == south:
            points_needed = high_bid - meld_ns
            if points_needed < 1:
                points_needed = 1
            msg6 = "\ncounters needed = "+str(points_needed)
        else:
            points_needed = high_bid - meld_ew
            if points_needed < 1:
                points_needed = 1
            msg6 = "\ncounters needed = "+str(points_needed)
        if ns_pointers != 0 or ew_pointers != 0:
            msg7 = "\nnorth/south took "+str(ns_pointers)
            msg8 = "\neast/west took "+str(ew_pointers)
        else:
            msg7 = ""
            msg8 = ""
    else:
        msg3 = ""
        msg4 = ""
        msg5 = ""
        msg6 = ""
        msg7 = ""
        msg8 = ""
    if Trump != 9:
        txt = msg2+" selected by "+msg1+msg3+msg4+msg5+msg6+msg7+msg8
        l = Label(frame1, text = txt,font=(NONE,18, "bold"),background="brown",foreground="white") 
        l.place(relx=1.0, rely=0.0,anchor=NE) 

#meld functions ################################################
def meld(player,hand):
    global meld_build,meld_source
    meld_build = []
    meld_source = hand[:]
    info(player,hand)
    #move 9's of trump
    if trump_nines > 0:
        meld_move([Trump*6],0) #move 9, don't force   
    #move runs
    if len(runs) > 0:
        meld_move([Trump*6+1,Trump*6+2,Trump*6+3,Trump*6+4,Trump*6+5],0)
    #move aces around
    if aces > 0:
        meld_move([5,11,17,23],0)
    #move kings around
    if kings > 0:
        meld_move([3,9,15,21],0)
    #move queens around
    if queens > 0:
        meld_move([2,8,14,20],0)
    #move jacks around
    if jacks > 0:
        meld_move([1,7,13,19],0)
    #move marriages
    index = 0
    for cnt in marriages_per_suit:
        if cnt > 0:
            meld_move([2+6*index,3+6*index],0)
        index = index + 1
    #move pinochles
    if pino > 0:
        meld_move([2,7],0)
    #force double ninies of trump
    if trump_nines == 2:
        meld_move([Trump*6],1)
    #force runs
    if len(runs) == 2:
        meld_move([Trump*6+1,Trump*6+2,Trump*6+3,Trump*6+4,Trump*6+5],1)
    #force double aces
    if aces == 2:
        meld_move([5,11,17,23],1)
    #force double kings
    if kings == 2:
        meld_move([3,9,15,21],1)
    #force double queens
    if queens == 2:
        meld_move([2,8,14,20],1)
    #force double jacks
    if jacks == 2:
        meld_move([1,7,13,19],1)
    #force double marriages
    index = 0
    for cnt in marriages_per_suit:
        if cnt == 2:
            meld_move([2+6*index,3+6*index],1)
        index = index + 1
    #force double pinochles
    if pino == 2:
        meld_move([2,7],1)
    show_meld(player,"white")
    meld_display(player)

#display cards in meld_build
def meld_display(player):
    global meld_build
    if player == south:
        return
#    if player == south:
#        fr = cframe0
#        hand = west_hand
    if player == west:
        fr = cframe1
    if player == north:
        fr = cframe2
    if player == east:
        fr = cframe3
    x=0
    for card in meld_build:
        l = Label(fr,image = cards[card])
        l.place(anchor = SW,  x = x, y = card_height)
        x = x + spacing

#move meld card to meld_build if found on meld_source and not at meld_build
#before calling first time, initialize meld_source to hand, meld_build to []
def meld_move(meld_inputs,force):
    global meld_source,meld_build
    for card in meld_inputs:
        if card in meld_source:
            if card not in meld_build or force == 1:
                meld_build.append(card)
                meld_source.remove(card)

def shoot_moon_check():
    global shoot_moon
    trump_tens = 0
    looser = 0
    if high_bid_player == south:
        return
    if high_bid_player == west:
        hand = west_hand[:]
    elif high_bid_player == north:
        hand = north_hand[:]
    else:
        hand = east_hand[:]
    info(high_bid_player,hand)
    if trump_aces != 2:
        return
    if scount[Trump] < 5:
        return #not enough trumps
    for card in hand:
        if suit(card) == Trump:
            if rank(card) == 4:
                trump_tens = trump_tens + 1
        elif rank(card) < 4:
            looser = looser + 1
    if trump_tens < 1:
        return
    if looser > 0:
        return
    shoot_moon = yes

##7 subs.py    #########################################################

def mouse_to_button():
    root.update()
    xx = frame1.winfo_x() + 438
    yy = frame1.winfo_y() + 384
    root.event_generate('<Motion>',warp=True,x=xx,y=yy)
    root.update()

def mouse_to_cards():
    root.update()
    xx = frame1.winfo_x() + 340
    yy = frame1.winfo_y() + 574
    root.event_generate('<Motion>',warp=True,x=xx,y=yy)
    root.update()

#show_meld
def show_meld(player,color):
    global melds
    if player == south:
        t0.configure(text = "meld="+str(melds[south]),fg = color)
    if player == west:
        t1.configure(text = "meld="+str(melds[west]),fg = color)
    if player == north:
        t2.configure(text = "meld="+str(melds[north]),fg = color)
    if player == east:
        t3.configure(text = "meld="+str(melds[east]),fg = color)

def clear_all_melds():
    show_meld(south,"brown")
    show_meld(west,"brown")
    show_meld(north,"brown")
    show_meld(east,"brown")

#show_max_bids
def show_max_bids(color):
    info(south,south_hand)
    t0.configure(text = "max bid="+str(max_bid[south]),fg = color)
    info(west,west_hand)
    t1.configure(text = "max_bid="+str(max_bid[west]),fg = color)
    info(north,north_hand)
    t2.configure(text = "max_bid="+str(max_bid[north]),fg = color)
    info(east,east_hand)
    t3.configure(text = "max_bid="+str(max_bid[east]),fg = color)

#count selected cards in south hand
def count_selects():
    count = 0
    for card in south_hand:
        if card > 99:
            count = count + 1
    return(count)

#clear selected flag in south hand
def clear_selects():
    global south_hand
    index = 0
    for card in south_hand:
        if card > 99:
            south_hand[index] = card - 100
        index = index + 1

#return selected card or 200 if none found,clear select of returned card
def get_next_select(remove):
    global south_hand
    indx = 0
    for card in south_hand:
        if card > 99:
            if remove == yes:
                south_hand.remove(card)
            else:
                south_hand[indx] = south_hand[indx] - 100
            card = card - 100
            return(card)
        indx = indx + 1
    return(200) #no selected cards found

#get next selected card or return -1
def get_select():
    global south_hand
    for card in south_hand:
        if card > 99:
            return(card)
    return(-1)

def clear_all_selects():
    global south_hand
    indx = 0
    for card in south_hand:
        if card > 99:
            south_hand[indx] = south_hand[indx] -100
        indx = indx + 1
           
def crt_players():
    p0.configure(text = "SOUTH",fg = "yellow")
    p1.configure(text = "WEST",fg = "yellow")
    p2.configure(text = "NORTH",fg = "yellow")
    p3.configure(text = "EAST",fg = "yellow")

def crt_clear_players():
    p0.configure(text = "")
    p1.configure(text = "")
    p2.configure(text = "")
    p3.configure(text = "")

def show_hands():
    clear_all_hand_displays()
    x=0
    y=card_height
    for card in west_hand:
        l = Label(cframe1,image = cards[card])
        l.place(anchor = SW,  x = x, y = y)
        x = x + spacing
    x=0
    for card in north_hand:
        l = Label(cframe2,image = cards[card])
        l.place(anchor = SW,  x = x, y = y)
        x = x + spacing
    x=0
    for card in east_hand:
        l = Label(cframe3,image = cards[card])
        l.place(anchor = SW,  x = x, y = y)
        x = x + spacing

def display_all_hands():
    show_hands()
    show_south_hand()

def clear_all_hand_displays():
    l = Label(cframe1,bg="brown",fg="brown",height=card_height+spacing, width = (spacing * 12)+75)
    l.place(anchor = NW, x=0, y=0)
    l = Label(cframe2,bg="brown",fg="brown",height=card_height+spacing, width = (spacing * 12)+75)
    l.place(anchor = NW, x=0, y=0)
    l = Label(cframe3,bg="brown",fg="brown",height=card_height+spacing, width = (spacing * 12)+75)
    l.place(anchor = NW, x=0, y=0)

def clear_south_hand():
    #clear frame using a label
    l = Label(cframe0,bg="brown",fg="brown",height=card_height+spacing, width = (spacing * 16)+75)
    l.place(anchor = NW, x=0, y=0)

def show_south_hand():
    clear_south_hand()
    #place card images in cframe0
    x=0
    y=card_height+spacing
    for card in south_hand:
        if card > 99:
            card = card - 100
            l = Label(cframe0,image = cards[card])
            l.place(anchor = SW,  x = x, y = y-spacing)
        else:
            l = Label(cframe0,image = cards[card])
            l.place(anchor = SW,  x = x, y = y)
        x = x + spacing

def suit(card):
    return(int(card/6))

def rank(card):
    return(card % 6)

def remove_dups(xs):
    """ Return a new list in which all adjacent
        duplicates from xs have been removed.
    """
    global dups,nodups
    nodups = []
    dups = []
    most_recent_elem = None
    for e in xs:
        if e != most_recent_elem:
            nodups.append(e)
            most_recent_elem = e
        else:
            dups.append(e)    

##8 info.py ############################################################

def build_ranks(player,hand):
    global clubranks,diamondranks,heartranks,spaderanks
    global total_aces,svalue,scount
    clubranks = []
    diamondranks = []
    heartranks = []
    spaderanks = []
    for card in hand:
        if suit(card) == spade:
            spaderanks.append(rank(card))
        elif suit(card) == diamond:
            diamondranks.append(rank(card))
        elif suit(card) == club: #clubs
            clubranks.append(rank(card))
        elif suit(card) == heart:
            heartranks.append(rank(card))
        svalue[suit(card)] = svalue[suit(card)] + rank(card)
        scount[suit(card)] = scount[suit(card)] + 1
        if rank(card) == 5:
            total_aces = total_aces + 1

def run_check(x):
    match = 0
    if 1 in x:
        match = match + 1
    if 2 in x:
        match = match + 1
    if 3 in x:
        match = match + 1
    if 4 in x:
        match = match + 1
    if 5 in x:
        match = match + 1
    return match

#check for j,q,k,ace around in clubranks,diamondranks,heartranks,spaderanks
#output - dups & nodups have suits that matched
def around(rank):
    global nodups, dups
    nodups = []
    dups = []
    count = 0
    for x in clubranks:
        if x == rank and count == 0:
            nodups.append(0)
            count = count + 1
        else:
            if x == rank and count == 1:
                dups.append(0)
    count = 0    
    for x in diamondranks:
        if x == rank and count == 0:
            nodups.append(1)
            count = count + 1
        else:
            if x == rank and count == 1:
                dups.append(1)
    count = 0
    for x in heartranks:
        if x == rank and count == 0:
            nodups.append(2)
            count = 1
        else:
            if x == rank and count == 1:
                dups.append(2)
    count = 0
    for x in spaderanks:
        if x == rank and count == 0:
            nodups.append(3)
            count = 1
        else:
            if x == rank and count ==1:
                dups.append(3)

def info(player,hand):
    global clubranks,diamondranks,heartranks,spaderanks
    global svalue,scount
    global runs,runh,aces,aceh,kings,kingh,queens,queenh,jacks,jackh
    global marriage_points,total_aces,meld_sel,trump_sel,trump_aces
    global marriages_per_suit
    global pino,pinoh,half_pino
    global trump_nines,max_bid,trumps,melds,last_bid
    clubranks = []
    diamondranks = []
    heartranks = []
    spaderanks = []
    svalue = [0,0,0,0] #clear suit value sum
    scount = [0,0,0,0] #clear suit card count
    runs = [] #suit list
    runh = [] #suits with 4 out of 5 run cards
    aces = 0 #count 0,1,2 of aces around
    aceh = 0 #count 0,1,2 of 3ace holes
    kings = 0
    kingh = 0
    queens = 0
    queenh = 0
    jacks = 0
    jackh = 0
    marriage_points = 0
    marriages_per_suit = []
    total_aces = 0
    pino = 0
    pinoh = 0
    half_pino = 0 # 1=diamonds 3=spades
    max_bid[player] = 0
    trump_sel = 0 #this hands trump choice
    trump_nines = 0 #
    trump_aces = 0
    meld_sel = 0 # this hands meld
#build rank list by suit & total value by suit  &  card count by suit
    build_ranks(player,hand)
#look for runs and partial runs
    for suitx in [club,diamond,heart,spade]:
        if suitx == club:
            ranks = clubranks[:]
        elif suitx == diamond:
            ranks = diamondranks[:]
        elif suitx == heart:
            ranks = heartranks[:]
        elif suitx == spade:
            ranks = spaderanks[:]
        remove_dups(ranks)
        nodup_match = run_check(nodups)
        dup_match = run_check(dups)
        if nodup_match == 5 and (Trump == 9 or Trump == suitx):
            runs.append(suitx)
        if nodup_match == 4 and (Trump == 9 or Trump == suitx):
            runh.append(suitx)
        if dup_match == 5 and (Trump == 9 or Trump == suitx):
            runs.append(suitx)
        if dup_match == 4 and (Trump == 9 or Trump == suitx):
            runh.append(suitx)
#select trump
    if Trump != 9:
        trump_sel = Trump #trump already set
    else:
        #select trump for this hand
        loop = 0
        while loop == 0:
            if len(runs) == 2:
                if svalue[runs[0]] >= svalue[runs[1]]:
                    trump_sel = runs[0]
                    break
                else:
                    trump_sel = runs[1]
                    break
            elif len(runs) == 1:
                trump_sel = runs[0]
                break
            elif len(runh) == 1:
                trump_sel = runh[0]
                break
#look for longest suit in scount
            else:
                trump_sel = max(scount)  # trial trump
                temp = []
                count = 0
                for x in scount:
                    if x == trump_sel:
                        temp.append(count)
                    count = count + 1
                if len(temp) == 1:
                    trump_sel = temp[0]
                    break
                if svalue[temp[0]] > svalue[temp[1]]:
                    trump_sel = temp[0]
                    break
                else:
                    trump_sel = temp[1]
                    break
        trumps[player] = trump_sel
#check for arounds and around holes
    for cardx in [jack,queen,king,ace]:
        around(cardx)
        if cardx == jack:
            if len(nodups) == 4:
                jacks = 1
            if len(dups) == 4:
                jacks = 2
            if len(nodups) == 3:
                jackh = 1
            if len(dups) == 3:
                jackh = 1
        if cardx == queen:
            if len(nodups) == 4:
                queens = 1
            if len(dups) == 4:
                queens = 2
            if len(dups) == 3:
                queenh = 1
            if len(nodups) == 3:
                queenh = 1
        if cardx == king:
            if len(nodups) == 4:
                kings = 1
            if len(dups) == 4:
                kings = 2
            if len(nodups) == 3:
                kingh = 1
            if len(dups) == 3:
                kingh = 1
        if cardx == ace:
            if len(nodups) == 4:
                aces = 1
            if len(dups) == 4:
                aces = 2
            if len(nodups) == 3:
                aceh = 1
            if len(dups) == 3:
                aceh = 1
#count trump nines and aces
    if trump_sel == club:
        temp = clubranks[:]
    elif trump_sel == diamond:
        temp = diamondranks[:]
    elif trump_sel == heart:
        temp = heartranks[:]
    else:
        temp = spaderanks[:]
        
    for card in temp:
        if card == nine:
            trump_nines = trump_nines + 1
        elif card == ace:
            trump_aces = trump_aces + 1
#get pinochle info
    dj = 0
    sq = 0
    for card in diamondranks:
        if card == jack:
            dj = dj + 1
    for card in spaderanks:
        if card == queen:
            sq = sq + 1
    if dj > 0 and sq > 0:
        pino = 1
        sq = sq -1
        dj = dj -1
    if dj > 0 and sq > 0:
        pino = 2
        sq =0
        dj = 0
    while dj > 0:
        pinoh = pinoh +1
        dj = dj -1
    while sq > 0:
        pinoh = pinoh + 1
        sq = sq -1
    if dj == 1:
        half_pino = 1
    elif sq == 1:
        half_pino = 3

# get value of marriages
    qq = 0 #count queens
    kk = 0 #count kings
    mcount = 0
    for card in spaderanks:
        if card == 2:
            qq = qq + 1
        elif card == 3:
            kk = kk + 1
    while kk > 0 and qq > 0:
        mcount = mcount + 1
        kk = kk -1
        qq = qq -1
    marriages_per_suit.append(mcount)
    if trump_sel == spade:
        mcount = mcount * 2
    marriage_points = marriage_points + mcount * 2

    qq = 0 #count queens
    kk = 0 #count kings
    mcount = 0
    for card in diamondranks:
        if card == queen:
            qq = qq + 1
        elif card == king:
            kk = kk + 1
    while kk > 0 and qq > 0:
        mcount = mcount + 1
        kk = kk -1
        qq = qq -1
    marriages_per_suit.append(mcount)
    if trump_sel == diamond:
        mcount = mcount * 2
    marriage_points = marriage_points + mcount * 2

    qq = 0 #count queens
    kk = 0 #count kings
    mcount = 0
    for card in clubranks:
        if card == queen:
            qq = qq + 1
        elif card == king:
            kk = kk + 1
    while kk > 0 and qq > 0:
        mcount = mcount + 1
        kk = kk -1
        qq = qq -1
    marriages_per_suit.append(mcount)
    if trump_sel == club:
        mcount = mcount * 2
    marriage_points = marriage_points + mcount * 2

    qq = 0 #count queens
    kk = 0 #count kings
    mcount = 0
    for card in heartranks:
        if card == 2:
            qq = qq + 1
        elif card == 3:
            kk = kk + 1
    while kk > 0 and qq > 0:
        mcount = mcount + 1
        kk = kk -1
        qq = qq -1
    marriages_per_suit.append(mcount)
    if trump_sel == heart:
        mcount = mcount * 2
    marriage_points = marriage_points + mcount * 2
        
#compute meld for this hand
    meld_sel = 0
    if len(runs) == 2:
        meld_sel = meld_sel + 146 #kludge, marriages counted seperatly
    elif len(runs) == 1:
        meld_sel = meld_sel + 11
    if aces == 2:
        meld_sel = meld_sel + 100
    elif aces == 1:
        meld_sel = meld_sel + 10
    if kings == 2:
        meld_sel = meld_sel + 80
    elif kings == 1:
        meld_sel = meld_sel + 8
    if queens == 2:
        meld_sel = meld_sel + 60
    elif queens == 1:
        meld_sel = meld_sel + 6
    if jacks == 2:
        meld_sel = meld_sel + 40
    elif jacks == 1:
        meld_sel = meld_sel + 4
    if pino == 2:
        meld_sel = meld_sel + 30
    elif pino == 1:
        meld_sel = meld_sel + 4
    meld_sel = meld_sel + marriage_points + trump_nines
    melds[player] = meld_sel

#max bid = meld + holes + trumplength + total aces + trump aces
    
    max_bid[player] = meld_sel  # init max_bid

    if len(runs)  == 0 and len(runh) > 0:
        max_bid[player] = max_bid[player] + 15
    if aceh > 0:
        max_bid[player] = max_bid[player] + 10
#    if kingh > 0:
#        max_bid[player] = max_bid[player] + 4
    if queenh > 0:
        max_bid[player] = max_bid[player] + 2
#    if jackh > 0:
#        max_bid[player] = max_bid[player] + 2
    if pinoh > 0:
        max_bid[player] = max_bid[player] + 2
        if pino == 1:
            max_bid[player] = max_bid[player] + 5
    max_bid[player] = max_bid[player] + total_aces * 2
    max_bid[player] = max_bid[player] + trump_aces *4
    max_bid[player] = max_bid[player] + scount[trump_sel] #length of trump suit
    if max_bid[player] > 40:
        max_bid[player] = max_bid[player] - 3
    if max_bid[player] < 25:
        max_bid[player] = max_bid[player] + 2


    #print for debug

#### init

def init_trick():
    global this_hand_spades,this_hand_diamonds,this_hand_clubs,this_hand_hearts
    global this_hand_counters,this_hand_losers,this_hand_top_cards
    this_hand_spades = []
    this_hand_diamonds = []
    this_hand_clubs = []
    this_hand_hearts = []
    this_hand_counters = []
    this_hand_losers = []
    this_hand_top_cards = []
    return

def init_hand():
    global high_bid_plalyer,high_bid,Trump,Brief_status_displaly,pass_count
    global shoot_moon,last_bid,max_bid,meld_ns,meld_ew,melds
    global trick_cards,cards_taken_ns,cards_taken_ew,spades_played,diamonds_played
    global clubs_played,hearts_played,total_spades_played,total_diamonds_played
    global total_clubs_played,total_hearts_played,suit_led,player_leading
    global ns_pointers,ew_pointers
    high_bid_player = deal_posn #default dealer bids 25
    high_bid = 25 #starting bid
    Trump = 9 #initialize trump to not defined
    brief_status_display = yes
    pass_count = 0
    shoot_moon = no
    last_bid = [25,25,25,25] #0=passed
    max_bid = [0,0,0,0]
    meld_ns = 0
    meld_ew = 0
    melds = [0,0,0,0]
    #history data
    trick_cards = [9,9,9,9] #cards played for this trick, 9=none
    cards_taken_ns = []
    cards_taken_ew = []
    spades_played = [0,0,0,0,0,0] #9,j,q,k,10,a  each with count of 0,1,2
    diamonds_played = [0,0,0,0,0,0]
    clubs_played = [0,0,0,0,0,0]
    hearts_played = [0,0,0,0,0,0]
    total_spades_played = 0
    total_diamonds_played = 0
    total_clubs_played = 0
    total_hearts_played = 0
    suit_led = 9
    player_leading = 9
    ns_pointers = 0
    ew_pointers = 0

##9 table.py   #########################################################
# control array/table for windows
#  format of table is  [window_open_function, window_close_function, win_type]
#                      win_type -- 0=sequential  1=bid loop  2=4card trick loop  3=12trick hand  4=game restart
DoWait = yes
NoWait = no
ctrl =(\
["pinoche",DoWait,open00,cback1_00,about,testm,quit_now," start ","about","     ","quit",win00_close],  #00
["shuffling",NoWait,open01,dummy,dummy,dummy,dummy,"     ","     ","     ","    ",win01_close], #01
["dealing",NoWait,open02,dummy,dummy,dummy,dummy,"      ","     ","     ","     ",win02_close], #02
["South bid",DoWait,open03,cback1_03,cback2_03,cback3_03,cback4_03,"pass","bid+","bid-","submit",win03_close], #03
["West bid",NoWait,open04,dummy,dummy,dummy,dummy,"      ","     ","     ","     ",win04_close], #04
["North bid",NoWait,open05,dummy,dummy,dummy,dummy,"      ","     ","     ","     ",win05_close], #05
["East bid",NoWait,open06,dummy,dummy,dummy,dummy,"      ","     ","     ","     ",win06_close], #06
["_____ won bid",DoWait,open07,cback1_07,dummy,testm,quit_now,"continue","     ","     ","quit",win07_close], #07
["West card exchange",DoWait,open08,cback1_08,dummy,testm,quit_now,"continue","     ","     ","quit",win08_close], #08
["East card exchange",DoWait,open09,cback1_09,dummy,testm,quit_now,"continue","     ","     ","quit",win09_close], #09
["select North cards",DoWait,open10,cback1_10,dummy,testm,quit_now,"    ","     ","     ","quit",win10_close], #10
["Select trump",DoWait,open11,cback1_11,cback2_11,cback3_11,cback4_11,"club","diamond","heart","spade",win11_close], #11
["North cards sent",DoWait,open12,cback1_12,dummy,testm,quit_now,"continue","     ","     ","quit",win12_close], #12
["Select xchg cards",DoWait,open13,cback1_13,dummy,testm,quit_now,"     ","     ","    ","quit",win13_close], #13
["Meld",DoWait,open14,cback1_14,dummy,cback3_14,quit_now,"continue","     ","     ","quit",win14_close], #14
["play card",DoWait,open15,cback1_15,dummy,testm,quit_now,"     ","     ","     ","quit",win15_close], #15
["Play West",NoWait,open16,dummy,dummy,dummy,dummy,"     ","     ","     ","     ",win16_close], #16
["Play North",NoWait,open17,dummy,dummy,dummy,dummy,"     ","     ","     ","     ",win17_close], #17
["Play East",NoWait,open18,dummy,dummy,dummy,dummy,"     ","     ","     ","     ",win18_close],  #18
["trick don",DoWait,open19,cback1_19,dummy,testm,quit_now,"continue","     ","     ","quit",win19_close], #19
["scoring  ",DoWait,open20,cback1_20,dummy,testm,quit_now,"continue","     ","     ","quit",win20_close], #20
["show winner",DoWait,open21,cback1_21,dummy,testm,quit_now,"continue","     ","     ","quit",win21_close], #21
["another game?",DoWait,open22,cback1_22,dummy,dummy,quit_now,"continue","     ","     ","quit",win22_close], #22
)

##m main.py    #########################################################

deck = []
with open("image/deck.txt", 'r') as f:
    for line in f:
        deck.append(int(line.strip()))

root.bind("<Button-1>", mouse)

ctrl_index = 0
saved_ctrl_index = 0
while quit_game == 0:
    show_status()
    if testing == yes:
        show_hands()
    saved_index = ctrl_index
    c1.configure(text = ctrl[saved_index][ctitle],fg="yellow")
    button1.configure(command=ctrl[saved_index][cback1])
    button2.configure(command=ctrl[saved_index][cback2])
    button3.configure(command=ctrl[saved_index][cback3])
    button4.configure(command=ctrl[saved_index][cback4])
    button1.configure(text=ctrl[saved_index][cback1_txt])
    button2.configure(text=ctrl[saved_index][cback2_txt])
    button3.configure(text=ctrl[saved_index][cback3_txt])
    button4.configure(text=ctrl[saved_index][cback4_txt])
    ctrl[saved_index][copen]()
    event_wait = ctrl[saved_index][cflag]  #get win type 0=normal 1=keep going   
    if event_wait == yes:
        while event_wait == yes:
            root.update()
            time.sleep(slowdown)
    else:
        root.update()
        time.sleep(slowdown)
    ctrl[saved_index][cclose]()
    if quit_game != 0:
        break
    slowdown = 0.4

with open("image/deck.txt", 'w') as f:
    for s in deck:
        f.write(str(s) + '\n')
root.quit()

#root.destroy()

