Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random as rnd
- maze = []
- # Note: Blocked cells/Walls are encoded as 0,
- # Hallways/Unblocked cells are encoded as 1
- # NODENAME , [nodeX, nodeY], [*list of nearby nodes*]
- # Nearby Node: [NODENAME, DISTANCE, DIRECTION]
- nodeList = [ ["A", [1, 1], [["B", 5, "R"], ["F", 10, "D"]]],
- ["B", [6, 1], [["A", 5, "L"], ["C", 5, "R"], ["H", 2, "D"]]],
- ["C", [11, 1], [["B", 5, "L"], ["D", 10, "D"]]],
- ["D", [11, 11], [["C", 10, "U"], ["E", 3, "L"]]],
- ["E", [8, 11], [["D", 3, "R"], ["F", 7, "L"], ["R", 2, "U"]]],
- ["F", [1, 11], [["A", 10, "U"], ["E", 7, "R"]]],
- ["G", [3, 3], [["J", 2, "D"], ["S", 1, "R"]]],
- ["H", [6, 3], [["B", 2, "U"], ["I", 1, "R"]]],
- ["I", [7, 3], [["H", 1, "L"], ["K", 2, "D"]]],
- ["J", [3, 5], [["G", 2, "U"], ["K", 4, "R"], ["M", 2, "D"]]],
- ["K", [7, 5], [["I", 2, "U"], ["J", 4, "L"], ["L", 2, "R"], ["N", 2, "D"]]],
- ["L", [9, 5], [["K", 2, "L"], ["T", 2, "U"], ["O", 2, "D"]]],
- ["M", [3, 7], [["J", 2, "U"], ["N", 4, "R"], ["P", 2, "D"]]],
- ["N", [7, 7], [["K", 2, "U"], ["M", 4, "L"], ["O", 2, "R"], ["Q", 2, "D"]]],
- ["O", [9, 7], [["L", 2, "U"], ["N", 2, "L"]]],
- ["P", [3, 9], [["M", 2, "U"], ["U", 1, "R"]]],
- ["Q", [7, 9], [["N", 2, "U"], ["R", 1, "R"], ["W", 1, "L"]]],
- ["R", [8, 9], [["Q", 1, "L"], ["V", 1, "R"], ["E", 2, "D"]]],
- ["S", [4, 3], [["G", 1, "L"]]],
- ["T", [9, 3], [["L", 2, "D"]]],
- ["U", [4, 9], [["P", 1, "L"]]],
- ["V", [9, 9], [["R", 1, "L"]]],
- ["W", [6, 9], [["Q", 1, "R"]]],
- ]
- '''
- Game Map:
- = = = = = = = = = = = = =
- = A B C =
- = = = = = = = = = =
- = = G S = H I = T = =
- = = = = = = = =
- = = J K L = =
- = = = = = = = =
- = = M N O = =
- = = = = = = = = =
- = = P U = W Q R V = =
- = = = = = = = = = =
- = F E D =
- = = = = = = = = = = = = =
- '''
- def makeMaze(): #Overly long function that builds up the maze list into a 13x13 matrix of 0's and 1's via a for-loop and if-else block
- for i in range(13):
- temp = []
- if i in (0, 12):
- for j in range(13):
- temp.append(0)
- elif i in (1, 11):
- temp.append(0)
- for j in range(11):
- temp.append(1)
- temp.append(0)
- elif i == 2:
- temp.append(0)
- temp.append(1)
- for j in range(4):
- temp.append(0)
- temp.append(1)
- for j in range(4):
- temp.append(0)
- temp.append(1)
- temp.append(0)
- elif i == 3:
- temp.append(0)
- temp.append(1)
- temp.append(0)
- temp.append(1)
- temp.append(1)
- temp.append(0)
- temp.append(1)
- temp.append(1)
- temp.append(0)
- temp.append(1)
- temp.append(0)
- temp.append(1)
- temp.append(0)
- elif i in (4, 6):
- temp.append(0)
- temp.append(1)
- temp.append(0)
- temp.append(1)
- for j in range(3):
- temp.append(0)
- temp.append(1)
- temp.append(0)
- temp.append(1)
- temp.append(0)
- temp.append(1)
- temp.append(0)
- elif i in (5, 7):
- temp.append(0)
- temp.append(1)
- temp.append(0)
- for j in range(7):
- temp.append(1)
- temp.append(0)
- temp.append(1)
- temp.append(0)
- elif i == 8:
- temp.append(0)
- temp.append(1)
- temp.append(0)
- temp.append(1)
- for j in range(3):
- temp.append(0)
- temp.append(1)
- for j in range(3):
- temp.append(0)
- temp.append(1)
- temp.append(0)
- elif i == 9:
- temp.append(0)
- temp.append(1)
- temp.append(0)
- temp.append(1)
- temp.append(1)
- temp.append(0)
- for j in range(4):
- temp.append(1)
- temp.append(0)
- temp.append(1)
- temp.append(0)
- elif i == 10:
- temp.append(0)
- temp.append(1)
- for j in range(6):
- temp.append(0)
- temp.append(1)
- temp.append(0)
- temp.append(0)
- temp.append(1)
- temp.append(0)
- maze.append(temp)
- def printMaze(px, py, robot): #Prints out the maze's current state, showing the position of the player and robot
- i = 0
- for row in maze:
- j = 0
- for cell in row:
- if j == px and i == py:
- print('@', end = ' ')
- elif j == robot[0] and i == robot[1]:
- print('&', end = ' ')
- elif j == 7 and (i == 5 or i == 7):
- print('?', end = ' ')
- elif cell == 0:
- print('#', end = ' ')
- elif cell == 1:
- print(' ', end = ' ')
- j += 1
- print()
- i += 1
- def moveRobot(robot): #Invoked after the player moves or waits. Uses the direction string of the robot to move it
- if robot[2] == 'U':
- robot[1] -= 1
- elif robot[2] == 'D':
- robot[1] += 1
- elif robot[2] == 'R':
- robot[0] += 1
- elif robot[2] == 'L':
- robot[0] -= 1
- def nodeCheck(robot): #Checks if the robot is on any of the lettered nodes in the nodeList
- for node in nodeList:
- if robot[0] == node[1][0] and robot[1] == node[1][1]:
- return True
- return False
- def getCurrentNode(robot): #Gets the index of the node in the nodeList the robot is on
- for node in nodeList:
- if robot[0] == node[1][0] and robot[1] == node[1][1]:
- return nodeList.index(node)
- def getAnyNode(nodeName): #Gets the index of a node in the nodeList based on it's lettered name
- for i in range(len(nodeList)):
- if nodeList[i][0] == nodeName:
- return i
- def checkPath(node, destination, axis): #Sees if there is a straight-line path from the given node to the destination coordinate along the indicated axis
- if axis == 'x':
- if node[0] > destination:
- for i in range(node[0], destination - 1, -1):
- if maze[node[1]][i] == 0:
- return False
- else:
- for i in range(destination, node[0] + 1, -1):
- if maze[node[1]][i] == 0:
- return False
- elif axis == 'y':
- if node[1] > destination:
- for i in range(node[1], destination - 1, -1):
- if maze[i][node[0]] == 0:
- return False
- else:
- for i in range(destination, node[1] + 1, -1):
- if maze[i][node[0]] == 0:
- return False
- else:
- return False
- return True
- def calcBestPath(player, robot): #Calculates the best path for the robot to take when it reaches a lettered node
- currentNode = getCurrentNode(robot)
- immNeighbors = nodeList[currentNode][2]
- maxDist = 0
- nextDir = ''
- if len(immNeighbors) == 4: #If the current node has four neighbors, choose a random direction
- directions = ('U', 'D', 'L', 'R')
- robot[2] = directions[rnd.randint(0,3)]
- #Only two 4-way nodes exist in the maze
- else:
- for neighbor in immNeighbors: #Do the following to each immediate neighbor-node of the current node
- neighborIndex = getAnyNode(neighbor[0])
- neighborCoords = nodeList[neighborIndex][1]
- #Get the index and coordinates of the neighbor-node
- #If the neighbor-node is not the node the robot was just at, and the player is not within a straight-line path of the neighbor-node, by either a vertical or horizontal path, process the neighbor-node
- if neighbor[0] != robot[3] \
- and not ( (player[0] == neighborCoords[0] and checkPath(neighborCoords, player[1], 'y') )\
- or (player[1] == neighborCoords[1] and checkPath(neighborCoords, player[0], 'x') )\
- ):
- #The first coordinate, [0], is the x, and [1] is the y. If the player and neighbor-node have the same x coordinate, they might have a vertical path or y-path between each other, and vice versa
- tempDist = neighbor[1]
- secNeighbors = nodeList[neighborIndex][2] #Get the secondary neighbors of the neighbor-node
- secDistances = []
- for otherNeighbor in secNeighbors: #Do the following for each secondary-neighbor-node
- otherCoords = nodeList[getAnyNode(otherNeighbor[0])][1] #Get the secondary-neighbor's coordinates
- #If the secondary neighbor node is not the current/original node, and the player does not have a straight-line path to the secondary neighbor node, by either a horizontal or vertical path, process the node
- if otherNeighbor[0] != nodeList[currentNode][0] \
- and not ( (player[0] == otherCoords[0] and checkPath(otherCoords, player[1], 'y') )\
- or (player[1] == otherCoords[1] and checkPath(otherCoords, player[0], 'x') )\
- ):
- secDistances.append(otherNeighbor[1])
- else: #0's must be appended in case of a failure of the above condition as to keep the distances list the same length as the list of neighbors, so the maximum distance neighbor's index can be chosen
- secDistances.append(0)
- bestNode = secDistances.index(max(secDistances))
- #After processing the secondary neighbor nodes, choose one furthest away and add its distance to the distance to the primary neighbor node
- tempDist += secNeighbors[bestNode][1]
- #If the path to the neighbor node and beyond is greater than the current maximum length path, update the maximum path length and the direction that the robot should move next
- if tempDist > maxDist:
- maxDist = tempDist
- nextDir = neighbor[2]
- robot[2] = nextDir
- #After processing all neighbor nodes, give the robot its next direction
- robot[3] = nodeList[currentNode][0]
- #Tell the robot of the node it just visited and got a new direction out of
- def spawnRobot(player, robot): #Spawns a robot on a random lettered node that the player is not on
- spawnNode = [-1, -1]
- while (spawnNode[0] == -1 and spawnNode[1] == -1) or (player[0] == spawnNode[0] and player[1] == spawnNode[1]):
- tempIndex = rnd.randint(0, len(nodeList) - 1)
- spawnNode[0] = nodeList[tempIndex][1][0]
- spawnNode[1] = nodeList[tempIndex][1][1]
- robot[0] = spawnNode[0]
- robot[1] = spawnNode[1]
- def main(): #Main function. Handles input, robot AI & movement, score-keeping, and updating the display
- playerCoordX = 1
- playerCoordY = 1
- playerScore = 0
- playerSteps = 0
- playerWaits = 0
- direction = ''
- wallMsg = "There's a wall there, try moving in another direction...\n"
- prompt = "Enter a direction to move [W:^, A:<, S:v, D:>] then ENTER," + \
- "\njust ENTER to wait, \'H\' then ENTER for help," + \
- "\n\'C\' then ENTER for Credits, or \'X\' to quit\n-={ "
- moved = False
- robotData = [-1, -1, 'direction', 'previousNode']
- spawnCountdown = 10
- robotInPlay = False
- helpMsg = "Welcome to Charlie Cook's Maze Game!" + \
- "\nThere are robots in this game (represented by \'&\')" + \
- "\nthat appear in the maze every now and again." + \
- "\nYou (represented by \'@\') need to catch them to earn points." + \
- "\nThe robots can sense where you are and will try to avoid you." + \
- "\nHowever, the \'?\' tiles mix them up and send them in a random direction." + \
- "\nUse this to your advantage! Good luck!\n"
- creditsMsg = "Coded by Charles \"Charlie\" \"The Gnarly\" Cook" + \
- "\nfrom November to December, 2017. All Rights Reserved.\n"
- makeMaze()
- printMaze(playerCoordX, playerCoordY, robotData)
- while direction.upper() != 'X':
- direction = str(input(prompt))
- while direction.upper() not in "WASDXHC":
- print("Error: Unknown Direction")
- direction = str(input(prompt))
- if direction.upper() == 'W':
- if maze[playerCoordY - 1][playerCoordX] == 1:
- playerCoordY -= 1
- moved = True
- playerSteps += 1
- else:
- print(wallMsg)
- elif direction.upper() == 'A':
- if maze[playerCoordY][playerCoordX - 1] == 1:
- playerCoordX -= 1
- moved = True
- playerSteps += 1
- else:
- print(wallMsg)
- elif direction.upper() == 'S':
- if maze[playerCoordY + 1][playerCoordX] == 1:
- playerCoordY += 1
- moved = True
- playerSteps += 1
- else:
- print(wallMsg)
- elif direction.upper() == 'D':
- if maze[playerCoordY][playerCoordX + 1] == 1:
- playerCoordX += 1
- moved = True
- playerSteps += 1
- else:
- print(wallMsg)
- elif direction.upper() == 'X':
- if str(input("Are you sure you want to quit? [Y/N]: ")).upper() == 'Y':
- print("Your final score was", playerScore, "point(s).")
- print("You took a total of", playerSteps, "step(s).")
- print("You waited for a total of", playerWaits, "turn(s).")
- print("See you later!")
- else:
- direction = ''
- elif direction == '':
- playerWaits += 1
- moved = True
- elif direction.upper() == 'H':
- print(helpMsg)
- elif direction.upper() == 'C':
- print(creditsMsg)
- if moved:
- if robotInPlay:
- moveRobot(robotData)
- if playerCoordX == robotData[0] and playerCoordY == robotData[1]:
- print("You caught a robot! Well done!")
- playerScore += 1
- print("Your score is now", playerScore, "points.")
- robotInPlay = False
- robotData[0] = -1
- robotData[1] = -1
- else:
- if nodeCheck(robotData):
- # print(robotData)
- calcBestPath([playerCoordX, playerCoordY], robotData)
- # print(robotData)
- else:
- spawnCountdown -= 1
- if spawnCountdown == 0:
- spawnCountdown = 10
- spawnRobot([playerCoordX, playerCoordY], robotData)
- print("A robot has appeared! Catch it!\n(You need to move onto the same spot as the robot to catch it.\nThey're small, and can run right under you!)")
- # print(robotData)
- robotInPlay = True
- calcBestPath([playerCoordX, playerCoordY], robotData)
- # print(robotData)
- moved = False
- printMaze(playerCoordX, playerCoordY, robotData)
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement