Question

Write a module of utility functions called util.py for manipulating 2-dimensional arrays of size 4x4. (These...

Write a module of utility functions called util.py for manipulating 2-dimensional arrays of size 4x4. (These functions will be used in Question 3.) The functions you need to write are as follows: def create_grid(grid):

"""create a 4x4 array of zeroes within grid"""

def print_grid (grid):

"""print out a 4x4 grid in 5-width columns within a box"""

def check_lost (grid):

"""return True if there are no 0 values and there are no adjacent values that are equal; otherwise False"""

def check_won (grid):

"""return True if a value>=32 is found in the grid; otherwise False"""

def copy_grid (grid):

"""return a copy of the given grid"""

def grid_equal (grid1, grid2):

"""check if 2 grids are equal - return boolean value"""

2048 is a puzzle game where the goal is to repeatedly merge adjacent numbers in a grid until the number 2048 is found. Your task in this question is to complete the code for a 2048 programme, using the utility module (util.py) from Question 2 and a supplied main programme (2048.py). The heart of the game is the set of merging functions that merge adjacent equal values and eliminate gaps - you are required ONLY to write these functions in a module named push.py:

def push_up (grid):

"""merge grid values upwards"""

def push_down (grid):

"""merge grid values downwards"""

def push_left (grid):

"""merge grid values left"""

def push_right (grid):

"""merge grid values right"""

Note: The check_won() function from util.py assumes you have won when you reach 32 - this is simply to make testing easier. The random number generator has been set to generate the same values each time for testing purposes.

testutil.py:

# grid utility routines
import util

# run test
def run_test (test):
if test == 0:
grid = []
util.create_grid (grid)
print (len (grid))
print (len (grid[0]))
print (len (grid[1]))
print (len (grid[2]))
print (len (grid[3]))
print (grid[0][0])
print (grid[1][2])
print (grid[2][1])
print (grid[3][3])
elif test == 1:
grid = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
util.print_grid (grid)
elif test == 2:
grid = [[2,0,2,0],[0,4,0,8],[0,16,0,128],[2,2,2,2]]
util.print_grid (grid)
elif test == 3:
grid = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
print (util.check_lost (grid))
elif test == 4:
grid = [[2,0,2,0],[0,4,0,8],[0,16,0,128],[2,2,2,2]]
print (util.check_lost (grid))
elif test == 5:
grid = [[2,2,2,2],[2,2,2,2],[2,2,2,2],[2,2,2,2]]
print (util.check_lost (grid))
elif test == 6:
grid = [[4,16,2,4],[2,4,16,2],[2,4,8,4],[4,8,4,2]]
print (util.check_lost (grid))
elif test == 7:
grid = [[4,2,8,2],[2,8,16,8],[16,32,8,4],[4,8,4,2]]
print (util.check_lost (grid))
elif test == 8:
grid = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
print (util.check_won (grid))
elif test == 9:
grid = [[2,0,2,0],[0,4,0,8],[0,16,0,128],[2,2,2,2]]
print (util.check_won (grid))
elif test == 10:
grid = [[2,2,2,2],[2,2,2,2],[2,2,2,2],[2,2,2,2]]
print (util.check_won (grid))
elif test == 11:
grid = [[4,16,2,4],[2,4,16,2],[2,4,8,4],[4,8,4,2]]
print (util.check_won (grid))
elif test == 12:
grid = [[2,32,2,4],[4,2,16,2],[8,0,8,4],[2,0,4,2]]
print (util.check_won (grid))
elif test == 13:
grid = [[2,2,8,0],[0,8,16,0],[16,32,8,8],[2,8,4,4]]
print (util.check_won (grid))
elif test == 14:
grid = [[64,32,32,2],[8,4,2,0],[4,2,0,0],[2,0,0,0]]
print (util.check_won (grid))
elif test == 15:
grid = [[64,32,32,2],[8,4,2,0],[4,2,0,0],[2,0,0,0]]
print (util.check_won (grid))
elif test == 16:
grid = [[128,4,0,0],[8,4,2,0],[4,2,0,2],[2,0,0,0]]
print (util.check_won (grid))
elif test == 17:
grid = [[4,2,8,2],[2,8,16,8],[16,32,8,4],[4,8,4,2]]
test_grid = util.copy_grid (grid)
print (grid[0][0],test_grid[0][0])
print (grid[1][2],test_grid[1][2])
print (grid[3][3],test_grid[3][3])
grid[0][0] = 64
grid[1][2] = 64
grid[3][3] = 64
print (grid[0][0],test_grid[0][0])
print (grid[1][2],test_grid[1][2])
print (grid[3][3],test_grid[3][3])
elif test == 18:
grid1 = [[4,2,8,2],[2,8,16,8],[16,32,8,4],[4,8,4,2]]
grid2 = [[4,2,8,2],[2,8,16,8],[16,32,8,4],[4,8,4,2]]
print (util.grid_equal (grid1, grid2))
elif test == 19:
grid1 = [[4,2,8,2],[2,8,16,8],[16,32,8,4],[4,8,4,2]]
grid2 = [[4,2,8,2],[2,8,16,4],[16,32,8,4],[4,8,4,2]]
print (util.grid_equal (grid1, grid2))
elif test == 20:
grid1 = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
grid2 = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
print (util.grid_equal (grid1, grid2))
elif test == 21:
grid1 = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
grid2 = [[2,4,8,16],[32,64,128,256],[512,1024,2048,4096],[8192,16384,32768,65536]]
print (util.grid_equal (grid1, grid2))
elif test == 22:
grid1 = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
grid2 = [[2,2,2,2],[2,2,2,2],[2,2,2,2],[2,2,2,2]]
print (util.grid_equal (grid1, grid2))
  
def run_one_test ():
test = int (input (""))
run_test (test)

def run_all_tests ():
for test in range (23):
print ("Test",test)
run_test (test)
  
run_one_test ()

2048.py:

# random number generator
import random
# grid utility routines
import util
# grid value merging routines
import push

def add_block (grid):
"""add a random number to a random location on the grid"""
# set distributon of number possibilities
options = [2,2,2,2,2,4]
# get random number
chosen = options[random.randint(0,len(options)-1)]
found = False
while (not found):
# get random location
x = random.randint (0, 3)
y = random.randint (0, 3)
# check and insert number
if (grid[x][y] == 0):
grid[x][y] = chosen
found = True

def play ():
"""generate grid and play game interactively"""
# create grid
grid = []
util.create_grid (grid)
# add 2 starting random numbers
add_block (grid)
add_block (grid)
won_message = False
while (True):
util.print_grid (grid)
key = input ("Enter a direction:\n")
if (key in ['x', 'u', 'd', 'l', 'r']):
# make a copy of the grid
saved_grid = util.copy_grid (grid)
if (key == 'x'):
# quit the game
return
# manipulate the grid depending on input
elif (key == 'u'):
push.push_up (grid)
elif (key == 'd'):
push.push_down (grid)
elif (key == 'r'):
push.push_right (grid)
elif (key == 'l'):
push.push_left (grid)
# check for a grid with no more gaps or legal moves
if util.check_lost (grid):
print ("Game Over!")
return
# check for a grid with the final number
elif util.check_won (grid) and not won_message:
print ("Won!")
won_message = True
# finally add a random block if the grid has changed
if not util.grid_equal (saved_grid, grid):
add_block (grid)

# initialize the random number generator to a fixed sequence
random.seed (12)
# play the game
play ()

I've been trying to solve this problem all week and its driving me insane. Please if someone could show me a step by step solution I would be eternally gratefull.

0 0
Add a comment Improve this question Transcribed image text
Request Professional Answer

Request Answer!

We need at least 10 more requests to produce the answer.

0 / 10 have requested this problem solution

The more requests, the faster the answer.

Request! (Login Required)


All students who have requested the answer will be notified once they are available.
Know the answer?
Add Answer to:
Write a module of utility functions called util.py for manipulating 2-dimensional arrays of size 4x4. (These...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Similar Homework Help Questions
  • Project Description Allow the user to specify M (the size of the hash table) then, (1)...

    Project Description Allow the user to specify M (the size of the hash table) then, (1) add items found in text file "Project1.txt" to h, an initially-empty instance of a HASH (reject all items that have a key that duplicates the key of a previously added item—item keys must be unique); (2) display h (see format shown below); (3) delete 4 randomly-chosen items from the h; and finally, (4) display h. Note M must be a prime number, so your...

  • COMPLETE THE _CONSTRUCT() AND CONSTRUCTTREE() FUNCTIONS class expressionTree:    class treeNode: def __init__(self, value, lchild, rchild):...

    COMPLETE THE _CONSTRUCT() AND CONSTRUCTTREE() FUNCTIONS class expressionTree:    class treeNode: def __init__(self, value, lchild, rchild): self.value, self.lchild, self.rchild = value, lchild, rchild def __init__(self): self.treeRoot = None    #utility functions for constructTree def mask(self, s): nestLevel = 0 masked = list(s) for i in range(len(s)): if s[i]==")": nestLevel -=1 elif s[i]=="(": nestLevel += 1 if nestLevel>0 and not (s[i]=="(" and nestLevel==1): masked[i]=" " return "".join(masked) def isNumber(self, expr): mys=s.strip() if len(mys)==0 or not isinstance(mys, str): print("type mismatch error: isNumber")...

  • Can you please enter this python program code into an IPO Chart? import random def menu():...

    Can you please enter this python program code into an IPO Chart? import random def menu(): print("\n\n1. You guess the number\n2. You type a number and see if the computer can guess it\n3. Exit") while True: #using try-except for the choice will handle the non-numbers #if user enters letters, then except will show the message, Numbers only! try: c=int(input("Enter your choice: ")) if(c>=1 and c<=3): return c else: print("Enter number between 1 and 3 inclusive.") except: #print exception print("Numbers Only!")...

  • Can figure out how get my program to keep track of a total score, here is...

    Can figure out how get my program to keep track of a total score, here is my code so far in python 3.6.6 import math import random import turtle def target(): """Turtle drawing the target"""    t = turtle.Turtle() wn = turtle.Screen() wn.bgcolor("black") t.hideturtle() t.speed(0)    #most outside circle worth 10 points t.setposition(0,-275) t.color("grey") t.begin_fill() t.circle(275) t.end_fill()    #2nd most outter circle worth 20 points t.penup() t.setposition(0,-200) t.pendown() t.color("red") t.begin_fill() t.circle(200) t.end_fill()    #3rd most outter circle worth 30 points...

  • Using a sort method and my previous code (put inside of addHours method if possible), how...

    Using a sort method and my previous code (put inside of addHours method if possible), how would I get the list of each employee's total hours to display in order of least amount of hours to greatest. An explanation for each step would also be great. import random #Create function addHours def addHours(lst): #Display added hours of employees print("\nEmployee# Weekly Hours") print("----------------------------") print(" 1 ",sum(lst[0])) print(" 2 ",sum(lst[1])) print(" 3 ",sum(lst[2])) #Create main function def main(): #Create first empty list...

  • (+30) Provide a python program which will Populate an array(list) of size 25 with integers in...

    (+30) Provide a python program which will Populate an array(list) of size 25 with integers in the range -100 (negative 100)   to +100 inclusive Display the array and its length (use the len function) Display the average of all the integers in the array Display the number of even integers (how many) Display the number of odd integers (how many) Display the number of integers > 0   (how many) Display the number of integers < 0   (how many) Display the...

  • 5.12 A5 Program Do you want to play. a. game? The Big Bang Theory fans may...

    5.12 A5 Program Do you want to play. a. game? The Big Bang Theory fans may recognize Rock Paper Scissors Lizard Spock as a game of chance that expands on the standard Rock Paper Scissors game. It introduces two new hand signs and several more rules. The rules: • Scissors cuts Paper • Paper covers Rock • Rock crushes Lizard • Lizard poisons Spock • Spock smashes Scissors • Scissors decapitates Lizard • Lizard eats Paper • Paper disproves Spock...

  • can someone solve this program using c++ (visual studio)? You have a grid of 4x4 cells...

    can someone solve this program using c++ (visual studio)? You have a grid of 4x4 cells which is filled by numbers from 1 to 8. Each number appears twice in the grid. The purpose of the Memory Game is to find the matching numbers. To start the game, Player 1 chooses two cells to uncover the numbers behind them. If the numbers match, player 1 gets to go on and uncover two more numbers. If the numbers don't match, player...

  • I need to complete the code by implementing the min function and the alpha betta pruning...

    I need to complete the code by implementing the min function and the alpha betta pruning in order to complete the tic tac toe game using pything. code: # -*- coding: utf-8 -*- """ Created on: @author: """ import random from collections import namedtuple GameState = namedtuple('GameState', 'to_move, utility, board, moves') infinity = float('inf') game_result = { 1:"Player 1 Wins", -1:"Player 2 Wins", 0:"It is a Tie" } class Game: """To create a game, subclass this class and implement actions,...

  • how do I write this code without the imports? I don't know what pickle is or...

    how do I write this code without the imports? I don't know what pickle is or os.path import pickle # to save and load history (as binary objects) import os.path #to check if file exists # character value mapping values = {'A': 1, 'B': 3, 'C': 3, 'D': 2, 'E': 1, 'F': 4, 'G': 2, 'H': 4, 'I': 1, 'J': 8, 'K': 5, 'L': 1, 'M': 3, 'N': 1, 'O': 1, 'P': 3, 'Q': 10, 'R': 1, ' S': 1,...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT