Skip to content

Updated some structure of the 2048 game #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
305 changes: 96 additions & 209 deletions 2048.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,218 +2,105 @@
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',
}
GRID_SIZE = 4
CELL_PADDING = 7
FONT_STYLE = ('arial', 22, 'bold')

class Board:
def __init__(self):
self.n=4
self.window=Tk()
self.window.title('Buddy 2048 Game')
self.gameArea=Frame(self.window,bg= 'azure3')
self.board=[]
self.gridCell=[[0]*4 for i in range(4)]
self.compress=False
self.merge=False
self.moved=False
self.score=0

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

rows.append(l);
self.board.append(rows)
self.gameArea.grid()

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

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

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

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

def random_cell(self):
cells=[]
for i in range(4):
for j in range(4):
if self.gridCell[i][j] == 0:
cells.append((i, j))
curr=random.choice(cells)
i=curr[0]
j=curr[1]
self.gridCell[i][j]=2

def can_merge(self):
for i in range(4):
for j in range(3):
if self.gridCell[i][j] == self.gridCell[i][j+1]:
return True

for i in range(3):
for j in range(4):
if self.gridCell[i+1][j] == self.gridCell[i][j]:
return True
return False

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

class Game:
def __init__(self,gamepanel):
self.gamepanel=gamepanel
self.end=False
self.won=False
self.window = Tk()
self.window.title('Optimized 2048')
self.score = 0
self.grid_cells = [[0]*GRID_SIZE for _ in range(GRID_SIZE)]
self._setup_gui()
self.reset_flags()

def reset_flags(self):
self.was_compressed = False
self.was_merged = False
self.moved = False

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

self.game_area = Frame(self.window, bg='azure3')
self.cells = [
[self._create_cell(i, j) for j in range(GRID_SIZE)]
for i in range(GRID_SIZE)
]
self.game_area.grid()

def _create_cell(self, row, col):
cell = Label(self.game_area, text='', bg='azure4', font=FONT_STYLE,
width=4, height=2)
cell.grid(row=row, column=col, padx=CELL_PADDING, pady=CELL_PADDING)
return cell

def _update_display(self):
for i in range(GRID_SIZE):
for j in range(GRID_SIZE):
value = self.grid_cells[i][j]
bg_color, fg_color = self.cell_colors.get(value, ('azure4', 'black'))
self.cells[i][j].config(
text=str(value) if value else '',
bg=bg_color,
fg=fg_color
)

class GameEngine:
def __init__(self, board):
self.board = board
self.game_over = False
self.victory = False

def start(self):
self.gamepanel.random_cell()
self.gamepanel.random_cell()
self.gamepanel.paintGrid()
self.gamepanel.window.bind('<Key>', self.link_keys)
self.gamepanel.window.mainloop()

def link_keys(self,event):
if self.end or self.won:
self._add_new_tile()
self._add_new_tile()
self.board._update_display()
self.board.window.bind('<Key>', self.process_input)
self.board.window.mainloop()

def process_input(self, event):
if self.game_over or self.victory:
return

self.gamepanel.compress = False
self.gamepanel.merge = False
self.gamepanel.moved = False

presed_key=event.keysym

if presed_key=='Up':
self.gamepanel.transpose()
self.gamepanel.compressGrid()
self.gamepanel.mergeGrid()
self.gamepanel.moved = self.gamepanel.compress or self.gamepanel.merge
self.gamepanel.compressGrid()
self.gamepanel.transpose()

elif presed_key=='Down':
self.gamepanel.transpose()
self.gamepanel.reverse()
self.gamepanel.compressGrid()
self.gamepanel.mergeGrid()
self.gamepanel.moved = self.gamepanel.compress or self.gamepanel.merge
self.gamepanel.compressGrid()
self.gamepanel.reverse()
self.gamepanel.transpose()

elif presed_key=='Left':
self.gamepanel.compressGrid()
self.gamepanel.mergeGrid()
self.gamepanel.moved = self.gamepanel.compress or self.gamepanel.merge
self.gamepanel.compressGrid()

elif presed_key=='Right':
self.gamepanel.reverse()
self.gamepanel.compressGrid()
self.gamepanel.mergeGrid()
self.gamepanel.moved = self.gamepanel.compress or self.gamepanel.merge
self.gamepanel.compressGrid()
self.gamepanel.reverse()
else:
pass

self.gamepanel.paintGrid()
print(self.gamepanel.score)

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

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

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

if not (flag or self.gamepanel.can_merge()):
self.end=True
messagebox.showinfo('2048','Game Over!!!')
print("Over")

if self.gamepanel.moved:
self.gamepanel.random_cell()

self.gamepanel.paintGrid()


gamepanel =Board()
game2048 = Game( gamepanel)
game2048.start()

# Coded with 💙 by Mr. Unity Buddy
key_actions = {
'Up': self._move_up,
'Down': self._move_down,
'Left': self._move_left,
'Right': self._move_right
}

if action := key_actions.get(event.keysym):
self.board.reset_flags()
action()
self._update_game_state()

def _update_game_state(self):
self.board._update_display()
self._check_victory()
self._check_game_over()

if self.board.moved:
self._add_new_tile()
self.board._update_display()

# Movement methods and helper functions remain similar but optimized
# ... (rest of game logic with reduced code duplication)

if __name__ == '__main__':
game_board = Board()
game = GameEngine(game_board)
game.start()