import random """ Author: James Tam Version: March 13, 2018 Exercise: * Randomly populates a 4x4 list * Prompts the user for a location (row,column) in the list * Prompts the user for a new character for that location * ToDo (student exercise): change the location (row,column) to the character specified by the user """ SIZE = 4 EMPTY = " " PERSON = "P" POOP = "O" ERROR = "!" CLEANED = "." # Randomly generates an 'occupant' for a location in the world def createElement(): tempNum = random.randrange(10)+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) # Creates the SIZExSIZE world. Randomly populates it with the # return values from function createElement 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) # Shows the elements of the world. All the elements in a row will # appear on the same line. 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 # Gets the new appearance for the location in the list to change def getCharacter(): newChar = input("Enter new character for the target location: ") return(newChar) # Gets (row,column) of square to change def getLocation(): row = int(input("Enter row (0-%d)" %(SIZE-1))) column = int(input("Enter column (0-%d)" %(SIZE-1))) return(row,column) # Based on the specified location(row,column) and the character, # the function will change the 2D list 'world' def transform(row,column,newChar,world): pass # Students write your answer here def start(): world = createWorld() display(world) row,column = getLocation() newChar = getCharacter() transform(row,column,newChar,world) display(world) start()