#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Posts
    5
    Rep Power
    0

    Program wont run, no errors given


    I'm making graphic version of ****head card game. I've completed the textual version first with succes, and now implemented most of the code from that in my GUI version. But my program wint start, when i compile it, python shell opens and does nothing.

    Here is my code:

    Code:
    from Tkinter import *
    from PIL import Image, ImageTk
    import random
    
    #Velicina ekrana
    HEIGHT = 960
    WIDTH = 1280
    
    
    #Dimenzije karata
    CARD_SIZE = (73, 98)
    CARD_BACK_SIZE = (71, 96)
    
    #Koordinate pozicija
    PLAYING_POS = (WIDTH/2,HEIGHT/2)
    DECK_POS = (WIDTH-100,HEIGHT/2)
    
    PLAYER_POS = (WIDTH/4,HEIGHT-150)
    KOMP_POS = (WIDTH/4,200)
    KOMP2_POS = (130,HEIGHT/4)
    KOMP3_POS = (WIDTH-130,HEIGHT/4)
    
    PLAYER_POS2 = (WIDTH/2,HEIGHT-100)
    KOMP_POS2 = (WIDTH/4,100)
    KOMP2_POS2 = (80,HEIGHT/4)
    KOMP3_POS2 = (WIDTH-80,HEIGHT/4)
    
    
    #Karte
    SUITS = ['C', 'S', 'H', 'D']
    RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
    VALUE = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'J':10, 'Q':11, 'K':12, 'A':13, '10':14}
    
    #Ostale varijable
    klik=0
    thrown_cards=[]
    
    class Cards:
        def __init__(self,suit,rank):
            self.suit = suit
            self.rank = rank
            self.karta = None
    
       
        def draw(self,position):
            CARD = Image.open ("cards.png")
            box = [RANKS.index(self.rank) * CARD_SIZE[0], SUITS.index(self.suit) * CARD_SIZE[1], CARD_SIZE[0] * (RANKS.index(self.rank)+1) , CARD_SIZE[1] * (SUITS.index(self.suit)+1)]
            cropped = CARD.crop(box)
            self.karta = ImageTk.PhotoImage(cropped)
            canvas.create_image(position, image=self.karta)
    
        def draw_back(self,position):    
            CB=Image.open("card_back.png")
            self.karta = ImageTk.PhotoImage(CB)
            canvas.create_image(position, image=self.karta)
    
        def draw_r(self,position):
            CARD = Image.open ("cards.png")
            box = [RANKS.index(self.rank) * CARD_SIZE[0], SUITS.index(self.suit) * CARD_SIZE[1], CARD_SIZE[0] * (RANKS.index(self.rank)+1) , CARD_SIZE[1] * (SUITS.index(self.suit)+1)]
            cropped = CARD.crop(box)
            rotated = cropped.rotate(90)
            self.karta = ImageTk.PhotoImage(rotated)
            canvas.create_image(position, image=self.karta)
    
        def draw_back_r(self,position):    
            CB=Image.open("card_back.png")
            CBR = CB.rotate(90)
            self.karta = ImageTk.PhotoImage(CBR)
            canvas.create_image(position, image=self.karta)
            
    
    class Deck:
        def __init__(self):
            self.deck_list = []
            # standard 52 card deck
            global SUITS
            global RANKS
            for s in SUITS:
                for r in RANKS:
                    self.deck_list.append(Cards(s, r))            
    
        def shuffle(self):
            return random.shuffle(self.deck_list)
    
        def draw_card(self):
            return self.deck_list.pop(0)
        
        def draw(self):
            for c in self.deck_list:
                c.draw_back(DECK_POS)
    
    
    class Hand:
        def __init__(self ):
            self.card_list=[]
            self.card_list2=[]
            self.card_list3=[]
        
        def add_card(self,card):
            self.card_list.append(card)
        def add_card2(self,card):
            self.card_list2.append(card)
        def add_card3(self,card):    
            self.card_list3.append(card)
    
        def vuci_kartu(self):
            if len(deck.deck_list) > 0 and len(self.card_list) < 3:
                self.card_list.append(deck.draw_card())
                
        def izaberi_kartu(self):
            self.choices = []
            if len(thrown_cards) > 0:
                if len(self.card_list) > 0:
                    for c in self.card_list:
                        if VALUE[c.rank] >= VALUE[thrown_cards[-1].rank] or VALUE[c.rank] == "2":
                            self.choices.append(c)
                elif len(self.card_list) == 0 and len(self.card_list2) > 0:
                    for c in self.card_list2:
                        if VALUE[c.rank] >= VALUE[thrown_cards[-1].rank] or c.rank == "2":
                            self.choices.append(c)
                else:
                    self.choices.append(random.choice(self.card_list3))
                self.choices.sort()
            else:
                if len(self.card_list) > 0:
                    self.card_list.sort()
                    self.choices.append(self.card_list[0])
                elif len(self.card_list) == 0 and len(self.card_list2) > 0:
                    self.card_list2.sort()
                    self.choices.append(self.card_list2[0])
                else:
                    self.choices.append(random.choice(self.card_list3))        
    
        def baci_kartu(self):
            global thrown_cards
            if len(self.choices) > 0:
                self.choices.sort()
                thrown_cards.append(self.choices[0])
                if len(self.card_list) > 0:
                    del self.card_list[self.card_list.index(self.choices[0])]
                elif len(self.card_list) == 0 and len(self.card_list2) > 0:
                    del self.card_list2[self.card_list2.index(self.choices[0])]
                else:
                    if len(thrown_cards) > 0:
                        if VALUE[self.choices[0].rank] >= VALUE[thrown_cards[-1].rank] or VALUE[self.choices[0].rank] != "2":
                            del self.card_list3[self.card_list3.index(self.choices[0])]
                        else:
                            del self.card_list3[self.card_list3.index(self.choices[0])]
                            self.card_list.extend(thrown_cards)
                            thrown_cards = []
                    else:
                        del self.card_list3[self.card_list3.index(self.choices[0])]
            else:
                self.card_list.extend(thrown_cards)
                thrown_cards = []
    
            
        def draw(self,position):
            pos = list(position)
            for c in self.card_list:
                    c.draw(pos)
                    pos[0] += CARD_SIZE[0]/3
                    
        def draw2(self,position):
            pos = list(position)
            for c in self.card_list3:
                    c.draw_back(pos)
                    pos[0] += CARD_SIZE[0]/3
    
        def draw3(self,position):
            pos = list(position)
            for c in self.card_list2:
                    c.draw(pos)
                    pos[0] += CARD_SIZE[0]/3
                    
        def draw_komp(self,position):
            pos = list(position)
            for c in self.card_list:
                    c.draw_back(pos)
                    pos[0] += CARD_SIZE[0]/3
                    
        def draw_komp_rotated(self,position):
            pos = list(position)
            for c in self.card_list:
                    c.draw_back_r(pos)
                    pos[0] += CARD_SIZE[0]/3
    
        def draw_komp_rotated2(self,position):
            pos = list(position)
            for c in self.card_list2:
                    c.draw_r(pos)
                    pos[0] += CARD_SIZE[0]/3
        
                    
    class Game:
        def __init__(self):
            global deck,igrac,igrac1,igrac2,igrac3
            deck = Deck()
            deck.shuffle()
            self.count = 4
            self.current_player = 0
            (igrac, igrac1, igrac2, igrac3) = (deal(deck) for i in 'abcd')
            
        def next_turn(self):
            self.current_player += 1
            self.current_player %= self.count
    
        def is_10(self):
            global thrown_cards
            if len(thrown_cards) > 0:
                if thrown_cards[-1].rank ==  "10":
                    thrown_cards = []
                    self.current_player -= 1
                    self.current_player %= self.count
    
        def iste4(self):
            global thrown_cards
            if len(thrown_cards) > 3:
                if thrown_cards[-1] == thrown_cards[-2] == thrown_cards[-3] == thrown_cards[-4]:
                    thrown_cards = []
                    self.current_player -= 1
                    self.current_player %= self.count
        
        def is_valid(self,card):
            if len(thrown_cards) > 0:
                if VALUE[card.rank] >= VALUE[thrown_cards[-1].rank] or card.rank == "2":
                    valid = True
                else:
                    valid = False
            else:
                valid = True
    
        def play(self):
            while True:      
                if self.current_player == 1:
                    igrac1.izaberi_kartu()
                    igrac1.baci_kartu()
                    igrac1.vuci_kartu()
                    self.next_turn()
                    self.is_10()
                    self.iste4()
                elif self.current_player == 2:
                    igrac2.izaberi_kartu()
                    igrac2.baci_kartu()
                    igrac2.vuci_kartu()
                    self.next_turn()
                    self.is_10()
                    self.iste4()
                elif self.current_player == 3:
                    igrac3.izaberi_kartu()
                    igrac3.baci_kartu()
                    igrac3.vuci_kartu()
                    self.next_turn()
                    self.is_10()
                    self.iste4()
                    
        def moj_red(self,kliknuta_karta):
            if self.current_player == 0:
                self.is_valid(kliknuta_karta)
                if valid:
                    thrown_cards.append(kliknuta_karta)
                    del igrac.card_list[klik]                    
                    igrac.vuci_kartu()
                    self.next_turn()
                    self.is_10()
                    self.iste4()
    
    
    def deal(deck):
        igrac = Hand()
        for f in (igrac.add_card, igrac.add_card2, igrac.add_card3):
            for i in 'abc':
                f(deck.draw_card())
        return igrac
    
    
    
    def grafika():
        while True:
            canvas.delete(ALL)
            deck.draw()
            igrac.draw(PLAYER_POS)
            igrac.draw2(PLAYER_POS2)
            igrac.draw3(PLAYER_POS2)
            igrac1.draw_komp(KOMP_POS)
            igrac1.draw2(KOMP_POS2)
            igrac1.draw3(KOMP_POS2)
            igrac2.draw_komp_rotated(KOMP2_POS)
            igrac2.draw_komp_rotated2(KOMP2_POS2)
            igrac2.draw3(KOMP2_POS2)
            igrac3.draw_komp_rotated(KOMP3_POS)
            igrac3.draw_komp_rotated2(KOMP3_POS2)
            igrac3.draw3(KOMP3_POS2)
            if len(thrown_cards)>0:
                thrown_cards[-1].draw(PLAYING_POS)
    
    def click(event):
        global klik
        klik = (event.x-PLAYER_POS[0]-36) //(CARD_SIZE[0]//3)
        if (len(igrac.card_list) == 0) and (len(igrac.card_list2) == 0) and (HEIGHT-148 < event.y < HEIGHT-52):
            kliknuta_karta = (igrac.card_list3[klik])
            kajla.moj_red(kliknuta_karta)
        elif (len(igrac.card_list) == 0) and (len(igrac.card_list2) > 0) and (HEIGHT-148 < event.y < HEIGHT-52):
            kliknuta_karta = (igrac.card_list2[klik])
            kajla.moj_red(kliknuta_karta)
        elif (HEIGHT-198 < event.y < HEIGHT-102):
            kliknuta_karta = (igrac.card_list[klik])
            kajla.moj_red(kliknuta_karta)
    
    
    
    def key(event):
        msg=int(event.keysym)
        if len(igrac.card_list) > 0 :
            kliknuta_karta = (igrac.card_list[msg-1])        
            kajla.moj_red(kliknuta_karta)
        elif (len(igrac.card_list) == 0) and (len(igrac.card_list2) > 0):
            kliknuta_karta = (igrac.card_list2[msg-1])        
            kajla.moj_red(kliknuta_karta)
        else:
            kliknuta_karta = (igrac.card_list3[msg-1])        
            kajla.moj_red(kliknuta_karta)
        
    
    root=Tk()
    
    kajla = Game()
    kajla.play()
    
    canvas = Canvas(root,height=100,width=100)
    canvas.pack()
    
    root.bind("<Key>",key)
    root.bind("<Button-1>",click)
    
    grafika()
    
    root.mainloop()
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,837
    Rep Power
    480
    Each time I see this my conclusion remains constant. There's no connection between game play and the graphics.
    Code:
    root=Tk()
    
    kajla = Game()
    kajla.play()   ####### play the entire game
    
    canvas = Canvas(root,height=100,width=100)  # now show something graphical
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Posts
    475
    Rep Power
    33
    And the play() function in Game does nothing as is (there is a hint). Add some print statements to see what is and is not happening.

    Comments on this post

    • b49P23TIvg agrees : Aaaah!
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Posts
    5
    Rep Power
    0
    I thought I connected game and graphics with function grafika()...

    However, shouldn't the canvas screen still appeard, even if game and graphics aren't connected?
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Posts
    475
    Rep Power
    33
    The canvas is not shown until mainloop() is called. It comes after grafika, which has a while True which is never exited, so I assume that you use a Control->C to exit the program so mainloop() is never called, etc.
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Posts
    475
    Rep Power
    33
    The following is a Tic-Tac-Toe game which may help with the logic and flow. Note that you can display an image with a button or label in addition to a canvas.
    Code:
    from Tkinter import *
    from functools import partial
    
    class TicTacToe:
       def __init__(self):
          self.top = Tk()
          self.top.geometry("150x145+10+10")
          self.button_dic = {}     ## pointer to buttons and StringVar()
          self.X_O_dict = {"X":[], "O":[]}  ## list of "X" and "O" moves
          self.top.title('Buttons TicTacToe Test')
          self.top_frame = Frame(self.top, width =500, height=500)
          self.buttons()
    
          self.top_frame.grid(row=0, column=1, sticky="WE")
          for ctr in range(0, 3):   ## configure all columns to the same size
             self.top_frame.grid_columnconfigure(ctr, minsize=50)
             self.top_frame.grid_rowconfigure(ctr, minsize=37)
    
          exit = Button(self.top_frame, text='Exit', \
                 command=self.top.quit).grid(row=10,column=0, columnspan=5)
    
          self.done=False  ## eliminate entry after win or loss
          self.player = True   ## True = "X", False = "O"
    
          self.top.mainloop()
    
       ##-------------------------------------------------------------------         
       def buttons(self):
          """ create 9 buttons, a 3x3 grid
          """
    
          b_row=0
          b_col=0
          for j in range(1, 10):
             sv=StringVar()
             sv.set(j)
             b = Button(self.top_frame, textvariable=sv, \
                        command=partial(self.cb_handler, j), bg='white')
             b.grid(row=b_row, column=b_col, sticky="WENS")
             self.button_dic[j]=[sv, b] ## button number-->(StringVar, Tkinter ID)
    
             b_col += 1
             if b_col > 2:
                b_col = 0
                b_row += 1
    
       ##----------------------------------------------------------------
       def cb_handler(self, square_number):
          player = "O"                       ## True = "X", False = "O"
          if self.player:
             player = "X"
    
          ##--- square not already occupied
          if square_number not in self.X_O_dict["X"] and \
             square_number not in self.X_O_dict["O"]:
    
             ## change button's text to "X" or "O"
             self.button_dic[square_number][0].set(player)
             self.X_O_dict[player].append(square_number)
    
             ## set background to already chosen
             self.button_dic[square_number][1].config(bg="lightgray")
             self.check_for_winner(self.X_O_dict[player])
             self.player = not self.player
          else:
             print "Occupied, pick another"
    
       ##----------------------------------------------------------------
       def check_for_winner( self, list_in ):
    
          winner_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], \
                         [1, 4, 7], [2, 5, 8], [3, 6, 9], \
                         [1, 5, 9], [3, 5, 7]]
          set_in=set(list_in)
          for winner in winner_list:
             if set(winner).issubset(set_in):
                if self.player:
                    self.display_and_exit('*** "X" Is A Winner ***')
                else:
                    self.display_and_exit('*** "O" Is A Winner ***')
    
          for square_number in range(1, 10):  ## check for all squares occupied
             if square_number not in self.X_O_dict["X"] and \
                square_number not in self.X_O_dict["O"]:
                return      ## not occupied
    
          ## no 'return' = all occupied
          self.display_and_exit("*****TIE*****")
    
       ##----------------------------------------------------------------
       def display_and_exit(self, msg_in):
           """ display the message passed in a pop-up box for self.ctr secs
           """
           if not self.done:     # eliminate multiple clicks
               self.done=True
               tl=Toplevel(self.top, takefocus=True)
               lb=Label(tl)
               lb.grid()
               self.ctr = 5
    
               def update_counter():
                   lb.configure(text=msg_in+"\n %d" %(self.ctr))
                   self.ctr -= 1
                   if self.ctr > -1:
                       lb.after(1000, update_counter)
                   else:
                       self.top.quit()
    
               update_counter()
           
    ##===================================================================
    BT=TicTacToe()
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Posts
    1
    Rep Power
    0
    thanxsssssssssss

IMN logo majestic logo threadwatch logo seochat tools logo