private void GenerateInitalRooms(LevelGraph playerLevel, string player, int quadrant, int levelXOffset, int levelZOffset) { int[] quadrantRooms; quadrantRooms = GetRoomExceptionsByQuadrant(quadrant); GenerateTutorialRooms(player, quadrantRooms); int skipRoom = quadrantRooms[1]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { int roomNumber = (i * size) + j; if (roomNumber != skipRoom) { int xOffset = j * 40 + levelXOffset; int zOffset = i * 32 + levelZOffset; Vector3 roomPosition = new Vector3(xOffset, 0, zOffset); // Create room in scene hierarchy string roomSuffix = RandomRoomPrefab(); string roomColor = Regex.Match(roomSuffix, @"\D+").Groups[0].Value; string name = "Room" + player + "-" + roomNumber; GameObject newRoom = GenerateRoom(roomSuffix, name, roomPosition, roomColor); // Add room to graph Node newRoomNode = AddGraphNode(playerLevel, newRoom, roomNumber, quadrantRooms, roomColor); GenerateDoorsAndWalls(playerLevel, newRoomNode, newRoom.transform, player, roomNumber, roomColor, roomPosition, quadrantRooms); } } } }
public GDWorldMapScreen(MonoSAMGame game, GraphicsDeviceManager gdm, GraphBlueprint g, Guid?initialFocus) : base(game, gdm) { Graph = new LevelGraph(this); GraphBlueprint = g; Initialize(g, initialFocus); }
public static Ghost Orange(LevelGraph graph) => new Ghost { _graph = graph, _targetPicker = new OrangeGhostTargetPicker(), _color = Color.Orange, _startPosition = new Vector2(13, 11), _homePosition = new Vector2(0, 33), };
public static Ghost Pink(LevelGraph graph) => new Ghost { _graph = graph, _targetPicker = new PinkGhostTargetPicker(), _color = Color.Pink, _startPosition = new Vector2(13, 11), _homePosition = new Vector2(0, -2), };
public static Ghost Blue(LevelGraph graph) => new Ghost { _graph = graph, _targetPicker = new BlueGhostTargetPicker(), _color = Color.Cyan, _startPosition = new Vector2(12, 11), _homePosition = new Vector2(28, 33), };
public static Ghost Red(LevelGraph graph) => new Ghost { _graph = graph, _targetPicker = new RedGhostTargetPicker(), _color = Color.Red, _startPosition = new Vector2(11, 11), _homePosition = new Vector2(24, -2), };
private static void OpenWindow(LevelGraph levelGraph) { var type = Type.GetType("UnityEditor.GameView,UnityEditor"); var window = EditorWindow.GetWindow <LevelGraphEditor>("Graph editor", type); window.Initialize(levelGraph); window.Show(); }
/// <summary> /// Setups default room shapes. /// These are used if a room does not have any room shapes assigned. /// </summary> /// <param name="mapDescription"></param> /// <param name="levelGraph"></param> protected void SetupDefaultRoomShapes(MapDescription <int> mapDescription, LevelGraph levelGraph) { var roomDescriptions = GetRoomDescriptions(levelGraph.DefaultRoomTemplateSets, levelGraph.DefaultIndividualRoomTemplates).Distinct(); foreach (var roomDescription in roomDescriptions) { mapDescription.AddRoomShapes(roomDescription); } }
/// <summary> /// Chunk generate method /// </summary> /// <param name="prevChunk"></param> /// <param name="offset"></param> /// <returns></returns> public Chunk GenerateChunk(Chunk prevChunk = null, float offset = 0) { var graph = LevelGraph.Generate(width, length, prevChunk?.graph); var offsetVector = new Vector3(0, 0, offset); var objects = GenerateCells(graph, levelConfig, levelObjectsPool, offsetVector); objects.AddRange(GenerateItems(graph, levelConfig, levelObjectsPool, offsetVector)); return(new Chunk(graph, objects, offsetVector)); }
/// <summary> /// Generate chunk items by graph nodes /// </summary> /// <param name="graph"></param> /// <param name="levelConfig"></param> /// <param name="pool"></param> /// <param name="chunkPosition"></param> /// <returns></returns> private static List <LevelObject> GenerateItems(LevelGraph graph, LevelConfig levelConfig, LevelObjectsPool pool, Vector3 chunkPosition) { const int itemsCount = 5; const int itemsCountOffset = 1; var levelObjects = new List <LevelObject>(); var orderedItems = levelConfig.items.OrderBy(item => item.generateChance).ToArray(); // Generate one items chain per graph row in random lane for (var y = 0; y < graph.length; y++) { var xShuffle = Shuffle <int> .ToQueue(Enumerable.Range(0, graph.width)); while (xShuffle.Count > 0) { var x = xShuffle.Dequeue(); var node = graph.nodes.Get(x, y); if (!node.passable) { continue; } var target = GetRandom(node.exits); // Build smooth items "path" by Bezier curve var offset = new Vector3(0, 0, 0.5f); var a = new Vector3(node.position.x, 0, node.position.y * LevelGraph.CellsPerNode) + offset; var d = new Vector3(target.x, 0, target.y * LevelGraph.CellsPerNode) + offset; var middle = new Vector3(0, 0, d.z - a.z) * 0.5f; var b = a + middle; var c = d - middle; var bezier = new Bezier(a, b, c, d); // Place items on curve in some range var from = Random.Range(0, itemsCountOffset + 1); var to = Random.Range(0, itemsCountOffset + 1) + itemsCount - itemsCountOffset; for (var i = from; i < to; i++) { var chance = Random.value; var inChunkPosition = bezier.GetPoint(1f / itemsCount * i); foreach (var itemConfig in orderedItems) { if (!itemConfig.CheckChance(chance)) { continue; } levelObjects.Add(itemConfig.SetupInstance(pool.CreateFor(itemConfig), inChunkPosition, chunkPosition)); break; } } break; } } return(levelObjects); }
private const float CutDistance = -3; // todo remove from here public Chunk(LevelGraph graph, IEnumerable <LevelObject> chunkObjects, Vector3 worldPosition) { this.graph = graph; this.worldPosition = worldPosition; objects = chunkObjects.ToList(); foreach (var levelObject in objects) { levelObject.SetActive(true); } }
public LevelMetadata GenerateLevel(int seed) { Random.InitState(seed); LevelGraph levelGraph = new LevelGraph(); levelGraph.GenerateGraph(preset.RoomCount, preset.CritPathLength, preset.MaxDoors, preset.Distribution); ProceduralLevel level = new ProceduralLevel(levelGraph, preset, true); return(level.LevelMetadata); }
public async override void PostInitialisation(object info = null) { if (LevelGraph != null) { LevelGraph.InitPlot("Date", "Level", format: "dd-MMM", relative: false); } if (MoneyGraph != null) { MoneyGraph.InitPlot("Date", "Value", format: "dd-MMM", relative: false); } }
//Creates a visual representation of the level graph using a free tree algorithm //The positions are written to the node instances private void GenerateLevel(LevelGraph graph) { FreeTreeVisualization freeTree = new FreeTreeVisualization(distance * 10f, graph.NodesCreated, graph.Rootnode); freeTree.FreeTree(); GenerateLevel(rootnode, null); if (isSeparate) { SeparateRooms(); } }
private void Generate() { ClearLevel(); if (randomizeSeed) { preset.Seed = Random.Range(0, 10000); } Random.InitState(preset.Seed); levelGraph = new LevelGraph(); levelGraph.GenerateGraph(preset.RoomCount, preset.CritPathLength, preset.MaxDoors, preset.Distribution); ProceduralLevel level = new ProceduralLevel(levelGraph, preset, debugInfo.SetStatic); SetDebugData(level.DebugData); //generatedObjects = level.GeneratedRooms; }
private void InitializeGameLevelRoom() { pathfinding = new LevelGraph((int)Size.Width, (int)Size.Height); for (int count = 0; count < pathfinding.Nodes.Length; count++) { pathfinding.Nodes[count].Position = GetWorldCoordinates(pathfinding.Nodes[count].Position); } for (int count = 0; count < SpawnPoints.Count; count++) { SpawnPoints[count] = GetWorldCoordinates(SpawnPoints[count]); } for (int count = 0; count < GoalPoints.Count; count++) { GoalPoints[count] = GetWorldCoordinates(GoalPoints[count]); } InitializeGameGraph(); }
private void UpdateLevelUsingGraph(LevelGraph playerLevel, string player) { // Replace doors that have been removed with walls foreach (Edge edge in playerLevel.RemovedDoorList) { ReplaceDoorWithWall(player, edge); } playerLevel.ClearRemovedDoors(); // Find all rooms with no doors attached and remove them; List <Node> isolatedRooms = playerLevel.GetIsolatedRooms(); foreach (Node room in isolatedRooms) { Destroy(room.RoomObject); } }
private Node AddGraphNode(LevelGraph playerLevel, GameObject newRoom, int roomNumber, int[] quadrantRooms, string roomColor) { Node newRoomNode = new Node(newRoom, roomNumber, roomColor); if (roomNumber == quadrantRooms[4]) { // Tutorial Adjacent Room playerLevel.TutorialAdjRoom = newRoomNode; } else if (roomNumber == quadrantRooms[2]) { // Switch Adjacent Room playerLevel.SwitchAdjRoom = newRoomNode; } // All other core level rooms playerLevel.RoomList.Add(newRoomNode); return(newRoomNode); }
/// <summary> /// Setups corridor room shapes. /// </summary> /// <param name="mapDescription"></param> /// <param name="levelGraph"></param> protected void SetupCorridorRoomShapes(MapDescription <int> mapDescription, LevelGraph levelGraph) { var corridorLengths = new List <int>(); var roomDescriptions = GetRoomDescriptions(levelGraph.CorridorRoomTemplateSets, levelGraph.CorridorIndividualRoomTemplates).Distinct().ToList(); if (roomDescriptions.Count == 0) { throw new ArgumentException("There must be at least 1 corridor room template if corridors are enabled."); } foreach (var roomDescription in roomDescriptions) { mapDescription.AddCorridorShapes(roomDescription); var corridorLength = RoomShapesLoader.GetCorridorLength(roomDescription); corridorLengths.Add(corridorLength); } mapDescription.SetWithCorridors(true, corridorLengths.Distinct().ToList()); }
private void SetAllDoorLightColors(LevelGraph playerLevel, string player) { // Set tutorial room light GameObject tutorialRoom = GameObject.Find("Room" + player + "TutorialExit"); string roomColor = playerLevel.TutorialAdjRoom.RoomColor; int tutorialAdjRoomNumber = playerLevel.TutorialAdjRoom.RoomNumber; string doorName = "DoorWest"; if (tutorialAdjRoomNumber == 0 || tutorialAdjRoomNumber == size * (size - 1)) { doorName = "DoorEast"; } ChangeDoorColor(tutorialRoom, doorName, roomColor); // Set switch room light GameObject switchRoom = GameObject.Find("Room100"); roomColor = playerLevel.SwitchAdjRoom.RoomColor; int switchAdjRoomNumber = playerLevel.SwitchAdjRoom.RoomNumber; doorName = "DoorSwitchEnterLeft"; if (switchAdjRoomNumber == 1 || switchAdjRoomNumber == size - 2) { doorName = "DoorSwitchEnterRight"; } ChangeDoorColor(switchRoom, doorName, roomColor); // Set core dungeon lights foreach (Edge edge in playerLevel.DoorList) { GameObject roomObject1 = edge.door1.RoomInside.RoomObject; GameObject roomObject2 = edge.door2.RoomInside.RoomObject; string roomColor1 = edge.door1.RoomInside.RoomColor; string roomColor2 = edge.door2.RoomInside.RoomColor; string doorName1 = "Door" + edge.door1.Direction; string doorName2 = "Door" + edge.door2.Direction; ChangeDoorColor(roomObject1, doorName1, roomColor2); ChangeDoorColor(roomObject2, doorName2, roomColor1); } }
/// <summary> /// Initialize the window with a given level graph. /// </summary> /// <param name="levelGraph"></param> public void Initialize(LevelGraph levelGraph) { LevelGraph = levelGraph; CurrentState = State.Idle; zoom = LevelGraph.EditorData.Zoom; panOffset = LevelGraph.EditorData.PanOffset; snapToGrid = EditorPrefs.GetBool(EditorConstants.SnapToGridEditorPrefsKey, false); connectionStartNode = null; // Initialize room nodes roomNodes = new List <RoomNode>(); foreach (var room in LevelGraph.Rooms) { if (room != null) { CreateRoomNode(room); } else { Debug.LogError($"There is a null room in the level graph {levelGraph.name}. This should not happen."); } } // Initialize connection nodes connectionNodes = new List <ConnectionNode>(); foreach (var connection in LevelGraph.Connections) { if (connection != null) { CreateConnectionNode(connection); } else { Debug.LogError($"There is a null connection in the level graph {levelGraph.name}. This should not happen."); } } }
public ProceduralLevel(LevelGraph graph, LevelGeneratorPreset preset, bool setIsStatic) { //IMPORTANT, multiply with the door size. Doors require the chunk to be aligned on the grid on GENERATION time //Ensure, that chunks are on the grid, since the doors align to the grid regardless of the chunk position, which //Will result in shifted doorpositions on repositioning the chunks tmpChunkPos = DoorDefinition.GlobalSize * -5000f; tmpChunkStep = DoorDefinition.GlobalSize * -50f; isGenerating = true; this.preset = preset; this.hallwayTiling = preset.HallwayTiling; this.distance = preset.RoomDistance; this.rootnode = graph.Rootnode; this.spacing = preset.Spacing; this.isSeparate = preset.IsSeparateRooms; this.hallwayMaterials = preset.HallwayMaterials; this.helper = new ChunkHelper(preset); this.debugData = new DebugData(); this.chunkInstantiator = ChunkInstantiator.Instance; this.hallwayMeta = new List <HallwayMeta> (); this.positionMeta = new List <RoomTransformation>(); this.levelMetadata = new LevelMetadata(); this.setIsStatic = setIsStatic; GenerateLevel(graph); if (!isConstraintError) { ApplyTransformation(); CreateHallways(); } else { HandleRollback(); } helper.CleanUp(); ChunkInstantiator.RemoveManualProperties(); isGenerating = false; }
private Embed createLevelEmbed(Character oldC, Character newC) { var mChanged = oldC.masteryLevel != newC.masteryLevel; var levelChanged = oldC.level != newC.level; var embed = new EmbedBuilder(); embed.WithColor(222, 39, 0); embed.WithTitle($"{newC.name} leveled up!").WithCurrentTimestamp(); embed.AddField("Name", newC.name, true); embed.AddField("Playtime", TimeSpan.FromSeconds(newC.age).ToString(@"d\d\ h\h\ m\m\ s\s"), true); embed.AddField("Gender", newC.gender, true); embed.AddField("Class", newC.profession, true); embed.AddField("Level", newC.level + (levelChanged ? $" (+{newC.level - oldC.level})" : ""), true); embed.AddField("Mastery-Level", newC.masteryLevel + (mChanged ? $" (+{newC.masteryLevel - oldC.masteryLevel})" : ""), true); embed.WithFooter(x => { x.Text = "GW2Tracker"; x.IconUrl = "https://1001019.v1.pressablecdn.com/wp-content/uploads/2012/08/GW2-Logo.jpg"; }); embed.WithImageUrl(LevelGraph.DrawPlot()); return(embed.Build()); }
public void Initialize() { SetupStyles(); var roomToRoomNodes = new Dictionary <Room, RoomNode>(); roomNodes = new List <RoomNode>(); foreach (var data in Data.Rooms) { var roomNode = CreateNode(data); roomToRoomNodes.Add(data, roomNode); } connectionNodes = new List <ConnectionNode>(); foreach (var data in Data.Connections) { CreateConnection(data, roomToRoomNodes[data.From], roomToRoomNodes[data.To]); } editorMode = EditorMode.Drag; connectionFrom = null; connectionProgress = null; StaticData = Data; }
/// <summary> /// Generate chunk cells by graph nodes /// </summary> /// <param name="graph"></param> /// <param name="levelConfig"></param> /// <param name="pool"></param> /// <param name="chunkPosition"></param> /// <returns></returns> private static List <LevelObject> GenerateCells(LevelGraph graph, LevelConfig levelConfig, LevelObjectsPool pool, Vector3 chunkPosition) { const int cellsPerNode = LevelGraph.CellsPerNode; var chunkLength = graph.length * cellsPerNode; var chunkWidth = graph.width; var obstaclePlaces = new List <Vector2Int>(); // Fill grid by wall and floor random configs var cells = new Grid <CellConfig>(chunkWidth, chunkLength); for (var l = 0; l < graph.length; l++) { for (var x = 0; x < graph.width; x++) { var node = graph.nodes.Get(x, l); var end = l * cellsPerNode + cellsPerNode; if (node.passable) { var y = l * cellsPerNode; var coordinates = new Vector2Int(x, y); // Store passable coordinate for placing some obstacle obstaclePlaces.Add(coordinates); for (; y < end; y++) { cells.Set(x, y, GetRandom(levelConfig.floors)); } } else { var y = l * cellsPerNode; cells.Set(x, y, levelConfig.walls[Random.Range(0, levelConfig.walls.Length)]); y++; if (graph.nodes.TryGet(x, l + 1, out var nextNode) && !nextNode.passable) { for (; y < end; y++) { cells.Set(x, y, GetRandom(levelConfig.walls)); } } else { for (; y < end; y++) { cells.Set(x, y, GetRandom(levelConfig.floors)); } } } } } // Try to place random obstacle config in previously founded coordinates foreach (var coordinates in obstaclePlaces) { var chance = Random.value; var obstacleConfigs = Shuffle <CellConfig> .ToQueue(levelConfig.obstacles); while (obstacleConfigs.Count > 0) { var config = obstacleConfigs.Dequeue(); // Check if obstacle placement restrictions passed if (!config.CheckPlacement(chance, coordinates, cells)) { continue; } cells.Set(coordinates, config); break; } } // Setup instances var gameObjects = new List <LevelObject>(cells.items.Length); gameObjects.AddRange(cells.items.Select((t, i) => t.SetupInstance(pool.CreateFor(t.prefab), ToVector3(cells.GetIndexCoordinates(i)), chunkPosition))); return(gameObjects); }
public void Awake() { instance = this; this.MakeStartingNodes(); // this.FillMap(); }
private Node AddGraphNode(LevelGraph playerLevel, GameObject newRoom, int roomNumber, int[] quadrantRooms, string roomColor) { Node newRoomNode = new Node(newRoom, roomNumber, roomColor); if (roomNumber == quadrantRooms[4]) { // Tutorial Adjacent Room playerLevel.TutorialAdjRoom = newRoomNode; } else if (roomNumber == quadrantRooms[2]) { // Switch Adjacent Room playerLevel.SwitchAdjRoom = newRoomNode; } // All other core level rooms playerLevel.RoomList.Add(newRoomNode); return newRoomNode; }
private void ClearWindow() { LevelGraph = null; connectionNodes.Clear(); roomNodes.Clear(); }
private void UpdateLevelUsingGraph(LevelGraph playerLevel, string player) { // Replace doors that have been removed with walls foreach (Edge edge in playerLevel.RemovedDoorList) { ReplaceDoorWithWall(player, edge); } playerLevel.ClearRemovedDoors(); // Find all rooms with no doors attached and remove them; List<Node> isolatedRooms = playerLevel.GetIsolatedRooms(); foreach (Node room in isolatedRooms) { Destroy(room.RoomObject); } }
private void GenerateDoorsAndWalls(LevelGraph playerLevel, Node roomNode, Transform doorParent, string player, int roomNum, string roomColor, Vector3 offset, int[] quadrantRooms) { const string switchRoomNumber = "100"; int quadrant = quadrantRooms[0]; bool switchDoor, switchWall, tutorialDoor; switchDoor = switchWall = tutorialDoor = false; if (roomNum == quadrantRooms[2]) { switchDoor = true; } else if (roomNum == quadrantRooms[3]) { switchWall = true; } else if (roomNum == quadrantRooms[4]) { tutorialDoor = true; } bool spawnWall; GameObject newObj; foreach (string direction in directions) { if (direction == "East") { spawnWall = (roomNum % size == (size - 1)) && !switchDoor && !tutorialDoor; } else if (direction == "West") { spawnWall = (roomNum % size == 0) && !switchDoor && !tutorialDoor; } else if (direction == "North") { spawnWall = (roomNum >= (size * (size - 1))) || (switchWall && quadrant <= 1); } else { spawnWall = (roomNum < size) || (switchWall && quadrant >= 2); } newObj = GenerateDoorOrWall(direction, player, roomNum, roomColor, offset, spawnWall); newObj.transform.SetParent(doorParent); if (direction == "East") { if (switchDoor && (quadrant == 0 || quadrant == 2)) { newObj.GetComponent <DoorController>().nextRoomNum = switchRoomNumber; GameObject.Find("DoorSwitchEnterLeft").GetComponent <DoorController>().nextRoomNum = player + "-" + roomNum; continue; } else if (tutorialDoor && (quadrant == 1 || quadrant == 3)) { newObj.GetComponent <DoorController>().nextRoomNum = player + "TutorialExit"; continue; } } else if (direction == "West") { if (switchDoor && (quadrant == 1 || quadrant == 3)) { newObj.GetComponent <DoorController>().nextRoomNum = switchRoomNumber; GameObject.Find("DoorSwitchEnterRight").GetComponent <DoorController>().nextRoomNum = player + "-" + roomNum; continue; } else if (tutorialDoor && (quadrant == 0 || quadrant == 2)) { newObj.GetComponent <DoorController>().nextRoomNum = player + "TutorialExit"; continue; } } // Add to graph if (!spawnWall) { int connectingRoom = GetConnectingRoom(roomNum, direction); // Only add doors connected to rooms with a lower number (avoid duplicates) if (connectingRoom < roomNum) { Node adjacentNode = playerLevel.GetRoomByNumber(connectingRoom); // Debug to make sure no null adjacent nodes are found if (adjacentNode == null) { Debug.LogError(player + ": room #" + roomNode.RoomNumber + " returned NULL adjacent room node #" + connectingRoom); } Edge newEdge = new Edge(roomNode, direction, adjacentNode); playerLevel.DoorList.Add(newEdge); } } } }
// Use this for initialization void Start() { GameObject rootNode = new GameObject("Root"); GameObject roomsObject = new GameObject("Rooms"); roomParent = roomsObject.transform; roomParent.SetParent(rootNode.transform); // Get level inputs - difficulty, size, and seed // maxDifficulty = LevelData.levelDifficulty; // depreciated, may be used later.. size = LevelData.levelSize; if (LevelData.randomLevel) { LevelData.GenerateRandomSeed(); } seed = LevelData.levelSeed; Debug.Log("Using Seed: " + seed); pseudoRandom = new System.Random(seed); // Instantiate Room Prefabs and Room Colors Remaning Lists //FillEmptyRoomColorList(); foreach (string color in colors) { ResetPrefabsRemainingByColor(color); } // Add the number and difficulty of each enemy color enemyTypeDifficulty.Add("Red", new int[] { 1, 2, 3 }); enemyTypeDifficulty.Add("Green", new int[] { 1, 2, 4 }); enemyTypeDifficulty.Add("Blue", new int[] { 1, 2, 3, 4 }); // Randomize level positioning int rightSidePlayer = pseudoRandom.Next(2); int topHalfPlayer = pseudoRandom.Next(2); // Generate gauntlet gauntletPosition = new Vector3((size - 1) * 40, 0, (size - 1) * 32); GenerateRoom("Gauntlet", "RoomGauntlet", gauntletPosition); string[] players = new string[] { "P1", "P2" }; foreach (string player in players) { // Quadrant: 0=bottom-left, 1=bottom-right, 2=top-left, 3=top-right int quadrant, xOffset, zOffset; quadrant = xOffset = zOffset = 0; bool shiftRight = (player == "P1" && rightSidePlayer == 0) || (player == "P2" && rightSidePlayer == 1); if (shiftRight) { xOffset = (size - 1) * 40; quadrant++; } bool shiftUp = (player == "P1" && topHalfPlayer == 0) || (player == "P2" && topHalfPlayer == 1); if (shiftUp) { zOffset = (size - 1) * 32; quadrant = quadrant + 2; } // Instantiate individual player level's LevelGraph playerLevel; if (player == "P1") { player1Level = new LevelGraph(player); playerLevel = player1Level; } else { player2Level = new LevelGraph(player); playerLevel = player2Level; } GenerateInitalRooms(playerLevel, player, quadrant, xOffset, zOffset); } // Perform graph traversal algorithms on both player's level graphs foreach (string player in players) { LevelGraph playerLevel; if (player == "P1") { playerLevel = player1Level; } else { playerLevel = player2Level; } playerLevel.AddAllAdjacentRooms(); playerLevel.GenerateLevel(pseudoRandom); // Calculate each room's distance from the switch room and spawn enemies based on that playerLevel.CalculateRoomDistances(); // Do a final level update to remove all distant deadend room chains playerLevel.PruneDistantDeadends(); // Modify in-game model of level to what the graph structure represents UpdateLevelUsingGraph(playerLevel, player); int maxDistance = playerLevel.MaxDistance; foreach (Node roomNode in playerLevel.RoomList) { string roomColor = roomNode.RoomObject.GetComponent <RoomController>().RoomColor; SpawnEnemies(roomNode, maxDistance, roomColor); } SetAllDoorLightColors(playerLevel, player); // playerLevel.Print(); } LoadRemainingAssets(); }
private void GenerateDoorsAndWalls(LevelGraph playerLevel, Node roomNode, Transform doorParent, string player, int roomNum, string roomColor, Vector3 offset, int[] quadrantRooms) { const string switchRoomNumber = "100"; int quadrant = quadrantRooms[0]; bool switchDoor, switchWall, tutorialDoor; switchDoor = switchWall = tutorialDoor = false; if (roomNum == quadrantRooms[2]) { switchDoor = true; } else if (roomNum == quadrantRooms[3]) { switchWall = true; } else if (roomNum == quadrantRooms[4]) { tutorialDoor = true; } bool spawnWall; GameObject newObj; foreach (string direction in directions) { if (direction == "East") { spawnWall = (roomNum % size == (size - 1)) && !switchDoor && !tutorialDoor; } else if (direction == "West") { spawnWall = (roomNum % size == 0) && !switchDoor && !tutorialDoor; } else if (direction == "North") { spawnWall = (roomNum >= (size * (size - 1))) || (switchWall && quadrant <= 1); } else { spawnWall = (roomNum < size) || (switchWall && quadrant >= 2); } newObj = GenerateDoorOrWall(direction, player, roomNum, roomColor, offset, spawnWall); newObj.transform.SetParent(doorParent); if (direction == "East") { if (switchDoor && (quadrant == 0 || quadrant == 2)) { newObj.GetComponent<DoorController>().nextRoomNum = switchRoomNumber; GameObject.Find("DoorSwitchEnterLeft").GetComponent<DoorController>().nextRoomNum = player + "-" + roomNum; continue; } else if (tutorialDoor && (quadrant == 1 || quadrant == 3)) { newObj.GetComponent<DoorController>().nextRoomNum = player + "TutorialExit"; continue; } } else if (direction == "West") { if (switchDoor && (quadrant == 1 || quadrant == 3)) { newObj.GetComponent<DoorController>().nextRoomNum = switchRoomNumber; GameObject.Find("DoorSwitchEnterRight").GetComponent<DoorController>().nextRoomNum = player + "-" + roomNum; continue; } else if (tutorialDoor && (quadrant == 0 || quadrant == 2)) { newObj.GetComponent<DoorController>().nextRoomNum = player + "TutorialExit"; continue; } } // Add to graph if (!spawnWall) { int connectingRoom = GetConnectingRoom(roomNum, direction); // Only add doors connected to rooms with a lower number (avoid duplicates) if (connectingRoom < roomNum) { Node adjacentNode = playerLevel.GetRoomByNumber(connectingRoom); // Debug to make sure no null adjacent nodes are found if (adjacentNode == null) { Debug.LogError(player + ": room #" + roomNode.RoomNumber + " returned NULL adjacent room node #" + connectingRoom); } Edge newEdge = new Edge(roomNode, direction, adjacentNode); playerLevel.DoorList.Add(newEdge); } } } }
public void CreateGraphAs3X2Grid() { grid3X2 = new LevelGraph(3, 2); }
protected async override void CheckForChange_Elapsed(object stateinfo) { try { if (ChannelConfig.Any(x => (bool)x.Value[TRACKLEVEL])) { if (PastInformation.character == null) { PastInformation.character = await GetCharacterEndpoint(CharacterName, APIKey); LevelGraph = new DatePlot($"{CharacterName.Replace(" ", "")}Level", "Date", "Level", "dd-MMM", false, true); LevelGraph.AddValueSeperate("Level", PastInformation.character.level, relative: false); LevelGraph.AddValueSeperate("M-Level", PastInformation.character.masteryLevel, relative: false); await UpdateTracker(); } else { Character pastInfo = PastInformation.character; Character currentInfo = await GetCharacterEndpoint(CharacterName, APIKey); if (currentInfo.level != pastInfo.level || currentInfo.masteryLevel != pastInfo.masteryLevel) { LevelGraph.AddValueSeperate("Level", pastInfo.level, relative: false); LevelGraph.AddValueSeperate("M-Level", pastInfo.masteryLevel, relative: false); LevelGraph.AddValueSeperate("Level", currentInfo.level, relative: false); LevelGraph.AddValueSeperate("M-Level", currentInfo.masteryLevel, relative: false); foreach (var channel in ChannelConfig.Where(x => (bool)x.Value[TRACKLEVEL])) { await OnMajorChangeTracked(channel.Key, createLevelEmbed(pastInfo, currentInfo)); } PastInformation.character = currentInfo; await UpdateTracker(); } } } if (ChannelConfig.Any(x => (bool)x.Value[TRACKACHIEVEMENTS])) { //ToDo } if (ChannelConfig.Any(x => (bool)x.Value[TRACKWEALTH])) { if (PastInformation.wallet == null) { PastInformation.wallet = (await GetWealth(APIKey)).FirstOrDefault(); MoneyGraph = new DatePlot($"{CharacterName.Replace(" ", "")}Gold", "Date", "Gold", "dd-MMM", false); MoneyGraph.AddValue("Gold", PastInformation.wallet.value, relative: false); await UpdateTracker(); } else { Wallet pastInfo = PastInformation.wallet; Wallet currentInfo = (await GetWealth(APIKey)).FirstOrDefault(); if (currentInfo.value != pastInfo.value) { MoneyGraph.AddValue("Gold", pastInfo.value, relative: false); MoneyGraph.AddValue("Gold", currentInfo.value, relative: false); foreach (var channel in ChannelConfig.Where(x => (bool)x.Value[TRACKWEALTH])) { await OnMajorChangeTracked(channel.Key, createWealthEmbed(pastInfo, currentInfo)); } PastInformation.wallet = currentInfo; await UpdateTracker(); } } } if (ChannelConfig.Any(x => (bool)x.Value[TRACKTPBUYS])) { if (PastInformation.buy == null) { PastInformation.buy = (await GetTPBuys(APIKey)).FirstOrDefault(); await UpdateTracker(); } else { TPTransaction pastInfo = PastInformation.buy; List <TPTransaction> currentInfo = (await GetTPBuys(APIKey)).TakeWhile(x => x.purchased > pastInfo.purchased).ToList(); currentInfo.Reverse(); foreach (var transaction in currentInfo) { foreach (var channel in ChannelConfig.Where(x => (bool)x.Value[TRACKTPBUYS])) { await OnMajorChangeTracked(channel.Key, await CreateTPBuyEmbed(transaction)); } } if (currentInfo.Count > 0) { PastInformation.buy = currentInfo.LastOrDefault(); await UpdateTracker(); } } } if (ChannelConfig.Any(x => (bool)x.Value[TRACKTPSELLS])) { if (PastInformation.sell == null) { PastInformation.sell = (await GetTPSells(APIKey)).FirstOrDefault(); await UpdateTracker(); } else { TPTransaction pastInfo = PastInformation.sell; List <TPTransaction> currentInfo = (await GetTPSells(APIKey)).TakeWhile(x => x.purchased > pastInfo.purchased).ToList(); currentInfo.Reverse(); foreach (var transaction in currentInfo) { foreach (var channel in ChannelConfig.Where(x => (bool)x.Value[TRACKTPSELLS])) { await OnMajorChangeTracked(channel.Key, await CreateTPSellEmbed(transaction)); } } if (currentInfo.Count > 0) { PastInformation.sell = currentInfo.LastOrDefault(); await UpdateTracker(); } } } if (ChannelConfig.Any(x => (bool)x.Value[TRACKTPDELIVERY])) { if (PastInformation.delivery == null) { PastInformation.delivery = await GetTPInbox(APIKey); await UpdateTracker(); } else { TPInbox pastInfo = PastInformation.delivery; TPInbox currentInfo = await GetTPInbox(APIKey); if (currentInfo.items.Count != pastInfo.items.Count || currentInfo.coins != pastInfo.coins) { foreach (var channel in ChannelConfig.Where(x => (bool)x.Value[TRACKTPDELIVERY])) { await OnMajorChangeTracked(channel.Key, CreateTPInboxEmbed(pastInfo, currentInfo)); } PastInformation.delivery = currentInfo; await UpdateTracker(); } } } if (ChannelConfig.Any(x => (bool)x.Value[TRACKEQUIPMENT])) { } } catch (Exception e) { await Program.MopsLog(new LogMessage(LogSeverity.Error, "", $" error by {Name}", e)); } }
// Use this for initialization void Start () { GameObject rootNode = new GameObject("Root"); GameObject roomsObject = new GameObject("Rooms"); roomParent = roomsObject.transform; roomParent.SetParent(rootNode.transform); // Get level inputs - difficulty, size, and seed // maxDifficulty = LevelData.levelDifficulty; // depreciated, may be used later.. size = LevelData.levelSize; if (LevelData.randomLevel) { LevelData.GenerateRandomSeed(); } seed = LevelData.levelSeed; Debug.Log("Using Seed: " + seed); pseudoRandom = new System.Random(seed); // Instantiate Room Prefabs and Room Colors Remaning Lists //FillEmptyRoomColorList(); foreach (string color in colors) { ResetPrefabsRemainingByColor(color); } // Add the number and difficulty of each enemy color enemyTypeDifficulty.Add("Red", new int[] {1, 2, 3}); enemyTypeDifficulty.Add("Green", new int[] {1, 2, 4}); enemyTypeDifficulty.Add("Blue", new int[] {1, 2, 3, 4}); // Randomize level positioning int rightSidePlayer = pseudoRandom.Next(2); int topHalfPlayer = pseudoRandom.Next(2); // Generate gauntlet gauntletPosition = new Vector3((size - 1) * 40, 0, (size - 1) * 32); GenerateRoom("Gauntlet", "RoomGauntlet", gauntletPosition); string[] players = new string[] {"P1", "P2"}; foreach (string player in players) { // Quadrant: 0=bottom-left, 1=bottom-right, 2=top-left, 3=top-right int quadrant, xOffset, zOffset; quadrant = xOffset = zOffset = 0; bool shiftRight = (player == "P1" && rightSidePlayer == 0) || (player == "P2" && rightSidePlayer == 1); if (shiftRight) { xOffset = (size - 1) * 40; quadrant++; } bool shiftUp = (player == "P1" && topHalfPlayer == 0) || (player == "P2" && topHalfPlayer == 1); if (shiftUp) { zOffset = (size - 1) * 32; quadrant = quadrant + 2; } // Instantiate individual player level's LevelGraph playerLevel; if (player == "P1") { player1Level = new LevelGraph(player); playerLevel = player1Level; } else { player2Level = new LevelGraph(player); playerLevel = player2Level; } GenerateInitalRooms(playerLevel, player, quadrant, xOffset, zOffset); } // Perform graph traversal algorithms on both player's level graphs foreach (string player in players) { LevelGraph playerLevel; if (player == "P1") { playerLevel = player1Level; } else { playerLevel = player2Level; } playerLevel.AddAllAdjacentRooms(); playerLevel.GenerateLevel(pseudoRandom); // Calculate each room's distance from the switch room and spawn enemies based on that playerLevel.CalculateRoomDistances(); // Do a final level update to remove all distant deadend room chains playerLevel.PruneDistantDeadends(); // Modify in-game model of level to what the graph structure represents UpdateLevelUsingGraph(playerLevel, player); int maxDistance = playerLevel.MaxDistance; foreach (Node roomNode in playerLevel.RoomList) { string roomColor = roomNode.RoomObject.GetComponent<RoomController>().RoomColor; SpawnEnemies(roomNode, maxDistance, roomColor); } SetAllDoorLightColors(playerLevel, player); // playerLevel.Print(); } LoadRemainingAssets(); }