Наследование: MonoBehaviour
    protected void paintTerrain(MapCell[,] map, Door d)
    {
        terrain = this.gameObject.GetComponent<Terrain>();
        float[,,] splatmapData = new float[terrain.terrainData.alphamapWidth, terrain.terrainData.alphamapHeight, terrain.terrainData.alphamapLayers];

        float[] splatWallWeights = new float[terrain.terrainData.alphamapLayers];
        splatWallWeights[0] = 0f;
        splatWallWeights[1] = 1f;

        float[] splatFloorWeights = new float[terrain.terrainData.alphamapLayers];
        splatFloorWeights[0] = 1f;
        splatFloorWeights[1] = 0f;

        int indexXmap, indexYmap;
        for (int i = 0; i < splatmapData.GetLength(0); i++)
        {
            for (int j = 0; j < splatmapData.GetLength(1); j++)
            {
                indexXmap = Mathf.Clamp(i/factor, 0, map.GetLength(0) - 1);
                indexYmap = Mathf.Clamp(j/factor, 0, map.GetLength(0) - 1);
                if (map[indexXmap, indexYmap].cellKind == MapCell.CellKind.WALL || map[indexXmap, indexYmap].cellKind == MapCell.CellKind.UNUSED)
                {
                    splatmapData = setSplatWeights(i, j, splatWallWeights, splatmapData);
                }
                else
                {
                    splatmapData = setSplatWeights(i, j, splatFloorWeights, splatmapData);
                }
            }
        }
        terrain.terrainData.SetAlphamaps(0, 0, splatmapData);
        terrain.Flush();
    }
Пример #2
0
 public void connectDoor(Door other)
 {
     otherDoor = other;
     other.otherDoor = (this);
     other.used = true;
     used = true;
 }
Пример #3
0
    // Update is called once per frame
    public void Update()
    {
        if (_lastSelectedCount != WindowCount)
        {
            WindowCountChanged(WindowCount);
            _lastSelectedCount = WindowCount;
        }

        if (_door != Door)
        {
            DoorChanged(Door);
            _door = Door;
        }

        if (_houseMaterial != HouseMaterial)
        {
            HouseMaterialChanged(HouseMaterial);
            _houseMaterial = HouseMaterial;
        }

        if (_doorMaterial != DoorMaterial)
        {
            DoorMaterialChanged(DoorMaterial);
            _doorMaterial = DoorMaterial;
        }

        if (_windowColor != WindowColor)
        {
            WindowColorChanged(WindowColor);
            _windowColor = WindowColor;
        }
    }
Пример #4
0
 private void Spawn(Door.Spawn spawn)
 {
     Vector3 spawnPosition = transform.position;
     switch (spawn) {
         case Door.Spawn.TOP:
             spawnPosition.x = 4.7f;
             spawnPosition.y = 0f;
             break;
         case Door.Spawn.BOTTOM:
             spawnPosition.x = 4.7f;
             spawnPosition.y = 5.5f;
             break;
         case Door.Spawn.LEFT:
             spawnPosition.x = 0f;
             spawnPosition.y = 3.5f;
             break;
         case Door.Spawn.RIGHT:
             spawnPosition.x = 9f;
             spawnPosition.y = 3.5f;
             Flip();
             break;
         case Door.Spawn.CENTER:
             spawnPosition.x = 3.5f;
             spawnPosition.y = 3.5f;
             break;
     }
     transform.position = spawnPosition;
 }
Пример #5
0
        private void UnlockDoor(Door door)
        {
            if (!Inventory.Contains(door.Key))
            {
                Print("You have nothing to unlock that with.");
                return;
            }

            if (IndirectObject == null)
            {
                if (Inventory.Items.Count == 1 && Inventory.Items[0] == door.Key)
                {
                    Print("(with the {0})", door.Key.Name);
                    Print("You unlock the {0}.", Object.Name);
                    Object.IsLocked = false;
                    return;
                }

                ObjectNotSpecified();
            }
            else if (IndirectObject == door.Key)
            {
                Print("You unlock the {0}.", Object.Name);
                Object.IsLocked = false;
            }

        }
 public MazyPrototypeFactory(Maze maze, Wall wall, Room room, Door door)
 {
     _maze = maze;
     _wall = wall;
     _room = room;
     _door = door;
 }
Пример #7
0
 public void TextureGet118()
 {
     using (PexDisposableContext disposables = PexDisposableContext.Create())
     {
       Door door;
       Texture2D texture2D;
       door = new Door
          (1, default(Point), default(Point), 0, default(Point), default(Point),
                                                 Orientation.H, RuneKey.Red, (Texture2D)null);
       door.Opened = false;
       texture2D = this.TextureGet(door);
       disposables.Add((IDisposable)texture2D);
       disposables.Dispose();
       Assert.IsNull((object)texture2D);
       Assert.IsNotNull((object)door);
       Assert.AreEqual<bool>(false, door.Opened);
       Assert.AreEqual<bool>(true, door.IsRuneDoor);
       Assert.AreEqual<RuneKey>(RuneKey.Red, door.KeyColor);
       Assert.AreEqual<Orientation>(Orientation.H, door.Orientation);
       Assert.IsNotNull(door.Areas);
       Assert.AreEqual<int>(2, door.Areas.Length);
       Assert.AreEqual<int>(0, door.Areas[0]);
       Assert.AreEqual<int>(0, door.Areas[1]);
       Assert.IsNull(door.Texture);
     }
 }
 public MazePrototypeFactory(Maze maze, Room room, Door door, Wall wall)
 {
     this.prototypeMaze = maze;
     this.prototypeRoom = room;
     this.prototypeDoor = door;
     this.prototypeWall = wall;
 }
Пример #9
0
    private void Start()
    {
        attachedDoor = gameObject.GetComponent<Door>();

        if (attachedDoor == null)
            Debug.LogError("This script needs to be on a gameObject that has the Door script attached.");
    }
Пример #10
0
    public static void BuildLevel()
    {
        Room room00 = new Room("room 00", "It's clearly a room");

        Room room01 = new Room("room 01", "It's clearly a room");
        Room room02 = new Room("room 02", "It's clearly a room");
        Room room10 = new Room("room 10", "It's clearly a room");
        Room room11 = new Room("room 11", "It's clearly a room");
        Room room12 = new Room("room 12", "It's clearly a room");
        //Room room20 = new Room("room 20", "room description");
        //Room room21 = new Room("room 21", "room description");
        Room room22 = new Room("room 22", "It's clearly a room");

        Item key = new Item("Key", "A brass object used to unlock a specific lock. Commonly known as a 'Key'", room11, null, Action.OpenDoor, room11);
        room11.AddItem(key);

        Door door = new Door("Door", "A wooden board with hinges on one side, usually used to block a passage way. Commonly known as a 'Door'", room12, room22, key, null, Action.None);
        door.locked = true;
        room12.doorSouth = door;
        room12.AddObject(door);
        room22.doorNorth = door;
        room22.AddObject(door);

        dungeon[0, 0] = room00;
        dungeon[0, 1] = room01;
        dungeon[0, 2] = room02;
        dungeon[1, 0] = room10;
        dungeon[1, 1] = room11;
        dungeon[1, 2] = room12;
        //dungeon[2, 0] = room20;
        //dungeon[2, 1] = room21;
        dungeon[2, 2] = room22;

        startingRoom = room00;
    }
 private static void AddOpenInteractions(Door door)
 {
     door.RemoveInteractionByType(OpenDoorToOtherSideInteraction.Singleton);
     door.AddInteraction(OpenDoorToOtherSideInteraction.Singleton);
     door.RemoveInteractionByType(OpenDoorInteraction.Singleton);
     door.AddInteraction(OpenDoorInteraction.Singleton);
 }
Пример #12
0
 public void UseDoor()
 {
     ToggleForceHide();
     Invoke("ToggleForceHide", 6);
     useableDoor = currentDoor.GetComponent<Door>();
     useableDoor.StartNewTeleport();
 }
Пример #13
0
        public void DoorCantBeUnlockedWithNotEnoughClues()
        {
            var testDoor = new Door(new QuickGraph.TaggedEdge<int, string>(0, 1, "test"), new Connection(0, 1), new Connection(0, 1), "door1", 0, 2);
            var clue0 = new Clue(testDoor, new List<int>());

            Assert.IsFalse(testDoor.CanDoorBeUnlockedWithClues(new List<Clue>(new Clue[] { clue0 })));
        }
Пример #14
0
 public void SubmitDirection(Door.Direction directionToSubmit)
 {
     foreach(IOverworldEventListener listener in IterateListeners<IOverworldEventListener>())
     {
         listener.SubmitDirection(directionToSubmit);
     }
 }
Пример #15
0
 public MapCell()
 {
     cellKind = CellKind.UNUSED;
     isBorder = false;
     zoneID = 0; // 0 = zona no asignada.
     door = null;
 }
 // Use this for initialization
 void Start()
 {
     meshRenderer = GetComponent<MeshRenderer>();
     boxCollider = GetComponent<BoxCollider>();
     cameraController = FindObjectOfType<CameraController>();
     cartController = FindObjectOfType<CartController>();
     door = FindObjectOfType<Door>();
 }
 protected void apply(MapCell[,] map,Door door)
 {
     terrain = this.gameObject.GetComponent<Terrain> ();
     //Debug.Log ("Dimensiones del mapa de alturas:" + terrain.terrainData.heightmapWidth + "x" + terrain.terrainData.heightmapHeight);
     float[,] heights = terrain.terrainData.GetHeights (0, 0, terrain.terrainData.heightmapWidth, terrain.terrainData.heightmapWidth);
     applyCellMap (heights,map);
     callPlayerCreator (door);
 }
Пример #18
0
 protected override void OnObjectTriggerExit( Collider pCollider )
 {
     base.OnObjectTriggerExit( pCollider );
     if ( pCollider.transform.parent.tag == "Opendoor" )
     {
         m_Door = null;
     }
 }
Пример #19
0
    // Use this for initialization
    void Start()
    {
        gTimer = this.gameObject.GetComponent<GameTimer>();

        doorCS = GameObject.FindGameObjectWithTag("Door").GetComponent<Door>();

        //personOBJ = GameObject.FindGameObjectWithTag("Detection").GetComponent<DetectionZone>().personOBJ.GetComponent<Person>();
    }
Пример #20
0
 public GearSet(PictureBox gearBox, PictureBox doorBox)
 {
     this.door = new Door();
     this.gear = new Gear();
     this.gearSetState = 0;
     this.gearBox = gearBox;
     this.doorBox = doorBox;
 }
Пример #21
0
    // Use this for initialization
    void Start()
    {
        doorCS = GameObject.FindGameObjectWithTag("Door").GetComponent<Door>();

        SpawnParent = GameObject.Find("People");

        Instantiate(SpawnPepoleOBJ, this.gameObject.transform.position, Quaternion.identity);
    }
Пример #22
0
 // Use this for initialization
 void Start()
 {
     for (int i = 0; i < door.Length; i++)
     {
         doorScript = door[i].GetComponent<Door>();
         doorScript.OpenSeseme();
     }
 }
Пример #23
0
        public void MultipleLockDoorCanBeUnlockedWithEnoughClues()
        {
            var testDoor = new Door(new QuickGraph.TaggedEdge<int, string>(0, 1, "test"), new Connection(0, 1), new Connection(0, 1), "door1", 0, 2);
            var clue0 = new Clue(testDoor, new List<int>());
            var clue1 = new Clue(testDoor, new List<int>());

            Assert.IsTrue(testDoor.CanDoorBeUnlockedWithClues(new List<Clue>(new Clue[] { clue0, clue1 })));
        }
Пример #24
0
 public MapPoint(int x, int y, Door door, int floor, int id = -1)
 {
     this.Id = id;
     this.x = x;
     this.y = y;
     this.door = door;
     this.floor = floor;
 }
Пример #25
0
    public static void changeState(Door controller, Door.Type type, bool locked)
    {
        controller.doorType = type;
        controller.isLocked = locked;

        controller.transform.FindChild("gold-texture").gameObject.SetActive(locked && type == Door.Type.GOLD);
        controller.transform.FindChild("red-texture").gameObject.SetActive(locked && type == Door.Type.RED);
    }
        /// <summary>
        /// Changes from one room to the room specified
        /// </summary>
        /// <param name="destinationRoom">Room to change to</param>
        public void ChangeRoom(Door door)
        {
            loadingTime = 0;
            game.GameState = GameState.RoomChange;

            ThreadStart threadStarter = delegate
            {
                // Delete all current doors in the game
                //foreach (Door door in game.DoorComponent.All)
                //{
                //    game.GarbagemanSystem.ScheduleVisit(door.EntityID);
                //}

                // Delete all the current rooms in the game
                //foreach (Room room in game.RoomComponent.All)
                //{
                //    game.GarbagemanSystem.ScheduleVisit(room.EntityID);
                //}

                // Load the destination room
                uint lastRoomEid = game.CurrentRoomEid;

                if (door.DestinationRoom == "TestDungeon1" && game.RoomComponent[lastRoomEid].roomName == "TestDungeon3" && game.QuestLogSystem.currentQuest.questName == QuestName.ReachNextRoom && game.QuestLogSystem.currentQuest.questStatus == QuestStatus.InProgress)
                {
                    game.QuestLogSystem.currentQuest.questStatus = QuestStatus.Finished;
                    game.QuestComponent[game.QuestLogSystem.currentQuest.EntityID] = game.QuestLogSystem.currentQuest;
                }

                DungeonCrawlerGame.LevelManager.LoadLevel(door.DestinationRoom);

                CleanupLastRoom(lastRoomEid);

                // Don't proceed until the room has finished loading
                // We wait for a certain time so that the screen doesn't flash black very quickly and then to the new room.
                while (loadingTime < 0.25f || DungeonCrawlerGame.LevelManager.Loading)
                {
                }

                // Move the player to a new position
                // TODO: Get this position from the spawn positions in the room
                foreach (Player player in game.PlayerComponent.All)
                {
                    Position position = game.PositionComponent[player.EntityID];
                    position.Center = DungeonCrawlerGame.LevelManager.getCurrentRoom().playerSpawns[door.DestinationSpawnName];
                    position.RoomID = DungeonCrawlerGame.LevelManager.getCurrentRoom().EntityID;
                    game.PositionComponent[player.EntityID] = position;

                    Collideable collision = game.CollisionComponent[player.EntityID];
                    collision.RoomID = DungeonCrawlerGame.LevelManager.getCurrentRoom().EntityID;
                    game.CollisionComponent[player.EntityID] = collision;
                }

                game.GameState = GameState.Gameplay;
            };

            Thread loadingThread = new Thread(threadStarter);
            loadingThread.Start();
        }
Пример #27
0
 public void ChangeGameDataDoor(Door d)
 {
     switch (d.Name)
     {
         case "prison door":
             data.PrisonDoorOpened = true;
             break;
     }
 }
Пример #28
0
        private static Level CreateLevel0()
        {
            Level lvl = new Level();

            lvl.Gravity = 9.80f;
            lvl.InitialPosition = new Vector2(0, -500);

            lvl.AssetName = "Level0";
            lvl.LevelIdentifier = 0;

            lvl.Tiles.Add(new Tile(new Rectangle(778, 0, 186, 281), Surface.Absorbs));
            lvl.Tiles.Add(new Tile(new Rectangle(964, 0, 420, 195), Surface.Normal));

            lvl.Tiles.Add(new Tile(new Rectangle(0, 473, 301, 151), Surface.Absorbs));
            lvl.Tiles.Add(new Tile(new Rectangle(301, 473, 411, 151), Surface.Normal));
            lvl.Tiles.Add(new Tile(new Rectangle(711, 473, 569, 151), Surface.Amplifies));

            lvl.Tiles.Add(new Tile(new Rectangle(0, 1500 - 364, 216, 364), Surface.Absorbs));
            lvl.Tiles.Add(new Tile(new Rectangle(216, 1500 - 364, 240, 364), Surface.Normal));
            lvl.Tiles.Add(new Tile(new Rectangle(456, 1500 - 364, 216, 364), Surface.Absorbs));
            lvl.Tiles.Add(new Tile(new Rectangle(672, 1500 - 364, 159, 364), Surface.Normal));
            lvl.Tiles.Add(new Tile(new Rectangle(0, 966, 216, 170), Surface.Normal));
            lvl.Tiles.Add(new Tile(new Rectangle(456, 966, 215, 170), Surface.Normal));

            lvl.Tiles.Add(new Tile(new Rectangle(936, 1500 - 421, 485, 421), Surface.Reflects));

            lvl.Tiles.Add(new Tile(new Rectangle(1718, 915, 282, 585), Surface.Absorbs));

            lvl.Checkpoints.Add(new Checkpoint(270, 1136 - 134, 0, 0, 4));
            lvl.Checkpoints.Add(new Checkpoint(680, 1136 - 134, 680, 1024, 1));
            lvl.Checkpoints.Add(new Checkpoint(1180, 1079 - 134, 1180, 1500, 1));
            lvl.Checkpoints.Add(new Checkpoint(1165, 473 - 134, 1275, 473, 2));
            lvl.Checkpoints.Add(new Checkpoint(75, 473 - 134, 100, 473, 2));

            Switch switch1 = new Switch(System.Guid.NewGuid(), new Vector2(1980, 815), Switch.SwitchState.Active);
            switch1.Actions.Add(new KeyValuePair<Guid, int>(Character.CharacterGuid, (int)Switch.SwitchState.Pressed));
            lvl.Obstacles.Add(switch1);

            Platform pf1 = new Platform(System.Guid.NewGuid(), new List<Vector2>() { new Vector2(1435, 1078), new Vector2(1607, 1078), new Vector2(1607, 473), new Vector2(1286, 473) }, 50, Platform.PlatformState.Forward);
            pf1.Actions.Add(new KeyValuePair<Guid, int>(switch1.Guid, (int)Platform.PlatformState.Startionary));
            lvl.Obstacles.Add(pf1);

            Door d1 = new Door(System.Guid.NewGuid(), new Vector2(778, 282), Door.DoorState.Stationary);
            d1.Actions.Add(new KeyValuePair<Guid, int>(switch1.Guid, (int)Door.DoorState.Opening));
            lvl.Obstacles.Add(d1);

            Enemy e1 = new Enemy(new Vector2(370, 472), 300);
            lvl.Actors.Add(e1);

            //Boundaries
            lvl.Tiles.Add(new Tile(new Rectangle(0, 1500 - 2, 2000, 2), Surface.Death));
            lvl.Tiles.Add(new Tile(new Rectangle(0, 0, 1500, 2), Surface.Absorbs));
            lvl.Tiles.Add(new Tile(new Rectangle(0, 0, 2, 2000), Surface.Absorbs));
            lvl.Tiles.Add(new Tile(new Rectangle(2000 - 2, 0, 2, 1500), Surface.Absorbs));

            return lvl;
        }
Пример #29
0
    protected override void OnObjectTriggerEnter( Collider pCollider )
    {
        base.OnObjectTriggerEnter( pCollider );

        if ( pCollider.transform.parent.tag == "Opendoor" )
        {
            m_Door = pCollider.transform.parent.GetComponent<Door>();
        }
    }
Пример #30
0
        public void DoorCantBeUnlockedWithTheWrongClues()
        {
            var testDoor = new Door(new QuickGraph.TaggedEdge<int, string>(0, 1, "test"), new Connection(0, 1), new Connection(0, 1), "door1", 0, 1);
            //door index is important here
            var testDoor2 = new Door(new QuickGraph.TaggedEdge<int, string>(0, 1, "test"), new Connection(0, 1), new Connection(0, 1), "door2", 1, 1);
            var clue0 = new Clue(testDoor2, new List<int>());

            Assert.IsFalse(testDoor.CanDoorBeUnlockedWithClues(new List<Clue>(new Clue[] { clue0 })));
        }
Пример #31
0
 private void Start()
 {
     door = GetComponent <Door>();
 }
Пример #32
0
        static void Main(string[] args)
        {
            // Assemble your system here from all the classes
            IDoor          _door          = new Door();
            IUsbCharger    _usbCharger    = new UsbChargerSimulator();
            IDisplay       _display       = new Display();
            IRFIDReader    _rfidReader    = new RFIDReaderSimulator();
            ILogWriter     _log           = new LogWriter();
            IChargeControl _charge        = new ChargeControl(_display, _usbCharger);
            StationControl stationControl = new StationControl(_door, _display, _rfidReader, _log, _charge);

            int  runs   = 0;
            bool finish = false;

            do
            {
                string input;

                if (runs == 0)
                {
                    System.Console.WriteLine("Welcome to ChargingLocker");
                    System.Console.WriteLine("Type 'Open' to open locker door");
                    System.Console.WriteLine("Type 'Close' to close locker door");
                    System.Console.WriteLine("Type 'Scan' to scan your RFID tag");
                    System.Console.WriteLine("Type 'Exit' to exit program");
                }
                else
                {
                    System.Console.WriteLine("Type 'List' to show all options");
                }
                runs = 1;
                System.Console.Write("Input: ");
                input = Console.ReadLine();

                if (string.IsNullOrEmpty(input))
                {
                    continue;
                }
                switch (input)
                {
                case "Exit" or "exit":
                    finish = true;
                    break;

                case "Open" or "open":
                    if (_door._lock == true)
                    {
                        _display.DisplayDoorIsLocked();
                    }
                    else
                    {
                        _door.DoorOpened();
                    }
                    break;

                case "Close" or "close":
                    if (_door._lock == true)
                    {
                        _display.DisplayDoorIsLocked();
                    }
                    else
                    {
                        _door.DoorClosed();
                    }
                    break;

                case "Scan" or "scan":
                    System.Console.WriteLine("Indtast RFID id: ");
                    string idString = System.Console.ReadLine();

                    int id = Convert.ToInt32(idString);
                    stationControl.runProgram(id);
                    break;

                case "List" or "list":
                    runs = 0;
                    break;

                default:
                    break;
                }
            } while (!finish);
        }
Пример #33
0
 public void UpdateDirLock(int[] answer, Door door)
 {
     touchController.enabled = false;
     this.answer             = answer;
     this.door = door;
 }
Пример #34
0
 // Use this for initialization
 void Start()
 {
     door         = FindObjectOfType <Door>();
     door.enabled = false;
     player       = FindObjectOfType <BasePlayerStats>();
 }
Пример #35
0
    void AddDoorToEnd(Room r, Vector2 dir)
    {
        Door newDoor = CreateDoor(r, dir);

        ExpandingDoors.Insert(ExpandingDoors.Count, newDoor);
    }
Пример #36
0
 override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
 {
     door = animator.gameObject.GetComponent <Door>();
     door.BoxCollider.enabled = true;
 }
Пример #37
0
        private Hall CreateHall(Room room, Door door)
        {
            //Calculate the position of the first segment
            List <Position> segments   = new List <Position>();
            Position        start      = new Position(room.Location);
            int             hallLength = _randomizer.ChooseCount(2, 10);
            Hall            result;

            switch (door.Wall)
            {
            case Direction.North:
            {
                start.Row--;
                start.Column += door.Position - 1;
                break;
            }

            case Direction.West:
            {
                start.Row    += door.Position - 1;
                start.Column += room.Size.Length + 1;
                break;
            }

            case Direction.East:
            {
                start.Row += door.Position - 1;
                start.Column--;
                break;
            }

            case Direction.South:
            {
                start.Row    += room.Size.Width + 1;
                start.Column += door.Position - 1;
                break;
            }

            default:
                throw new ApplicationException(string.Format("Unknown direction for wall {0}", door.Wall));
            }

            bool hallSuccess = false;

            segments.Add(start);
            hallLength--;
            for (int retry = 0; retry < MaxPlacementRetries; retry++)
            {
                Position  prevSegment            = start;
                Direction backtrackDirection     = GetOppositeDirection(door.Wall);
                Direction prevBacktrackDirection = backtrackDirection;
                if (segments.Count == hallLength + 1)
                {
                    //success!
                    hallSuccess = true;
                    break;
                }
                for (int i = 0; i < hallLength; i++)
                {
                    Direction nextDirection;
                    Position  nextSegment = new Position(prevSegment);
                    do
                    {
                        nextDirection = _randomizer.ChooseDirection();
                    } while (nextDirection == backtrackDirection || nextDirection == prevBacktrackDirection);

                    switch (nextDirection)
                    {
                    case Direction.North:
                        nextSegment.Row--;
                        break;

                    case Direction.West:
                        nextSegment.Column++;
                        break;

                    case Direction.East:
                        nextSegment.Column--;
                        break;

                    case Direction.South:
                        nextSegment.Row++;
                        break;

                    default:
                        throw new ApplicationException(string.Format("Unknown next direction for hall {0}", door.Wall));
                    }
                    if (CanPlaceHallSegment(nextSegment) == false)
                    {
                        //reset the entire hall and retry
                        segments.Clear();
                        segments.Add(start);
                        break;
                    }
                    else
                    {
                        prevSegment            = nextSegment;
                        prevBacktrackDirection = GetOppositeDirection(nextDirection);
                        segments.Add(nextSegment);
                    }
                }
            }

            if (hallSuccess == true)
            {
                //hall was successfully placed create it
                result = new Hall(GetNextHallName());
                result.StartRoomName = room.Name;
                result.Segments      = segments.ToArray();

                door.ConnectedHallName = result.Name;
            }
            else
            {
                //hall could not be placed return null
                result = null;
            }

            return(result);
        }
Пример #38
0
		private static bool LoadLevel(String filepath, out Tile[][] tileset, out List<Entity> entities, out List<Cause> causes, out List<Effect> effects, out List<Trigger> triggers, out List<Light> lights)
		{
			try
			{
				StreamReader xmlReader = new StreamReader(filepath);
				XmlSerializer xmlSerializer = new XmlSerializer(typeof(Level));
				Level level = (Level)xmlSerializer.Deserialize(xmlReader);

				entities = new List<Entity>();
				causes = new List<Cause>();
				effects = new List<Effect>();
				triggers = new List<Trigger>();
				lights = new List<Light>();

				#region Load Tileset

				int x = Convert.ToInt32(level.Tileset.x);
				int y = Convert.ToInt32(level.Tileset.y);

				tileset = new Tile[x][];

				for (int i = 0; i < x; i++)
					tileset[i] = new Tile[y];

				for (int j = 0; j < y; j++)
					for (int i = 0; i < x; i++)
						tileset[i][j] = new Tile(new Point(i, j), x, y, (TileType)level.Tileset.Tile[j * x + i].state);

				#endregion

				#region Load Entities

				if (level.Entities.Button != null)
				{
					foreach (ButtonInfo bInfo in level.Entities.Button)
					{
						Button b = new Button(bInfo.xPos, bInfo.yPos);
						b = LoadEntity<ButtonInfo, Button>(bInfo, b);
						entities.Add(b);
					}
				}

				if (level.Entities.BreakableDoor != null)
				{
					foreach (BreakableDoorInfo bdi in level.Entities.BreakableDoor)
					{
						BreakableDoor breakableDoor = new BreakableDoor(bdi.xPos, bdi.yPos);
						breakableDoor.MaxHits = bdi.maxHits;
						breakableDoor = LoadEntity<BreakableDoorInfo, BreakableDoor>(bdi, breakableDoor);
						entities.Add(breakableDoor);
					}
				}

				if (level.Entities.Cannon != null)
				{
					foreach (CannonInfo cInfo in level.Entities.Cannon)
					{
						Cannon c = new Cannon(cInfo.xPos, cInfo.yPos);
						c.BallSpeed = cInfo.shotVelocity;
						c.Stupidity = cInfo.stupidity;
						c = LoadEntity<CannonInfo, Cannon>(cInfo, c);
						entities.Add(c);
					}
				}

				if (level.Entities.Door != null)
				{
					foreach (DoorInfo dInfo in level.Entities.Door)
					{
						Door d = new Door(dInfo.xPos, dInfo.yPos);
						d.Dir = (Direction)dInfo.dir;
						d = LoadEntity<DoorInfo, Door>(dInfo, d);
						entities.Add(d);
					}
				}

				if (level.Entities.LaserShooter != null)
				{
					foreach (LaserShooterInfo lsi in level.Entities.LaserShooter)
					{
						LaserShooter ls = new LaserShooter(lsi.xPos, lsi.yPos);
						ls.BeamWidth = lsi.beamWidth;
						ls.ShotsPerSecond = lsi.shotsPerSecond;
						ls.Stupidity = lsi.stupidity;
						ls = LoadEntity<LaserShooterInfo, LaserShooter>(lsi, ls);
						entities.Add(ls);
					}
				}

				if (level.Entities.Ball != null)
				{
					foreach (BallInfo ballInfo in level.Entities.Ball)
					{
						Ball ball = new Ball(ballInfo.xPos, ballInfo.yPos);
						ball.Friction = ballInfo.friction;
						ball = LoadEntity<BallInfo, Ball>(ballInfo, ball);
						entities.Add(ball);
					}
				}

				if (level.Entities.Block != null)
				{
					foreach (BlockInfo blockInfo in level.Entities.Block)
					{
						Block block = new Block(blockInfo.xPos, blockInfo.yPos);
						block.Friction = blockInfo.friction;
						block = LoadEntity<BlockInfo, Block>(blockInfo, block);
						entities.Add(block);
					}
				}

				if (level.Entities.Player != null)
				{
					PlayerInfo pi = level.Entities.Player;
					Player player = new Player(pi.xPos, pi.yPos);
					player = LoadEntity<PlayerInfo, Player>(pi, player);
					entities.Add(player);
				}

				if (level.Entities.PuzzleBox != null)
				{
					foreach (PuzzleBoxInfo pbi in level.Entities.PuzzleBox)
					{
						PuzzleBox pb = new PuzzleBox(pbi.xPos, pbi.yPos);
						pb = LoadEntity<PuzzleBoxInfo, PuzzleBox>(pbi, pb);
						entities.Add(pb);
					}
				}

				if (level.Entities.SpikeWall != null)
				{
					foreach (SpikeWallInfo swi in level.Entities.SpikeWall)
					{
						SpikeWall sw = new SpikeWall(swi.xPos, swi.yPos);
						sw.Dir = (Direction)swi.dir;
						sw = LoadEntity<SpikeWallInfo, SpikeWall>(swi, sw);
						entities.Add(sw);
					}
				}

				if (level.Entities.Teleporter != null)
				{
					foreach (TeleporterInfo tInfo in level.Entities.Teleporter)
					{
						Teleporter t = new Teleporter(tInfo.xPos, tInfo.yPos);
						t = LoadEntity<TeleporterInfo, Teleporter>(tInfo, t);
						entities.Add(t);
					}
				}

				#endregion

				if (level.Triggers != null)
				{
					#region Load Causes

					if (level.Triggers.Cause != null)
					{
						foreach (LevelTriggersCause curCause in level.Triggers.Cause)
						{
							switch (curCause.type)
							{
								case causeType.CauseAND:
									{
										CauseAND c = new CauseAND();
										string[] data = curCause.Value.Split(',');
										c.Cause1 = causes.Find(cause => cause.ID == data[0]);
										c.Cause2 = causes.Find(cause => cause.ID == data[1]);
										c.ID = curCause.id;
										causes.Add(c);
										break;
									}
								case causeType.CauseButton:
									{
										CauseButton c = new CauseButton();
										c.Button = entities.Find(ent => ent.ID == curCause.Value) as Button;
										c.ID = curCause.id;
										causes.Add(c);
										break;
									}
								case causeType.CauseEntityDestruction:
									{
										CauseEntityDestruction c = new CauseEntityDestruction();
										c.Entity = entities.Find(ent => ent.ID == curCause.Value);
										c.ID = curCause.id;
										causes.Add(c);
										break;
									}
								case causeType.CauseLocation:
									{
										CauseLocation c = new CauseLocation();
										string[] data = curCause.Value.Split(',');
										c.Player = entities.Find(ent => ent.ID == data[0]) as Player;
										c.MinimumX = float.Parse(data[1]);
										c.MaximumX = float.Parse(data[2]);
										c.MinimumY = float.Parse(data[3]);
										c.MaximumY = float.Parse(data[4]);
										c.ID = curCause.id;
										causes.Add(c);
										break;
									}
								case causeType.CauseNOT:
									{
										CauseNOT c = new CauseNOT();
										c.Cause = causes.Find(cause => cause.ID == curCause.Value);
										c.ID = curCause.id;
										causes.Add(c);
										break;
									}
								case causeType.CauseOR:
									{
										CauseOR c = new CauseOR();
										string[] data = curCause.Value.Split(',');
										c.Cause1 = causes.Find(cause => cause.ID == data[0]);
										c.Cause2 = causes.Find(cause => cause.ID == data[1]);
										c.ID = curCause.id;
										causes.Add(c);
										break;
									}
								case causeType.CauseTimePassed:
									{
										CauseTimePassed c = new CauseTimePassed();
										c.TriggerTime = int.Parse(curCause.Value);
										c.ID = curCause.id;
										causes.Add(c);
										break;
									}
								case causeType.CauseXOR:
									{
										CauseXOR c = new CauseXOR();
										string[] data = curCause.Value.Split(',');
										c.Cause1 = causes.Find(cause => cause.ID == data[0]);
										c.Cause2 = causes.Find(cause => cause.ID == data[1]);
										c.ID = curCause.id;
										causes.Add(c);
										break;
									}
							}
						}
					}

					#endregion

					#region Load Effects

					if (level.Triggers.Effect != null)
					{
						foreach (LevelTriggersEffect curEffect in level.Triggers.Effect)
						{
							switch (curEffect.type)
							{
								case effectType.EffectAND:
									{
										EffectAND e = new EffectAND();
										string[] data = curEffect.Value.Split(',');
										e.Effect1 = effects.Find(effect => effect.ID == data[0]);
										e.Effect2 = effects.Find(effect => effect.ID == data[1]);
										e.ID = curEffect.id;
										effects.Add(e);
										break;
									}
								case effectType.EffectDoor:
									{
										EffectDoor e = new EffectDoor();
										e.Door = entities.Find(ent => ent.ID == curEffect.Value) as Door;
										e.ID = curEffect.id;
										effects.Add(e);
										break;
									}
								case effectType.EffectEndGame:
									{
										EffectEndGame e = new EffectEndGame();
										e.CharlieSheen = bool.Parse(curEffect.Value);
										e.ID = curEffect.id;
										effects.Add(e);
										break;
									}
								case effectType.EffectList:
									{
										EffectList e = new EffectList();
										string[] data = curEffect.Value.Split(',');
										foreach (string s in data)
										{
											e.List.Add(effects.Find(effect => effect.ID == s));
										}
										effects.Add(e);
										break;
									}
								case effectType.EffectRaiseBridge:
									{
										EffectRaiseBridge e = new EffectRaiseBridge();
										string[] data = curEffect.Value.Split(',');
										e.TileX = int.Parse(data[0]);
										e.TileY = int.Parse(data[1]);
										e.ID = curEffect.id;
										effects.Add(e);
										break;
									}
								case effectType.EffectRemoveEntity:
									{
										EffectRemoveEntity e = new EffectRemoveEntity();
										e.Entity = entities.Find(ent => ent.ID == curEffect.Value);
										e.ID = curEffect.id;
										effects.Add(e);
										break;
									}
								case effectType.EffectTriggerTimer:
									{
										EffectTriggerTimer e = new EffectTriggerTimer();
										e.Cause = causes.Find(cause => cause.ID == curEffect.Value) as CauseTimePassed;
										e.ID = curEffect.id;
										effects.Add(e);
										break;
									}
							}
						}
					}

					#endregion

					#region Load Triggers

					if (level.Triggers.Trigger != null)
					{
						foreach (LevelTriggersTrigger triggerData in level.Triggers.Trigger)
						{
							Trigger t = new Trigger();
							t.Cause = causes.Find(cause => cause.ID == triggerData.cause);
							t.Effect = effects.Find(effect => effect.ID == triggerData.effect);
							triggers.Add(t);
						}
					}

					#endregion
				}

				#region Load Lights

				if (level.Lights != null)
				{
					for (int i = 0; i < level.Lights.Length; i++)
					{
						LightInfo ll = level.Lights[i];
						Light l = new Light();
						l.Index = ll.index;
						string[] ambient = ll.ambient.Split(',');
						l.AmbientR = float.Parse(ambient[0]);
						l.AmbientG = float.Parse(ambient[1]);
						l.AmbientB = float.Parse(ambient[2]);
						l.AmbientA = float.Parse(ambient[3]);
						string[] diffuse = ll.diffuse.Split(',');
						l.DiffuseR = float.Parse(diffuse[0]);
						l.DiffuseG = float.Parse(diffuse[1]);
						l.DiffuseB = float.Parse(diffuse[2]);
						l.DiffuseA = float.Parse(diffuse[3]);
						string[] position = ll.position.Split(',');
						l.PositionX = float.Parse(position[0]);
						l.PositionY = float.Parse(position[1]);
						l.PositionZ = float.Parse(position[2]);
						l.PositionW = float.Parse(position[3]);
						l.ConstantAttenuation = ll.constAtten;
						l.LinearAttenuation = ll.linAtten;
						l.QuadraticAttenuation = ll.quadAtten;
						lights.Add(l);
					}
				}

				#endregion

				UIEntListEditor.entList = entities;
				UICauseListEditor.causeList = causes;
				UIEffectListEditor.effectList = effects;
				UIFormEffectListEditor.effectList = effects;

				return true;
			}
			catch (Exception e)
			{
				causes = null;
				effects = null;
				entities = null;
				tileset = null;
				triggers = null;
				lights = null;
				System.Windows.Forms.MessageBox.Show("Error. Unable to load level. Reason: " + e.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
				return false;
			}
		}
Пример #39
0
 public static void RegisterDoor(Door door)
 {
     instance.LockedDoor = door;
 }
Пример #40
0
    public bool Solve(out int result)
    {
        result = 0;

        foreach (var door in Doors)
        {
            if (door.TimePassed == door.Period)
            {
                door.TimePassed = 0;
            }

            door.Independent = -((door.Period - door.TimePassed) % door.Period) + door.Index;
            //door.Independent = -door.Period + door.TimePassed + door.Index;
        }

        if (Doors.Count() == 1)
        {
            result = -Doors.First().Independent;
            return(true);
        }


        /////////////////////////

        Door ValueDoor = Doors[0];

        if (!Utils.SolveDiophanLinearEquation(-ValueDoor.Period, Doors[1].Period, -ValueDoor.Independent + Doors[1].Independent, out Door door1, out Door door2))
        {
            return(false);
        }
        LinkedList <Door> doorsConstraints = new LinkedList <Door>();

        ValueDoor.Independent = ValueDoor.Independent + ValueDoor.Period * door1.Independent;
        ValueDoor.Period      = ValueDoor.Period * door1.Period;

        doorsConstraints.AddLast(door1);
        doorsConstraints.AddLast(door2);

        /////////////////////////


        foreach (var door in Doors.Skip(2))
        {
            if (!Utils.SolveDiophanLinearEquation(-ValueDoor.Period, door.Period, -ValueDoor.Independent + door.Independent, out door1, out door2))
            {
                return(false);
            }

            ValueDoor.Independent = ValueDoor.Independent + ValueDoor.Period * door1.Independent;
            ValueDoor.Period      = ValueDoor.Period * door1.Period;

            foreach (var doorscontraint in doorsConstraints)
            {
                doorscontraint.Independent = doorscontraint.Independent + doorscontraint.Period * door1.Independent;
                doorscontraint.Period      = doorscontraint.Period * door1.Period;
            }

            doorsConstraints.AddLast(door2);
        }

        doorsConstraints.AddLast(ValueDoor);
        if (!CreateInterval(doorsConstraints, out int minIntValue, out int maxIntValue))
        {
            return(false);
        }

        if (ValueDoor.Period == 0)
        {
            if ((-ValueDoor.Independent) <= maxIntValue && (-ValueDoor.Independent) >= minIntValue)
            {
                result = ValueDoor.Independent;
            }
            else
            {
                return(false);
            }
        }
        else if (ValueDoor.Period < 0)
        {
            var value = ValueDoor.Period * maxIntValue - ValueDoor.Independent;
            result = value;
        }
        else //  if (ValueDoor.Period < 0)
        {
            var value = ValueDoor.Period * minIntValue - ValueDoor.Independent;
            result = value;
        }

        return(true);
    }
Пример #41
0
 public DoorOpenState(Door door)
 {
     Initialize();
     this.Door = door;
 }
Пример #42
0
        public void TestEnterInRoom()
        {
            var door = new Door(Door.DoorState.Close, new Room(), new Point(1, 0));

            Assert.AreNotEqual(door.EnterRoom(), null);
        }
        public void WorkTheDoor()
        {
            // Declare the FSM and specify the starting state.
            var doorFsmCompiler = TinyStateMachine <DoorState, DoorEvents> .Create <Door>(DoorState.Closed);

            // Now configure the state transition table.
            doorFsmCompiler.Tr(DoorState.Closed, DoorEvents.Open, DoorState.Open)
            .Tr <bool>(DoorState.Open, DoorEvents.Close, DoorState.Closed)
            .On((d, slammed) => d.WasSlammed = slammed);

            var doorFsm = doorFsmCompiler.Compile();

            var door = new Door()
            {
                Memory = doorFsm.CreateMemory()
            };

            // As specified in the constructor, the door starts closed.
            Debug.Assert(door.Memory.IsInState(DoorState.Closed));

            // Let's trigger a transition
            doorFsm.Fire(DoorEvents.Open, door);

            // Door is now open.
            Debug.Assert(door.Memory.IsInState(DoorState.Open));

            // create as many doors as needed
            var otherDoor = new Door()
            {
                Memory = doorFsm.CreateMemory()
            };

            // The state machine is shared, but the state is not
            Debug.Assert(otherDoor.Memory.IsInState(DoorState.Closed));

            // According to the transition table, closing a door requires
            // a bool argument. The following will throw an exception
            bool exceptionWasThrown = false;

            try {
                // Let's trigger the other transition
                doorFsm.Fire(DoorEvents.Close, door);
            }
            catch {
                exceptionWasThrown = true;
            }
            Debug.Assert(exceptionWasThrown == true);

            // Door is still open.
            Debug.Assert(door.Memory.IsInState(DoorState.Open));

            // Slam it this time
            doorFsm.Fire(DoorEvents.Close, door, true);

            // Door is now closed.
            Debug.Assert(door.Memory.IsInState(DoorState.Closed));

            // Door is was slammed.
            Debug.Assert(door.WasSlammed);

            // still closed
            Debug.Assert(otherDoor.Memory.IsInState(DoorState.Closed));

            // According to the transition table, a closed door
            // cannot be closed. The following will throw an exception
            exceptionWasThrown = false;
            try {
                doorFsm.Fire(DoorEvents.Close, door);
            }
            catch {
                exceptionWasThrown = true;
            }
            Debug.Assert(exceptionWasThrown == true);
        }
Пример #44
0
 public void AddDoor(Door door)
 {
     doors.Add(door);
 }
Пример #45
0
    void AddDoorToFront(Room r, Vector2 dir)
    {
        Door newDoor = CreateDoor(r, dir);

        ExpandingDoors.Insert(0, newDoor);
    }
Пример #46
0
 public void Setup()
 {
     uut = new Door();
 }
Пример #47
0
        public static Level GenerateLevel(int difficulty, bool exportImage)
        {
            int width  = 256;
            int height = 256;

            Level level = new Level(width, height);

            level = carveOutCenterCorridors(level);
            level = generateCorridors(level);
            level = generateRooms(level);
            level = populateDoors(level);
            level = generateItems(level);

            for (int y = 0; y < level.Matrix.Height; y++)
            {
                for (int x = 0; x < level.Matrix.Width; x++)
                {
                    if (level.Matrix.TerrainMatrix[x, y].TileLoc == Tile.TileLocation.Corridor)
                    {
                        level.Matrix.TerrainMatrix[x, y] = new Tile(x, y)
                        {
                            IsSolid = false, Token = TokenReference.FLOOR_EMPTY, ForegroundColor = level.Matrix.TerrainMatrix[x, y].ForegroundColor, TileLoc = Tile.TileLocation.Corridor
                        }
                    }
                    ;
                    else if (level.Matrix.TerrainMatrix[x, y].TileLoc == Tile.TileLocation.Room)
                    {
                        level.Matrix.TerrainMatrix[x, y] = new Tile(x, y)
                        {
                            IsSolid = false, Token = TokenReference.FLOOR_EMPTY, ForegroundColor = level.Matrix.TerrainMatrix[x, y].ForegroundColor, TileLoc = Tile.TileLocation.Room
                        }
                    }
                    ;
                    else if (level.Matrix.TerrainMatrix[x, y].TileLoc == Tile.TileLocation.Wall)
                    {
                        level.Matrix.TerrainMatrix[x, y] = new Tile(x, y)
                        {
                            IsSolid = true, Token = TokenReference.WALL, ForegroundColor = level.Matrix.TerrainMatrix[x, y].ForegroundColor, TileLoc = Tile.TileLocation.Wall
                        }
                    }
                    ;
                    else if (level.Matrix.TerrainMatrix[x, y].TileLoc == Tile.TileLocation.Door)
                    {
                        level.Matrix.TerrainMatrix[x, y] = new Tile(x, y)
                        {
                            IsSolid = false, Token = TokenReference.FLOOR_EMPTY, TileLoc = Tile.TileLocation.Door
                        };
                        Door door = new Door(level)
                        {
                            X = x, Y = y
                        };
                        level.Entities.Add(door);
                    }
                }
            }

            if (exportImage)
            {
                ExportPNG(level);
            }

            return(level);
        }
Пример #48
0
 public void Init()
 {
     door = new Door(1, save, "test");
 }
Пример #49
0
 // Start is called before the first frame update
 void Start()
 {
     door = doorGO.GetComponent <Door>();
 }
Пример #50
0
        public void Deserialize(Stream input)
        {
            const Endian endian = Endian.Little;

            var roomCount = input.ReadValueU32(endian);

            var rooms = new Room[roomCount];

            for (uint i = 0; i < roomCount; i++)
            {
                var room = new Room();
                room.Type       = input.ReadValueU32(endian);
                room.Variant    = input.ReadValueU32(endian);
                room.Difficulty = input.ReadValueU8();
                room.Name       = input.ReadString(endian);
                room.Weight     = input.ReadValueF32(endian);
                room.Width      = input.ReadValueU8();
                room.Height     = input.ReadValueU8();

                var doorCount  = input.ReadValueU8();
                var spawnCount = input.ReadValueU16(endian);

                room.Doors = new Door[doorCount];
                for (int j = 0; j < doorCount; j++)
                {
                    var door = new Door();
                    door.X        = input.ReadValueS16(endian);
                    door.Y        = input.ReadValueS16(endian);
                    door.Exists   = input.ReadValueB8();
                    room.Doors[j] = door;
                }

                room.Spawns = new Spawn[spawnCount];
                for (int j = 0; j < spawnCount; j++)
                {
                    var spawn = new Spawn();
                    spawn.X = input.ReadValueS16(endian);
                    spawn.Y = input.ReadValueS16(endian);

                    var entityCount = input.ReadValueU8();

                    spawn.Entities = new Entity[entityCount];
                    for (int k = 0; k < entityCount; k++)
                    {
                        var entity = new Entity();
                        entity.Type       = input.ReadValueU16(endian);
                        entity.Variant    = input.ReadValueU16(endian);
                        entity.Subtype    = input.ReadValueU16(endian);
                        entity.Weight     = input.ReadValueF32(endian);
                        spawn.Entities[k] = entity;
                    }

                    room.Spawns[j] = spawn;
                }

                rooms[i] = room;
            }

            this._Rooms.Clear();
            this._Rooms.AddRange(rooms);
        }
Пример #51
0
        public override void Start()
        {
            base.Start();

            captain          = Character.Controlled;
            radioSpeakerName = TextManager.Get("Tutorial.Radio.Watchman");
            GameMain.GameSession.CrewManager.AllowCharacterSwitch = false;

            var revolver = captain.Inventory.FindItemByIdentifier("revolver");

            revolver.Unequip(captain);
            captain.Inventory.RemoveItem(revolver);

            var captainscap = captain.Inventory.FindItemByIdentifier("captainscap");

            captainscap.Unequip(captain);
            captain.Inventory.RemoveItem(captainscap);

            var captainsuniform = captain.Inventory.FindItemByIdentifier("captainsuniform");

            captainsuniform.Unequip(captain);
            captain.Inventory.RemoveItem(captainsuniform);

            var steerOrder = Order.PrefabList.Find(order => order.AITag == "steer");

            captain_steerIcon      = steerOrder.SymbolSprite;
            captain_steerIconColor = steerOrder.Color;

            // Room 2
            captain_equipmentObjectiveSensor = Item.ItemList.Find(i => i.HasTag("captain_equipmentobjectivesensor")).GetComponent <MotionSensor>();
            captain_equipmentCabinet         = Item.ItemList.Find(i => i.HasTag("captain_equipmentcabinet")).GetComponent <ItemContainer>();
            captain_firstDoor      = Item.ItemList.Find(i => i.HasTag("captain_firstdoor")).GetComponent <Door>();
            captain_firstDoorLight = Item.ItemList.Find(i => i.HasTag("captain_firstdoorlight")).GetComponent <LightComponent>();

            SetDoorAccess(captain_firstDoor, captain_firstDoorLight, true);

            // Room 3
            captain_medicObjectiveSensor = Item.ItemList.Find(i => i.HasTag("captain_medicobjectivesensor")).GetComponent <MotionSensor>();
            captain_medicSpawnPos        = Item.ItemList.Find(i => i.HasTag("captain_medicspawnpos")).WorldPosition;
            tutorial_submarineDoor       = Item.ItemList.Find(i => i.HasTag("tutorial_submarinedoor")).GetComponent <Door>();
            tutorial_submarineDoorLight  = Item.ItemList.Find(i => i.HasTag("tutorial_submarinedoorlight")).GetComponent <LightComponent>();
            var medicInfo = new CharacterInfo(Character.HumanConfigFile, "", JobPrefab.List.Find(jp => jp.Identifier == "medicaldoctor"));

            captain_medic = Character.Create(medicInfo, captain_medicSpawnPos, "medicaldoctor");
            captain_medic.GiveJobItems(null);
            captain_medic.CanSpeak = captain_medic.AIController.Enabled = false;
            SetDoorAccess(tutorial_submarineDoor, tutorial_submarineDoorLight, false);

            // Submarine
            captain_enteredSubmarineSensor    = Item.ItemList.Find(i => i.HasTag("captain_enteredsubmarinesensor")).GetComponent <MotionSensor>();
            tutorial_submarineReactor         = Item.ItemList.Find(i => i.HasTag("engineer_submarinereactor")).GetComponent <Reactor>();
            captain_navConsole                = Item.ItemList.Find(i => i.HasTag("command")).GetComponent <Steering>();
            captain_navConsoleCustomInterface = Item.ItemList.Find(i => i.HasTag("command")).GetComponent <CustomInterface>();
            captain_sonar         = captain_navConsole.Item.GetComponent <Sonar>();
            captain_statusMonitor = Item.ItemList.Find(i => i.HasTag("captain_statusmonitor"));

            tutorial_submarineReactor.CanBeSelected = false;
            tutorial_submarineReactor.IsActive      = tutorial_submarineReactor.AutoTemp = false;

            tutorial_lockedDoor_1 = Item.ItemList.Find(i => i.HasTag("tutorial_lockeddoor_1")).GetComponent <Door>();
            tutorial_lockedDoor_2 = Item.ItemList.Find(i => i.HasTag("tutorial_lockeddoor_2")).GetComponent <Door>();
            SetDoorAccess(tutorial_lockedDoor_1, null, false);
            SetDoorAccess(tutorial_lockedDoor_2, null, false);

            var mechanicInfo = new CharacterInfo(Character.HumanConfigFile, "", JobPrefab.List.Find(jp => jp.Identifier == "mechanic"));

            captain_mechanic = Character.Create(mechanicInfo, WayPoint.GetRandom(SpawnType.Human, mechanicInfo.Job, Submarine.MainSub).WorldPosition, "mechanic");
            captain_mechanic.GiveJobItems();

            var securityInfo = new CharacterInfo(Character.HumanConfigFile, "", JobPrefab.List.Find(jp => jp.Identifier == "securityofficer"));

            captain_security = Character.Create(securityInfo, WayPoint.GetRandom(SpawnType.Human, securityInfo.Job, Submarine.MainSub).WorldPosition, "securityofficer");
            captain_security.GiveJobItems();

            var engineerInfo = new CharacterInfo(Character.HumanConfigFile, "", JobPrefab.List.Find(jp => jp.Identifier == "engineer"));

            captain_engineer = Character.Create(engineerInfo, WayPoint.GetRandom(SpawnType.Human, engineerInfo.Job, Submarine.MainSub).WorldPosition, "engineer");
            captain_engineer.GiveJobItems();

            captain_mechanic.CanSpeak             = captain_security.CanSpeak = captain_engineer.CanSpeak = false;
            captain_mechanic.AIController.Enabled = captain_security.AIController.Enabled = captain_engineer.AIController.Enabled = false;
        }
Пример #52
0
        /// <summary>
        /// Loads the level from a txt file at a given path
        /// </summary>
        /// <param name="levelName"></param>
        /// <returns></returns>
        public static Level Load(string levelName, LL ll)
        {
            worldObjects = new Dictionary <string, WorldObject>();
            dialogues    = new Dictionary <string, Phrase[]>();

            // Create XML reader settings
            XmlReaderSettings settings = new XmlReaderSettings();

            settings.IgnoreComments = true;                         // Exclude comments

            // Create reader based on settings
            XmlReader   reader = XmlReader.Create("Resources/levels/" + levelName + ".xml", settings);
            XmlDocument doc    = new XmlDocument();

            doc.Load(reader);

            XmlNode objectNode = doc.DocumentElement.SelectSingleNode("definition/objects");

            foreach (XmlNode node in objectNode.ChildNodes)
            {
                WorldObject obj = new WorldObject()
                {
                    Name        = XmlUtil.Get(node, "name", ll.GetTrans("resource.default.name")),
                    Description = XmlUtil.Get(node, "desc", ll.GetTrans("resource.default.desc")),
                    BlocksPath  = XmlUtil.Get(node, "block", true),
                    Texture     = BooleanTexture.FromFile("Resources/" + XmlUtil.Get(node, "img", ll.GetTrans("resource.default.texture"))),
                };

                string id = XmlUtil.Get(node, "id", "error");

                if (!worldObjects.ContainsKey(id))
                {
                    worldObjects.Add(id, obj);
                }
            }

            XmlNode levelNode = doc.DocumentElement;

            Level result = new Level();

            result.OnLoadTrigger = XmlUtil.Get(levelNode, "onload", string.Empty);
            result.Name          = levelName;

            Character character = new Character()
            {
                BlocksPath  = true,
                Id          = "avatar",
                Name        = "Avatar",
                Description = "This is me!",
                Texture     = BooleanTexture.FromFile("Resources/bmps/avatar_self.bmp"),
            };

            result.Avatar = character;


            XmlNode eventNode = doc.DocumentElement.SelectSingleNode("definition/events");

            if (eventNode != null)
            {
                foreach (XmlNode node in eventNode.ChildNodes)
                {
                    string name = node.Name;

                    if (name == "eventgroup")
                    {
                        EventGroup group = new EventGroup();
                        group.id                = XmlUtil.Get(node, "id", string.Empty);
                        group.conditions        = XmlUtil.GetArray(node, "if", ' ');
                        group.inverseConditions = XmlUtil.GetArray(node, "not", ' ');

                        foreach (XmlNode childNode in node.ChildNodes)
                        {
                            group.events.Add(loadEvent(childNode));
                        }

                        result.Events.Add(group);
                    }

                    if (name == "event")
                    {
                        result.Events.Add(loadEvent(node));
                    }
                }
            }

            XmlNode triggerNode = doc.DocumentElement.SelectSingleNode("triggers");

            if (triggerNode != null)
            {
                foreach (XmlNode node in triggerNode.ChildNodes)
                {
                    EventTrigger trigger = new EventTrigger();

                    trigger.x          = Constants.TILE_SIZE * XmlUtil.Get(node, "x", 0);
                    trigger.y          = Constants.TILE_SIZE * XmlUtil.Get(node, "y", 0);
                    trigger.width      = Constants.TILE_SIZE * XmlUtil.Get(node, "width", 1);
                    trigger.height     = Constants.TILE_SIZE * XmlUtil.Get(node, "height", 1);
                    trigger.levelEvent = XmlUtil.Get(node, "event", string.Empty);

                    if (result.Events.FirstOrDefault(e => e.id.Equals(trigger.levelEvent)) == null)
                    {
                        Console.WriteLine("WARNING: Trigger " + trigger.levelEvent + " pointing to unkown event!");
                    }

                    result.Triggers.Add(trigger);
                }
            }

            XmlNode decoNode = doc.DocumentElement.SelectSingleNode("decos");

            if (decoNode != null)
            {
                foreach (XmlNode node in decoNode.ChildNodes)
                {
                    if (node.Name.Equals(S_RANGE))
                    {
                        int x      = XmlUtil.Get(node, "x", 0);
                        int y      = XmlUtil.Get(node, "y", 0);
                        int width  = XmlUtil.Get(node, "width", 1);
                        int height = XmlUtil.Get(node, "height", 1);

                        WorldObject blueprint = worldObjects[XmlUtil.Get(node.ChildNodes[0], "obj", "default")];
                        int         dimX      = blueprint.Width / Constants.TILE_SIZE;
                        int         dimY      = blueprint.Height / Constants.TILE_SIZE;

                        for (int i = 0; i < width; i++)
                        {
                            for (int j = 0; j < height; j++)
                            {
                                result.Objects.Add(createDeco(node.ChildNodes[0], x + i * dimX, y + j * dimY));
                            }
                        }
                    }
                    else
                    {
                        int x = XmlUtil.Get(node, "x", 0);
                        int y = XmlUtil.Get(node, "y", 0);

                        result.Objects.Add(createDeco(node, x, y));
                    }
                }
            }

            XmlNode itemNode = doc.DocumentElement.SelectSingleNode("items");

            if (itemNode != null)
            {
                foreach (XmlNode node in itemNode.ChildNodes)
                {
                    WorldObject blueprint = worldObjects[XmlUtil.Get(node, "obj", "default")];

                    Item item = new Item()
                    {
                        X                 = Constants.TILE_SIZE * XmlUtil.Get(node, "x", 0),
                        Y                 = Constants.TILE_SIZE * XmlUtil.Get(node, "y", 0),
                        Conditions        = XmlUtil.GetArray(node, "if", ' '),
                        InverseConditions = XmlUtil.GetArray(node, "not", ' '),
                        Id                = XmlUtil.Get(node, "id", "object"),
                        Rotation          = XmlUtil.Get(node, "r", Direction.DOWN),
                        BlocksPath        = blueprint.BlocksPath,
                        Texture           = blueprint.Texture,
                        Name              = blueprint.Name,
                        Description       = blueprint.Description,
                    };

                    string eventId = "pick_up_" + item.Id;

                    Event pickUpEvent = new Event();
                    pickUpEvent.id                = eventId;
                    pickUpEvent.conditions        = new string[0];
                    pickUpEvent.inverseConditions = new string[] { item.Id + "_gefunden" };
                    pickUpEvent.actions.Add(new PickItem(item));

                    EventTrigger trigger = new EventTrigger();
                    trigger.x          = item.X;
                    trigger.y          = item.Y;
                    trigger.levelEvent = eventId;
                    trigger.height     = 1;
                    trigger.width      = 1;

                    result.Triggers.Add(trigger);
                    result.Events.Add(pickUpEvent);

                    if (!Game.HasKnowledge(item.Id + "_gefunden"))
                    {
                        Phrase talk = new Phrase()
                        {
                            text = "Du hast " + blueprint.Name + " gefunden.",
                            sets = new string[] { "hat_" + item.Id, item.Id + "_gefunden" }
                        };

                        item.Event = new Event(talk);
                        result.Objects.Add(item);
                    }
                }
            }

            //XmlNode containerNode = doc.DocumentElement.SelectSingleNode("containers");

            //foreach (XmlNode node in containerNode.ChildNodes)
            //{
            //    WorldObject blueprint = worldObjects[XmlUtil.Get(node, "obj", "default")];

            //    Container container = new Container()
            //    {
            //        Id = XmlUtil.Get(node, "id", "object"),
            //        X = Constants.TILE_SIZE * XmlUtil.Get(node, "x", 0),
            //        Y = Constants.TILE_SIZE * XmlUtil.Get(node, "y", 0),
            //        Rotation = XmlUtil.Get(node, "r", Direction.DOWN),
            //        BlocksPath = blueprint.BlocksPath,
            //        Texture = blueprint.Texture,
            //        Name = blueprint.Name,
            //        Description = blueprint.Description,
            //        IsLocked = Boolean.Parse(node.Attributes["locked"].Value),
            //        KeyIds = XmlUtil.Get(node, "key", new char[] { ' ' })
            //    };

            //    foreach (XmlNode item in node.ChildNodes)
            //    {
            //        WorldObject itemBlueprint = worldObjects[XmlUtil.Get(item, "obj", "default")];

            //        container.Items.Add(new Item()
            //        {
            //            Id = XmlUtil.Get(node, "id", "object"),
            //            X = container.X,
            //            Y = container.Y,
            //            Rotation = container.Rotation,
            //            BlocksPath = itemBlueprint.BlocksPath,
            //            Texture = itemBlueprint.Texture,
            //            Name = itemBlueprint.Name,
            //            Description = itemBlueprint.Description
            //        });
            //    }

            //    result.Objects.Add(container);
            //}

            XmlNode doorNode = doc.DocumentElement.SelectSingleNode("doors");

            if (doorNode != null)
            {
                foreach (XmlNode node in doorNode.ChildNodes)
                {
                    WorldObject blueprint = worldObjects[XmlUtil.Get(node, "obj", "default")];

                    Door door = new Door()
                    {
                        X                 = Constants.TILE_SIZE * XmlUtil.Get(node, "x", 0),
                        Y                 = Constants.TILE_SIZE * XmlUtil.Get(node, "y", 0),
                        Conditions        = XmlUtil.GetArray(node, "if", ' '),
                        InverseConditions = XmlUtil.GetArray(node, "not", ' '),
                        Rotation          = XmlUtil.Get(node, "r", Direction.DOWN),
                        Target            = XmlUtil.Get(node, "target", ""),
                        TargetX           = Constants.TILE_SIZE * XmlUtil.Get(node, "targetX", 0),
                        TargetY           = Constants.TILE_SIZE * XmlUtil.Get(node, "targetY", 0),
                        BlocksPath        = blueprint.BlocksPath,
                        Texture           = blueprint.Texture,
                        Name              = blueprint.Name,
                        Description       = blueprint.Description,
                    };

                    result.Objects.Add(door);
                }
            }


            XmlNode npcNode = doc.DocumentElement.SelectSingleNode("npcs");

            if (npcNode != null)
            {
                foreach (XmlNode node in npcNode.ChildNodes)
                {
                    WorldObject blueprint = worldObjects[XmlUtil.Get(node, "obj", "default")];

                    NPC npc = new NPC()
                    {
                        Id                = XmlUtil.Get(node, "id", "object"),
                        X                 = Constants.TILE_SIZE * XmlUtil.Get(node, "x", 0),
                        Y                 = Constants.TILE_SIZE * XmlUtil.Get(node, "y", 0),
                        Conditions        = XmlUtil.GetArray(node, "if", ' '),
                        InverseConditions = XmlUtil.GetArray(node, "not", ' '),
                        Rotation          = XmlUtil.Get(node, "r", Direction.DOWN),
                        BlocksPath        = blueprint.BlocksPath,
                        Texture           = blueprint.Texture,
                        Name              = blueprint.Name,
                        Description       = blueprint.Description,
                        Trigger           = XmlUtil.Get(node, "trigger", string.Empty)
                    };

                    result.Objects.Add(npc);
                }
            }

            result.OnKnowledgeChanged();

            return(result);
        }
Пример #53
0
        public Level3()
        {
            Console.WriteLine("Level3");
            Reset();
            timebarSpace = 10.768F;
            this.Add(new SpriteGameObject("spr_background"));
            thePlayer = new Player(2, 3);
            door      = new Door(1, 0);

            xaxis = new Xaxis(8, "Map/spr_horizontal_art_blue");
            yaxis = new Yaxis(13, "Map/spr_vertical_art_blue");
            goal  = new MainGoal(23, 13);

            Mouse.SetPosition(GameEnvironment.Screen.X / 2, GameEnvironment.Screen.Y / 2);

            floors = new GameObjectList();
            walls  = new GameObjectList();
            goals  = new GameObjectList();

            inputScreen = new InputScreen(GameEnvironment.Screen.X / 2 - 64 * 2, GameEnvironment.Screen.Y);
            inputanswer = new InputAnswer(GameEnvironment.Screen.X / 2 - 64 * 2, GameEnvironment.Screen.Y);
            timeGround  = new SpriteGameObject("Map/time_ground");

            guards       = new GameObjectList();
            lasers       = new GameObjectList();
            times        = new GameObjectList();
            score        = new Score(12, 20, (int)time);
            Axis_nums    = new Axis_numbers(13, 8);
            switchBoards = new GameObjectList();

            this.Add(floors);
            this.Add(switchBoards);
            this.Add(lasers);
            this.Add(walls);
            this.Add(door);
            this.Add(xaxis);
            this.Add(yaxis);
            this.Add(Axis_nums);
            this.Add(goal);
            this.Add(goals);
            this.Add(guards);
            this.Add(thePlayer);
            this.Add(inputScreen);
            this.Add(timeGround);
            this.Add(times);
            this.Add(score);
            this.Add(inputanswer);

            FloorSetup();
            WallSetup();
            TimeBarSetup();
            SoundSetup();

            goals.Add(new ExtraGoal(2, 13));
            goals.Add(new ExtraGoal(7, 13));
            goals.Add(new ExtraGoal(12, 13));
            goals.Add(new ExtraGoal(17, 13));
            goals.Add(new ExtraGoal(7, 2));
            goals.Add(new ExtraGoal(12, 2));
            goals.Add(new ExtraGoal(17, 2));
            goals.Add(new ExtraGoal(23, 2));
            goals.Add(new ExtraGoal(23, 3));
            goals.Add(new ExtraGoal(23, 4));
            goals.Add(new ExtraGoal(24, 2));
            goals.Add(new ExtraGoal(24, 3));
            goals.Add(new ExtraGoal(24, 4));
            goals.Add(new ExtraGoal(25, 2));
            goals.Add(new ExtraGoal(25, 3));
            goals.Add(new ExtraGoal(25, 4));

            lasers.Add(new Laser(new Vector2(1, 10), new Vector2(28, 9), Color.Red, xaxis.gridPos, yaxis.gridPos));
            lasers.Add(new Laser(new Vector2(16, 6), new Vector2(28, 12), Color.Blue, xaxis.gridPos, yaxis.gridPos));
            lasers.Add(new Laser(new Vector2(1, 6), new Vector2(28, 7), Color.Yellow, xaxis.gridPos, yaxis.gridPos));
            lasers.Add(new Laser(new Vector2(16, 10), new Vector2(28, 4), Color.DarkGray, xaxis.gridPos, yaxis.gridPos));

            switchBoards.Add(new SwitchBoard(9, 3, Color.Red));
            switchBoards.Add(new SwitchBoard(14, 3, Color.Blue));
            switchBoards.Add(new SwitchBoard(4, 3, Color.Yellow));
            switchBoards.Add(new SwitchBoard(19, 3, Color.DarkGray));

            guards.Add(new Guard(new Vector2(2, 9), new Vector2(25, 6)));
            guards.Add(new Guard(new Vector2(27, 1), new Vector2(21, 14)));
        }
Пример #54
0
    //TODO: I really hate this, I don't want to have to make a class based on an enum
    public void AddObjectEntity(ObjectData data)
    {
        switch (data.type)
        {
        case ObjectType.Chest:
            Chest temp = new Chest(ScriptableObject.Instantiate(mCurrentMap.Data.chestType));
            temp.Spawn(GetMapTilePosition(data.TilePosition));
            break;

        case ObjectType.FallingRock:
            FallingRock temp2 = new FallingRock(Resources.Load("Prototypes/Entity/Objects/FallingRock") as EntityPrototype);
            temp2.Spawn(GetMapTilePosition(data.TilePosition));
            break;

        case ObjectType.FlowerBed:
            FlowerBed temp3 = new FlowerBed(Resources.Load("Prototypes/Entity/Objects/FlowerBed") as EntityPrototype);
            temp3.Spawn(GetMapTilePosition(data.TilePosition));
            break;

        case ObjectType.Tree:
            Tree temp4 = new Tree(Resources.Load("Prototypes/Entity/Objects/Tree") as EntityPrototype);
            temp4.Spawn(GetMapTilePosition(data.TilePosition));
            break;

        case ObjectType.Medbay:
            MedicalBay temp5 = new MedicalBay(Resources.Load("Prototypes/Entity/Objects/Medbay") as EntityPrototype);
            temp5.Spawn(GetMapTilePosition(data.TilePosition));
            break;

        case ObjectType.Door:
            if (mCurrentMap.mapType != MapType.BossMap)
            {
                Door temp6 = new Door(Resources.Load("Prototypes/Entity/Objects/Door") as DoorPrototype);
                if (mCurrentMap.Data.hasMiniboss)
                {
                    temp6.locked = true;
                }
                temp6.Spawn(GetMapTilePosition(data.TilePosition));
            }
            break;

        case ObjectType.NavSystem:
            NavSystem temp7 = new NavSystem(Resources.Load("Prototypes/Entity/Objects/NavSystem") as EntityPrototype);
            temp7.Spawn(GetMapTilePosition(data.TilePosition));
            break;

        case ObjectType.BouncePad:
            BouncePad temp8 = new BouncePad(Resources.Load("Prototypes/Entity/Objects/BouncePad") as EntityPrototype);
            temp8.Spawn(GetMapTilePosition(data.TilePosition));
            break;

        case ObjectType.Spikes:
            Spikes temp9 = new Spikes(Resources.Load("Prototypes/Entity/Objects/Spikes") as EntityPrototype);
            temp9.Spawn(GetMapTilePosition(data.TilePosition));
            break;

        case ObjectType.Iceblock:
            Iceblock temp10 = new Iceblock(Resources.Load("Prototypes/Entity/Objects/Iceblock") as EntityPrototype);
            temp10.Spawn(GetMapTilePosition(data.TilePosition));
            break;

        case ObjectType.AnalysisCom:
            AnalysisCom temp11 = new AnalysisCom(Resources.Load("Prototypes/Entity/Objects/AnalysisCom") as EntityPrototype);
            temp11.Spawn(GetMapTilePosition(data.TilePosition));
            break;

        case ObjectType.Item:
            if (data is ItemObjectData itemData)
            {
                ItemObject temp12 = new ItemObject(ItemDatabase.GetItem(itemData.itemType), Resources.Load("Prototypes/Entity/Objects/ItemObject") as EntityPrototype);
                temp12.Spawn(GetMapTilePosition(data.TilePosition));
            }
            break;

        case ObjectType.SmallGatherable:
            Gatherable temp13 = new Gatherable(Resources.Load("Prototypes/Entity/Objects/Gatherables/Small Blue Vein") as GatherablePrototype);
            temp13.Spawn(GetMapTilePosition(data.TilePosition));
            break;

        case ObjectType.LargeGatherable:
            Gatherable temp14 = new Gatherable(Resources.Load("Prototypes/Entity/Objects/Gatherables/Large Blue Vein") as GatherablePrototype);
            temp14.Spawn(GetMapTilePosition(data.TilePosition));
            break;

        case ObjectType.SaveMachine:
            SaveMachine temp15 = new SaveMachine(Resources.Load("Prototypes/Entity/Objects/SaveMachine") as EntityPrototype);
            temp15.Spawn(GetMapTilePosition(data.TilePosition));
            break;

        case ObjectType.BreakableTile:
            BreakableTile temp16 = new BreakableTile(Resources.Load("Prototypes/Entity/Objects/BreakableTile") as EntityPrototype);
            temp16.Spawn(GetMapTilePosition(data.TilePosition));
            break;

        case ObjectType.PracticeBot:
            PracticeBot temp17 = new PracticeBot(Resources.Load("Prototypes/Entity/Objects/PracticeBot") as EntityPrototype);
            temp17.Spawn(GetMapTilePosition(data.TilePosition));
            break;

        case ObjectType.ShipTeleporter:
            ShipTeleporter temp18 = new ShipTeleporter(Resources.Load("Prototypes/Entity/Objects/ShipTeleporter") as EntityPrototype);
            temp18.Spawn(GetMapTilePosition(data.TilePosition));
            break;

        case ObjectType.MovingPlatform:
            MovingPlatform temp19 = new MovingPlatform(Resources.Load("Prototypes/Entity/Objects/MovingPlatform") as EntityPrototype);
            temp19.Spawn(GetMapTilePosition(data.TilePosition));
            break;
        }
    }
 public OpenDoorCommand(Door door)
 {
     this._door = door;
 }
Пример #56
0
        public void Status_InitialState_Closed()
        {
            var door = new Door(number: 1);

            Assert.That(door.Status, Is.EqualTo(DoorStatus.Closed));
        }
Пример #57
0
        static void Main(string[] args)
        {
            int opt = -1;



            while (opt != 0)
            {
                Console.WriteLine("Program Bentuk-Bentuk : ");
                Console.WriteLine("============================================================");
                Console.WriteLine("1. Persegi Sama Sisi");
                Console.WriteLine("2. Ubin (Turuan Dari Persegi Sama Sisi)");
                Console.WriteLine("3. Eternit / Plafon (Turuan Dari Persegi Sama Sisi)");
                Console.WriteLine("4. Kubus (Turuan Dari Persegi Sama Sisi 3D)");
                Console.WriteLine("............................................................");
                Console.WriteLine("5. Persegi Panjang");
                Console.WriteLine("6. Papan Tulis (Turuan Dari Persegi Panjang)");
                Console.WriteLine("7. Pintu (Turuan Dari Persegi Panjang)");
                Console.WriteLine("8. Balok (Turuan Dari Persegi Panjang 3D)");
                Console.WriteLine("............................................................");
                Console.WriteLine("9. Lingkaran");
                Console.WriteLine("10. Bola");
                Console.WriteLine("11. Kerucut");
                Console.WriteLine("............................................................");
                Console.WriteLine("0. Keluar");
                Console.WriteLine("------------------------------------------------------------");

                Console.Write("Pilih Opsi : ");
                opt = Convert.ToInt32(Console.ReadLine());

                switch (opt)
                {
                case 1:
                    Square sqr1 = new Square();
                    sqr1.input().display();
                    break;

                case 2:
                    Tile tle1 = new Tile();
                    tle1.input().display();
                    break;

                case 3:
                    Plasterboard plb = new Plasterboard();
                    plb.input().display();
                    break;

                case 4:
                    Cube cube = new Cube();
                    cube.input().display();
                    break;

                case 5:
                    Rectangle rct1 = new Rectangle();
                    rct1.input().display();
                    break;


                case 6:
                    WhiteBoard whtb = new WhiteBoard();
                    whtb.input().display();
                    break;

                case 7:
                    Door door = new Door();
                    door.input().display();
                    break;

                case 8:
                    Block block = new Block();
                    block.input().display();
                    break;

                case 9:
                    Circle circle = new Circle();
                    circle.input().display();
                    break;

                case 10:
                    Sphere sphere = new Sphere();
                    sphere.input().display();
                    break;

                case 11:
                    Cone cone = new Cone();
                    cone.input().display();
                    break;

                default:
                    break;
                }

                Console.WriteLine("\n\n");
            }
        }
Пример #58
0
        private void CheckDoorsInPath()
        {
            for (int i = 0; i < 2; i++)
            {
                WayPoint currentWaypoint = null;
                WayPoint nextWaypoint    = null;
                Door     door            = null;
                bool     shouldBeOpen    = false;

                if (currentPath.Nodes.Count == 1)
                {
                    door         = currentPath.Nodes.First().ConnectedDoor;
                    shouldBeOpen = door != null;
                }
                else
                {
                    if (i == 0)
                    {
                        currentWaypoint = currentPath.CurrentNode;
                        nextWaypoint    = currentPath.NextNode;
                    }
                    else
                    {
                        currentWaypoint = currentPath.PrevNode;
                        nextWaypoint    = currentPath.CurrentNode;
                    }
                    if (currentWaypoint?.ConnectedDoor == null)
                    {
                        continue;
                    }

                    if (nextWaypoint == null)
                    {
                        //the node we're heading towards is the last one in the path, and at a door
                        //the door needs to be open for the character to reach the node
                        shouldBeOpen = true;
                    }
                    else
                    {
                        door = currentWaypoint.ConnectedGap.ConnectedDoor;
                        if (door.LinkedGap.IsHorizontal)
                        {
                            int dir = Math.Sign(nextWaypoint.WorldPosition.X - door.Item.WorldPosition.X);
                            shouldBeOpen = (door.Item.WorldPosition.X - character.WorldPosition.X) * dir > -50.0f;
                        }
                        else
                        {
                            int dir = Math.Sign(nextWaypoint.WorldPosition.Y - door.Item.WorldPosition.Y);
                            shouldBeOpen = (door.Item.WorldPosition.Y - character.WorldPosition.Y) * dir > -80.0f;
                        }
                    }
                }

                if (door == null)
                {
                    return;
                }

                //toggle the door if it's the previous node and open, or if it's current node and closed
                if (door.IsOpen != shouldBeOpen)
                {
                    Controller closestButton = null;
                    float      closestDist   = 0;
                    bool       canAccess     = CanAccessDoor(door, button =>
                    {
                        if (currentWaypoint == null)
                        {
                            return(true);
                        }
                        // Check that the button is on the right side of the door.
                        if (door.LinkedGap.IsHorizontal)
                        {
                            int dir = Math.Sign(nextWaypoint.WorldPosition.X - door.Item.WorldPosition.X);
                            if (button.Item.WorldPosition.X * dir > door.Item.WorldPosition.X * dir)
                            {
                                return(false);
                            }
                        }
                        else
                        {
                            int dir = Math.Sign(nextWaypoint.WorldPosition.Y - door.Item.WorldPosition.Y);
                            if (button.Item.WorldPosition.Y * dir > door.Item.WorldPosition.Y * dir)
                            {
                                return(false);
                            }
                        }
                        float distance = Vector2.DistanceSquared(button.Item.WorldPosition, character.WorldPosition);
                        if (closestButton == null || distance < closestDist)
                        {
                            closestButton = button;
                            closestDist   = distance;
                        }
                        return(true);
                    });
                    if (canAccess)
                    {
                        if (door.HasIntegratedButtons)
                        {
                            door.Item.TryInteract(character, false, true);
                            buttonPressCooldown = ButtonPressInterval;
                            break;
                        }
                        else if (closestButton != null)
                        {
                            if (Vector2.DistanceSquared(closestButton.Item.WorldPosition, character.WorldPosition) < MathUtils.Pow(closestButton.Item.InteractDistance * 2, 2))
                            {
                                closestButton.Item.TryInteract(character, false, true);
                                buttonPressCooldown = ButtonPressInterval;
                                break;
                            }
                            else
                            {
                                // Can't reach the button closest to the character.
                                // It's possible that we could reach another buttons.
                                // If this becomes an issue, we could go through them here and check if any of them are reachable
                                // (would have to cache a collection of buttons instead of a single reference in the CanAccess filter method above)
                                var body = Submarine.PickBody(character.SimPosition, character.GetRelativeSimPosition(closestButton.Item), collisionCategory: Physics.CollisionWall | Physics.CollisionLevel);
                                if (body != null)
                                {
                                    if (body.UserData is Item item)
                                    {
                                        var d = item.GetComponent <Door>();
                                        if (d == null || d.IsOpen)
                                        {
                                            return;
                                        }
                                    }
                                    // The button is on the wrong side of the door or a wall
                                    currentPath.Unreachable = true;
                                }
                                return;
                            }
                        }
                    }
                    else if (shouldBeOpen)
                    {
#if DEBUG
                        DebugConsole.NewMessage($"{character.Name}: Pathfinding error: Cannot access the door", Color.Yellow);
#endif
                        currentPath.Unreachable = true;
                        return;
                    }
                }
            }
        }
Пример #59
0
    public static bool SolveDiophanLinearEquation(int a1, int a2, int independent, out Door door1, out Door door2)
    {
        door1 = null;
        door2 = null;

        int gcd = 0;
        LinkedList <EuclideanResult> result = new LinkedList <EuclideanResult>();

        if (a1 > a2)
        {
            gcd = Utils.GCD_Aux(a1, a2, result);
        }
        else
        {
            gcd = Utils.GCD_Aux(a2, a1, result);
        }

        if (independent % gcd != 0)
        {
            return(false);
        }
        int a1Sol, a2Sol;

        if (a1 > a2)
        {
            GetEuclideanLinearEquation(result, out a1Sol, out a2Sol);
        }
        else
        {
            GetEuclideanLinearEquation(result, out a2Sol, out a1Sol);
        }

        int cocient = independent / gcd;

        a1Sol *= cocient;
        a2Sol *= cocient;

        door1 = new Door {
            Period = a2 / gcd, Independent = -a1Sol
        };
        door2 = new Door {
            Period = a1 / gcd, Independent = -a2Sol
        };

        return(true);
    }
Пример #60
0
    void InstantiateMap()
    {
        /*
         * for(int i = height_cnt - 2; i >= height_cnt - 4; i --)
         * {
         * map[i, 1] = map[i, 2] = 0;
         * }
         */

        for (int i = 0; i < entryHeight; i++)
        {
            for (int j = 0; j < entryWidth; j++)
            {
                map[1 + i, width_cnt / 2 - entryWidth / 2 + j] = 2;               // + (int)GameManager.Direction.Down;
                map[height_cnt - 2 - i, width_cnt / 2 - entryWidth / 2 + j]  = 2; // + (int)GameManager.Direction.Up;
                map[height_cnt / 2 - entryHeight / 2 + i, 1 + j]             = 2; // + (int)GameManager.Direction.Left;
                map[height_cnt / 2 - entryHeight / 2 + i, width_cnt - 2 - j] = 2; // + (int)GameManager.Direction.Right;
            }
        }

        for (int i = 0; i < height_cnt; i++)
        {
            for (int j = 0; j < width_cnt; j++)
            {
                GameObject gobj   = null;
                bool       isDoor = false;
                if (i == 0 || i == height_cnt - 1 || j == 0 || j == width_cnt - 1)
                {
                    gobj = wallTiles[0];
                }
                else
                {
                    if (map[i, j] == 1)
                    {
                        gobj = blockTiles[0];
                    }
                    else if (map[i, j] >= 2)
                    {
                        continue;
                    }
                }
                if (gobj != null)
                {
                    GameObject inst = Instantiate(gobj, new Vector3(j * blocksize, i * blocksize, 0), Quaternion.identity) as GameObject;
                    tiles.Add(inst);
                    if (isDoor)
                    {
                        Door doorScript = inst.GetComponent <Door>();
                        doorScript.direction = (GameManager.Direction)(map[i, j] - 2);
                    }
                    //Debug.Log(gobj.GetComponent<SpriteRenderer>().bounds.size);
                }
                else //if (i < height_cnt - 4 || j > 2)
                {
                    Pos newpos;
                    newpos.x = i;
                    newpos.y = j;
                    emptyPosList.Add(newpos);
                }
            }
        }

        //instantiate doors
        float[] doorY = { 1.5f, height_cnt / 2 - 0.5f, height_cnt / 2 - 0.5f, height_cnt - 2.5f };
        float[] doorX = { width_cnt / 2 - 0.5f, 1.5f, width_cnt - 2.5f, width_cnt / 2 - 0.5f };
        GameManager.Direction[] doorDir =
        {
            GameManager.Direction.Down,  GameManager.Direction.Left,
            GameManager.Direction.Right, GameManager.Direction.Up
        };
        for (int i = 0; i < 4; i++)
        {
            GameObject inst = Instantiate(doorTile, new Vector3(doorX[i] * blocksize, doorY[i] * blocksize, 0), Quaternion.identity) as GameObject;
            tiles.Add(inst);
            Door doorScript = inst.GetComponent <Door>();
            doorScript.direction = doorDir[i];
        }
    }