import sys import random # # Author: James Tam # Version: March 3, 2010 # A program that uses a 2x2 list to represent a randomly generated character- # based world. MAX_ROWS = 4 MAX_COLUMNS = 4 NO_COMBINATIONS = 10 # function generateElement # Maps an integer value to a character value. # Although the precondition for this function is that the number is within the # range of 1 - 10, an error message is generated for values outside those # bounds. def generateElement (temp): anElement = '?' if (temp >= 1) and (temp <= 6): anElement = ' ' elif (temp >= 7) and (temp <= 9): anElement = '*' elif (temp == 10): anElement = '.' else: print "<< Error with the random no. generator.>>" print "<< Value should be 1-10 but random value is ", temp anElement = '!' return anElement # Traverses the grid and randomly sets each element to one of the following # values: # 60% chance the element will contain a space. # 30% chance the element will contain a star. # 10% chance the element will contain a dot. # If the element contains an exclaimation mark then there was an error # with the random number generator. def initialize (aGrid): for r in range (0, MAX_ROWS, 1): for c in range (0, MAX_COLUMNS, 1): temp = random.randint(1, NO_COMBINATIONS) aGrid[r][c] = generateElement(temp) def display (aGrid): for r in range (0, MAX_ROWS, 1): for c in range (0, MAX_COLUMNS, 1): sys.stdout.write(aGrid[r][c]) print def displayLines (aGrid): for r in range (0, MAX_ROWS, 1): print " - - - -" for c in range (0, MAX_COLUMNS, 1): sys.stdout.write ('|') sys.stdout.write (aGrid[r][c]) print '|' print " - - - -" # MAIN FUNCTION # Create a reference to a 1D array aGrid = [] # Loop: # Each iteration of the outer loop creates one row and adds it # to the array. # Each iteration of the inner loop then steps through each element. # of the the row and creates and intializes the elements for the # row. for r in range (0, MAX_ROWS, 1): aGrid.append ([]) for c in range (0, MAX_COLUMNS, 1): aGrid[r].append (" ") initialize(aGrid) print "Displaying grid" print "===============" display (aGrid) print print "Displaying grid with bounding lines" print "===================================" displayLines (aGrid)