import random # May 29, 2020 # Minor stylistic changes, functionality is the same # Original version: March 9, 2011 SIZE = 4 NUM_RANDOM_VALUES = 10 EMPTY = " " PERSON = "P" PET = "T" POOP = "O" ERROR = "!" CLEANED = "." # @createElement(none) # * Randomly generates an 'occupant' for a location in the world # @returns(list element, string of length one) def createElement(): tempNum = random.randrange(NUM_RANDOM_VALUES)+1 # 50% chance empty if ((tempNum >= 1) and (tempNum <= 5)): tempElement = EMPTY # 20% of a person elif ((tempNum >= 6) and (tempNum <= 7)): tempElement = PERSON # 10% chance of pet elif (tempNum == 8): tempElement = PET # 20% chance of poop in that location (lots in this world) elif ((tempNum >= 9) and (tempNum <= 10)): tempElement = POOP # In case there's a bug in the random number genrator else: tempElement = ERROR return(tempElement) # @ createWorld(none) # Creates the SIZExSIZE world. Randomly populates it with the # return values from function createElement. # returns(reference to the 2D list) def createWorld(): world = [] # Create a variable that refers to a 1D list. r = 0 # Outer 'r' loop traverses the rows. # Each iteration of the outer loop creates a new 1D list. while (r < SIZE): world.append([]) # Create new empty row c = 0 # The inner 'c' loop traverses the columns of the newly # created 1D list creating and initializing each element # to the value returned by createElement() while (c < SIZE): element = createElement() world[r].append(element) c = c + 1 r = r + 1 return(world) # @displayWorld(none) # * Shows the elements of the world. All the elements in a row will # appear on the same line. # @returns(nothing) def display(world): print("OUR WORLD") print("========") r = 0 while (r < SIZE): # Each iteration accesses a single row c = 0 while (c < SIZE): # Each iteration accesses an element in a row print(world[r][c], end="") c = c + 1 print() # Done displaying row, move output to the next line r = r + 1 # @getLocation(none) # * Gets (row,column) of square to evaluate # @return(integer,integer) # Argument: any valid (row,column) coordinate # Return: True when location contains a space, false otherwise def isSpace(row,column,world): space = False if (world[row][column] == EMPTY): space = True return(space) # Starting execution point for the program def start(): world = createWorld() display(world) row,column = getLocation() space = isSpace(row,column,world) print("Location: (%d/%d) contains space?" %(row,column), space) start()