def main(): try: # Read input inputJson = sys.stdin.read() # Parse json parsedJson = json.loads(inputJson.replace("\n", "")) jsonDungeon, playerName, jsonPoint = parsedJson jsonLevel = jsonDungeon["level"] jsonPlayers = jsonDungeon["players"] jsonEnemies = jsonDungeon["adversaries"] jsonExitLocked = jsonDungeon["exit-locked"] game = convertJsonDungeon(jsonLevel, jsonPlayers, jsonEnemies, jsonExitLocked) # Validate if playerName not in game.players: status = MoveStatus.PLAYERINVALID else: status = arbitraryMove(intifyTuple(jsonPoint), game) if status == status.NONE: status = getSuccessStatus(intifyTuple(jsonPoint), game) # Output output = buildOutput(status, playerName, jsonPoint, jsonDungeon) print(json.dumps(output)) except json.JSONDecodeError: print("Malformed input.") sys.exit(1) except KeyboardInterrupt: print("Exiting...") sys.exit(0)
def convertJsonHallway(fromPoint: list, toPoint: list, waypoints: list): allWaypoints = waypoints + [toPoint] fromTemp = fromPoint tiles = dict() while len(allWaypoints) > 0: # loop through all waypoints toTemp = allWaypoints[0] # current waypoint to segment fromRow, fromCol = intifyTuple( tuple(fromTemp)) # hallway beginning location toRow, toCol = intifyTuple(tuple(toTemp)) # hallway ending location # tempDict here if fromCol == toCol: # means we have a vertical segment toBigger = toRow > fromRow # means we are going visually down for i in range(0, abs(toRow - fromRow)): # for every row going down newTilePos = (fromRow + i, fromCol) if toBigger else ( fromRow - i, fromCol) # get the next location row, col = newTilePos if row in tiles.keys(): tiles[row].update({col: Tile(TileEnum.DEFAULT)}) else: tiles[row] = {col: Tile(TileEnum.DEFAULT)} # add to temp elif fromRow == toRow: # means we have a horizontal segment tempColDict = dict() toBigger = toCol > fromCol for i in range(0, abs(toCol - fromCol)): newTilePos = (fromRow, fromCol + i) if toBigger else (fromRow, fromCol - i) row, col = newTilePos tempColDict[col] = Tile(TileEnum.DEFAULT) if fromRow in tiles.keys(): tiles[fromRow].update(tempColDict) else: tiles[fromRow] = tempColDict else: print(" YOU GAVE US A BAD LIST OF WAYPOINTS SIR") # add to tiles dict fromTemp = toTemp del allWaypoints[0] lastRow, lastCol = toPoint if lastRow in tiles.keys(): tiles[lastRow].update({lastCol: Tile(TileEnum.DEFAULT)}) else: tiles[lastRow] = {lastCol: Tile(TileEnum.DEFAULT)} # NOTE: origin = -1,-1 for a hallway board = Board(tiles, intifyTuple(tuple(fromPoint)), (-1, -1), BoardEnum.HALLWAY, [intifyTuple(tuple(fromPoint)), intifyTuple(tuple(toPoint))]) return board
def convertJsonLevel(rooms: list, hallways: list, objects: list): boundsList = lambda boundaryData: [boundaryData["rows"], boundaryData["columns"]] roomBoards = [ convertJsonRoom(room["origin"], boundsList(room["bounds"]), room["layout"]) for room in rooms] hallwayBoards = [ convertJsonHallway(hallway["from"], hallway["to"], hallway["waypoints"]) for hallway in hallways] keyObj = list(filter(lambda obj: obj["type"] == "key", objects)).pop() exitObj = list(filter(lambda obj: obj["type"] == "exit", objects)).pop() keyLoc = intifyTuple(tuple(keyObj["position"])) exitLoc = intifyTuple(tuple(exitObj["position"])) return Level(keyLoc, exitLoc, roomBoards + hallwayBoards, False)
def main(): output = {} try: inputJson = sys.stdin.read() parsedJson = json.loads(inputJson.replace("\n", "")) jsonLevel, jsonPoint = parsedJson givenPoint = intifyTuple(tuple(jsonPoint)) rooms = jsonLevel["rooms"] hallways = jsonLevel["hallways"] objects = jsonLevel["objects"] level = convertJsonLevel(rooms, hallways, objects) currentRoom = whichBoardInLevel(level, givenPoint) if currentRoom != -1: outputTraversable = isTraversable(level, currentRoom, givenPoint) outputObject = objectOutput(objects, givenPoint) outputType = typeOutput(level, currentRoom) outputReachable = reachableRoomOrigins(level, currentRoom) else: outputTraversable = False outputObject = None outputType = 'void' outputReachable = [] output['traversable'] = outputTraversable output['object'] = outputObject output['type'] = outputType output['reachable'] = outputReachable print(json.dumps(output)) except json.JSONDecodeError: print("Malformed input.") sys.exit(1) except KeyboardInterrupt: print("Exiting...") sys.exit(0)
def executeTurns(game: Dungeon, maxNumTurns: int, jsonActorMoveListList: list, jsonNameList: list, jsonLevel: dict): # Send initial player updates to all players in game managerTrace = getPlayersUpdates(game, []) i = 0 while i < maxNumTurns: # 0. Exit checking if anyOutOfMoves(jsonActorMoveListList) or isCurrentLevelOver(game): break # 1. Run all moves in turn for j in range(len(jsonActorMoveListList) ): # execute each move for a player in a turn playerMoveList = jsonActorMoveListList[j] validMove = False while not validMove and len(playerMoveList) > 0: # do first move in playerMoveList, if valid, set flag move = playerMoveList[0] playerName = jsonNameList[j] if not isPlayerInGame(playerName, game): break currLevel: Level = game.levels[game.currLevel] player = getPlayer(currLevel, playerName) # pot bug?? dest = move["to"] # apply if not dest: # skipped turn validMove = True managerTrace.append([playerName, move, "OK"]) # pot bug adding?? managerTrace = getPlayersUpdates(game, managerTrace) elif playerCanMoveTo(intifyTuple(dest), player, currLevel, 2): GameManager.move(playerName, intifyTuple(dest), game) # pot bug not mutating?? managerTrace.append( getMoveStatus(currLevel, playerName, move)) # pot bug wrong return types?? managerTrace = getPlayersUpdates(game, managerTrace) validMove = True else: managerTrace.append([playerName, move, "Invalid"]) validMove = False del playerMoveList[0] i += 1 return managerTrace, game
def getMoveStatus(currLevel: Level, playerName: str, move: dict): dest = intifyTuple(move["to"]) if destHasKey(dest, currLevel): return [playerName, move, "Key"] elif destHasExit(dest, currLevel): return [playerName, move, "Exit"] elif destHasEnemy(dest, currLevel.boards[whichBoardInLevel(currLevel, dest)]): return [playerName, move, "Eject"] else: return [playerName, move, "OK"]
def convertJsonRoom(origin: list, boundaryData: list, tileLayout: list): boardEnum = BoardEnum.ROOM dimensions = intifyTuple(tuple(boundaryData)) upperLeftCorner = intifyTuple(tuple(origin)) tiles = dict() doorLocations = [] for r in range(len(tileLayout)): relRow = r + upperLeftCorner[0] tempColDict = dict() for c in range(len(tileLayout[r])): relCol = c + upperLeftCorner[1] if tileLayout[r][c] == 0: tempColDict[relCol] = Tile(TileEnum.WALL) elif tileLayout[r][c] == 2: tempColDict[relCol] = Tile(TileEnum.DOOR) doorLocations.append((relRow, relCol)) else: tempColDict[relCol] = Tile(TileEnum.DEFAULT) tiles[relRow] = tempColDict return Board(tiles, upperLeftCorner, dimensions, boardEnum, doorLocations)
def convertJsonRoom(origin: list, boundaryData: list, tileLayout: list): boardEnum = BoardEnum.ROOM dimensions = intifyTuple(tuple(boundaryData)) upperLeftCorner = intifyTuple(tuple(origin)) tiles = [] doorLocations = [] for i in range(len(tileLayout)): for j in range(len(tileLayout[i])): relX = i + upperLeftCorner[0] relY = j + upperLeftCorner[1] if tileLayout[i][j] == 0: temp = Tile(TileEnum.WALL, (relX, relY), False) tiles.append(temp) elif tileLayout[i][j] == 2: temp = Tile(TileEnum.DOOR, (relX, relY), False) tiles.append(temp) doorLocations.append((relX, relY)) else: temp = Tile(TileEnum.DEFAULT, (relX, relY), False) tiles.append(temp) return Board(tiles, upperLeftCorner, dimensions, boardEnum, doorLocations)
def convertJsonHallway(fromPoint: list, toPoint: list, waypoints: list): allWaypoints = waypoints + [toPoint] fromTemp = fromPoint tiles = [] while len(allWaypoints) > 0: toTemp = allWaypoints[0] fromX, fromY = intifyTuple(tuple(fromTemp)) toX, toY = intifyTuple(tuple(toTemp)) if fromX == toX: toBigger = toY > fromY for i in range(0, abs(toY - fromY)): newTilePos = (fromX, fromY + i) if toBigger else (fromX, fromY - i) newTile = Tile(TileEnum.DEFAULT, newTilePos) tiles.append(newTile) elif fromY == toY: toBigger = toX > fromX for i in range(0, abs(toX - fromX)): newTilePos = (fromX + i, fromY) if toBigger else (fromX - i, fromY) newTile = Tile(TileEnum.DEFAULT, newTilePos) tiles.append(newTile) else: print(" YOU GAVE US A BAD LIST OF WAYPOINTS SIR") fromTemp = toTemp fromX, fromY = fromTemp del allWaypoints[0] tiles.append(Tile(TileEnum.DEFAULT, tuple(toPoint))) # NOTE: origin = -1,-1 for a hallway board = Board(tiles, intifyTuple(tuple(fromPoint)), (-1, -1), BoardEnum.HALLWAY, [intifyTuple(tuple(fromPoint)), intifyTuple(tuple(toPoint))]) # for tile in board.tiles: # log(str(tile.location)) return board
def executeTurn(conn: socket.socket): """ Awaits a move from the given player connection and returns a location tuple or None if turn is skipped or connection fails. :params conn: socket.socket """ conn.sendall("move".encode('utf-8')) while True: try: resp = conn.recv(4096).decode('utf-8') playerMove = json.loads(resp) conn.sendall("\nok".encode('utf-8')) to = intifyTuple(playerMove["to"]) if playerMove["to"] else None return to except json.JSONDecodeError: # FIXME getting eof tries to decode but sock disconnected conn.sendall("Invalid move. Try again".encode('utf-8')) except ConnectionResetError: raise PlayerDisconnect except BrokenPipeError: raise PlayerDisconnect
def objectOutput(objects: list, givenPoint: tuple): for entry in objects: if intifyTuple(tuple(entry['position'])) == givenPoint: return entry['type'] return None
def convertJsonEnemy(jsonEnemy: dict): newEnemy = Enemy(jsonEnemy["name"], intifyTuple(jsonEnemy["position"])) return newEnemy
def convertJsonPlayer(jsonPlayer: dict): newPlayer = Player(jsonPlayer["name"], intifyTuple(jsonPlayer["position"])) return newPlayer