示例#1
0
 public override Tile GetTile(Direction direction)
 {
     Tile tile = new Tile();
     tile.x = 1;
     tile.y = 0;
     return tile;
 }
示例#2
0
        public IEnumerable<ISpaceRouteElement> GetToNeighbour(IEntity entity, Tile currentTile, Tile targetTile)
        {
            var moveDirection = currentTile.Neighbours.Single(t => t.Item1 == targetTile).Item2;
            var currentSpace = entity.Location.Space; //currentTile.LayoutManager.FindCurrentSpace(entity);

            var curTileBridges = entity.GroupLayout.AllSpaces
                .Where(s => s.Sides.Contains(moveDirection))
                .Where(s => s == currentSpace || currentTile.LayoutManager.IsFree(s));

            var targetTileBridges = entity.GroupLayout.AllSpaces
                .Where(s => s.Sides.Contains(moveDirection.Opposite))
                .Where(s => targetTile.LayoutManager.IsFree(s));

            var bridges = curTileBridges.Join(targetTileBridges,
                ospace => ospace.Sides.First(s => s != moveDirection),
                ispace => ispace.Sides.First(s => s != moveDirection.Opposite),
                Tuple.Create);

            var bridgesRoutes = bridges
                .Select(b => GetToSpace(entity, currentTile, b.Item1)?.Concat(new FourthSpaceRouteElement(b.Item2, targetTile).ToEnumerable()).ToArray())
                .Where(r => r != null)
                .ToArray();

            if (bridgesRoutes.Any())
            {
                var minLen = bridgesRoutes.Min(x => x.Length);
                return bridgesRoutes.First(br => br.Length == minLen);
            }
            else
                return null;
        }
示例#3
0
    void Update()
    {
        if (!playedClip)
        {
            tile = tileManager.GetClosestTile(gameObject.transform.position);
            if (tile.HasFault())
            {
                if (tile.GetFault().CanExplode())
                {
                    source.PlayOneShot(softBang, 1);
                    playedClip = true;
                }
                else
                {
                    source.PlayOneShot(loudBang, 1);
                    playedClip = true;
                }
            }
            else
            {
                source.PlayOneShot(loudBang, 1);
                playedClip = true;
            }

        }
        die += Time.deltaTime;
        if (die >= 0.6f)
        {
            Destroy(gameObject);
        }
        if (gameObject.GetComponent<CircleCollider2D>().radius <= 0.05f)
        {
            gameObject.GetComponent<CircleCollider2D>().radius += 0.002f;
        }
    }
示例#4
0
 public TileLayer(int width, int height, string name, Tile[,] data)
 {
     _width = width;
     _height = height;
     _name = name;
     _data = data;
 }
示例#5
0
 private Tile LoadBasicTile(string name, TileType tileType, bool hot = false, bool ice = false)
 {
     Tile t = new Tile("Tiles/" + name, tileType);
     t.Hot = hot;
     t.Ice = ice;
     return t;
 }
    Effect visionEffect; // The vision effect to add to the player

    #endregion Fields

    #region Methods

    public override void Activate(Tile targetTile)
    {
        Player playerScript = Player.MyPlayer.GetComponent<Player>(); // The player's script
        int indexOfEffect; // The index of the effect if it is already attached
        List<Effect> turnEffects; // The turn effects in the player

        if (Amount == 0) // We are out cameras
            return;
        else {
            turnEffects = playerScript.GetTurnEffects();
            if (turnEffects.Contains(visionEffect)) { // Effect exists
                indexOfEffect = turnEffects.IndexOf(visionEffect);
                turnEffects[indexOfEffect].IncreaseTurnsRemaining(visionEffect.TurnsRemaining());
            } else // Attach the effect
                playerScript.AttachTurnEffect(visionEffect);
            if (SoundManagerScript.Singleton != null) { /* Play activated sound effect */
                // Move sound manager to this object
                SoundManagerScript.Singleton.gameObject.transform.position = gameObject.transform.position;
                SoundManagerScript.Singleton.PlaySingle3D(ActivateEfx);
            }
            Amount--;
            UpdateContextAwareBox();
            if (Amount == 0) { // Destroy this item
                Player.MyPlayer.GetComponent<Player>().RemoveItem(this, false);
                Destroy(gameObject);
                PhotonNetwork.Destroy(gameObject);
            }
        }
    }
示例#7
0
	void Start()
	{
		rank = UnitRank.Knight;
		//Debug.Log("Knight Start has been called");
		// Get current tile position
		CurrentTile = transform.GetComponentInParent<Tile>();
		//Debug.Log ("CurrentTile : "+CurrentTile);
		
		
		//this will find the village associated with this Knight, which will be the variable home.
		PathFind = transform.gameObject.GetComponentInParent<PathFinding>();
		List<Tile> tiles = PathFind.GetTiles(CurrentTile);
		//Debug.Log (tiles.Count);
		
		foreach (Tile t in tiles)
		{
			if (t.HasVillage)
			{
				Home = t.Village.transform.GetComponent<Village>();
			}
		}
		
		_neutral = false;
		_home = false;
		_enemy = false;
		_water = false;
		
		// TODO: Test purposes only
		CurrentTile.HasKnight = true;
		//Debug.Log(CurrentTile);
		
		Glow = transform.FindChild("Glow").gameObject;
	}
示例#8
0
 public void Test()
 {
     Tile tile1 = new Tile
     {
         TileSetId = 1,
         TileId = 2,
     };
     Tile tile2 = new Tile
     {
         TileSetId = 1,
         TileId = 2,
     };
     Tile tile3 = new Tile
     {
         TileSetId = 1,
         TileId = 3,
     };
     Assert.IsTrue(Tile.Equals(tile1, tile2));
     Assert.IsFalse(Tile.Equals(tile1, tile3));
     Assert.IsFalse(Tile.Equals(tile1, null));
     Assert.IsTrue(tile1.Equals(tile2));
     Assert.IsFalse(tile1.Equals(tile3));
     Assert.IsFalse(tile1.Equals(null));
     Assert.IsTrue(tile1 == tile2);
     Assert.IsFalse(tile1 != tile2);
     Assert.IsFalse(tile1 == tile3);
     Assert.IsTrue(tile1 != tile3);
     Assert.IsFalse(tile1 == null);
     Assert.IsTrue(tile1 != null);
 }
    /**
     * Activate function
     *
     * Arguments
     * - Tile targetTile - The tile being targetted
     */
    public override void Activate(Tile targetTile)
    {
        GameObject primaryAbilityButton; // The primary ability button

        primaryAbilityButton = ClassPanel.GetComponent<ClassPanelScript>().PrimaryAbilityButton;

        /* Count the number of traps we have */
        trapCount = MAX_TRAPS;
        foreach (Trap t in Object.FindObjectsOfType<Trap>()) {
            PhotonView pv = t.GetComponent<PhotonView>();
            if (pv != null && pv.isMine) // This is our trap
                trapCount--;
        }

        if (trapCount == 0) { // Don't do anything. Out of traps
            primaryAbilityButton.SetActive(false);
            return;
        }

        primaryAbilityButton.SetActive(true); // We still have traps
        SpawnTrap(Tile.TileMiddle(targetTile).x, 0, Tile.TileMiddle(targetTile).z);

        if ((trapCount - 1) == 0) // Out of traps
            primaryAbilityButton.SetActive(false);
    }
示例#10
0
 public LoadingScreen(Texture2D bg, float screenx, float screeny, GraphicsDevice g)
 {
     this.g = g;
     background = bg;
     screen = new Vector2(screenx, screeny);
     loadingTile = new SolidColorTile(Color.Red, g);
 }
示例#11
0
		public void CoordinatesIn()
		{
			Tile<TileTests.Item> t0 = new Tile<TileTests.Item>(new Area(0, 0, 100, 100), new TileTests.Item(0, 0, Color.Red));
			t0.Fill(c => c.X > 25 && c.X < 75 && c.Y > 30 && c.Y < 60 ? new TileTests.Item(c.X, c.Y, c.X == c.Y ? Color.Yellow : Color.Green) : new TileTests.Item(c.X, c.Y, Color.Red));

			IQuantifiedTile<TileTests.Item> q0 = t0.AsQuantified(10, 10);

			string signature0 = q0.GetImage(1000, 1000, (z, s) =>
                z.ToBitmap(100, 50, z.X + "\n" + z.Y)).Item.GetSignature();

			foreach (ICoordinate c in q0.GetCoordinatesIn(250, 250, 600, 600))
			{
				t0.Find(c).Color = Color.Blue;
			}

			string signature1 = q0.GetImage(1000, 1000, (z, s) =>
                z.ToBitmap(100, 50, z.X + "\n" + z.Y)).Item.GetSignature();

			foreach (ICoordinate c in q0.GetCoordinatesIn(52, 52, 62, 62))
			{
				t0.Find(c).Color = Color.White;
			}

			string signature2 = q0.GetImage(1000, 1000, (z, s) =>
                z.ToBitmap(100, 50, z.X + "\n" + z.Y)).Item.GetSignature();

			foreach (ICoordinate c in q0.GetCoordinatesIn(12, 12, 13, 13))
			{
				t0.Find(c).Color = Color.Black;
			}

			string signature3 = q0.GetImage(1000, 1000, (z, s) =>
                z.ToBitmap(100, 50, z.X + "\n" + z.Y)).Item.GetSignature();
		}
示例#12
0
 public HashSet<Tile> GetTilesInArea(Tile start, int radius, int verticalAllowance)
 {
     if (start == null) return null;
     return Search(start, delegate(Tile arg) {
         return arg.distance <= radius && (Mathf.Abs(start.height - arg.height) <= verticalAllowance);
     });
 }
 public Board(){
    this.tile = new Tile[100];
    for(int i=0;i<tiles.length;i++){
       tiles[i]=new Tile();
    }
   generateBoard();
 }
	// Generate a line from one coordinate to another
	// You can ask for it to be totaly walls or totally floor, based on the bool
	// False: Walls
	// True: Floor
	public static void makeLine(Tile[,] map, Coord begin, Coord end, bool applyFloor) {

		// Assert in range
		if( begin.isOOB (map.GetLength(0), map.GetLength (1), Direction.Stop) ||
		    end.isOOB (map.GetLength(0), map.GetLength (1), Direction.Stop) )
			return;
		
		int startX = begin.x;
		int endX = end.x;
		int startY = begin.y;
		int endY = end.y;


		// Find the linear spacing appropriate from point
		// including the endpoint
		int lengthX = Math.Abs( endX - startX );

		var linspace = new List<Double>();
			linspace = LinSpace (startY, endY, lengthX, true).ToList ();

		// Now it's time to actually put our money where our mouth is
		for(int i = startX; i < endX; i++) {
			int j = (int) linspace[i] ;
			map[i,j].property = applyFloor ? TileType.Floor1 : TileType.OuterWall1;
		}

		// Phew! Thought this one was so easy, didn't cha!?

		return;
	}
示例#15
0
        private static void ColorizeText(RichTextBox box, Tile<GSTToken<char>> tile)
        {
            TextRange tr ;

            if("A" == box.Name)
            {
                /*
                tr = new TextRange(box.Document.ContentStart.GetPositionAtOffset(tile.IndexOnA),
                                   box.Document.ContentStart.GetPositionAtOffset(tile.IndexOnA + tile.Tokens.Count()));
                /* */
                box.Selection.Select(box.Document.ContentStart.GetPositionAtOffset(tile.IndexOnA),
                                box.Document.ContentStart.GetPositionAtOffset(tile.IndexOnA + tile.Tokens.Count()));
            }
            else
            {
                box.Selection.Select(box.Document.ContentStart.GetPositionAtOffset(tile.IndexOnB),
                                box.Document.ContentStart.GetPositionAtOffset(tile.IndexOnB + tile.Tokens.Count()));
                /*
                tr = new TextRange(box.Document.ContentStart.GetPositionAtOffset(tile.IndexOnB),
                                   box.Document.ContentStart.GetPositionAtOffset(tile.IndexOnB + tile.Tokens.Count()));
                /* */
            }

            box.Selection.ApplyPropertyValue(TextElement.ForegroundProperty,
                                                 new SolidColorBrush(
                                                     _ltForeground[_indexColorLookup % _ltForeground.Length]));

            box.Selection.ApplyPropertyValue(TextElement.BackgroundProperty,
                                                 new SolidColorBrush(
                                                     _ltBackground[_indexColorLookup % _ltForeground.Length]));
        }
示例#16
0
    public override IEnumerator Traverse(Tile tile)
    {
        // Store the distance between the start tile and target tile
        float dist = Mathf.Sqrt(Mathf.Pow(tile.pos.x - unit.tile.pos.x, 2) + Mathf.Pow(tile.pos.y - unit.tile.pos.y, 2));

        yield return StartCoroutine(base.Traverse(tile));

        // Fly high enough not to clip through any ground tiles
        float y = Tile.stepHeight * 10;
        float duration = (y - jumper.position.y) * 0.5f;
        Tweener tweener = jumper.MoveToLocal(new Vector3(0, y, 0), duration, EasingEquations.EaseInOutQuad);
        while (tweener != null)
            yield return null;

        // Turn to face the general direction
        Directions dir;
        Vector3 toTile = (tile.center - transform.position);
        if (Mathf.Abs(toTile.x) > Mathf.Abs(toTile.z))
            dir = toTile.x > 0 ? Directions.East : Directions.West;
        else
            dir = toTile.z > 0 ? Directions.North : Directions.South;
        yield return StartCoroutine(Turn(dir));

        // Move to the correct position
        duration = dist * 0.5f;
        tweener = transform.MoveTo(tile.center, duration, EasingEquations.EaseInOutQuad);
        while (tweener != null)
            yield return null;

        // Land
        duration = (y - tile.center.y) * 0.5f;
        tweener = jumper.MoveToLocal(Vector3.zero, 0.5f, EasingEquations.EaseInOutQuad);
        while (tweener != null)
            yield return null;
    }
 public override void Activate(Tile targetTile)
 {
     GameObject instantiatedStunTurret; // The object instantiated
     Vector3 instantiatePosition; // Where to instantiate
     if (Amount == 0) // Out of turrets
         return;
     else { // Instantiate Turret
         Amount--;
         instantiatePosition = new Vector3(Tile.TileMiddle(targetTile).x, 0f, Tile.TileMiddle(targetTile).z);
         instantiatedStunTurret = PhotonNetwork.Instantiate(
                 "Prefabs/DeployableStunTurret",
                 instantiatePosition,
                 Quaternion.identity,
                 0
         );
         if (SoundManagerScript.Singleton != null) { /* Play activated sound effect */
             // Move sound manager to this object
             SoundManagerScript.Singleton.gameObject.transform.position = gameObject.transform.position;
             SoundManagerScript.Singleton.PlaySingle3D(ActivateEfx);
         }
         UpdateContextAwareBox();
         instantiatedStunTurret.GetComponent<DeployableStunTurretActionScript>().enabled = true; // Enable script
         if (Amount == 0) { // Remove the item
             Player.MyPlayer.GetComponent<Player>().RemoveItem(this, false);
             Destroy(gameObject);
             PhotonNetwork.Destroy(gameObject);
         }
     }
 }
示例#18
0
    void boardSetup()
    {
        gridHolder = new GameObject("Grid").transform;
        //GameObject startTile;
        //GameObject instance = Instantiate(startTile, new Vector3(0f, 0f, 0f), Quaternion.identity) as GameObject;
        //instance.transform.SetParent(gridHolder);

        List<Tile> theInit = new List<Tile>();
        for (int x = 0; x < columns; x++)
        {
            for (int y = 0; y < columns; y++)
            {
                tiles[x, y] = new Tile(x, y, false, false, false);
            }
        }

        tiles[0, 0].setFlags(true,true,false);
        for (int x = 1; x < 5; x++) { tiles[x, 0].setFlags(true, false, false); }
        for (int y = 1; y < 8; y++){tiles[4, y].setFlags(true, false, false);  }
        for (int x = 5; x < 10; x++) { tiles[x, 7].setFlags(true, false, false); }
        for (int x = 7; x < 10; x++) { tiles[x, 6].setFlags(true, false, false); }
        for (int x = 7; x < 10; x++) { tiles[x, 8].setFlags(true, false, false); }
        tiles[8, 7].setFlags(true, false, true);

        for (int x = 0; x < 10; x++)
        {
            for (int y = 0; y < 10; y++)
            {
                GameObject instance = Instantiate(moreTiles[x,y], new Vector3(x, y, 0f), Quaternion.identity) as GameObject;
                instance.transform.SetParent(gridHolder);

            }
        }
    }
示例#19
0
 public object[] makeNode(Tile t, int moves)
 {
     object[] rtnNode = new object[2];
     rtnNode [0] = t;
     rtnNode [1] = moves;
     return rtnNode;
 }
示例#20
0
文件: Map.cs 项目: GStick/YourWorld
 // #############################################################################################
 /// Constructor: <summary>
 ///              	Create a map from a tile
 ///              </summary>
 ///
 /// In:		<param name="_tile"></param>
 ///
 // #############################################################################################
 public Map(Tile _tile)
 {
     m_Tile = _tile;
     Reset(_tile.Width, _tile.Height, 16,4);
     LidBase = 64;
     Pavement = 7;
 }
    /**
     * Override Activate function
     */
    public override void Activate(Tile targetTile)
    {
        Debug.Log("APRestorer to activate");
        Player target; // The target

        target = Player.PlayerAtTile(targetTile); // Get target

        if (target == null)
            return; // No target found

        if (SoundManagerScript.Singleton != null) { /* Play activated sound effect */
            // Move sound manager to this object
            SoundManagerScript.Singleton.gameObject.transform.position = gameObject.transform.position;
            SoundManagerScript.Singleton.PlaySingle3D(ActivateEfx);
        }

        target.IncreaseStatValue(Stat.AP, InstantEffects[Stat.AP][0]);
        Amount--;
        UpdateContextAwareBox();
        if (Amount == 0) { // Destroy this item
            Player.MyPlayer.GetComponent<Player>().RemoveItem(this, false);
            Destroy(gameObject);
            PhotonNetwork.Destroy(gameObject);
        }
    }
示例#22
0
    private void genBoard()
    {
        winReqs = new Dictionary<string, int>();
        Ending[] endings = Ending.findEndings(data).ToArray();
        foreach (Ending ending in endings) {
            winReqs[ending.edgeId] = 0;
        }
        int width = MathData.GetInt(data.SelectSingleNode(XmlUtilities.WIDTH));
        int height = MathData.GetInt(data.SelectSingleNode(XmlUtilities.HEIGHT));
        Tile.BOARD_HEIGHT = height;
        Tile[,] tiles = new Tile[width, height];
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                GameObject go = Instantiate(tile) as GameObject;
                go.transform.position = new Vector3((float)x, (float)y, 0f);
                go.transform.parent = gameObject.transform;
                Tile t = go.GetComponent<Tile>();
                tiles[x, y] = t;
                t.ending = endings[Random.Range(0, endings.Length)];
                winReqs[t.ending.edgeId]++;

                if (x > 0) {
                    tiles[x-1, y].right = t;
                    t.left = tiles[x-1, y];
                }
                if (y > 0) {
                    tiles[x, y-1].up = t;
                    t.down = tiles[x, y-1];
                }
            }
        }
    }
示例#23
0
	// Get a list of all the tiles that are connected using BFS
	public List<Tile> GetTiles(Tile root)
	{
		List<Tile> tileList = new List<Tile>();
		
		Queue<Tile> q = new Queue<Tile>();
		
		q.Enqueue(root);
		
		while (q.Count > 0)
		{
			// pop the first item in the queue
			Tile current = q.Dequeue();
			tileList.Add(current);
			
			// if nothing pops, then all tiles have been found
			if (current == null)
				continue;
			
			// loop through all of root's neighbouring tiles 
			foreach (Transform tile in current.Neighbours)
			{
				_color = root.GetComponent<Renderer>().material.color;
				Color tileColor = tile.GetComponent<Renderer>().material.color;
				
				// get the tile component from the transform
				Tile t = tile.GetComponent<Tile>();
				
				// if the two colours match, then the tile is a neighbour
				// Enqueue the tile if it is not found in _tiles and in q
				if (_color == tileColor && !(tileList.Contains(t)) && !(q.Contains(t)))
					q.Enqueue(t);
			}
		}
		return tileList;
	}
示例#24
0
        public Grid(World world) {
            using (StreamReader sr = new StreamReader("testmap.txt")) {
                List<string> lines = new List<string>();
                while (!sr.EndOfStream) {
                    lines.Add(sr.ReadLine());
                }
                xDimension = lines[0].Length;
                yDimension = lines.Count;
                tiles = new Tile[xDimension, yDimension];
                for (int i = 0; i < xDimension; i++)
                {
                    for (int j = 0; j < yDimension; j++)
                    {
                        tiles[i, j] = new Tile(i, j, new Rectangle((int)(i*TileSize),(int)(j*TileSize),(int)TileSize,(int)TileSize));
                        if (lines[j][i] == '#')
                        {
                            tiles[i, j].passable = false;
                            Body body = BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(TileSize), ConvertUnits.ToSimUnits(TileSize), 10, ConvertUnits.ToSimUnits(GetWindowCenterPos(tiles[i, j])));
                            body.BodyType = BodyType.Static;
                            body.CollidesWith = Category.All;
                            body.CollisionCategories = Category.All;
                            tileBodies.Add(body);
                        }
                            
                    }
                }

            }

            AssignNeighbours();

            pathfinder = new Pathfinder(this);

        }
示例#25
0
        public TextureMenu(Tile TileSelected, TextureIndex Index ,List<GuiItem> Garbage)
            : base("TileMenu")
        {
            this.Index = Index;
            this.Garbage = Garbage;
            this.TileSelected = TileSelected;

            foreach (TextureEntry Entry in Index.TextureList)
            {
                if (TileSelected.Type == TileType.Normal)
                {
                    if (Entry.Name.StartsWith("Normal"))
                    {
                        MenuItems.Add(new MenuItem(Entry.Name, Entry.Name));
                    }
                }
                else if(TileSelected.Type == TileType.Obstacle)
                {
                    if (Entry.Name.StartsWith("Obstacle"))
                    {
                        MenuItems.Add(new MenuItem(Entry.Name, Entry.Name));
                    }
                }
                else if (TileSelected.Type == TileType.CreepEnd || TileSelected.Type == TileType.CreepStart || TileSelected.Type == TileType.CreepPath)
                {
                    if (Entry.Name.StartsWith("Creep"))
                    {
                        MenuItems.Add(new MenuItem(Entry.Name, Entry.Name));
                    }
                }
            }

            FixAttribute();
        }
        public void TestAreValidNeighboursTop()
        {
            Tile emptyTile = new Tile(string.Empty, 1);
            Tile currentTile = new Tile("12", 5);

            Assert.IsTrue(MatrixGenerator.AreValidNeighbours(emptyTile, currentTile), "Empty tile are not neighbours.");
        }
        public void CreateSetupActuators(Tile currentTile)
        {
            var actuators = builder.CurrentMap.GetTileData(currentTile.GridPosition).Actuators;
            if (actuators.Any())
            {
                var factory = parser.TryMatchFactory(actuators, false);
                if (factory != null)
                {
                    currentTile.SubItems.Add(factory.CreateItem(builder, currentTile, actuators));
                }
                else
                {
                    if (actuators.All(x => x.ActuatorType != 5 && x.ActuatorType != 6))
                    {
                        foreach (var i in actuators)
                        {
                            Point? absolutePosition = null;
                            if (i.ActionLocation is RemoteTarget)
                                absolutePosition = ((RemoteTarget)i.ActionLocation).Position.Position.ToAbsolutePosition(builder.CurrentMap);

                            currentTile.SubItems.Add(new Actuator(builder.GetWallPosition(i.TilePosition, currentTile), $"{absolutePosition} {i.DumpString()}"));
                        }
                    }
                    else
                    {

                    }
                }
            }
        }
示例#28
0
文件: PathFinder.cs 项目: VicBoss/KR
    public static Path<Tile> FindPath(
        Tile start,
        Tile destination)
    {
        var closed = new HashSet<Tile>();
        var queue = new PriorityQueue<double, Path<Tile>>();
        queue.Enqueue(0, new Path<Tile>(start));

        while (!queue.IsEmpty)
        {
            var path = queue.Dequeue();

            if (closed.Contains(path.LastStep))
                continue;
            if (path.LastStep.Equals(destination))
                return path;

            closed.Add(path.LastStep);

            foreach (Tile n in path.LastStep.Neighbours)
            {
                double d = distance(path.LastStep, n);
                var newPath = path.AddStep(n, d);
                queue.Enqueue(newPath.TotalCost + estimate(n, destination), 
                    newPath);
            }
        }

        return null;
    }
示例#29
0
    static void Main(string[] args) {
        string[] inputs;
        inputs = Console.ReadLine().Split(' ');
        int W = int.Parse(inputs[0]);
        int H = int.Parse(inputs[1]);
        Tiles = new Tile[W, H];
        inputs = Console.ReadLine().Split(' ');
        int X = int.Parse(inputs[0]);
        int Y = int.Parse(inputs[1]);
        for (int y = 0; y < H; y++) {
            string R = Console.ReadLine();
            for (int x = 0; x < R.Length; x++) {
                Tiles[x, y] = new Tile(x, y, R[x] == '#');
                Tiles[x, y].BuildLinks(W, H);
                if ((x == 0 || y == 0 || x == W - 1 || y == H - 1) && !Tiles[x, y].IsWall) {
                    OuterTiles.Add(Tiles[x, y]);
                }
            }
        }

        Tile start = Tiles[X, Y];
        foreach (Tile t in OuterTiles) {
            if (DistanceBetween(start, t) != -1) {
                EntryPoints.Add(t);
            }
        }

        EntryPoints = EntryPoints.OrderBy(e => e.X).ThenBy(e => e.Y).ToList();
        Console.WriteLine(EntryPoints.Count);
        foreach (Tile t in EntryPoints) {
            Console.WriteLine("{0} {1}", t.X, t.Y);
        }
    }
    private float Width; //width (X) of map

    #endregion Fields

    #region Methods

    //Builds all the fluff
    public void BuildFluff(Tile [,] gd, float scale)
    {
        //Prep variables
        Fluff = new GameObject();
        Fluff.name = "Fluff";
        Fluff.transform.position = new Vector3(0f, 0f, 0f);
        Grid = gd;
        Scale = scale;
        Width = gd.GetLength(0);
        Height = gd.GetLength(1);

        //Loop through the grid, adding fluff spots as appropriate
        for (int i = 1; i < Width - 1; i++)
        {
            for (int j = 1; j < Height - 1; j++)
            {
                //Check walls
                if (Grid[i, j].getType() == "Rock")
                {
                    AddWallLight(i, j);
                }

                //Check floors
                if (Grid[i, j].getType() == "Floor")
                {
                    //AddCornerLight(i, j); not fully functional yet
                    AddParticles(i, j);
                }
            }
        }
    }
示例#31
0
 void AddTile(Tile _tile)
 {
     m_tiles.Add(_tile);
 }
示例#32
0
        public static void AutoSlopeForSpike(int i, int j)
        {
            byte adj  = 0;
            Tile tile = Main.tile[i, j];

            tile.halfBrick(false);
            tile.slope(SlopeID.None);
            if (Main.tile[i - 1, j - 1].active())
            {
                adj |= tl;
            }
            if (Main.tile[i, j - 1].active())
            {
                adj |= t;
            }
            if (Main.tile[i + 1, j - 1].active())
            {
                adj |= tr;
            }
            if (Main.tile[i - 1, j].active())
            {
                adj |= l;
            }
            if (Main.tile[i + 1, j].active())
            {
                adj |= r;
            }
            if (Main.tile[i - 1, j + 1].active())
            {
                adj |= bl;
            }
            if (Main.tile[i, j + 1].active())
            {
                adj |= b;
            }
            if (Main.tile[i + 1, j + 1].active())
            {
                adj |= br;
            }
            bool sloped = true;

retry:
            switch (adj)
            {
            case bl | b | br:
                tile.halfBrick(true);
                break;

            case t | l:
                tile.slope(SlopeID.TopLeft);
                break;

            case t | r:
                tile.slope(SlopeID.TopRight);
                break;

            case b | l:
                tile.slope(SlopeID.BottomLeft);
                break;

            case b | r:
                tile.slope(SlopeID.BottomRight);
                break;

            case b | bl:
                tile.slope(SlopeID.BottomRight);
                break;

            case b | br:
                tile.slope(SlopeID.BottomLeft);
                break;

            case t | tl:
                tile.slope(SlopeID.TopRight);
                break;

            case t | tr:
                tile.slope(SlopeID.TopLeft);
                break;

            case l | tl:
                tile.slope(SlopeID.BottomLeft);
                break;

            case l | bl:
                tile.slope(SlopeID.TopLeft);
                break;

            case r | tr:
                tile.slope(SlopeID.BottomRight);
                break;

            case r | br:
                tile.slope(SlopeID.BottomLeft);
                break;

            default:
                if (sloped)
                {
                    sloped = false;
                    adj   &= t | l | r | b;
                    goto retry;
                }
                break;
            }
        }
示例#33
0
        public static void FelnumRunner(int i, int j, double strength, int steps, int type, float speedX = 0f, float speedY = 0f)
        {
            double  currStrength = strength;
            float   step         = steps;
            Vector2 pos          = default;

            pos.X = i;
            pos.Y = j;
            Vector2 speed = default;

            speed.X = genRand.Next(-10, 11) * 0.1f;
            speed.Y = genRand.Next(-10, 11) * 0.1f;
            if (speedX != 0f || speedY != 0f)
            {
                speed.X = speedX;
                speed.Y = speedY;
            }
            while (currStrength > 0.0 && step > 0f)
            {
                if (pos.Y < 0f && step > 0f && type == 59)
                {
                    step = 0f;
                }
                currStrength = strength * (step / steps);
                step        -= 1f;
                int num3 = (int)(pos.X - currStrength * 0.5);
                int num4 = (int)(pos.X + currStrength * 0.5);
                int num5 = (int)(pos.Y - currStrength * 0.5);
                int num6 = (int)(pos.Y + currStrength * 0.5);
                if (num3 < 1)
                {
                    num3 = 1;
                }
                if (num4 > Main.maxTilesX - 1)
                {
                    num4 = Main.maxTilesX - 1;
                }
                if (num5 < 1)
                {
                    num5 = 1;
                }
                if (num6 > Main.maxTilesY - 1)
                {
                    num6 = Main.maxTilesY - 1;
                }
                for (int k = num3; k < num4; k++)
                {
                    for (int l = num5; l < num6; l++)
                    {
                        if (!((Math.Abs(k - pos.X) + Math.Abs(l - pos.Y)) < strength * 0.5 * (1.0 + genRand.Next(-10, 11) * 0.015)))
                        {
                            continue;
                        }
                        Tile tile = Main.tile[k, l];
                        if (tile.type == TileID.Cloud || tile.type == TileID.Dirt || tile.type == TileID.Grass || tile.type == TileID.Stone || tile.type == TileID.RainCloud || tile.type == TileID.Stone)
                        {
                            tile.type = (ushort)type;
                            if (!tile.active() && OriginWorld.GetAdjTileCount(k, l) > 3)
                            {
                                tile.active(true);
                            }
                            SquareTileFrame(k, l);
                            if (Main.netMode == NetmodeID.Server)
                            {
                                NetMessage.SendTileSquare(-1, k, l, 1);
                            }
                        }
                    }
                }
                pos     += speed;
                speed.X += genRand.Next(-10, 11) * 0.05f;
                if (speed.X > 1f)
                {
                    speed.X = 1f;
                }
                if (speed.X < -1f)
                {
                    speed.X = -1f;
                }
                speed.Y += genRand.Next(-10, 11) * 0.05f;
                if (speed.Y > 1f)
                {
                    speed.Y = 1f;
                }
                if (speed.Y < -1f)
                {
                    speed.Y = -1f;
                }
            }
        }
示例#34
0
        public static void HellRunner(int i, int j, double strength, int steps, int type, bool addTile = false, float speedX = 0f, float speedY = 0f, bool noYChange = false, bool overRide = true)
        {
            double  num    = strength;
            float   num2   = steps;
            Vector2 vector = default(Vector2);

            vector.X = i;
            vector.Y = j;
            Vector2 vector2 = default(Vector2);

            vector2.X = (float)WorldGen.genRand.Next(-10, 11) * 0.1f;
            vector2.Y = (float)WorldGen.genRand.Next(-10, 11) * 0.1f;
            if (speedX != 0f || speedY != 0f)
            {
                vector2.X = speedX;
                vector2.Y = speedY;
            }
            bool flag  = type == 368;
            bool flag2 = type == 367;

            while (num > 0.0 && num2 > 0f)
            {
                if (vector.Y < 0f && num2 > 0f && type == 59)
                {
                    num2 = 0f;
                }
                num        = strength * (double)(num2 / (float)steps);
                num2      -= 1f;
                duskLeft   = (int)((double)vector.X - num * 0.5);
                duskRight  = (int)((double)vector.X + num * 0.5);
                duskTop    = (int)((double)vector.Y - num * 0.5);
                duskBottom = (int)((double)vector.Y + num * 0.5);
                if (duskLeft < 1)
                {
                    duskLeft = 1;
                }
                if (duskRight > Main.maxTilesX - 1)
                {
                    duskRight = Main.maxTilesX - 1;
                }
                if (duskTop < Main.maxTilesY - 200)
                {
                    duskTop = Main.maxTilesY - 200;
                }
                if (duskBottom > Main.maxTilesY - 1)
                {
                    duskBottom = Main.maxTilesY - 1;
                }
                int   tilesSinceSpike = 0;
                Point?spike           = null;
                for (int k = duskLeft; k < duskRight; k++)
                {
                    spike = null;
                    for (int l = duskBottom; l > duskTop; l--)
                    {
                        if (!((Math.Abs(k - vector.X) + Math.Abs(l - vector.Y)) < strength * 0.5))
                        {
                            continue;
                        }
                        if (Main.tile[k, l].type == TileID.Pots)
                        {
                            Main.tile[k, l].type = 0;
                            Main.tile[k, l].active(false);
                            continue;
                        }
                        if (Main.tile[k, l].type == type)
                        {
                            continue;
                        }
                        if (Main.tile[k, l].liquid != 0)
                        {
                            Tile tile = Main.tile[k, l];
                            tile.type = (ushort)type;
                            tile.active(active: true);
                            tile.liquid = 0;
                            tile.lava(lava: false);
                            //WorldGen.paintTile(k, l, 29);
                            Main.tile[k + 1, l].slope(0);
                            Main.tile[k - 1, l].slope(0);
                            if (l < Main.maxTilesY)
                            {
                                Main.tile[k, l + 1].slope(0);
                            }
                            Main.tile[k, l - 1].slope(0);
                            if (Main.tile[k, l - 1].liquid != 0)
                            {
                                continue;
                            }
                            spike = new Point(k, l);
                            continue;
                        }
                        if ((Main.tile[k, l].active()) || Main.tile[k, l].wall == WallID.ObsidianBrickUnsafe || Main.tile[k, l].wall == WallID.HellstoneBrickUnsafe)
                        {
                            Tile tile = Main.tile[k, l];
                            if (TileID.Sets.CanBeClearedDuringGeneration[tile.type])
                            {
                                if (tile.type == TileID.ObsidianBrick || tile.type == TileID.HellstoneBrick || tile.wall != 0 || (!Main.tileSolid[tile.type] && tile.type != TileID.Containers && tile.type != TileID.Containers2))
                                {
                                    tile.wall = 0;
                                    bool tileleft = Main.tile[k - 1, l].type == type && Main.tile[k - 1, l].active();
                                    if (!tileleft && Main.tile[k, l - 1].type != TileID.Containers && Main.tile[k, l - 1].type != TileID.Containers2)
                                    {
                                        tile.type = 0;
                                        tile.active(false);
                                        continue;
                                    }
                                }
                                tile.type = (ushort)type;
                                tile.active(active: true);
                                //tile.liquid = 0;
                                //tile.lava(lava: false);
                                //WorldGen.paintTile(k, l, 29);
                            }
                        }
                    }
                    if (spike.HasValue)
                    {
                        int l = spike.Value.Y;
                        if (WorldGen.genRand.Next(0, 10 + OriginWorld.HellSpikes.Count) <= tilesSinceSpike / 5)
                        {
                            Origins.instance.Logger.Info("Adding spike @ " + k + ", " + l);
                            OriginWorld.HellSpikes.Add((new Point(k, l), WorldGen.genRand.Next(5, 10) + tilesSinceSpike / 5));
                            //WorldGen.paintTile(k, l, 11);
                            tilesSinceSpike = -7;
                        }
                        else
                        {
                            tilesSinceSpike++;
                        }
                    }
                }
                vector += vector2;
                if (num > 50.0)
                {
                    vector    += vector2;
                    num2      -= 1f;
                    vector2.Y += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                    vector2.X += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                    if (num > 100.0)
                    {
                        vector    += vector2;
                        num2      -= 1f;
                        vector2.Y += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                        vector2.X += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                        if (num > 150.0)
                        {
                            vector    += vector2;
                            num2      -= 1f;
                            vector2.Y += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                            vector2.X += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                            if (num > 200.0)
                            {
                                vector    += vector2;
                                num2      -= 1f;
                                vector2.Y += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                vector2.X += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                if (num > 250.0)
                                {
                                    vector    += vector2;
                                    num2      -= 1f;
                                    vector2.Y += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                    vector2.X += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                    if (num > 300.0)
                                    {
                                        vector    += vector2;
                                        num2      -= 1f;
                                        vector2.Y += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                        vector2.X += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                        if (num > 400.0)
                                        {
                                            vector    += vector2;
                                            num2      -= 1f;
                                            vector2.Y += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                            vector2.X += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                            if (num > 500.0)
                                            {
                                                vector    += vector2;
                                                num2      -= 1f;
                                                vector2.Y += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                                vector2.X += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                                if (num > 600.0)
                                                {
                                                    vector    += vector2;
                                                    num2      -= 1f;
                                                    vector2.Y += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                                    vector2.X += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                                    if (num > 700.0)
                                                    {
                                                        vector    += vector2;
                                                        num2      -= 1f;
                                                        vector2.Y += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                                        vector2.X += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                                        if (num > 800.0)
                                                        {
                                                            vector    += vector2;
                                                            num2      -= 1f;
                                                            vector2.Y += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                                            vector2.X += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                                            if (num > 900.0)
                                                            {
                                                                vector    += vector2;
                                                                num2      -= 1f;
                                                                vector2.Y += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                                                vector2.X += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                vector2.X += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                if (vector2.X > 1f)
                {
                    vector2.X = 1f;
                }
                if (vector2.X < -1f)
                {
                    vector2.X = -1f;
                }
                if (!noYChange)
                {
                    vector2.Y += (float)WorldGen.genRand.Next(-10, 11) * 0.05f;
                    if (vector2.Y > 1f)
                    {
                        vector2.Y = 1f;
                    }
                    if (vector2.Y < -1f)
                    {
                        vector2.Y = -1f;
                    }
                }
                else if (type != 59 && num < 3.0)
                {
                    if (vector2.Y > 1f)
                    {
                        vector2.Y = 1f;
                    }
                    if (vector2.Y < -1f)
                    {
                        vector2.Y = -1f;
                    }
                }
                if (type == 59 && !noYChange)
                {
                    if ((double)vector2.Y > 0.5)
                    {
                        vector2.Y = 0.5f;
                    }
                    if ((double)vector2.Y < -0.5)
                    {
                        vector2.Y = -0.5f;
                    }
                    if ((double)vector.Y < Main.rockLayer + 100.0)
                    {
                        vector2.Y = 1f;
                    }
                    if (vector.Y > (float)(Main.maxTilesY - 300))
                    {
                        vector2.Y = -1f;
                    }
                }
            }
        }
示例#35
0
 public static void SetTileFast(Vector2i tPos, Tile tile)
 {
     tile = GetTileType(tile).Preprocess(tile, tPos);
     GetChunkSafe(tPos.x, tPos.y).SetTile(tPos.x & Chunk.Size - 1, tPos.y & Chunk.Size - 1, tile);
 }
示例#36
0
 public static void SetTile(Vector2i tPos, Tile tile)
 {
     SetTileAdvanced(tPos, tile);
     RebuildChunks();
 }
示例#37
0
 public static TileType GetTileType(Tile tile)
 {
     return(tilesList[tile.ID]);
 }
示例#38
0
 public TileActor(TileEngine tileEngine, Tile tile)
 {
     this.tileEngine = tileEngine;
     this.tile       = tile;
 }
示例#39
0
 void DrawTile(Tile t, PaintEventArgs pea) {
     pea.Graphics.DrawRectangle(Pens.WhiteSmoke, 0, 0, sqs, sqs);
     if (t.c == Color.LightGreen) { if (help) pea.Graphics.DrawEllipse(Pens.LightGreen, 0, 0, sqs, sqs); }
     else if (t.c != Color.Empty) pea.Graphics.FillEllipse(new SolidBrush(t.c), 0, 0, sqs, sqs);
 }
示例#40
0
    //
    // Optimized tile bank means to remove duplicates
    //
    public TileBank(PalettizedImage _image, bool _optimized)
    {
        //
        m_tiles = new List <Tile>();

        //
        int w       = _image.m_width;
        int h       = _image.m_height;
        int tiles_w = w >> 3;
        int tiles_h = h >> 3;

        //
        m_allTileInstances = new Dictionary <int, TileInstance>();

        //
        // Normally I write loops that iterate on Y first and then X, but sprites on Mega Drive should actually be
        // exported Y first then X, so if we do the Y in the inner loop that means the first two tiles are at 0,0
        // and 0,8, which means Y down. So instead of reordering anything at export time I reorder here instead.
        //
        // Oooh, I just realized this probably isn't true for sprite animation frames, so I probably still need to
        // do some clever iterations and stuff here. ARGH!
        //
        int x, y;

        for (x = 0; x < tiles_w; x++)
        {
            for (y = 0; y < tiles_h; y++)
            {
                int pixel_x = x * Tile.Width;
                int pixel_y = y * Tile.Height;

                Tile newTile = new Tile(_image, pixel_x, pixel_y);

                if (_optimized)
                {
                    TileInstance tileInstance = GetTileInstance(newTile);
                    if (tileInstance == null)
                    {
                        //Debug.Log ("Adding tile from coordinates "+pixel_x+","+pixel_y );
                        AddTile(newTile);

                        // Get the newly created instance
                        tileInstance = GetTileInstance(newTile);
                    }
                    else
                    {
                        //Debug.Log ("Ignoring tile from coordinates "+pixel_x+","+pixel_y );
                    }
                    int i = (y * tiles_w) + x;
                    m_allTileInstances[i] = tileInstance;
                }
                else
                {
                    // If we're not building an optimized tile bank we always export all tiles
                    AddTile(newTile);

                    // Get the newly created instance
                    TileInstance tileInstance = GetTileInstance(newTile);
                    int          i            = (y * tiles_w) + x;
                    m_allTileInstances[i] = tileInstance;
                }
            }
        }

        Debug.Log("tile instances=" + m_allTileInstances.Count);
    }
示例#41
0
 public void GetCurrentTile()
 {
     currentTile         = GetTargetTile(gameObject);
     currentTile.current = true;
 }
示例#42
0
 void TileClicked(Tile t, int x, int y) {
     if (x != 0 && x != sqs && y != 0 && y != sqs
         && ValidMove(t.Location.X / sqs, t.Location.Y / sqs, true)) {
         UpdateStatus();
     }
 }
        private bool LoadVersion8(GR.Memory.ByteBuffer Data)
        {
            DisplayModeFile = (DisplayMode)Data.ByteAt(4);
            TileColorMode   = (ColorMode)Data.ByteAt(5);

            byte flags = Data.ByteAt(6);

            BackgroundColor  = Data.ByteAt(7);
            MultiColor1      = Data.ByteAt(8);
            MultiColor2      = Data.ByteAt(9);
            BackgroundColor4 = Data.ByteAt(10);

            BaseCellColorColorMatrix = Data.ByteAt(11);
            BaseCellColorScreenLo    = Data.ByteAt(12);
            BaseCellColorScreenHi    = Data.ByteAt(13);

            bool tileSysEnabled = ((flags & 0x01) != 0);


            ushort charDataBlockID      = 0xdab0;
            ushort charAttributeBlockID = 0xdab1;
            ushort charSetColorBlockID  = 0;
            ushort tileSetDataBlockID   = 0;
            ushort tileSetColorBlockID  = 0;
            ushort tileSetTagBlockID    = 0;
            ushort tileSetNameBlockID   = 0;
            ushort mapDataBlockID       = 0;

            int curBlockID = 0xdab2;

            if (TileColorMode == ColorMode.PER_CHAR)
            {
                charSetColorBlockID = (ushort)curBlockID++;
            }
            if (tileSysEnabled)
            {
                tileSetDataBlockID = (ushort)curBlockID++;
                if (TileColorMode == ColorMode.PER_TILE)
                {
                    tileSetColorBlockID = (ushort)curBlockID++;
                }
                tileSetTagBlockID  = (ushort)curBlockID++;
                tileSetNameBlockID = (ushort)curBlockID++;
            }
            mapDataBlockID = (ushort)curBlockID++;

            if (!tileSysEnabled)
            {
                // fake tiles (one per char)
                TileWidth  = 1;
                TileHeight = 1;
                NumTiles   = 256;

                for (int i = 0; i < NumTiles; ++i)
                {
                    Tile tile = new Tile();

                    tile.CharData.Resize((uint)(TileWidth * TileHeight * 2));
                    tile.CharData.SetU16At(0, (ushort)i);

                    tile.ColorData.Resize((uint)(TileWidth * TileHeight));
                    tile.ColorData.SetU8At(0, (byte)CustomColor);

                    Tiles.Add(tile);
                }
            }

            var reader = Data.MemoryReader();

            reader.Skip(14);

            while (reader.DataAvailable)
            {
                ushort blockID = reader.ReadUInt16NetworkOrder();

                if (blockID == charDataBlockID)
                {
                    // Character data block

                    // CHARCNT: Character image count minus one( 16 - bit, LSBF ).
                    NumChars = reader.ReadUInt16() + 1;

                    // CHARDAT : Character image data( eight bytes / rows per image for CHARCNT images, rows are in TB order ).
                    for (int charIndex = 0; charIndex < NumChars; ++charIndex)
                    {
                        SingleChar newChar = new SingleChar();
                        newChar.Data  = new GR.Memory.ByteBuffer();
                        newChar.Color = CustomColor;
                        reader.ReadBlock(newChar.Data, 8);
                        Characters.Add(newChar);
                    }

                    if (!tileSysEnabled)
                    {
                        if (NumChars < 256)
                        {
                            // add all chars for safety reasons
                            for (int i = NumChars; i < 256; ++i)
                            {
                                SingleChar newChar = new SingleChar();
                                newChar.Data  = new GR.Memory.ByteBuffer(8);
                                newChar.Color = CustomColor;

                                Characters.Add(newChar);
                            }
                        }
                    }
                }
                else if (blockID == charAttributeBlockID)
                {
                    // char attributes
                    // BLKMARK: Block marker(0xDA, 0xB1).
                    // CHARATTS: Char attribute data, one byte per char image for CHARCNT images, low nybble = colour, high nybble = material.
                    //           nb.colours are only stored when the colouring mode is "per character".
                    for (int charIndex = 0; charIndex < NumChars; ++charIndex)
                    {
                        if (TileColorMode == ColorMode.PER_CHAR)
                        {
                            Characters[charIndex].Color = reader.ReadUInt8() & 0x0f;
                            if (!tileSysEnabled)
                            {
                                Tiles[charIndex].ColorData.SetU8At(0, (byte)Characters[charIndex].Color);
                            }
                        }
                    }
                }
                else if (blockID == charSetColorBlockID)
                {
                    // Character set colours block (only present if the project uses per-char colouring)...
                    //
                    // BLKMARK         : Block marker (0xDA, 0xBn).
                    // MTRXCOLRS_CHARS : Char colour data, 1-3 bytes per char image for CHARCNT images...
                    //
                    //    Colour_CmLo : Colour Matrix Low nybble (0-15) (not present if DISP_MODE is Bitmap_HR).
                    //    Colour_SmLo : Screen Matrix Low nybble (0-15) (only present if DISP_MODE is Bitmap_HR or Bitmap_MC).
                    //    Colour_SmHi : Screen Matrix High nybble (0-15) (only present if DISP_MODE is Bitmap_HR or Bitmap_MC).
                    //
                    //    Notes:-
                    //    - The colours in this block are intended for transfer to the C64 colour RAM cells and/or screen RAM cells.
                    //    - The usage / usefulness of a colour will depend on the display mode.
                    //    - Only the low nybbles of each byte are currently used, each provides a colour 0-15.

                    for (int i = 0; i < NumChars; ++i)
                    {
                        if (DisplayModeFile != DisplayMode.BITMAP_HIRES)
                        {
                            Characters[i].Color = reader.ReadUInt8();
                        }
                        if ((DisplayModeFile == DisplayMode.BITMAP_MC) ||
                            (DisplayModeFile == DisplayMode.BITMAP_HIRES))
                        {
                            // screen color lo
                            reader.ReadUInt8();
                            // screen color hi
                            reader.ReadUInt8();
                        }
                        if (!tileSysEnabled)
                        {
                            // use the charset color for our faked tiles
                            Tiles[i].ColorData.SetU8At(0, (byte)Characters[i].Color);
                        }
                    }
                }
                else if (blockID == tileSetDataBlockID)
                {
                    // Tile data block

                    // TILECNT: Tile count minus one(16 - bit, LSBF).
                    NumTiles = reader.ReadUInt16() + 1;

                    // TILEWID: Tile width( byte).
                    TileWidth = reader.ReadUInt8();
                    // TILEHEI: Tile height( byte).
                    TileHeight = reader.ReadUInt8();

                    // TILEDAT: Tile data, 16 bits per tile cell( LSBF) for TILEWID* TILEHEI cells * TILECNT items, cells are in LRTB order.
                    for (int i = 0; i < NumTiles; ++i)
                    {
                        Tile tile = new Tile();

                        tile.CharData.Resize((uint)(TileWidth * TileHeight * 2));
                        tile.ColorData.Resize((uint)(TileWidth * TileHeight));

                        Tiles.Add(tile);
                    }
                    if (NumChars < 256)
                    {
                        // add all chars for safety reasons
                        for (int i = NumChars; i < 256; ++i)
                        {
                            SingleChar newChar = new SingleChar();
                            newChar.Data = new GR.Memory.ByteBuffer(8);
                            Characters.Add(newChar);
                        }
                    }
                    for (int i = 0; i < NumTiles; ++i)
                    {
                        for (int j = 0; j < TileWidth * TileHeight; ++j)
                        {
                            Tiles[i].CharData.SetU16At(j * 2, reader.ReadUInt16());
                        }
                    }
                }
                else if (blockID == tileSetColorBlockID)
                {
                    // Tile color block

                    // BLKMARK         : Block marker (0xDA, 0xBn).
                    // MTRXCOLRS_TILES : Tile colour data, 1-3 bytes per tile for TILECNT tiles...
                    //
                    //    Colour_CmLo : Colour Matrix Low nybble (0-15) (not present if DISP_MODE is Bitmap_HR).
                    //    Colour_SmLo : Screen Matrix Low nybble (0-15) (only present if DISP_MODE is Bitmap_HR or Bitmap_MC).
                    //    Colour_SmHi : Screen Matrix High nybble (0-15) (only present if DISP_MODE is Bitmap_HR or Bitmap_MC).
                    //
                    //    Notes:-
                    //    - The colours in this block are intended for transfer to the C64 colour RAM cells and/or screen RAM cells.
                    //    - The usage / usefulness of a colour will depend on the display mode.
                    //    - Only the low nybbles of each byte are currently used, each provides a colour 0-15.

                    for (int i = 0; i < NumTiles; ++i)
                    {
                        if (DisplayModeFile != DisplayMode.BITMAP_HIRES)
                        {
                            // tile generic color
                            reader.ReadUInt8();
                        }
                        if ((DisplayModeFile == DisplayMode.BITMAP_MC) ||
                            (DisplayModeFile == DisplayMode.BITMAP_HIRES))
                        {
                            // screen color lo
                            reader.ReadUInt8();
                            // screen color hi
                            reader.ReadUInt8();
                        }
                    }
                }
                else if (blockID == tileSetTagBlockID)
                {
                    // BLKMARK  : Block marker (0xDA, 0xBn).
                    // TILETAGS : Tile tag values, one byte per tile for TILECNT items.
                    for (int i = 0; i < NumTiles; ++i)
                    {
                        byte tileTag = reader.ReadUInt8();
                    }
                }
                else if (blockID == tileSetNameBlockID)
                {
                    // BLKMARK  : Block marker (0xDA, 0xBn).
                    // TILETAGS : Tile tag values, one byte per tile for TILECNT items.
                    for (int i = 0; i < NumTiles; ++i)
                    {
                        // zero terminated strings (urgh)
                        string name = "";
                        char   c    = (char)0;
                        do
                        {
                            c = (char)reader.ReadUInt8();
                            if (c != 0)
                            {
                                name += c;
                            }
                        }while (c != 0);
                        Tiles[i].Name = name;
                    }
                }
                else if (blockID == mapDataBlockID)
                {
                    // BLKMARK : Block marker (0xDA, 0xBn).
                    // MAPWID: Map Width(16 - bit, LSBF).
                    // MAPHEI: Map height(16 - bit, LSBF).
                    // MAPDAT: Map data, 16 bits per cell( LSBF ) for MAPWID* MAPHEI cells, cells are in LRTB order.
                    MapWidth  = reader.ReadUInt16();
                    MapHeight = reader.ReadUInt16();

                    MapData = new GR.Memory.ByteBuffer((uint)(MapWidth * MapHeight));
                    if (!tileSysEnabled)
                    {
                        // map has color data
                        MapColorData = new GR.Memory.ByteBuffer((uint)(MapWidth * MapHeight));
                    }

                    for (int i = 0; i < MapHeight; ++i)
                    {
                        for (int j = 0; j < MapWidth; ++j)
                        {
                            ushort mapData = reader.ReadUInt16();

                            // we only support 8 bytes per char
                            MapData.SetU8At(i * MapWidth + j, (byte)mapData); // do we?? Mega65!

                            if (TileColorMode == ColorMode.PER_CHAR)
                            {
                                MapColorData.SetU8At(i * MapWidth + j, (byte)Characters[(byte)mapData].Color);
                            }
                        }
                    }
                }
                else
                {
                    Debug.Log("Unexpected block ID: " + blockID.ToString("X"));
                    return(false);
                }
            }
            return(true);
        }
 //Need to call this function when the entity move
 protected void OnMove()
 {
     tile.entity = null;
     tile        = world.GetTile((int)transform.position.x % World.width, (int)transform.position.y % World.height);
     tile.entity = this;
 }
        private bool LoadVersion5(GR.Memory.ByteBuffer Data)
        {
            BackgroundColor = Data.ByteAt(4);
            MultiColor1     = Data.ByteAt(5);
            MultiColor2     = Data.ByteAt(6);
            CustomColor     = Data.ByteAt(7);
            TileColorMode   = (ColorMode)Data.ByteAt(8);

            byte flags   = Data.ByteAt(9);
            bool noTiles = ((flags & 0x01) == 0);

            DisplayModeFile = DisplayMode.HIRES;
            if ((flags & 0x04) != 0)
            {
                DisplayModeFile = DisplayMode.MULTICOLOR;
            }
            bool isExpanded = ((flags & 0x02) != 0);

            NumChars   = Data.UInt16At(10) + 1;
            NumTiles   = Data.UInt16At(12) + 1;
            TileWidth  = Data.ByteAt(14);
            TileHeight = Data.ByteAt(15);

            MapWidth  = Data.UInt16At(16);
            MapHeight = Data.UInt16At(18);

            if (noTiles)
            {
                // fake tiles
                TileWidth  = 1;
                TileHeight = 1;
                NumTiles   = 256;
            }


            int headerSize          = 20;
            int offsetToCharData    = headerSize;
            int offsetToCharAttribs = offsetToCharData + NumChars * 8;
            int offsetToTileData    = offsetToCharAttribs + NumChars;
            int offsetToTileColors  = offsetToTileData + NumTiles * TileWidth * TileHeight * 2;

            if ((isExpanded) ||
                (noTiles))
            {
                offsetToTileColors = offsetToTileData;
            }
            int offsetToMapData = offsetToTileColors + NumTiles;

            if ((TileColorMode != ColorMode.PER_TILE) ||
                (noTiles))
            {
                offsetToMapData = offsetToTileColors;
            }

            // char_data/char_attribs
            for (int charIndex = 0; charIndex < NumChars; ++charIndex)
            {
                SingleChar newChar = new SingleChar();
                newChar.Data = Data.SubBuffer(offsetToCharData + charIndex * 8, 8);
                if (TileColorMode == ColorMode.PER_CHAR)
                {
                    newChar.Color = Data.ByteAt(offsetToCharAttribs + charIndex) & 0x0f;
                }
                else
                {
                    newChar.Color = CustomColor;
                }

                Characters.Add(newChar);
            }

            // tile_data
            if (noTiles)
            {
                for (int i = 0; i < NumTiles; ++i)
                {
                    Tile tile = new Tile();

                    tile.CharData.Resize((uint)(TileWidth * TileHeight * 2));
                    tile.CharData.SetU16At(0, (ushort)i);

                    tile.ColorData.Resize((uint)(TileWidth * TileHeight));
                    tile.ColorData.SetU8At(0, (byte)CustomColor);

                    Tiles.Add(tile);
                }
                if (NumChars < 256)
                {
                    // add all chars for safety reasons
                    for (int i = NumChars; i < 256; ++i)
                    {
                        SingleChar newChar = new SingleChar();
                        newChar.Data = new GR.Memory.ByteBuffer(8);
                        if (TileColorMode == ColorMode.PER_CHAR)
                        {
                            newChar.Color = Data.ByteAt(offsetToCharAttribs + i) & 0x0f;
                        }
                        else
                        {
                            newChar.Color = CustomColor;
                        }

                        Characters.Add(newChar);
                    }
                }
            }
            else
            {
                for (int i = 0; i < NumTiles; ++i)
                {
                    Tile tile = new Tile();

                    tile.CharData.Resize((uint)(TileWidth * TileHeight * 2));
                    tile.ColorData.Resize((uint)(TileWidth * TileHeight));

                    Tiles.Add(tile);
                }

                if (isExpanded)
                {
                    byte curCharIndex = 0;
                    for (int i = 0; i < NumTiles; ++i)
                    {
                        for (int j = 0; j < TileWidth * TileHeight; ++j)
                        {
                            Tiles[i].CharData.SetU16At(j * 2, curCharIndex);
                            ++curCharIndex;
                        }
                    }
                }
                else
                {
                    // tile_data.      Size = NUM_TILES * TILE_WIDTH * TILE_HEIGHT bytes * 2 bytes. (only exists if CHAR_DATA is not "Expanded")
                    for (int i = 0; i < NumTiles; ++i)
                    {
                        for (int j = 0; j < TileWidth * TileHeight; ++j)
                        {
                            Tiles[i].CharData.SetU16At(j * 2, Data.UInt16At(offsetToTileData + i * TileWidth * TileHeight * 2 + j * 2));
                        }
                    }
                }
            }

            // TILE_COLOURS.   Size = NUM_TILES bytes (1 byte per tile = "RAM colour". only exists if COLOR_MODE = 1 (Per Tile)
            if (TileColorMode == ColorMode.PER_TILE)
            {
                for (int i = 0; i < NumTiles; ++i)
                {
                    for (int y = 0; y < TileHeight; ++y)
                    {
                        for (int x = 0; x < TileWidth; ++x)
                        {
                            Tiles[i].ColorData.SetU8At(x + y * TileWidth, (byte)(Data.ByteAt(offsetToTileColors + i) & 0x0f));
                        }
                    }
                }
            }
            else if (TileColorMode == ColorMode.PER_CHAR)
            {
                // with V5 this actually means per character
                for (int i = 0; i < NumTiles; ++i)
                {
                    for (int y = 0; y < TileHeight; ++y)
                    {
                        for (int x = 0; x < TileWidth; ++x)
                        {
                            byte charColor = (byte)Characters[Tiles[i].CharData.ByteAt(2 * (x + y * TileWidth))].Color;
                            Tiles[i].ColorData.SetU8At(x + y * TileWidth, charColor);
                        }
                    }
                }
            }
            else if (TileColorMode == ColorMode.GLOBAL)
            {
                for (int i = 0; i < NumTiles; ++i)
                {
                    for (int y = 0; y < TileHeight; ++y)
                    {
                        for (int x = 0; x < TileWidth; ++x)
                        {
                            Tiles[i].ColorData.SetU8At(x + y * TileWidth, (byte)CustomColor);
                        }
                    }
                }
            }

            /*
             * else if ( TileColorMode == ColorMode.PER_TILE_CELL )
             * {
             * for ( int i = 0; i < NumTiles; ++i )
             * {
             *  for ( int y = 0; y < TileHeight; ++y )
             *  {
             *    for ( int x = 0; x < TileWidth; ++x )
             *    {
             *      Tiles[i].ColorData.SetU8At( x + y * TileWidth, (byte)( Data.ByteAt( offsetCellAttribs + i * TileWidth * TileHeight + x + y * TileHeight ) & 0x0f ) );
             *    }
             *  }
             * }
             * }*/

            // MAP_DATA.        Size =  MAP_WID x MAP_HEI bytes.
            // tile indices are now 16 bit! for now force 8bit

            //MapData = Data.SubBuffer( offsetMapData, MapWidth * MapHeight * 2 );

            MapData = new GR.Memory.ByteBuffer((uint)(MapWidth * MapHeight));

            for (int i = 0; i < MapHeight; ++i)
            {
                for (int j = 0; j < MapWidth; ++j)
                {
                    MapData.SetU8At(i * MapWidth + j, Data.ByteAt(offsetToMapData + 2 * (i * MapWidth + j)));
                }
            }
            return(true);
        }
示例#46
0
 public void AddNeighbor(Sides side, Tile tile)
 {
     neighbors[(int)side] = tile;
     CalculateAutotileID();
 }
示例#47
0
    void UpdateDragging()
    {
        if (Input.GetMouseButtonDown(0))
        {
            dragStartPosition = currFramePosition;
        }

        int start_x = Mathf.FloorToInt(dragStartPosition.x);
        int end_x   = Mathf.FloorToInt(currFramePosition.x);
        int start_y = Mathf.FloorToInt(dragStartPosition.y);
        int end_y   = Mathf.FloorToInt(currFramePosition.y);

        if (end_x < start_x)
        {
            int tmp = end_x;
            end_x   = start_x;
            start_x = tmp;
        }
        if (end_y < start_y)
        {
            int tmp = end_y;
            end_y   = start_y;
            start_y = tmp;
        }

        while (dragPreviewGameObjects.Count > 0)
        {
            GameObject go = dragPreviewGameObjects[0];
            dragPreviewGameObjects.RemoveAt(0);
            Pooling.Despawn(go);
        }

        if (Input.GetMouseButton(0))
        {
            for (int x = start_x; x <= end_x; x++)
            {
                for (int y = start_y; y <= end_y; y++)
                {
                    Tile t = WorldController.Instance.World.GetTileAt(x, y);

                    if (t != null)
                    {
                        GameObject go = Pooling.Spawn(circleCursorPrefab, new Vector3(x, y, 0), Quaternion.identity);
                        go.transform.SetParent(this.transform, true);
                        dragPreviewGameObjects.Add(go);
                    }
                }
            }
        }

        if (Input.GetMouseButtonUp(0))
        {
            for (int x = start_x; x <= end_x; x++)
            {
                for (int y = start_y; y <= end_y; y++)
                {
                    Tile t = WorldController.Instance.World.GetTileAt(x, y);
                    if (t != null)
                    {
                        t.Type = Tile.TileType.Floor;
                    }
                }
            }
        }
    }
        private bool LoadVersion7(GR.Memory.ByteBuffer Data)
        {
            BackgroundColor  = Data.ByteAt(4);
            MultiColor1      = Data.ByteAt(5);
            MultiColor2      = Data.ByteAt(6);
            BackgroundColor4 = Data.ByteAt(7);
            CustomColor      = Data.ByteAt(8);
            TileColorMode    = (ColorMode)Data.ByteAt(9);

            // only uses values 0 to 2, which maps fine
            DisplayModeFile = (DisplayMode)Data.ByteAt(10);

            byte flags          = Data.ByteAt(11);
            bool tileSysEnabled = ((flags & 0x01) != 0);


            ushort charDataBlockID      = 0xdab0;
            ushort charAttributeBlockID = 0xdab1;
            ushort mapDataBlockID       = 0xdab2;


            if (!tileSysEnabled)
            {
                // fake tiles (one per char)
                TileWidth  = 1;
                TileHeight = 1;
                NumTiles   = 256;

                for (int i = 0; i < NumTiles; ++i)
                {
                    Tile tile = new Tile();

                    tile.CharData.Resize((uint)(TileWidth * TileHeight * 2));
                    tile.CharData.SetU16At(0, (ushort)i);

                    tile.ColorData.Resize((uint)(TileWidth * TileHeight));
                    tile.ColorData.SetU8At(0, (byte)CustomColor);

                    Tiles.Add(tile);
                }
            }

            var reader = Data.MemoryReader();

            reader.Skip(12);

            while (reader.DataAvailable)
            {
                ushort blockID = reader.ReadUInt16NetworkOrder();

                if (blockID == mapDataBlockID)
                {
                    if (tileSysEnabled)
                    {
                        // Tile data block

                        // TILECNT: Tile count minus one(16 - bit, LSBF).
                        NumTiles = reader.ReadUInt16() + 1;

                        // TILEWID: Tile width( byte).
                        TileWidth = reader.ReadUInt8();
                        // TILEHEI: Tile height( byte).
                        TileHeight = reader.ReadUInt8();

                        // TILEDAT: Tile data, 16 bits per tile cell( LSBF) for TILEWID* TILEHEI cells * TILECNT items, cells are in LRTB order.
                        for (int i = 0; i < NumTiles; ++i)
                        {
                            Tile tile = new Tile();

                            tile.CharData.Resize((uint)(TileWidth * TileHeight * 2));
                            tile.ColorData.Resize((uint)(TileWidth * TileHeight));

                            Tiles.Add(tile);
                        }
                        if (NumChars < 256)
                        {
                            // add all chars for safety reasons
                            for (int i = NumChars; i < 256; ++i)
                            {
                                SingleChar newChar = new SingleChar();
                                newChar.Data = new GR.Memory.ByteBuffer(8);
                                Characters.Add(newChar);
                            }
                        }
                        for (int i = 0; i < NumTiles; ++i)
                        {
                            for (int j = 0; j < TileWidth * TileHeight; ++j)
                            {
                                Tiles[i].CharData.SetU16At(j * 2, reader.ReadUInt16());
                            }
                        }
                    }
                    else
                    {
                        // BLKMARK : Block marker (0xDA, 0xBn).
                        // MAPWID: Map Width(16 - bit, LSBF).
                        // MAPHEI: Map height(16 - bit, LSBF).
                        // MAPDAT: Map data, 16 bits per cell( LSBF ) for MAPWID* MAPHEI cells, cells are in LRTB order.
                        MapWidth  = reader.ReadUInt16();
                        MapHeight = reader.ReadUInt16();

                        MapData = new GR.Memory.ByteBuffer((uint)(MapWidth * MapHeight));

                        for (int i = 0; i < MapHeight; ++i)
                        {
                            for (int j = 0; j < MapWidth; ++j)
                            {
                                MapData.SetU8At(i * MapWidth + j, (byte)reader.ReadUInt16());
                            }
                        }
                    }
                }

                if (blockID == charDataBlockID)
                {
                    // Character data block

                    // CHARCNT: Character image count minus one( 16 - bit, LSBF ).
                    NumChars = reader.ReadUInt16() + 1;

                    // CHARDAT : Character image data( eight bytes / rows per image for CHARCNT images, rows are in TB order ).
                    for (int charIndex = 0; charIndex < NumChars; ++charIndex)
                    {
                        SingleChar newChar = new SingleChar();
                        newChar.Data  = new GR.Memory.ByteBuffer();
                        newChar.Color = CustomColor;
                        reader.ReadBlock(newChar.Data, 8);
                        Characters.Add(newChar);
                    }

                    if (!tileSysEnabled)
                    {
                        if (NumChars < 256)
                        {
                            // add all chars for safety reasons
                            for (int i = NumChars; i < 256; ++i)
                            {
                                SingleChar newChar = new SingleChar();
                                newChar.Data  = new GR.Memory.ByteBuffer(8);
                                newChar.Color = CustomColor;

                                Characters.Add(newChar);
                            }
                        }
                    }
                }
                else if (blockID == charAttributeBlockID)
                {
                    // char attributes
                    // BLKMARK: Block marker(0xDA, 0xB1).
                    // CHARATTS: Char attribute data, one byte per char image for CHARCNT images, low nybble = colour, high nybble = material.
                    //           nb.colours are only stored when the colouring mode is "per character".
                    for (int charIndex = 0; charIndex < NumChars; ++charIndex)
                    {
                        if (TileColorMode == ColorMode.PER_CHAR)
                        {
                            Characters[charIndex].Color = reader.ReadUInt8() & 0x0f;
                            if (!tileSysEnabled)
                            {
                                Tiles[charIndex].ColorData.SetU8At(0, (byte)Characters[charIndex].Color);
                            }
                        }
                    }
                }
            }
            return(true);
        }
示例#49
0
    public void DoBuild(Tile t)
    {
        if (buildMode == BuildMode.FURNITURE)
        {
            // Create the Furniture and assign it to the tile

            // FIXME: This instantly builds the furnite:
            //WorldController.Instance.World.PlaceFurniture( buildModeObjectType, t );

            // Can we build the furniture in the selected tile?
            // Run the ValidPlacement function!

            string furnitureType = buildModeObjectType;

            if (
                WorldController.Instance.world.IsFurniturePlacementValid(furnitureType, t) &&
                t.pendingFurnitureJob == null
                )
            {
                // This tile position is valid for this furniture
                // Create a job for it to be build

                Job j;

                if (WorldController.Instance.world.furnitureJobPrototypes.ContainsKey(furnitureType))
                {
                    // Make a clone of the job prototype
                    j = WorldController.Instance.world.furnitureJobPrototypes[furnitureType].Clone();
                    // Assign the correct tile.
                    j.tile = t;
                }
                else
                {
                    Debug.LogError("There is no furniture job prototype for '" + furnitureType + "'");
                    j = new Job(t, furnitureType, FurnitureActions.JobComplete_FurnitureBuilding, 0.1f, null);
                }

                j.furniturePrototype = WorldController.Instance.world.furniturePrototypes[furnitureType];


                // FIXME: I don't like having to manually and explicitly set
                // flags that preven conflicts. It's too easy to forget to set/clear them!
                t.pendingFurnitureJob = j;
                j.RegisterJobStoppedCallback((theJob) => { theJob.tile.pendingFurnitureJob = null; });

                // Add the job to the queue
                WorldController.Instance.world.jobQueue.Enqueue(j);
            }
        }
        else if (buildMode == BuildMode.FLOOR)
        {
            // We are in tile-changing mode.
            t.Type = buildModeTile;
        }
        else if (buildMode == BuildMode.DECONSTRUCT)
        {
            // TODO
            if (t.furniture != null)
            {
                t.furniture.Deconstruct();
            }
        }
        else
        {
            Debug.LogError("UNIMPLMENTED BUILD MODE");
        }
    }
        private bool LoadVersion4(GR.Memory.ByteBuffer Data)
        {
            BackgroundColor = Data.ByteAt(4);
            MultiColor1     = Data.ByteAt(5);
            MultiColor2     = Data.ByteAt(6);
            CustomColor     = Data.ByteAt(7);
            TileColorMode   = (ColorMode)Data.ByteAt(8);
            DisplayModeFile = (DisplayMode)Data.ByteAt(9);

            NumChars   = Data.UInt16At(10) + 1;
            NumTiles   = Data.ByteAt(12) + 1;
            TileWidth  = Data.ByteAt(13);
            TileHeight = Data.ByteAt(14);

            MapWidth  = Data.UInt16At(15);
            MapHeight = Data.UInt16At(17);

            bool isExpanded = (Data.ByteAt(19) != 0);

            int offsetToCharAttribs = 24 + NumChars * 8;

            for (int charIndex = 0; charIndex < NumChars; ++charIndex)
            {
                SingleChar newChar = new SingleChar();
                newChar.Data  = Data.SubBuffer(24 + charIndex * 8, 8);
                newChar.Color = Data.ByteAt(offsetToCharAttribs + charIndex) & 0x0f;

                Characters.Add(newChar);
            }

            for (int i = 0; i < NumTiles; ++i)
            {
                Tile tile = new Tile();

                tile.CharData.Resize((uint)(TileWidth * TileHeight * 2));
                tile.ColorData.Resize((uint)(TileWidth * TileHeight));

                Tiles.Add(tile);
            }

            if (isExpanded)
            {
                byte curCharIndex = 0;
                for (int i = 0; i < NumTiles; ++i)
                {
                    for (int j = 0; j < TileWidth * TileHeight; ++j)
                    {
                        Tiles[i].CharData.SetU16At(j * 2, curCharIndex);
                        ++curCharIndex;
                    }
                }
            }
            else
            {
                // CELL_DATA.      Size = NUM_TILES * TILE_SIZE * TILE_SIZE bytes * 2 bytes. (only exists if CHAR_DATA is not "Expanded")
                int offsetCellData = 24 + NumChars * 8 + NumChars;
                for (int i = 0; i < NumTiles; ++i)
                {
                    for (int j = 0; j < TileWidth * TileHeight; ++j)
                    {
                        Tiles[i].CharData.SetU16At(j * 2, Data.UInt16At(offsetCellData + i * TileWidth * TileHeight * 2 + j * 2));
                    }
                }
            }
            // CELL_ATTRIBS.   Size = NUM_TILES * TILE_SIZE * TILE_SIZE bytes (exists for ALL modes)

            int offsetCellAttribs = 24 + NumChars * 8 + NumChars;

            if (!isExpanded)
            {
                offsetCellAttribs += NumTiles * TileWidth * TileHeight * 2;
            }
            for (int i = 0; i < NumTiles; ++i)
            {
                for (int y = 0; y < TileHeight; ++y)
                {
                    for (int x = 0; x < TileWidth; ++x)
                    {
                        if (TileColorMode == ColorMode.PER_CHAR)
                        {
                            Tiles[i].ColorData.SetU8At(x + y * TileWidth, (byte)(Data.ByteAt(offsetCellAttribs + i * TileWidth * TileHeight + x + y * TileHeight) & 0x0f));
                        }
                        else
                        {
                            Tiles[i].ColorData.SetU8At(x + y * TileWidth, (byte)CustomColor);
                        }
                    }
                }
            }

            // TILE_ATTRIBS.   Size = NUM_TILES bytes (1 byte per tile = "RAM colour". only exists if COLOR_MODE = 1 (Per Tile)
            int offsetTileAttribs = offsetCellAttribs + NumTiles * TileWidth * TileHeight;

            if (TileColorMode == ColorMode.PER_TILE)
            {
                for (int i = 0; i < NumTiles; ++i)
                {
                    for (int y = 0; y < TileHeight; ++y)
                    {
                        for (int x = 0; x < TileWidth; ++x)
                        {
                            Tiles[i].ColorData.SetU8At(x + y * TileWidth, (byte)(Data.ByteAt(offsetTileAttribs + i) & 0x0f));
                        }
                    }
                }
            }

            /*
             * if ( TileColorMode == ColorMode.PER_TILE_CELL )
             * {
             * for ( int i = 0; i < NumTiles; ++i )
             * {
             *  for ( int y = 0; y < TileHeight; ++y )
             *  {
             *    for ( int x = 0; x < TileWidth; ++x )
             *    {
             *      Tiles[i].ColorData.SetU8At( x + y * TileWidth, (byte)( Data.ByteAt( offsetCellAttribs + i * TileWidth * TileHeight + x + y * TileHeight ) & 0x0f ) );
             *    }
             *  }
             * }
             * }*/

            // MAP_DATA.        Size =  MAP_WID x MAP_HEI bytes.
            int offsetMapData = offsetTileAttribs;

            if (TileColorMode == ColorMode.PER_TILE)
            {
                offsetMapData += NumTiles;
            }

            MapData = Data.SubBuffer(offsetMapData, MapWidth * MapHeight);
            return(true);
        }
示例#51
0
    IEnumerator Move(Vector3Int target)
    {
        Vector2 pos;
        Vector2 dir;
        float   distance;
        float   distance_temp;

        float             _distance;
        Vector2           post_pos;
        List <Vector3Int> path = new List <Vector3Int>();//A STAR 를 통해 target까지 가는 vec3int  List

        path = PathFinder(Cur, target);

        dir = GameManager.instance.map.CellToWorld(Cur) - transform.position;
        dir.Normalize();
        distance      = Vector2.Distance(this.transform.position, GameManager.instance.map.CellToWorld(Cur));
        distance_temp = 99999999;
        if (distance > 0.1f) //처음에 위치 맞추기
        {
            _ani.SetBool("Run", true);
            _ani.SetFloat("DirX", dir.x);
            _ani.SetFloat("DirY", dir.y);

            while (true)
            {
                this.transform.Translate(dir * Time.deltaTime);
                distance = Vector2.Distance(this.transform.position, GameManager.instance.map.CellToWorld(Cur));
                yield return(null);

                if (distance > distance_temp || distance < 0.01f) //dist가 작아지다가 커지면
                {
                    break;
                }

                distance_temp = distance;
                post_pos      = this.transform.position;
            }
            _ani.SetBool("Run", false);
        }


        Tile _tile = Resources.Load <Tile>("Tile/1");

        if (path == null)
        {
            Goal = ChooseGoal();

            target = Goal;

            path = PathFinder(Cur, target);
        }
        if (path.Count == 0)
        {
            if (GameManager.instance.IsTileChangeOK(Cur))
            {
                GameManager.instance.map.SetTile(Cur, _tile);
            }
            GameManager.instance.map.SetTileFlags(Cur, TileFlags.None);
            GameManager.instance.map.SetColor(Cur, _color);
            transform.position += Vector3.forward * (-transform.position.z + Cur.z + 2);

            dir = GameManager.instance.map.CellToWorld(Cur) - transform.position;
            dir.Normalize();

            distance_temp = 99999999;
            distance      = Vector2.Distance(this.transform.position, GameManager.instance.map.CellToWorld(Cur));

            if (distance > 0.1f)
            {
                _ani.SetBool("Run", true);
                _ani.SetFloat("DirX", dir.x);
                _ani.SetFloat("DirY", dir.y);
            }
            while (true)
            {
                this.transform.Translate(dir * Time.deltaTime);
                distance = Vector2.Distance(this.transform.position, GameManager.instance.map.CellToWorld(Cur));
                yield return(null);

                if (distance > distance_temp || distance < 0.01f) //dist가 작아지다가 커지면
                {
                    break;
                }

                distance_temp = distance;
                post_pos      = this.transform.position;
            }
            _ani.SetBool("Run", false);
        }
        while (path.Count != 0)
        {
            _ani.SetBool("Run", true);
            Next = path[0];

            vec3_temp = path[0] - Cur;
            if (vec3_temp.x == 0 && vec3_temp.y == 1)
            {
                dir.x = -1f;
                dir.y = 0.5f;
            }
            else if (vec3_temp.x == 0 && vec3_temp.y == -1)
            {
                dir.x = 1f;
                dir.y = -0.5f;
            }
            else if (vec3_temp.x == 1 && vec3_temp.y == 0)
            {
                dir.x = 1f;
                dir.y = 0.5f;
            }
            else
            {
                dir.x = -1f;
                dir.y = -0.5f;
            }
            pos = GameManager.instance.map.CellToWorld(Next);
            dir.Normalize();

            _ani.SetFloat("DirX", dir.x);
            _ani.SetFloat("DirY", dir.y);
            distance_temp = 99999999;
            _distance     = 0;
            post_pos      = transform.position;
            IsYChanged    = false;
            IsMoving      = true;
            while (true)
            {
                this.transform.Translate(dir * Time.deltaTime);
                distance   = Vector2.Distance(this.transform.position, pos);
                _distance += Vector2.Distance(this.transform.position, post_pos);
                yield return(null);

                if (distance > distance_temp || distance < 0.01f) //dist가 작아지다가 커지면
                {
                    break;
                }

                if (!IsYChanged && _distance > 0.2f) //거의다 도착했을때
                {
                    IsYChanged          = true;
                    transform.position += Vector3.up * (Next.z - Cur.z) * 0.25f;
                    transform.position += Vector3.forward * (Next.z - Cur.z);
                    if (IsOnBarrack)
                    {
                        transform.position += Vector3.forward;
                    }
                    distance_temp = 99999999;
                    Cur           = Next;
                    continue;
                }
                distance_temp = distance;
                post_pos      = this.transform.position;
            }
            Cur      = Next;
            IsMoving = false;
            path.RemoveAt(0);

            this.transform.position = pos;
            transform.position     += Vector3.forward * (-transform.position.z + Cur.z + 2);
            if (IsOnBarrack)
            {
                transform.position += Vector3.forward;
            }
            if (GameManager.instance.IsTileChangeOK(Cur))
            {
                GameManager.instance.map.SetTile(Cur, _tile);
            }
            GameManager.instance.map.SetTileFlags(Cur, TileFlags.None);
            GameManager.instance.map.SetColor(Cur, _color);
        }
        _ani.SetBool("Run", false);

        yield return(new WaitForSeconds(0.5f));

        if (GameManager.instance.IsBarrackOK(Cur))//주변에 건물 있는지
        {
            prefab_Barrack = Instantiate(GameManager.instance.Barrack, GameManager.instance.change.CellToWorld(Cur), Quaternion.identity);
            prefab_Barrack.transform.position          += 2 * Vector3.forward;
            prefab_Barrack.GetComponent <Node>().Master = Master;
            prefab_Barrack.GetComponent <Node>().Pos    = Cur;
            IsOnBarrack = true;
            GameManager.instance.TileMaster[Cur.x + GameManager.instance.mapsize / 2, Cur.y + GameManager.instance.mapsize / 2] = Master;
        }
        if (!IsStand)
        {
            UnitState = (int)ActState.stand;
        }
        else
        {
            IsStand = false;
        }
        if (IsChase)
        {
            UnitState = (int)ActState.chase;
        }

        yield return(null);
    }
示例#52
0
 public override void OnCollideTile(Tile tile, bool isInitialCollision)
 {
     Intercept();
 }
示例#53
0
    void Update()
    {
        if (Amount <= 0)
        {
            CharMerge.Remove(this.gameObject);
            Destroy(this.gameObject);
        }
        if (IsOnBarrack)
        {
            GetComponent <SpriteRenderer>().sortingOrder = 1;
        }
        else
        {
            GetComponent <SpriteRenderer>().sortingOrder = 0;
        }
        timer += Time.deltaTime;
        if (timer >= 1)
        {
            timer = 0;
            if (GameManager.instance.money[Master] > 0)
            {
                GameManager.instance.money[Master] -= Mathf.CeilToInt((Amount ^ 2) / 100);
            }
        }
        switch (UnitState)
        {
        case (int)ActState.stand:
            _ani.SetBool("Run", false);
            _ani.SetBool("Attack", false);
            if (Goal == Cur)
            {
                Goal = ChooseGoal();
            }
            if (Goal == Cur)     //주변에 점령할 것이 없는경우 또는 맨처음!
            {
                if (CharMerge.Count != 0)
                {
                    UnitState = (int)ActState.merge;
                    break;
                }
            }
            else
            {
                if (!CharMerge.Contains(this.gameObject))
                {
                    CharMerge.Add(this.gameObject);
                }
            }
            StartCoroutine(Move(Goal));
            UnitState = (int)ActState.run;
            break;

        case (int)ActState.merge:
            if (CharMerge.Count == 0)
            {
                UnitState = (int)ActState.run;
                break;
            }

            Goal = CharMerge[Random.Range(0, CharMerge.Count)].GetComponent <Unit>().Cur;
            StartCoroutine(Move(Goal));
            UnitState = (int)ActState.run;
            break;

        case (int)ActState.run:
            break;

        case (int)ActState.attack:
            if (Enemy == null)
            {
                _ani.SetBool("Attack", false);
                UnitState = (int)ActState.run;
                StartCoroutine(Move(Cur));
                break;
            }
            if (!prefab_Fight)
            {
                prefab_Fight = Instantiate(GameManager.instance.prefabs[0], (transform.position + Enemy.transform.position) / 2, Quaternion.identity);
                prefab_Fight.transform.localScale *= 0.5f;
                Destroy(prefab_Fight, 0.5f);
            }
            fightingtimer += Time.deltaTime;
            if (fightingtimer >= 1)
            {
                fightingtimer = 0;

                if (Enemy == null)
                {
                    _ani.SetBool("Attack", false);
                    StartCoroutine(Move(Cur));
                }
                else if (Enemy.GetComponent <Unit>() != null)    //적이 캐릭터면
                {
                    Enemy.GetComponent <Unit>().Amount -= Mathf.CeilToInt(Amount / 10f);
                    Amount--;
                }
                else if (Enemy.GetComponent <Node>() != null)    //적이 배럭이면
                {
                    Enemy.GetComponent <Node>().HP -= Amount * 5;
                    Amount--;
                }
                else if (Enemy.GetComponent <TreeAndBush>() != null)   //적이 방해물이면
                {
                    Enemy.GetComponent <TreeAndBush>().HP -= Amount * 5;
                    Amount--;
                }
            }
            break;

        case (int)ActState.build:
            //가장 가까운 빌드 할수있는곳 찾아서 move하고 move 한뒤 그곳에 빌드 할수 있는지 체크하고 지음
            break;

        case (int)ActState.chase:
            if (ChaseUnit == null)
            {
                IsChase   = false;
                UnitState = (int)ActState.stand;
                break;
            }
            StopAllCoroutines();
            StartCoroutine(Chase(ChaseUnit));
            UnitState = (int)ActState.run;
            //케릭터를 누르고 버튼을 눌러 그 캐릭터의 cur 위치로 move하도록 함
            break;

        case (int)ActState.barrigate:
            if (Next == Goal)
            {
                IsBarrigate = false;
                StopAllCoroutines();

                prefab_Obstacle = Instantiate(GameManager.instance.Obstacle, GameManager.instance.change.CellToWorld(Goal), Quaternion.identity);
                prefab_Obstacle.GetComponent <TreeAndBush>().Pos = Goal;
                Next = Cur;

                GameManager.instance.TileMaster[Goal.x + GameManager.instance.mapsize / 2, Goal.y + GameManager.instance.mapsize / 2] = 5;
                //GameManager.instance.change.SetTile(Goal, _tile);
                _ani.SetBool("Run", false);

                UnitState = (int)ActState.run;
            }
            //가장 가까운 빌드 할수있는곳 찾아서 move하고 move 한뒤 그곳에 빌드 할수 있는지 체크하고 지음
            break;

        case (int)ActState.bridge:
            //가장 가까운 빌드 할수있는곳 찾아서 move하고 move 한뒤 그곳에 빌드 할수 있는지 체크하고 지음
            if (Goal == Cur)
            {
                float distance = Vector2.Distance(this.transform.position, GameManager.instance.map.CellToWorld(Goal));
                if (distance < 0.1f)
                {
                    IsBridge = false;

                    Tile _tile = Resources.Load <Tile>("Tile/BridgeLU");    //지형에 따라 RU

                    GameManager.instance.map.SetTile(BridgeLocation, _tile);

                    //UnitState = (int)ActState.stand;  //Move에서 이미 Stand로 넘어감
                }
            }

            break;
        }
    }
示例#54
0
    // void UpdateCursor()
    // {
    //   // Update the box cursor position
    // Tile tileHovered = WorldController.Instance.GetTileAtWorldCoord(currFramePosition);
    //   if (tileHovered != null)
    //   {
    //     boxCursor.SetActive(true);
    //     Vector3 cursorPosition = new Vector3(tileHovered.X, tileHovered.Y, 0);
    //     boxCursor.transform.position = cursorPosition;
    //   }
    //   else
    //   {
    //     boxCursor.SetActive(false);
    //   }
    // }

    void UpdateDrag()
    {
        // If over UI element, return
        if (EventSystem.current.IsPointerOverGameObject())
        {
            return;
        }

        // Start drag
        if (Input.GetMouseButtonDown(0))
        {
            dragStartPosition = currFramePosition;
        }

        int start_x = Mathf.FloorToInt(dragStartPosition.x);
        int end_x   = Mathf.FloorToInt(currFramePosition.x);
        int start_y = Mathf.FloorToInt(dragStartPosition.y);
        int end_y   = Mathf.FloorToInt(currFramePosition.y);

        if (end_x < start_x)
        {
            int tmp = end_x;
            end_x   = start_x;
            start_x = tmp;
        }

        if (end_y < start_y)
        {
            int tmp = end_y;
            end_y   = start_y;
            start_y = tmp;
        }

        // Clean up old drag previews
        while (dragPreviewGameObjects.Count > 0)
        {
            GameObject go = dragPreviewGameObjects[0];
            dragPreviewGameObjects.RemoveAt(0);
            SimplePool.Despawn(go);
        }

        if (Input.GetMouseButton(0))
        {
            // Display a preview of the drag area
            for (int x = start_x; x <= end_x; x++)
            {
                for (int y = start_y; y <= end_y; y++)
                {
                    Tile t = WorldController.Instance.World.GetTileAt(x, y);
                    if (t != null)
                    {
                        // Display the building hint on top of this tile position
                        GameObject go = SimplePool.Spawn(boxCursorPrefab, new Vector3(x, y, 0), Quaternion.identity);
                        dragPreviewGameObjects.Add(go);
                    }
                }
            }
        }

        // End drag
        if (Input.GetMouseButtonUp(0))
        {
            for (int x = start_x; x <= end_x; x++)
            {
                for (int y = start_y; y <= end_y; y++)
                {
                    Tile tile = WorldController.Instance.World.GetTileAt(x, y);
                    if (tile != null)
                    {
                        if (buildModeIsObjects)
                        {
                            // Create the Furniture and assign it to the Tile.
                            WorldController.Instance.World.PlaceFurniture(buildModeObjectType, tile);
                        }
                        else
                        {
                            // Tile-changing mode.
                            tile.Type = buildModeTile;
                        }
                    }
                }
            }
        }
    }
示例#55
0
        public override float SpawnChance(NPCSpawnInfo spawnInfo)
        {
            Tile tile = Framing.GetTileSafely(spawnInfo.spawnTileX, spawnInfo.spawnTileY);

            return(tile.active() && spawnInfo.spawnTileType != TileType <VitricSpike>() && spawnInfo.player.GetModPlayer <BiomeHandler>().ZoneGlass ? 0.75f : 0f);
        }
示例#56
0
    IEnumerator Chase(GameObject targetUnit)
    {
        Vector2    pos;
        Vector2    dir;
        Vector3Int target = targetUnit.GetComponent <Unit>().Cur;
        float      distance;
        float      distance_temp;

        float             _distance;
        Vector2           post_pos;
        List <Vector3Int> path = new List <Vector3Int>();//A STAR 를 통해 target까지 가는 vec3int  List

        path = PathFinder(Cur, target);

        dir = GameManager.instance.map.CellToWorld(Cur) - transform.position;
        dir.Normalize();
        distance      = Vector2.Distance(this.transform.position, GameManager.instance.map.CellToWorld(Cur));
        distance_temp = 99999999;
        _ani.SetBool("Run", true);

        if (distance > 0.1f) //처음에 위치 맞추기
        {
            _ani.SetFloat("DirX", dir.x);
            _ani.SetFloat("DirY", dir.y);

            while (true)
            {
                this.transform.Translate(dir * Time.deltaTime);
                distance = Vector2.Distance(this.transform.position, GameManager.instance.map.CellToWorld(Cur));
                yield return(null);

                if (distance > distance_temp || distance < 0.01f) //dist가 작아지다가 커지면
                {
                    break;
                }

                distance_temp = distance;
                post_pos      = this.transform.position;
            }
        }

        if (path == null)
        {
            Goal = ChooseGoal();

            target = Goal;

            path = PathFinder(Cur, target);
        }
        Tile _tile = Resources.Load <Tile>("Tile/1");

        if (path.Count == 0)
        {
            if (GameManager.instance.IsTileChangeOK(Cur))
            {
                GameManager.instance.map.SetTile(Cur, _tile);
            }
            GameManager.instance.map.SetTileFlags(Cur, TileFlags.None);
            GameManager.instance.map.SetColor(Cur, _color);
            transform.position += Vector3.forward * (-transform.position.z + Cur.z + 2);

            dir = GameManager.instance.map.CellToWorld(Cur) - transform.position;
            dir.Normalize();

            distance_temp = 99999999;
            distance      = Vector2.Distance(this.transform.position, GameManager.instance.map.CellToWorld(Cur));

            if (distance > 0.1f)
            {
                _ani.SetFloat("DirX", dir.x);
                _ani.SetFloat("DirY", dir.y);
            }
            while (true)
            {
                this.transform.Translate(dir * Time.deltaTime);
                distance = Vector2.Distance(this.transform.position, GameManager.instance.map.CellToWorld(Cur));
                yield return(null);

                if (distance > distance_temp || distance < 0.01f) //dist가 작아지다가 커지면
                {
                    break;
                }

                distance_temp = distance;
                post_pos      = this.transform.position;
            }
        }
        else
        {
            Next = path[0];


            vec3_temp = path[0] - Cur;
            if (vec3_temp.x == 0 && vec3_temp.y == 1)
            {
                dir.x = -1f;
                dir.y = 0.5f;
            }
            else if (vec3_temp.x == 0 && vec3_temp.y == -1)
            {
                dir.x = 1f;
                dir.y = -0.5f;
            }
            else if (vec3_temp.x == 1 && vec3_temp.y == 0)
            {
                dir.x = 1f;
                dir.y = 0.5f;
            }
            else
            {
                dir.x = -1f;
                dir.y = -0.5f;
            }
            pos = GameManager.instance.map.CellToWorld(Next);
            dir.Normalize();

            _ani.SetFloat("DirX", dir.x);
            _ani.SetFloat("DirY", dir.y);
            distance_temp = 99999999;
            _distance     = 0;
            post_pos      = transform.position;
            IsYChanged    = false;
            IsMoving      = true;
            while (true)
            {
                this.transform.Translate(dir * Time.deltaTime);
                distance   = Vector2.Distance(this.transform.position, pos);
                _distance += Vector2.Distance(this.transform.position, post_pos);
                yield return(null);

                if (distance > distance_temp || distance < 0.01f) //dist가 작아지다가 커지면
                {
                    break;
                }

                if (!IsYChanged && _distance > 0.2f) //거의다 도착했을때
                {
                    IsYChanged          = true;
                    transform.position += Vector3.up * (Next.z - Cur.z) * 0.25f;
                    transform.position += Vector3.forward * (Next.z - Cur.z);
                    if (IsOnBarrack)
                    {
                        transform.position += Vector3.forward;
                    }
                    distance_temp = 99999999;
                    Cur           = Next;
                    continue;
                }
                distance_temp = distance;
                post_pos      = this.transform.position;
            }
            Cur      = Next;
            IsMoving = false;

            this.transform.position = pos;
            transform.position     += Vector3.forward * (-transform.position.z + Cur.z + 2);
            if (IsOnBarrack)
            {
                transform.position += Vector3.forward;
            }
            if (GameManager.instance.IsTileChangeOK(Cur))
            {
                GameManager.instance.map.SetTile(Cur, _tile);
            }
            GameManager.instance.map.SetTileFlags(Cur, TileFlags.None);
            GameManager.instance.map.SetColor(Cur, _color);
        }
        UnitState = (int)ActState.chase;

        yield return(null);
    }
示例#57
0
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            var state = Keyboard.GetState();

            float moveSpeed = 250f * ((float)gameTime.ElapsedGameTime.TotalMilliseconds / 1000f);

            bool anyDown     = false;
            var  newPosition = Position;

            if (state.IsKeyDown(Keys.W))
            {
                newPosition.Y += -moveSpeed;
                Orientation    = Orientation.Top;
                anyDown        = true;
            }

            if (state.IsKeyDown(Keys.A))
            {
                newPosition.X += -moveSpeed;
                Orientation    = Orientation.Left;
                anyDown        = true;
            }

            if (state.IsKeyDown(Keys.D))
            {
                newPosition.X += moveSpeed;
                Orientation    = Orientation.Right;
                anyDown        = true;
            }

            if (state.IsKeyDown(Keys.S))
            {
                newPosition.Y += moveSpeed;
                Orientation    = Orientation.Bottom;
                anyDown        = true;
            }


            // Collision detection
            if (anyDown)
            {
                var tile = _mapService.GetTileAt(newPosition);
                _collisionCheckTile = tile;

                CollisionBounds = new Rectangle((int)(newPosition.X - Origin.X / 2) + 4, (int)(newPosition.Y - Origin.Y) + 32 + 8, 32 - 8, 24);

                var gameObjects = _gameObjectManager.GetCollidingFoliageGameObjects(this, CollisionBounds);

                if (tile != null && tile.Traversable && !gameObjects.Any())
                {
                    Position = newPosition;
                }
            }

            _currentAnimation = _walkingAnimationSet.GetAnimationForOrientation(Orientation);
            foreach (var sheets in _currentAnimation.AnimatedSpriteSheets)
            {
                sheets.Update(gameTime);

                if (!anyDown)
                {
                    sheets.Reset();
                }
                else
                {
                    sheets.Update(gameTime);
                }
            }

            _camera.Position = new Vector2((int)Position.X, (int)Position.Y);
        }
    public void constructLevel()
    {
        Tile.destroyAllTiles();
        for (int i = 0; i < levelObjects.Count; i++)
        {
            Destroy(levelObjects [i]);
        }
        levelObjects = new List <GameObject> ();

        int        nRows        = this.levels [this.currentLevel].nRows;
        int        nCols        = this.levels [this.currentLevel].nCols;
        int        playerSpawnX = 1;
        int        playerSpawnY = 2;
        int        goalX        = 0;
        int        goalY        = 0;
        GameObject tilePrefab   = groundPrefab;

        int[,] lab = this.levels [this.currentLevel].getMaze();

        for (int i = 0; i < nRows; i++)
        {
            for (int j = 0; j < nCols; j++)
            {
                int type = lab[i, j];

                if (type > 0)
                {
                    // Make 0 also be an alias for ground
                    if (type == 1 || type == 0)
                    {
                        tilePrefab = groundPrefab;
                    }
                    else if (type == 4)
                    {
                        tilePrefab = groundPrefab;
                        goalX      = j;
                        goalY      = i;
                    }
                    else if (type == 2)
                    {
                        tilePrefab = wallPrefab;
                    }
                    Tile tile = Tile.make(tilePrefab, j, nRows - i, type);

                    if (type == 2)
                    {
                        SpriteRenderer spt = tile.GetComponent <SpriteRenderer> ();
                        if (tile.isBoundary())
                        {
                            if (UnityEngine.Random.Range(0f, 1f) > 0.5f)
                            {
                                spt.sprite = boundaryWall1;
                            }
                            else
                            {
                                spt.sprite = boundaryWall2;
                            }
                        }
                        else
                        {
                            if (UnityEngine.Random.Range(0f, 1f) > 0.5f)
                            {
                                spt.sprite = removeableWall1;
                            }
                            else
                            {
                                spt.sprite = removeableWall2;
                            }
                        }
                    }
                }
            }
        }

        bool isLastLevel = currentLevel == (GameConstants.numLevels - 1);

        // Spawn the goal
        GameObject goal = Instantiate(goalPrefab, new Vector2(goalX, goalY), Quaternion.identity) as GameObject;

        levelObjects.Add(goal);

        // Spawn the key to the next level
        if (!isLastLevel)
        {
            Tile keySpawn = Tile.getRandomFloorTile(playerSpawnX, playerSpawnY, MINIMUM_KEY_DELTA_DISTANCE);
            this.addKey(keySpawn);
        }

        // Spawn the food (power ups)
        for (int i = 0; i < GameConstants.numFoodPerLevel; i++)
        {
            Tile foodSpawn = Tile.getRandomFloorTile();
            levelObjects.Add(
                Instantiate(this.foodPrefab, new Vector2(foodSpawn.x, foodSpawn.y), Quaternion.identity) as GameObject);
        }

        // Spawn pickaxes
        for (int i = 0; i < GameConstants.numPickaxesPerLevel; i++)
        {
            Tile pickaxeSpawn = Tile.getRandomFloorTile();
            levelObjects.Add(
                Instantiate(this.pickaxePrefab, new Vector2(pickaxeSpawn.x, pickaxeSpawn.y), Quaternion.identity) as GameObject);
        }

        // Spawn the enemies
        for (int i = 0; i < GameConstants.numEnemies; i++)
        {
            this.addEnemy(Tile.getRandomFloorTile(playerSpawnX, playerSpawnY, MINIMUM_ENEMY_SPAWN_DISTANCE));
        }

        // Spawn the boss
        if (isLastLevel)
        {
            Tile       bossSpawnPosition = Tile.getRandomFloorTile(playerSpawnX, playerSpawnY, MINIMUM_ENEMY_SPAWN_DISTANCE);
            GameObject boss = Instantiate(bossPrefab, new Vector3(bossSpawnPosition.x, bossSpawnPosition.y, 0), Quaternion.identity) as GameObject;
        }

        player.transform.position = new Vector2(playerSpawnX, playerSpawnY);
    }
示例#59
0
 public void attack(Tile target)
 {
     attackTile = target;
     attackToTarget();
 }
示例#60
0
	void Update() {
		if(Input.GetMouseButtonDown(0)) {
			RaycastHit hit;
			Ray ray = cam.ScreenPointToRay(Input.mousePosition);
			if(placingEntrance || placingExit) {
				if(Physics.Raycast(ray, out hit, Mathf.Infinity)) {
					Tile selected = hit.transform.gameObject.GetComponent<Tile>();
					if(!selected.IsAHill()) {
						for(int x = 0; x < mg.width; x++) {
							for(int y = 0; y < mg.height; y++) {
								if(mg.map[x, y] == selected) {
									if(x == 0 || y == 0 || x == mg.width-1 || y == mg.height-1) {
										GameObject current = null;
										if(placingEntrance) {
											if(placedEntrance) {
												current = mg.entrance;
											} else {
												current = Instantiate(mg.portalPrefab, Vector3.zero, Quaternion.identity);
												current.transform.SetParent(mg.transform);
											}
										} else {
											if(placedExit) {
												current = mg.exit;
											} else {
												current = Instantiate(mg.portalPrefab, Vector3.zero, Quaternion.identity);
												current.transform.SetParent(mg.transform);
											}
										}
										current.transform.localScale = new Vector3(mg.size, mg.size, 0.1f);
										int angle = FindAngle(hit.point);
										current.transform.eulerAngles = new Vector3(0, angle, 0);
										current.transform.position = FindPosition(angle, selected.transform.position);
										Portal portal = current.GetComponent<Portal>();
										if(placingEntrance) {
											portal.setSide(true);
											placingEntrance = false;
											if(!placedEntrance) {
												placedEntrance = true;
												mg.entrance = current;
											}
										} else {
											portal.setSide(false);
											placingExit = false;
											if(!placedExit) {
												placedExit = true;
												mg.exit = current;
											}
										}
									}
								}
							}
						}
					}
				}
			} else {
				if(Physics.Raycast(ray, out hit, Mathf.Infinity)) {
					Tile currentTile = hit.transform.GetComponent<Tile>();
					currentTile.SetIsAHill(!currentTile.IsAHill());
				}
			}
		}
	}