Below are the puzzle.py and logic.py scripts.
puzzle.py handles the graphical part of the game and is also host to the game object, which contains the game matrix and the score which we'll need in order to interface with it. It runs under tkinter.
logic.py handles the logic of the game, just as the name suggests. It includes what actions to take based on what keys are pressed and how to transform the game matrix.
In [ ]:
# %load puzzle.py
from tkinter import *
from logic import *
from random import *
SIZE = 500
GRID_LEN = 4
GRID_PADDING = 10
BACKGROUND_COLOR_GAME = "#92877d"
BACKGROUND_COLOR_CELL_EMPTY = "#9e948a"
BACKGROUND_COLOR_DICT = { 2:"#eee4da", 4:"#ede0c8", 8:"#f2b179", 16:"#f59563", \
32:"#f67c5f", 64:"#f65e3b", 128:"#edcf72", 256:"#edcc61", \
512:"#edc850", 1024:"#edc53f", 2048:"#edc22e" }
CELL_COLOR_DICT = { 2:"#776e65", 4:"#776e65", 8:"#f9f6f2", 16:"#f9f6f2", \
32:"#f9f6f2", 64:"#f9f6f2", 128:"#f9f6f2", 256:"#f9f6f2", \
512:"#f9f6f2", 1024:"#f9f6f2", 2048:"#f9f6f2" }
FONT = ("Verdana", 40, "bold")
KEY_UP_ALT = "\'\\uf700\'"
KEY_DOWN_ALT = "\'\\uf701\'"
KEY_LEFT_ALT = "\'\\uf702\'"
KEY_RIGHT_ALT = "\'\\uf703\'"
KEY_UP = "'w'"
KEY_DOWN = "'s'"
KEY_LEFT = "'a'"
KEY_RIGHT = "'d'"
class GameGrid(Frame):
score=0
def __init__(self):
self.score=0
Frame.__init__(self)
self.grid()
self.master.title('2048')
self.master.bind("<Key>", self.key_down)
#self.gamelogic = gamelogic
self.commands = { KEY_UP: up, KEY_DOWN: down, KEY_LEFT: left, KEY_RIGHT: right,
KEY_UP_ALT: up, KEY_DOWN_ALT: down, KEY_LEFT_ALT: left, KEY_RIGHT_ALT: right }
self.grid_cells = []
self.init_grid()
self.init_matrix()
self.update_grid_cells()
def init_grid(self):
background = Frame(self, bg=BACKGROUND_COLOR_GAME, width=SIZE, height=SIZE)
background.grid()
for i in range(GRID_LEN):
grid_row = []
for j in range(GRID_LEN):
cell = Frame(background, bg=BACKGROUND_COLOR_CELL_EMPTY, width=SIZE/GRID_LEN, height=SIZE/GRID_LEN)
cell.grid(row=i, column=j, padx=GRID_PADDING, pady=GRID_PADDING)
# font = Font(size=FONT_SIZE, family=FONT_FAMILY, weight=FONT_WEIGHT)
t = Label(master=cell, text="", bg=BACKGROUND_COLOR_CELL_EMPTY, justify=CENTER, font=FONT, width=4, height=2)
t.grid()
grid_row.append(t)
self.grid_cells.append(grid_row)
def gen(self):
return randint(0, GRID_LEN - 1)
def init_matrix(self):
self.matrix = new_game(4)
self.matrix=add_two(self.matrix)
self.matrix=add_two(self.matrix)
def update_grid_cells(self):
for i in range(GRID_LEN):
for j in range(GRID_LEN):
new_number = self.matrix[i][j]
if new_number == 0:
self.grid_cells[i][j].configure(text="", bg=BACKGROUND_COLOR_CELL_EMPTY)
else:
self.grid_cells[i][j].configure(text=str(new_number), bg=BACKGROUND_COLOR_DICT[new_number], fg=CELL_COLOR_DICT[new_number])
self.update_idletasks()
def key_down(self, event):
if type(event) is str:
key = event
else:
key = repr(event.char)
print(key)
if key in self.commands:
self.matrix,done,newscore = self.commands[key](self.matrix)
self.score+=newscore
print("+",newscore,"=",self.score)
if done:
self.matrix = add_two(self.matrix)
self.update_grid_cells()
done=False
if game_state(self.matrix)=='win':
self.grid_cells[1][1].configure(text="You",bg=BACKGROUND_COLOR_CELL_EMPTY)
self.grid_cells[1][2].configure(text="Win!",bg=BACKGROUND_COLOR_CELL_EMPTY)
if game_state(self.matrix)=='lose':
self.grid_cells[1][1].configure(text="You",bg=BACKGROUND_COLOR_CELL_EMPTY)
self.grid_cells[1][2].configure(text="Lose!",bg=BACKGROUND_COLOR_CELL_EMPTY)
def generate_next(self):
index = (self.gen(), self.gen())
while self.matrix[index[0]][index[1]] != 0:
index = (self.gen(), self.gen())
self.matrix[index[0]][index[1]] = 2
In [1]:
# %load logic.py
#
# CS1010FC --- Programming Methodology
#
# Mission N Solutions
#
# Note that written answers are commented out to allow us to run your
# code easily while grading your problem set.
from random import *
#######
#Task 1a#
#######
# [Marking Scheme]
# Points to note:
# Matrix elements must be equal but not identical
# 1 mark for creating the correct matrix
def new_game(n):
matrix = []
for i in range(n):
matrix.append([0] * n)
return matrix
###########
# Task 1b #
###########
# [Marking Scheme]
# Points to note:
# Must ensure that it is created on a zero entry
# 1 mark for creating the correct loop
def add_two(mat):
a=randint(0,len(mat)-1)
b=randint(0,len(mat)-1)
while(mat[a][b]!=0):
a=randint(0,len(mat)-1)
b=randint(0,len(mat)-1)
mat[a][b]=2
return mat
###########
# Task 1c #
###########
# [Marking Scheme]
# Points to note:
# Matrix elements must be equal but not identical
# 0 marks for completely wrong solutions
# 1 mark for getting only one condition correct
# 2 marks for getting two of the three conditions
# 3 marks for correct checking
def game_state(mat):
for i in range(len(mat)):
for j in range(len(mat[0])):
if mat[i][j]==2048:
return 'win'
for i in range(len(mat)-1): #intentionally reduced to check the row on the right and below
for j in range(len(mat[0])-1): #more elegant to use exceptions but most likely this will be their solution
if mat[i][j]==mat[i+1][j] or mat[i][j+1]==mat[i][j]:
return 'not over'
for i in range(len(mat)): #check for any zero entries
for j in range(len(mat[0])):
if mat[i][j]==0:
return 'not over'
for k in range(len(mat)-1): #to check the left/right entries on the last row
if mat[len(mat)-1][k]==mat[len(mat)-1][k+1]:
return 'not over'
for j in range(len(mat)-1): #check up/down entries on last column
if mat[j][len(mat)-1]==mat[j+1][len(mat)-1]:
return 'not over'
return 'lose'
###########
# Task 2a #
###########
# [Marking Scheme]
# Points to note:
# 0 marks for completely incorrect solutions
# 1 mark for solutions that show general understanding
# 2 marks for correct solutions that work for all sizes of matrices
def reverse(mat):
new=[]
for i in range(len(mat)):
new.append([])
for j in range(len(mat[0])):
new[i].append(mat[i][len(mat[0])-j-1])
return new
###########
# Task 2b #
###########
# [Marking Scheme]
# Points to note:
# 0 marks for completely incorrect solutions
# 1 mark for solutions that show general understanding
# 2 marks for correct solutions that work for all sizes of matrices
def transpose(mat):
new=[]
for i in range(len(mat[0])):
new.append([])
for j in range(len(mat)):
new[i].append(mat[j][i])
return new
##########
# Task 3 #
##########
# [Marking Scheme]
# Points to note:
# The way to do movement is compress -> merge -> compress again
# Basically if they can solve one side, and use transpose and reverse correctly they should
# be able to solve the entire thing just by flipping the matrix around
# No idea how to grade this one at the moment. I have it pegged to 8 (which gives you like,
# 2 per up/down/left/right?) But if you get one correct likely to get all correct so...
# Check the down one. Reverse/transpose if ordered wrongly will give you wrong result.
def cover_up(mat):
new=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
done=False
for i in range(4):
count=0
for j in range(4):
if mat[i][j]!=0:
new[i][count]=mat[i][j]
if j!=count:
done=True
count+=1
return (new,done)
def merge(mat):
done=False
newscore=0
for i in range(4):
for j in range(3):
if mat[i][j]==mat[i][j+1] and mat[i][j]!=0:
mat[i][j]*=2
mat[i][j+1]=0
newscore=mat[i][j]
done=True
return (mat,done,newscore)
def up(game):
print("up")
# return matrix after shifting up
game=transpose(game)
game,done=cover_up(game)
temp=merge(game)
game=temp[0]
done=done or temp[1]
newscore=temp[2]
game=cover_up(game)[0]
game=transpose(game)
return (game,done,newscore)
def down(game):
print("down")
game=reverse(transpose(game))
game,done=cover_up(game)
temp=merge(game)
game=temp[0]
done=done or temp[1]
newscore=temp[2]
game=cover_up(game)[0]
game=transpose(reverse(game))
return (game,done,newscore)
def left(game):
print("left")
# return matrix after shifting left
game,done=cover_up(game)
temp=merge(game)
game=temp[0]
done=done or temp[1]
newscore=temp[2]
game=cover_up(game)[0]
return (game,done,newscore)
def right(game):
print("right")
# return matrix after shifting right
game=reverse(game)
game,done=cover_up(game)
temp=merge(game)
game=temp[0]
done=done or temp[1]
newscore=temp[2]
game=cover_up(game)[0]
game=reverse(game)
return (game,done,newscore)
In [ ]: