Advertisement
furas

Python - Tkinter - Fifteen

Jan 6th, 2016
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Dora Jambor, dorajambor@gmail.com
  2. # January, 2016
  3. # Implementation of the game fifteen in Python
  4.  
  5. #import time, pdb
  6. from Tkinter import *
  7.  
  8. # ---------- parameters ----------
  9.  
  10. # Dimensions
  11. min_dim = 3
  12. max_dim = 9
  13.  
  14. # Board elements
  15. d = 0
  16. board = []
  17. counter = 0
  18.  
  19. # Location of blank space
  20. blankx = 0
  21. blanky = 0
  22.  
  23. # ---------- functions ----------
  24.  
  25. def greet():
  26.     print 'This is the Game of Fifteen!'
  27.  
  28. def dim():
  29.     # global d # if you use "return" you don't need access to global variable.
  30.                # you can even use different name - for example `result`.
  31.    
  32.     result = int(raw_input('Insert the dimension of the board: '))
  33.    
  34.     while True:
  35.         if result >=min_dim and result <= max_dim:
  36.             break
  37.         result = int(raw_input('Try again: '))
  38.        
  39.     return result
  40.  
  41. # Initialize the board
  42. '''
  43. This fills up the two-dimensional board[][] list with numbers ascending
  44. from the inputted dimension to 1
  45. '''
  46. def setup():
  47.     global blankx, blanky, game_running
  48.  
  49.     # set or reset all data and variables
  50.     # without creating board and buttons
  51.  
  52.     # label is now invisible
  53.     label.lower()
  54.    
  55.     # set blank
  56.     blankx = d - 1
  57.     blanky = d - 1
  58.  
  59.     # fill board with numbers - it changes buttons too
  60.     # StringVar requires the use of get() and set()
  61.    
  62.     numbers = d * d
  63.  
  64.     for row in board:
  65.         for string_var in row:
  66.  
  67.             numbers -= 1
  68.  
  69.             if numbers == 0:
  70.                 string_var.set(' ')
  71.             else:
  72.                 string_var.set(str(numbers))
  73.  
  74.     # set other variables
  75.     game_running = True
  76.  
  77.  
  78. # Play the game
  79. '''
  80. A function called by Tkinter that allows the user to interact with the game board
  81. and play the game by moving the tiles.
  82. '''  
  83. def play(i, j):
  84.     global blankx, blanky, game_running
  85.  
  86.     #print 'play i,j:', i, j
  87.     #print 'blankx, blanky:', blankx, blanky
  88.    
  89.     if game_running:
  90.        
  91.         if (blankx, blanky) in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
  92.            
  93.             # StringVar requires the use of get() and set()
  94.             #board[blanky][blankx] = board[j][i]
  95.             #board[j][i] = ' '
  96.             board[blanky][blankx].set( board[j][i].get() )
  97.             board[j][i].set(' ')
  98.  
  99.             # you don't need it - StringVar do it for you
  100.             #buttons[blanky][blankx]['text'] = buttons[j][i]['text']
  101.             #buttons[j][i]['text'] = '   '
  102.            
  103.             blanky = j
  104.             blankx = i
  105.            
  106.             if won():
  107.                 # lable is now visible
  108.                 label.lift()
  109.                 game_running = False
  110.  
  111.     # probably you don't need it - `label for winning` will call `setup`
  112.     #else:
  113.         # reset board (without creating new board) and restart game
  114.     #    setup()
  115.  
  116.                                                                        
  117. def won():
  118.  
  119.     # StringVar ('char') requires the use of get() and set()
  120.    
  121.     number = 0
  122.  
  123.     for row in board:
  124.         for string_var in row:
  125.            
  126.             number += 1
  127.            
  128.             if number == d * d and string_var.get() == ' ':
  129.                 return True
  130.             elif string_var.get() != str(number):
  131.                 return False
  132.                
  133.     return True
  134.  
  135.  
  136. # ---------- main ----------
  137.  
  138. # - befor tkinter window -
  139.  
  140. greet()
  141. d = dim()
  142.  
  143. # - create window -
  144.  
  145. root = Tk()
  146. root.config(bg = 'black', borderwidth=4)
  147. root.wm_title("Game of Fifteen")
  148.  
  149. # - label for winning -
  150.  
  151. label = Button(root, text="You won!", fg="pink",font=("Helvetica",15), comman=setup)
  152. label.config(bg='black')
  153. label.grid(row=0, column=0, ipadx=5, ipady=5)
  154.  
  155. # - frame for the board game -
  156.  
  157. frame = Frame(root)
  158. frame.config(bg='black')
  159. frame.grid(row=0, column=0) # added to grid after label will hide label
  160.  
  161. # - creat board - only once - without numbers
  162.  
  163. # fill board with StringVars
  164.  
  165. for _ in range(d): # if you don't need `j` then you can use `_`
  166.     row = []
  167.     for _ in range(d): # if you don't need `i` then you can use `_`
  168.         # new StringVar for every tile
  169.         string_var = StringVar()
  170.  
  171.         # append StringVar object, not text from StringVar - get()
  172.         row.append(string_var) # without .get()
  173.  
  174.     board.append(row)
  175.  
  176. # - create buttons - only once - without numbers
  177.  
  178. # if you use StringVar you don't need direct access to buttons
  179. #buttons = []
  180.    
  181. for j, row in enumerate(board):
  182.     #buttons_row = []
  183.     for i, string_var in enumerate(row):
  184.         # v = StringVar() # don't need it
  185.  
  186.         b = Label(frame, textvariable=string_var, bg='pink', font=("Helvetica", 30))
  187.  
  188.         # you can't assign normal text to textvariable
  189.         # and you don't have to - put empty text into StringVar in board
  190.         #if board[j][i]== d * d:
  191.         #   b = Label(frame, textvariable = '   ', bg='pink',font=("Helvetica", 30))
  192.            
  193.         b.grid(row=j, column=i, sticky="nsew", ipadx=8, padx=4, pady=4)
  194.         # ipadx to make 3x3-board bigger and hide `label for winning`
  195.        
  196.         # if you want to click widget then maybe you should use Button()
  197.         # and command= to assing function
  198.        
  199.         b.bind('<Button-1>',lambda e, i=i,j=j:play(i,j))
  200.        
  201.         #buttons_row.append(b)
  202.     #buttons.append(buttons_row)
  203.  
  204. # - fill board with numbers and start game -
  205. setup()    # start over
  206.  
  207. root.mainloop()    # start engine
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement