Use Python 3 to build a 2048 Game: Task 1 Your first task will be to implement t
ID: 3722388 • Letter: U
Question
Use Python 3 to build a 2048 Game:
Task 1
Your first task will be to implement the function createGrid() that takes two parameters row and col and returns the grid for the game. You will be using a list of lists to represent the grid. The list should contain row number of lists, each with a length col. All the elements of this data structure should be 0.
Task 2
Once you are finished with Task 1, you can begin this task. Be sure to erase the test code from the previous task. Now, you will implement the setCell()and getCell() functions to set and access values in the grid. We can imagine the elements of the grid to be associated with a cell number. That is each element of the grid is a cell. So, in a (4 x 4) grid, the cells are numbered 0 through 15. As a result, instead of accessing an element using, say, grid._grid[1][2], we access that element with grid.getCell(6). Implement setCell() such that it takes two arguments, cell and val, and assigns the value of val to cell number cell in the grid. Implement getCell() such that it takes an argument, cell, and returns the value in the grid at cell number cell.
Task 3
Implement the collapsible() function. This function should return True if the grid can be collapsed in any of the four directions. It should return False otherwise. Uncomment the line near the bottom that calls the function testCollapsible() and run the file with Python. If your implementation is correct it should print that all the tests have passed.
Hint: One way to know if the grid is collapsible is if there is an empty tile in the grid.
Task 4
In Task 4 you must complete the collapseRow() function. This function is given a list of numbers as an argument and it should return a LEFT-collapsed list, and a True if the list was collapsed or False if it was not. The code for your function must collapse the list conforming to the rules of 2048. That is, if it is passed the list [2, 0, 2, 4], after collapsing to the left the function should return the list [4, 4, 0, 0]. In order to test your implementation, you can use the tests.py file that is given to you. Uncomment the line near the bottom that calls the function testCollapseRow() and run the file with Python. If your implementation is correct it should print that all the tests have passed.
Task 5
In this task, you will use the collapseRow() function to implement collapseLeft(), collapseRight(), collapseDown() and collapseUp(). For collapseLeft(), you merely need to collapse every row of the grid using collapseRow(). collapseRight() is implemented similarly except, in this case, you would reverse each row before collapsing them. Use this idea, to implement collapseDown() and collapseUp(). All four functions should return True if the grid was collapsed and False otherwise.
Task 6
Implement the function updateEmptiesSet(). This function is used after every collapse action in the game. The function should update the emptiesSet list to contain the new set of empty cells after a collapse. Tests for this function can be found in the tests.py file.
SKELETON CODE
import random as rnd
import os
import sys
class Grid():
def __init__(self, row=4, col=4, initial=2):
self.row = row # number of rows in grid
self.col = col # number of columns in grid
self.initial = initial # number of initial cells filled
self.score = 0
self._grid = self.createGrid(row, col) # creates the grid specified above
self.emptiesSet = list(range(row * col)) # list of empty cells
for _ in range(self.initial): # assignation to two random cells
self.assignRandCell(init=True)
def createGrid(self, row, col):
"""
Create the grid here using the arguments row and col
as the number of rows and columns of the grid to be made.
The function should return the grid to be used in __init__()
"""
pass
def setCell(self, cell, val):
"""
This function should take two arguments cell and val and assign
the cell of the grid numbered 'cell' the value in val.
This function does not need to return anything.
You should use this function to change values of the grid.
"""
pass
def getCell(self, cell):
""""
This function should return the value in cell number 'cell'
of the grid.
You should use this function to access values of the grid
"""
pass
def assignRandCell(self, init=False):
"""
This function assigns a random empty cell of the grid
a value of 2 or 4.
In __init__() it only assigns cells the value of 2.
The distribution is set so that 75% of the time the random cell is
assigned a value of 2 and 25% of the time a random cell is assigned
a value of 4
"""
if len(self.emptiesSet):
cell = rnd.sample(self.emptiesSet, 1)[0]
if init:
self.setCell(cell, 2)
else:
cdf = rnd.random()
if cdf > 0.75:
self.setCell(cell, 4)
else:
self.setCell(cell, 2)
self.emptiesSet.remove(cell)
def drawGrid(self):
"""
This function draws the grid representing the state of the game
grid
"""
for i in range(self.row):
line = ' |'
for j in range(self.col):
if not self.getCell((i * self.row) + j):
line += ' '.center(5) + '|'
else:
line += str(self.getCell((i * self.row) + j)).center(5) + '|'
print(line)
print()
def updateEmptiesSet(self):
"""
This function should update the list of empty cells of the grid.
"""
pass
def collapsible(self):
"""
This function should test if the grid of the game is collapsible
in any direction (left, right, up or down.)
It should return True if the grid is collapsible.
It should return False otherwise.
"""
pass
def collapseRow(self, lst):
"""
This function takes a list lst and collapses it to the LEFT.
This function should return two values:
1. the collapsed list and
2. True if the list is collapsed and False otherwise.
"""
pass
def collapseLeft(self):
"""
This function should use collapseRow() to collapse all the rows
in the grid to the LEFT.
This function should return True if any row of the grid is collapsed
and False otherwise.
"""
pass
def collapseRight(self):
"""
This function should use collapseRow() to collapse all the rows
in the grid to the RIGHT.
This function should return True if any row of the grid is collapsed
and False otherwise.
"""
pass
def collapseUp(self):
"""
This function should use collapseRow() to collapse all the columns
in the grid to UPWARD.
This function should return True if any column of the grid is
collapsed and False otherwise.
"""
pass
def collapseDown(self):
"""
This function should use collapseRow() to collapse all the columns
in the grid to DOWNWARD.
This function should return True if any column of the grid is
collapsed and False otherwise.
"""
pass
class Game():
def __init__(self, row=4, col=4, initial=2):
"""
Creates a game grid and begins the game
"""
self.game = Grid(row, col, initial)
self.play()
def printPrompt(self):
"""
Prints the instructions and the game grid with a move prompt
"""
if sys.platform == 'win32':
os.system("cls")
else:
os.system("clear")
print('Press "w", "a", "s", or "d" to move Up, Left, Down or Right respectively.')
print('Enter "p" to quit. ')
self.game.drawGrid()
print(' Score: ' + str(self.game.score))
def play(self):
moves = {'w' : 'Up',
'a' : 'Left',
's' : 'Down',
'd' : 'Right'}
stop = False
collapsible = True
while not stop and collapsible:
self.printPrompt()
key = input(' Enter a move: ')
while not key in list(moves.keys()) + ['p']:
self.printPrompt()
key = input(' Enter a move: ')
if key == 'p':
stop = True
else:
move = getattr(self.game, 'collapse' + moves[key])
collapsed = move()
if collapsed:
self.game.updateEmptiesSet()
self.game.assignRandCell()
collapsible = self.game.collapsible()
if not collapsible:
if sys.platform == 'win32':
os.system("cls")
else:
os.system("clear")
print()
self.game.drawGrid()
print(' Score: ' + str(self.game.score))
print('No more legal moves.')
def main():
game = Game()
#main()
Explanation / Answer
import random as rnd
import os
import sys
class Grid():
def __init__(self, row=4, col=4, initial=2):
self.row = row # number of rows in grid
self.col = col # number of columns in grid
self.initial = initial # number of initial cells filled
self.score = 0
self.cells = {}
self._grid = self.createGrid(row, col) # creates the grid specified above
self.emptiesSet = list(range(row * col)) # list of empty cells
for _ in range(self.initial): # assignation to two random cells
self.assignRandCell(init=True)
def createGrid(self, row, col):
grid = [] # Create a list that will contain our grid
n = 0 # Counter that stores the current cell number
for r in range (row): # Create a list that will hold a row
newRow = []
for c in range(col): # Append a 0 to the row based on the col number
newRow.append(0)
self.cells[n] = (r,c)
n += 1
grid.append(newRow)
return grid
def setCell(self, cell, val):
i1 = self.cells[cell][0] # getting cell's row
i2 = self.cells[cell][1] # getting cell's column
self._grid[i1][i2] = val
"""
This function should take two arguments cell and val and assign
the cell of the grid numbered 'cell' the value in val.
This function does not need to return anything.
You should use this function to change values of the grid.
"""
def getCell(self, cell):
i1 = self.cells[cell][0] # getting cell's row
i2 = self.cells[cell][1] # getting cell's column
return self._grid[i1][i2]
""""
This function should return the value in cell number 'cell'
of the grid.
You should use this function to access values of the grid
"""
def assignRandCell(self, init=False):
"""
This function assigns a random empty cell of the grid
a value of 2 or 4.
In __init__() it only assigns cells the value of 2.
The distribution is set so that 75% of the time the random cell is
assigned a value of 2 and 25% of the time a random cell is assigned
a value of 4
"""
if len(self.emptiesSet):
cell = rnd.sample(self.emptiesSet, 1)[0]
if init:
self.setCell(cell, 2)
else:
cdf = rnd.random()
if cdf > 0.75:
self.setCell(cell, 4)
else:
self.setCell(cell, 2)
self.emptiesSet.remove(cell)
def drawGrid(self):
"""
This function draws the grid representing the state of the game
grid
"""
for i in range(self.row):
line = ' |'
for j in range(self.col):
if not self.getCell((i * self.row) + j):
line += ' '.center(5) + '|'
else:
line += str(self.getCell((i * self.row) + j)).center(5) + '|'
print(line)
print()
def updateEmptiesSet(self):
empty = []
for i in range (0,self.row*self.col): # terate through each possible cell
if self.getCell(i) == 0:
empty.append(i)
self.emptiesSet = empty
"""
This function should update the list of empty cells of the grid.
"""
def collapsible(self):
for i in range (0,self.row*self.col): # iterate through each possible cell
if self.getCell(i) == 0:
return True
elif i !=0 and ((i+1) %self.col != 0) and (self.getCell(i) == self.getCell(i+1)): # if we are not looking at an end column and two consecutive cells have the same value
return True
elif i < (self.row*self.col)-self.row and self.getCell(i) == self.getCell(i+self.col): # if we are not looking at the last row and a cell + the cell in the following row are the same value
return True
return False
"""
This function should test if the grid of the game is collapsible
in any direction (left, right, up or down.)
It should return True if the grid is collapsible.
It should return False otherwise.
"""
def collapseRow(self, lst):
state = False
#print('b4',lst)
# first remove any possible spaces, add them to the end
# then look for consecutive numbers after blank spaces are gone
while lst[0] == 0 and not all(i == 0 for i in lst):
lst.remove(0)
lst.append(0)
state = True
print(lst)
for i in range(len(lst)):
while i+1 < len(lst) and lst[i] == 0 and lst[i+1] != 0:
lst.remove(0)
lst.append(0)
state = True
for i in range(len(lst)):
while i+1 < len(lst) and lst[i] != 0 and lst[i] == lst[i+1]:
lst[i] += lst.pop(i+1)
self.score += lst[i]
lst.append(0)
state = True
#print('NEW',lst)
return lst,state
'''for i in range (0,self.row*self.col): # iterate through each possible cell
if i !=0 and ((i+1) %self.col != 0) and (self.getCell(i) == self.getCell(i+1)): # if we are not looking at an end column and two consecutive cells have the same value
return True
return False'''
"""
This function takes a list lst and collapses it to the LEFT.
This function should return two values:
1. the collapsed list and
2. True if the list is collapsed and False otherwise.
"""
def collapseLeft(self):
collapsed = False
for r in range(0,self.row): # iterate through the number of rows
row = [] # create an empty list for the row
for c in range(0,self.col): # for each column in the row
row.append(self.getCell(c+(r*self.col))) # get the cell and append it to the row
lst,collapse = self.collapseRow(row) # collapse the row
for i in range(len(lst)): # for each item in the now collapsed row
self.setCell(i+(r*self.col),lst[i]) # set the cells accordingly
if collapse:
collapsed = True
return collapsed
"""
This function should use collapseRow() to collapse all the rows
in the grid to the LEFT.
This function should return True if any row of the grid is collapsed
and False otherwise.
"""
def collapseRight(self):
collapsed = False
for r in range(0,self.row): # iterate through the number of rows
row = [] # create an empty list for the row
for c in range(0,self.col): # for each column in the row
row.append(self.getCell(c+(r*self.col))) # get the cell and append it to the row
row = list(reversed(row))
lst,collapse = self.collapseRow(row) # collapse the row
if collapse:
collapsed = True
lst = list(reversed(lst))
for i in range(len(lst)): # for each item in the now collapsed row
self.setCell(i+(r*self.col),lst[i]) # set the cells accordingly
return collapsed
"""
This function should use collapseRow() to collapse all the rows
in the grid to the RIGHT.
This function should return True if any row of the grid is collapsed
and False otherwise.
"""
def collapseUp(self):
collapsed = False
for c in range(0,self.col): # iterate through the number of columns
col = [] # create an empty list for the row
for r in range(0,self.row): # for each row
col.append(self.getCell(c+(r*self.col))) # get the cell and append it to the row
#print('trying: ',col)
#col = list(reversed(col))
lst,collapse = self.collapseRow(col) # collapse the row
#print('WOA',lst)
if collapse:
collapsed = True
#lst = list(reversed(lst))
#print('reverse woaaa',lst)
for i in range(len(lst)): # for each item in the now collapsed row
self.setCell(c+(i*self.row),lst[i]) # set the cells accordingly
#print(self._grid)
return collapsed
"""
This function should use collapseRow() to collapse all the columns
in the grid to UPWARD.
This function should return True if any column of the grid is
collapsed and False otherwise.
"""
def collapseDown(self):
collapsed = False
for c in range(0,self.col): # iterate through the number of columns
col = [] # create an empty list for the row
for r in range(0,self.row): # for each row
col.append(self.getCell(c+(r*self.col))) # get the cell and append it to the row
#print('trying: ',col)
col = list(reversed(col))
lst,collapse = self.collapseRow(col) # collapse the row
#print('WOA',lst)
if collapse:
collapsed = True
lst = list(reversed(lst))
#print('reverse woaaa',lst)
for i in range(len(lst)): # for each item in the now collapsed row
self.setCell(c+(i*self.row),lst[i]) # set the cells accordingly
#print(self._grid)
return collapsed
"""
This function should use collapseRow() to collapse all the columns
in the grid to DOWNWARD.
This function should return True if any column of the grid is
collapsed and False otherwise.
"""
pass
class Game():
def __init__(self, row=4, col=4, initial=2):
"""
Creates a game grid and begins the game
"""
self.game = Grid(row, col, initial)
self.play()
def printPrompt(self):
"""
Prints the instructions and the game grid with a move prompt
"""
if sys.platform == 'win32':
os.system("cls")
else:
os.system("clear")
print('Press "w", "a", "s", or "d" to move Up, Left, Down or Right respectively.')
print('Enter "p" to quit. ')
self.game.drawGrid()
print(' Score: ' + str(self.game.score))
def play(self):
moves = {'w' : 'Up',
'a' : 'Left',
's' : 'Down',
'd' : 'Right'}
stop = False
collapsible = True
while not stop and collapsible:
self.printPrompt()
key = input(' Enter a move: ')
while not key in list(moves.keys()) + ['p']:
self.printPrompt()
key = input(' Enter a move: ')
if key == 'p':
stop = True
else:
move = getattr(self.game, 'collapse' + moves[key])
collapsed = move()
if collapsed:
self.game.updateEmptiesSet()
self.game.assignRandCell()
collapsible = self.game.collapsible()
if not collapsible:
if sys.platform == 'win32':
os.system("cls")
else:
os.system("clear")
print()
self.game.drawGrid()
print(' Score: ' + str(self.game.score))
print('No more legal moves.')
def main():
game = Game()
main()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.