import random # Author: James Tam # Version: Fall, 2022 """ New learning objective: * Boundary checking using named constants. * Defining and using a Boolean function for boundary checking. """ SIZE = 4 FIELD = " " FOREST = "^" WATER = "W" BURNT = "F" ERROR = "!" """ @ display() @ argument: 2D list of char(length 1 string), simulated game world @ return value: none @ @ Shows the current state of the world """ def display(world): r = -1 c = -1 for r in range (0,SIZE,1): for c in range (0,SIZE,1): print(world[r][c], end="") print() print() """ @ editLocation @ editLocation(int,int,2DList reference) @ returns(nothing) @ Changes the selected location to an exclaimation mark """ def editLocation(row,column,world): world[row][column] = "!" """ @ generateElemement @ a random number argument (precondition 1<=number<=100) @ returns a string of length one (an element to populate world """ def generateElement(randomNumber): element = ERROR if ((randomNumber >= 1) and (randomNumber <= 50)): element = FIELD elif ((randomNumber >= 51) and (randomNumber <= 80)): element = FOREST elif ((randomNumber >= 81) and (randomNumber <= 100)): element = WATER else: element = ERROR return(element) """ @ getLocation @ getLocation(nothing) @ returns(int,int) @ Prompts the user for a given location(row,column) """ def getLocation(): outOfBounds = True row = -1 column = -1 while (outOfBounds == True): print("Enter location of square to change to a !") row = int(input("Enter a row (0-3): ")) column = int(input("Enter a column (0-3): ")) outside = isOut(row,column) if (outside == True): print("Row=%d, Col=%d" %(row,column), end = " ") print("is outside range of 0-" + str(SIZE) + "." ) else: outOfBounds = False return(row,column) def initialize(): world = [] r = -1 c = -1 randomNumber = -1 newElement = ERROR for r in range (0,SIZE,1): randomNumber = random.randrange(1,101) element = generateElement(randomNumber) tempRow = [element] * SIZE world.append(tempRow) # Add in new empty row print(tempRow) return(world) """ @ isOut @ isOut(int,int) @ returns(Boolean) @for a given location(row,column) function determines if the location is within the list bounds. """ def isOut(row,column): outside = False if ((row < 0) or \ (row >= SIZE) or \ (column < 0) or \ (column >= SIZE)): outside = True return(outside) # MAIN EXECUTION POINT def start(): stillRunning = True answer = "" row = -1 column = -1 world = initialize() while(stillRunning): #while(stillRunning == True): display(world) row,column = getLocation() editLocation(row,column,world) answer = input("Hit enter to continue,'q' to quit: ") if ((answer == "q") or (answer == "Q")): stillRunning = False start()