SoFunction
Updated on 2024-11-17

python based tkinter make graphical interface 2048 game

2048 Game Output

Project prerequisites

The prerequisites are as follows:

1. Python
2. Tkinter

establish

Code:

from tkinter import *
from tkinter import messagebox
import random

class Board:
 bg_color={

 '2': '#eee4da',
 '4': '#ede0c8',
 '8': '#edc850',
 '16': '#edc53f',
 '32': '#f67c5f',
 '64': '#f65e3b',
 '128': '#edcf72',
 '256': '#edcc61',
 '512': '#f2b179',
 '1024': '#f59563',
 '2048': '#edc22e',
 }
 color={
  '2': '#776e65',
 '4': '#f9f6f2',
 '8': '#f9f6f2',
 '16': '#f9f6f2',
 '32': '#f9f6f2',
 '64': '#f9f6f2',
 '128': '#f9f6f2',
 '256': '#f9f6f2',
 '512': '#776e65',
 '1024': '#f9f6f2',
 '2048': '#f9f6f2',
 }

 def __init__(self):
 =Tk()
 ('ProjectGurukul 2048 Game')
 =Frame(,bg= 'azure3')
 =[]
 =[[0]*4 for i in range(4)]
 =False
 =False
 =False
 =0

 for i in range(4):
  rows=[]
  for j in range(4):
  l=Label(,text='',bg='azure4',
  font=('arial',22,'bold'),width=4,height=2)
  (row=i,column=j,padx=7,pady=7)

  (l)
  (rows)
 ()

 def reverse(self):
 for ind in range(4):
  i=0
  j=3
  while(i<j):
  [ind][i],[ind][j]=[ind][j],[ind][i]
  i+=1
  j-=1

 def transpose(self):
 =[list(t)for t in zip(*)]

 def compressGrid(self):
 =False
 temp=[[0] *4 for i in range(4)]
 for i in range(4):
  cnt=0
  for j in range(4):
  if [i][j]!=0:
   temp[i][cnt]=[i][j]
   if cnt!=j:
   =True
   cnt+=1
 =temp

 def mergeGrid(self):
 =False
 for i in range(4):
  for j in range(4 - 1):
  if [i][j] == [i][j + 1] and [i][j] != 0:
   [i][j] *= 2
   [i][j + 1] = 0
    += [i][j]
    = True

 def random_cell(self):
 cells=[]
 for i in range(4):
  for j in range(4):
  if [i][j] == 0:
   ((i, j))
 curr=(cells)
 i=curr[0]
 j=curr[1]
 [i][j]=2
 
 def can_merge(self):
 for i in range(4):
  for j in range(3):
  if [i][j] == [i][j+1]:
   return True
 
 for i in range(3):
  for j in range(4):
  if [i+1][j] == [i][j]:
   return True
 return False

 def paintGrid(self):
 for i in range(4):
  for j in range(4):
  if [i][j]==0:
   [i][j].config(text='',bg='azure4')
  else:
   [i][j].config(text=str([i][j]),
   bg=self.bg_color.get(str([i][j])),
   fg=(str([i][j])))


class Game:
 def __init__(self,gamepanel):
 =gamepanel
 =False
 =False

 def start(self):
 .random_cell()
 .random_cell()
 ()
 ('<Key>', self.link_keys)
 ()
 
 def link_keys(self,event):
 if  or :
  return

  = False
  = False
  = False

 presed_key=

 if presed_key=='Up':
  ()
  ()
  ()
   =  or 
  ()
  ()

 elif presed_key=='Down':
  ()
  ()
  ()
  ()
   =  or 
  ()
  ()
  ()

 elif presed_key=='Left':
  ()
  ()
   =  or 
  ()

 elif presed_key=='Right':
  ()
  ()
  ()
   =  or 
  ()
  ()
 else:
  pass

 ()
 print()

 flag=0
 for i in range(4):
  for j in range(4):
  if([i][j]==2048):
   flag=1
   break

 if(flag==1): #found 2048
  =True
  ('2048', message='You Wonnn!!')
  print("won")
  return

 for i in range(4):
  for j in range(4):
  if [i][j]==0:
   flag=1
   break

 if not (flag or .can_merge()):
  =True
  ('2048','Game Over!!!')
  print("Over")

 if :
  .random_cell()
 
 ()
 

gamepanel =Board()
game2048 = Game( gamepanel)
()

Explanation:

We have defined two classes in our code:

Variables:

  • Bg_color: This is a dictionary that stores the background color of each cell.
  • Color: This is a dictionary to store the foreground color of each cell.
  • Window: It is the main window of tkinter.
  • gameArea: This is a tkinter frame widget.
  • gridCell: this is a 4×4 integer matrix that stores the actual integer values of all cells.
  • Board: this is the 4×4 grid of the tkinter tab widget that displays the cell's value on the tkinter window. It is also used to configure the background and foreground of the cell based on its gridCell value.
  • Score: It stores the player's current score.

The rest are just flag variables.

Function:

  • __init __(self): this is the constructor. It initializes all variables with appropriate default values, e.g. gridCell defaults to " 0", move, merge defaults to False, etc.
  • Reverse: reverses the gridCell matrix.
  • Transpose: it uses the zip function and performs a transpose of the gridCell matrix.
  • CompressGrid: It moves all non-empty cells to the left, so merging can be done easily.
  • mergeGrid: If two neighboring cells have the same gridCell value, then add their gridCell values.
  • Random_cell: first store all empty cells in a list, then select a random cell from the created list and make its gridCell value 2
  • Can_merge: returns a boolean value indicating that we can merge any two cells. We can merge two cells if and only if they have the same gridCell value.
  • paintGrid: assigns foreground and background colors to each cell in a 4×4 grid corresponding to its gridCell value.

This class doesn't have a lot of variables, just a few boolean variables indicating the state of the game.

Function:

  • __init __(self): this is the constructor. It initializes all variables with appropriate default values.
  • To start: call random_cell twice, assign '2' to the gridCell values of the two random cells, then draw the grid, then, call link_keys to link up, down, left and right keys.
  • Link_keys: first, it checks whether the game is won or lost, and if so, it executes the return statement without performing any action. Otherwise, it continues execution.

Methods:

  • For the left slide, we will first compress and then merge the gridCell matrix, and then if compress or merge is true (indicating that the value of the matrix is affected by the first two functions), then we need to compress the grid again.
  • For an upward shift, we will do a transpose, then a swipe to the left, and then another transpose to return to the original order.
  • Moving down is the same as moving up, but we need to invert the matrix.
  • Again, moving to the right is the same as moving left + backward.
  • After each operation, we need to check the game state, and if all the cells are occupied and we cannot even merge any two cells, i.e., no action can change the state of the matrix, the game is over.

If any cell value reaches 2048, the player wins and a message box flashes on the screen announcing the winner.

summarize

We have successfully developed the popular 2048 game in python. It was fun to develop the game instead of playing someone else's game, and now we will play the game we developed ourselves.

Above is the details of python based on tkinter to create a graphical interface 2048 game, more information about python graphical interface 2048 game please pay attention to my other related articles!