Example #1
0
    /// <summary>
    /// Raises the drag gesture event. This event is raised by FingerGestures's DragRecognizer component.
    /// Determine the selected tile and in which direction the user dragged it and tell the <see cref="Match3BoardGameLogic"/>
    /// that we've started moving that tile in that direction.
    /// </summary>
    /// <param name='eventData'>
    /// Event data.
    /// </param>
    public void OnDragGesture(DragGesture eventData)
    {
        if (dragLock > 0)
        {
            tapSelectedTile = null;
            return;
        }

        // Check if we've selected any tile.
        if (eventData.StartSelection != null && eventData.StartSelection.layer == Match3Globals.Instance.layerBoardTile)
        {
            if (eventData.Phase == ContinuousGesturePhase.Started)
            {
                // Cancel the tap selected tile if we've done a drag gesture.
                tapSelectedTile = null;

                AbstractTile      dragSelectedTile = eventData.StartSelection.GetComponent <AbstractTile>();
                TileMoveDirection moveDirection    = Match3BoardGameLogic.GetTileMoveDirection(eventData.TotalMove);

                if (InputFilter == null || InputFilter(dragSelectedTile, null, moveDirection))
                {
//					Debug.Log("Drag event started! Start Selection: " + eventData.StartSelection + " -> totalMove = " + eventData.TotalMove);
                    if (boardGameLogic.TryToMoveTile(dragSelectedTile, moveDirection))
                    {
                        //boardGameLogic.loseConditions.NewMove();
                    }
                }
            }
        }
    }
Example #2
0
        private void CreateTile(AbstractTile prefab, Vector2Int position)
        {
            AbstractTile tile = Instantiate(prefab, transform);

            tile.SetWorldPosition(position);
            _tiles.Add(tile);
        }
Example #3
0
        private bool Resume(AbstractTile n)
        {
            while (_open.Count > 0)
            {
                var p = _open.Dequeue();
                _closed.Add(p);

                if (p == n)
                {
                    return(true);
                }

                foreach (var q in _graph.AdjacentVertices(p).Reverse())
                {
                    var gScore = _gScore.GetValueOrDefault(p, double.PositiveInfinity) + Metrics.Octile(p, q);
                    var fScore = gScore + Metrics.Octile(q, _start);

                    if (!_open.Contains(q) && !_closed.Contains(q))
                    {
                        _open.Enqueue(q, double.PositiveInfinity);
                    }

                    if (_open.Contains(q) && fScore < _open.GetPriority(q))
                    {
                        _gScore[q] = gScore;
                        _open.UpdatePriority(q, fScore);
                    }
                }
            }

            return(false);
        }
	bool InputFilter(AbstractTile selectedTile, AbstractTile destinationTile, TileMoveDirection moveDirection) 
	{
		if (pieceToMove == null || pieceToMoveDestination == null) {
			return true;
		}
		
		AbstractTile tileToMove = pieceToMove.Tile;
		AbstractTile tileToMoveDest = pieceToMoveDestination.Tile;
		
		if (destinationTile == null) 
		{
			Match3BoardGameLogic boardLogic = Match3BoardGameLogic.Instance;
			BoardCoord targetBoardPos = selectedTile.BoardPiece.BoardPosition;
			targetBoardPos.OffsetByAndClamp(boardLogic.tilesMoveDirections[(int)moveDirection], boardLogic.boardData.NumRows - 1, boardLogic.boardData.NumColumns - 1);
			destinationTile = boardLogic.boardData[targetBoardPos].Tile;
		}
		
		if (tileToMove == selectedTile && tileToMoveDest == destinationTile ||
			tileToMove == destinationTile && tileToMoveDest == selectedTile)
		{
			disableTutorial = true;
			TileSwitchInput.Instance.InputFilter = null;
			return true;
		}

		return false;
	}
Example #5
0
    /*
     * Function will be called after a player arrives to his destination.
     * Set this player's PlayerMovement to disabled, and as described in the usage section
     * of that script.
     */
    private void OnPlayerArrived(EventInfo eventInfo)
    {
        AbstractTile currentTile = currentPlayer.GetCurrentTile();
        // convert tile to interface, to use each tile's type's specific functions
        ITile currentTileInterface = currentTile as ITile;

        currentPlayer.playerMovement.enabled = false;
        if (!currentTile.tileHasOwner())
        {
            // prompt player to pay
            if (currentTile.GetTILE_TYPE() != TILE_TYPE.EMPTY)
            {
                currentTileInterface.prompyBuyLocation();
                GUImanager.EnableButton(BUTTON_TYPE.BUY);
            }
        }
        else
        {
            if (currentTile.tileHasItem())
            {
                currentTile.buyItem(currentPlayer);
            }
            // if tile has an item, player is forced to buy item if he has enough money
            // GUImanager.promptTileBuy(currentPlayer.GetCurrentTile().getTileCard());
        }
        GUImanager.EnableButton(BUTTON_TYPE.END_TURN);
    }
 private Func <EventDTO> Vaetis()
 {
     return(() => new EventDTO(
                "Uus väetis",
                "Kaval teadlane leiutas uue väetise, mida ta korralikult kontrollida pole jõudnud, aga mis annaks külale palju suurema saagi ja heaolu",
                "Kasuta uut väetist",
                "Keela väetise kasutamine",
                () =>
     {
         AbstractTile riverTile = TileManager.Instance.GetRandomTileByType(TileType.RIVER);
         var surroundingTileLayers = TileManager.Instance.getTilesInRadius(riverTile, 2, true);
         foreach (List <GameObject> layers in surroundingTileLayers.Values.ToList())
         {
             foreach (var tile in layers)
             {
                 tile.GetComponent <AbstractTile>().groundPollution += 0.3f;
             }
         }
         CountyProperties.Instance.SetWellness(CountyProperties.Instance.wellness + 10);
         CountyProperties.Instance.SetFood(CountyProperties.Instance.food + 1000);
     },
                () =>
     {
         CountyProperties.Instance.SetWellness(CountyProperties.Instance.wellness - 10);
         CountyProperties.Instance.SetFood(CountyProperties.Instance.food - 300);
     }));
 }
        public static void RotateTIntersection(AbstractTile tile,
                                               Direction perpendicularDirection, IEnumerable <AbstractTile> connectTo)
        {
            Transform[] connections = connectTo.Select(connection => connection.CachedTransform).ToArray();

            // For every Neighbor rotate perpendicular towards neighbor
            // then check if the abs direction to the other neighbors is the same
            // if that is the case, we are rotated correctly (because it's a T crossing)
            for (int i = 0; i < connections.Length; i++)
            {
                Transform currentDirection = connections[i];
                tile.CachedTransform.DirectionLookAtTransform(perpendicularDirection, currentDirection);

                Transform neighbor2 = connections[(i + 1) % connections.Length];
                Transform neighbor3 = connections[(i + 2) % connections.Length];

                Vector3 neighbor2Delta = (neighbor2.position - tile.CachedTransform.position).normalized.Abs();
                Vector3 neighbor3Delta = (neighbor3.position - tile.CachedTransform.position).normalized.Abs();

                if (neighbor2Delta == neighbor3Delta)
                {
                    return;
                }
            }

            Debug.LogError("Could not rotate intersection correctly", tile);
        }
 public void RemoveTile(AbstractTile destroyedTile)
 {
     if (destroyedTile == Tile)
     {
         Tile = null;
     }
 }
    private Func <EventDTO> MetsaIstutamine()
    {
        return(() => new EventDTO(
                   "Metsa istutamine",
                   "Külaelanikud tahavad metsa juurde istutada. Kas lubad?",
                   "Jah",
                   "Ei",
                   () =>
        {
            AbstractTile tile = TileManager.Instance.GetRandomTileByType(TileType.GRASS);
            // CountyProperties.Instance.SetFood(CountyProperties.Instance.food + 50);
            if (tile != null)
            {
                TileManager.Instance.AddTileByPos(tile.transform.position.ToVector3Int(), TileType.FOREST);
                CountyProperties.Instance.SetWellness(CountyProperties.Instance.wellness + 5);
                CountyProperties.Instance.SetGlobalAirPoll(CountyProperties.Instance.globalAirpoll - 2);
                TileManager.Instance.amountOfForests++;

                // TileManager.Instance.RemoveTileByPosition(tile.transform.position.ToVector3Int());
            }
        },
                   () =>
        {
            CountyProperties.Instance.SetWellness(CountyProperties.Instance.wellness - 10);
        }));
    }
 /// <summary>
 /// Raises the tile changed event whenever the board piece <see cref="Tile"/> property is changed.
 /// </summary>
 /// <param name='newTile'>
 /// Changed tile.
 /// </param>
 public virtual void RaiseTileChangedEvent(AbstractTile newTile)
 {
     if (onTileChanged != null)
     {
         onTileChanged(this, newTile);
     }
 }
 /// <summary>
 /// Raises the event OnTileDestroyed. This event is usually called by the <see cref="Match3Tile.Destroy()"/> method.
 /// </summary>
 /// <param name='destroyedTile'>
 /// Destroyed tile.
 /// </param>
 public virtual void RaiseEventTileDestroyed(AbstractTile destroyedTile)
 {
     if (onTileDestroyed != null)
     {
         onTileDestroyed(this, destroyedTile);
     }
 }
Example #12
0
        private AbstractTile InstantiateTile(GridData data, Transform parent, TileType type, Vector2Int gridPosition)
        {
            GameObject prefab = prefabsPerTileTypes.First(pair => pair.Key.Equals(type)).Value.GetRandomItem();

            if (prefab == null)
            {
                throw new NullReferenceException($"A prefab for {type} is not assigned!");
            }

            GameObject instance = Instantiate(prefab, parent);

            instance.transform.position += CalculatePosition(data, parent, gridPosition);

            instance.name = $"{type.ToString()} {gridPosition.ToString()}";

            AbstractTile tile = instance.GetComponent <AbstractTile>();

            if (tile == null)
            {
                throw new NullReferenceException($"Prefab {prefab.name} does not have an AbstractTileComponent attached to it!");
            }

            tile.Initialize(gridPosition);

            return(tile);
        }
Example #13
0
        private static void AddNeighborsToTile(AbstractTile[,] grid, AbstractTile tile)
        {
            Vector2Int gridPosition = tile.GridPosition;

            // Make sure we can never sample below 0,0
            Vector2Int samplePosition = Vector2Int.zero;

            samplePosition.x = Mathf.Max(0, gridPosition.x - 1);
            samplePosition.y = Mathf.Max(0, gridPosition.y - 1);

            AbstractTile neighbor = grid[samplePosition.y, gridPosition.x];             // One below us, in the same column

            if (neighbor != tile)
            {
                tile.AddNeighbor(neighbor);
                neighbor.AddNeighbor(tile);
            }

            neighbor = grid[gridPosition.y, samplePosition.x];             // One before us, in the same row

            if (neighbor != tile)
            {
                tile.AddNeighbor(neighbor);
                neighbor.AddNeighbor(tile);
            }
        }
Example #14
0
 public void OnNeighborDestroy(AbstractBoardPiece sender, AbstractTile neighbor)
 {
     if (neighbor && (neighbor as NormalTile).IsMatched)
     {
         NumLayers--;
     }
 }
Example #15
0
    public void SwitchTiles(AbstractTile src, AbstractTile dst)
    {
        AbstractBoardPiece dstBoardPiece = dst.BoardPiece;

        src.BoardPiece.Tile = dst;
        dstBoardPiece.Tile  = src;
    }
Example #16
0
    public void OnTileTapped(AbstractTile tile)
    {
        BoardCoord targetCoord = tile.BoardPiece.BoardPosition;

        if (selectedTile == typeof(BombTile))
        {
            GameObject.Destroy(tile.gameObject);
            BombTile newTile = Match3BoardRenderer.Instance.SpawnSpecificTileAt(targetCoord, selectedTile, TileColorType.None) as BombTile;
            newTile.TileColor = RuleEntry.genericColors[Random.Range(0, Match3BoardRenderer.maxNumBoardColors)];
            newTile.UpdateMaterial();
        }
        else if (selectedTile == typeof(DirectionalDestroyTile))
        {
            GameObject.Destroy(tile.gameObject);

            DirectionalDestroyTile newTile = null;
            if (Random.value > 0.5f)
            {
                newTile = Match3BoardRenderer.Instance.SpawnSpecificTileAt(targetCoord, typeof(RowDestroyTile), TileColorType.None) as DirectionalDestroyTile;
            }
            else
            {
                newTile = Match3BoardRenderer.Instance.SpawnSpecificTileAt(targetCoord, typeof(ColumnDestroyTile), TileColorType.None) as DirectionalDestroyTile;
            }

            newTile.TileColor = RuleEntry.genericColors[Random.Range(0, Match3BoardRenderer.maxNumBoardColors)];
            newTile.UpdateMaterial();
        }
        else if (selectedTile == typeof(ColorBombTile))
        {
            GameObject.Destroy(tile.gameObject);

            ColorBombTile newTile = Match3BoardRenderer.Instance.SpawnSpecificTileAt(targetCoord, selectedTile, TileColorType.None) as ColorBombTile;
        }
    }
Example #17
0
    protected void ActionOnTweenComplete()
    {
        pathIndex++;
        AbstractTile tile = selectionList[pathIndex].Tile;

        if (tile != null)
        {
            selectionList[pathIndex].Tile.Destroy();
        }

        if (pathIndex == selectionList.Count - 1)
        {
            PossibleMatchesController.Instance.EnabledCount++;

            Match3BoardGameLogic.Instance.boardData.ApplyActionToAll((boardPiece) => {
                (boardPiece as Match3BoardPiece).BlockCount--;
            });

            Match3BoardGameLogic.Instance.boardData.ApplyActionToAll((boardPiece) => {
                (boardPiece as Match3BoardPiece).UpdateOrphanState();
            });

            StartCoroutine(EndOfPathMovement());

            return;
        }

        HOTween.To(torchEffectInstance.transform, torchMovementSpeed,
                   new TweenParms().Prop("position", selectionList[pathIndex + 1].transform.position + effectOffset)
                   .Ease(EaseType.Linear)
                   .SpeedBased()
                   .OnComplete(ActionOnTweenComplete));
    }
Example #18
0
 public void OnTileMovingChanged(AbstractTile tile)
 {
     if (!tile.IsMoving)
     {
         TryCheckStableBoard();
     }
 }
Example #19
0
    public override bool TryToMoveTile(AbstractTile srcTile, AbstractTile dstTile)
    {
        if (srcTile == dstTile || srcTile == null || dstTile == null)
        {
            return(false);
        }

        if (CanMoveTile(srcTile, dstTile.BoardPiece))
        {
            Match3Tile srcMatch3Tile = srcTile as Match3Tile;
            Match3Tile dstMatch3Tile = dstTile as Match3Tile;

            if (OnUserStartedTilesSwitch != null)
            {
                OnUserStartedTilesSwitch(srcMatch3Tile, dstMatch3Tile);
            }

            srcMatch3Tile.RaiseEventTileTappedFirst();

            srcMatch3Tile.IsTileSwitching = true;
            dstMatch3Tile.IsTileSwitching = true;
            BoardAnimations.SwitchTilesAnim(true, srcMatch3Tile, dstMatch3Tile);

            return(true);
        }

        return(false);
    }
	public void OnTileTapped(AbstractTile tile) 
	{
		BoardCoord targetCoord = tile.BoardPiece.BoardPosition;
		
		if (selectedTile == typeof(BombTile)) 
		{
			GameObject.Destroy(tile.gameObject);
			BombTile newTile = Match3BoardRenderer.Instance.SpawnSpecificTileAt(targetCoord, selectedTile, TileColorType.None) as BombTile;
			newTile.TileColor = RuleEntry.genericColors[Random.Range(0, Match3BoardRenderer.maxNumBoardColors)];
			newTile.UpdateMaterial();
		}
		else if (selectedTile == typeof(DirectionalDestroyTile)) 
		{
			GameObject.Destroy(tile.gameObject);
			
			DirectionalDestroyTile newTile = null;
			if (Random.value > 0.5f) {
				newTile = Match3BoardRenderer.Instance.SpawnSpecificTileAt(targetCoord, typeof(RowDestroyTile), TileColorType.None) as DirectionalDestroyTile;
			}
			else {
				newTile = Match3BoardRenderer.Instance.SpawnSpecificTileAt(targetCoord, typeof(ColumnDestroyTile), TileColorType.None) as DirectionalDestroyTile;
			}
			
			newTile.TileColor = RuleEntry.genericColors[Random.Range(0, Match3BoardRenderer.maxNumBoardColors)];
			newTile.UpdateMaterial();
		}
		else if (selectedTile == typeof(ColorBombTile))
		{
			GameObject.Destroy(tile.gameObject);
			
			ColorBombTile newTile = Match3BoardRenderer.Instance.SpawnSpecificTileAt(targetCoord, selectedTile, TileColorType.None) as ColorBombTile;
		}
	}
Example #21
0
 public Population(AbstractTile home, uint popCapacity)
 {
     numPeople        = 0;
     employed         = 0;
     wealth           = 0f;
     this.home        = home;
     this.popCapacity = popCapacity;
 }
Example #22
0
    void TilePassing(AbstractTile ourTile)
    {
        float dt = logicalTurnLength / length;

        GrassChange(ourTile, dt);
        RabbitChange(ourTile, dt);
        FoxChange(ourTile, dt);
    }
 public void Initialize(SpaceTimeGraph graph, int w)
 {
     _rra     = new RRAStar(graph.Graph, Start, Target);
     _graph   = graph;
     _w       = w;
     Position = Start;
     Path.Add(Start);
 }
Example #24
0
        private static void SpawnBuildings()
        {
            for (int y = 0; y < grid.GetLength(0); y++)
            {
                for (int x = 0; x < grid.GetLength(1); x++)
                {
                    AbstractTile tile = grid[y, x];

                    if (!(tile is AbstractBuildingTile buildingTile))
                    {
                        continue;
                    }

                    TileData tileData = UserSettings.GameData.GridData[new Vector2IntSerializable(x, y)];

                    buildingTile.SetSoilType(tileData.SoilType);
                    buildingTile.SetFoundationType(tileData.FoundationType);
                    buildingTile.SetBuildingType(tileData.BuildingType);

                    if (tileData.HasDebris)
                    {
                        buildingTile.SpawnDebris(tileData.BuildingType, tileData.BuildingTier);
                        continue;
                    }

                    // If there's a building, the tier would be higher than 0
                    if (tileData.BuildingTier > 0)
                    {
                        buildingTile.SpawnBuilding(false);

                        BuildingHealth buildingHealth = buildingTile.Building.GetComponent <BuildingHealth>();

                        buildingHealth.SetCurrentHealth(tileData.SoilHealth, tileData.FoundationHealth, tileData.BuildingHealth);
                    }
                    else
                    {
                        if (tileData.HasSoil)
                        {
                            buildingTile.SpawnSoil();

                            if (tileData.HasFoundation)
                            {
                                buildingTile.SpawnFoundation();
                            }
                        }

                        continue;
                    }

                    BuildingUpgrade buildingUpgrade = buildingTile.Building.GetComponent <BuildingUpgrade>();

                    while (buildingTile.Building.CurrentTier != tileData.BuildingTier)
                    {
                        buildingUpgrade.Upgrade();
                    }
                }
            }
        }
Example #25
0
        protected override void AddRiverNeighbor(AbstractTile tile)
        {
            base.AddRiverNeighbor(tile);

            if (RiverNeighbors.Count == 2)             // Corners should only have 2 tiles connected to it
            {
                TileRotateUtil.RotateCorner(this, ending1, ending2, RiverNeighbors.Select(roadTile => roadTile as AbstractTile));
            }
        }
        public override void AddNeighbor(AbstractTile tile)
        {
            base.AddNeighbor(tile);

            if (tile is IRoadTile)
            {
                AddRoadNeighbor(tile);
            }
        }
        public override void AddNeighbor(AbstractTile tile)
        {
            base.AddNeighbor(tile);

            if (tile is IWaterTile)
            {
                AddRiverNeighbor(tile);
            }
        }
        protected override void AddRoadNeighbor(AbstractTile tile)
        {
            base.AddRoadNeighbor(tile);

            if (RoadNeighbors.Count == 3)             // TIntersections should only have 3 roads connected to it
            {
                TileRotateUtil.RotateTIntersection(this, perpendicular, RoadNeighbors.Select(roadTile => roadTile as AbstractTile));
            }
        }
Example #29
0
    public void CreateBaseTileAtPos(AbstractTile t, TileManager manager)
    {
        GameObject obj = Instantiate(baseTilePrefab, transform);

        obj.transform.position = t.transform.position;
        manager.tileArray[t.TilePosition.x, t.TilePosition.y] = obj.GetComponent <AbstractTile>();
        manager.BaseTileList.Add(obj.GetComponent <BaseTile>());
        obj.GetComponent <AbstractTile>().TilePosition = t.TilePosition;
    }
Example #30
0
    public override void RaiseEventTileSwitchAnimEnded(AbstractTile neighborTile)
    {
        base.RaiseEventTileSwitchAnimEnded(neighborTile);

        if (!IsMatched)
        {
            movedByInput = false;
        }
    }
Example #31
0
 /*
  * used by the tile to assign itself to this player, also checks if the player
  * won the game
  */
 public void addLandToOwned(AbstractTile boughtTile)
 {
     OwnedLands.Add(boughtTile);
     fillTileItem(boughtTile);
     if (playerHasWon())
     {
         print("Player won:" + (playerIndex + 1));
     }
 }
	protected void OnTileDestroyedAction(AbstractBoardPiece sender, AbstractTile destroyedTile) {
		
		//Early out for those scenarios in witch you would not want to pop a frost tile
		if (destroyedTile is  LockedTile || destroyedTile is SnowTile || destroyedTile is FreezerTile)
		{
			return;
		}
		
		NumLayers--;
	}
	protected void OnTileChanged(AbstractBoardPiece sender, AbstractTile tile)
	{
		if(tile is DropTile)
		{
			DropTile dropTile = tile as DropTile;
			
			if(!dropTile.isSwitching && !dropTile.isDropping)
			{
				StartCoroutine(dropTile.Drop());
			}
		}
	}
Example #34
0
	public void OnNeighborDestroy(AbstractBoardPiece sender, AbstractTile neighbor)
	{	
		if(neighbor && (neighbor as NormalTile).IsMatched)
		{
			Destroy ();
			FreezerController.Instance.freezerDestroyedThisTurn = true;
			FreezerController.Instance.allFreezers.Remove(this);
			
			//Tile release
			//BoardPiece.Tile = null;
		}
	}
	protected void RaiseEventTilesSwitchAnimFinished(bool canRaiseGlobalSwitchEvent, AbstractBoardAnimations sender, AbstractTile src, AbstractTile dst) {
		// These 2 tiles aren't animating anymore.
		src.IsMoving = false;
		dst.IsMoving = false;
		
		(src as Match3Tile).GravityEnabled = true;
		(dst as Match3Tile).GravityEnabled = true;
		
		if (canRaiseGlobalSwitchEvent && onTilesSwitchAnimFinished != null) {
			onTilesSwitchAnimFinished(sender, src, dst);
		}
	}
Example #36
0
	void OnTileSelected(AbstractTile tile)
	{
		if (!tile.IsMoving && tile.IsDestructible && !tile.IsDestroying && tile.IsUserMoveable && !(tile as NormalTile).IsFrozen()) 
		{
			Match3Tile.OnTileTap -= OnTileSelected;
			tileToDestroy = tile as NormalTile;
			
			effectPosition = tile.cachedTransform;
			
			ActuallyUsingItem();
			DoItem();
		}
	}
	public abstract bool TryToMoveTile(AbstractTile tile, TileMoveDirection moveDirection);
	public abstract bool TryToMoveTile(AbstractTile srcTile, AbstractTile dstTile);
Example #39
0
	public void TileMoved(AbstractBoardAnimations sender, AbstractTile srcTile, AbstractTile dstTile) 
	{
		StartTimer();
	}
	public override void TileMoving(AbstractTile targetTile) {
		
	}
	public override void EndMoveTile(AbstractTile targetTile) {
		
	}
Example #42
0
	public void SwitchTiles(AbstractTile src, AbstractTile dst) {
		AbstractBoardPiece dstBoardPiece = dst.BoardPiece;

		src.BoardPiece.Tile = dst;
		dstBoardPiece.Tile = src;
	}
Example #43
0
	public override void RaiseEventTileSwitchAnimEnded (AbstractTile neighbourTile) {
		base.RaiseEventTileSwitchAnimEnded (neighbourTile);
		
		if (neighbourTile is BombTile) {
			// Destroy and trigger neighbor tile.
			neighbourTile.Destroy();
		}
	}
	/// <summary>
	/// Determines whether this tile instance is a valid target for colorBombInteraction
	/// </summary>
	/// <returns>
	/// <c>true</c> if this instance is valid target; otherwise, <c>false</c>.
	/// </returns>
	public bool IsValidTarget(AbstractTile tile, TileColorType destroyColor)
	{ 
		NormalTile target = tile as NormalTile;
		
//		if (target != null &&
//			target.IsDestructible &&
//			target.TileColor == destroyColor)
//		{
//			return true;
//		}
//		return false;
//		
		return target != null &&
			   target.IsDestructible &&
			   target.TileColor == destroyColor &&
			   !target.IsDestroying &&	
			   !(target is SnowTile) &&
			   !target.IsFrozen();
	}
Example #45
0
	public override void RaiseEventTileSwitchAnimEnded (AbstractTile neighborTile)
	{
		base.RaiseEventTileSwitchAnimEnded (neighborTile);
		
		if ( !IsMatched ) {
			movedByInput = false;
		}
	}
	public void OnTilesSwitchAnimFinished(AbstractBoardAnimations sender, AbstractTile srcTile, AbstractTile dstTile) {
//		Debug.Log("Switch anim finished!");
		// Update the board positions of the animated tiles (update the board logic after the animation finishes).
		boardData.SwitchTiles(srcTile, dstTile);

		Match3Tile srcMatch3Tile = srcTile as Match3Tile;
		Match3Tile dstMatch3Tile = dstTile as Match3Tile;
		
		bool foundMatches = matchesFinder.FindMatches();
		
		if (( !foundMatches || (!srcMatch3Tile.IsMatched && !dstMatch3Tile.IsMatched) ) &&
			(srcMatch3Tile.SwitchBackOnMatchFail && dstMatch3Tile.SwitchBackOnMatchFail)) 
		{
			if (OnUserTilesSwitchBad != null) {
				OnUserTilesSwitchBad(srcMatch3Tile, dstMatch3Tile);
			}

			srcMatch3Tile.IsTileSwitching = true;
			dstMatch3Tile.IsTileSwitching = true;

			BoardAnimations.SwitchTilesAnim(false, srcMatch3Tile, dstMatch3Tile,
				(_sender, _srcTile, _dstTile) => 
				{
					boardData.SwitchTiles(_srcTile, _dstTile);
					_srcTile.IsTileSwitching = false;
					_dstTile.IsTileSwitching = false;
				}
			);
			
			srcMatch3Tile.RaiseEventSwitchBackOnFail(dstMatch3Tile);
			dstMatch3Tile.RaiseEventSwitchBackOnFail(srcMatch3Tile);
		} 
		else if (srcMatch3Tile.IsMatched || dstMatch3Tile.IsMatched) {
			srcMatch3Tile.IsTileSwitching = false;
			dstMatch3Tile.IsTileSwitching = false;
			
			loseConditions.NewMove();
			
			srcMatch3Tile.RaiseEventSwitchSuccess(dstMatch3Tile);
			dstMatch3Tile.RaiseEventSwitchSuccess(srcMatch3Tile);
		}
		else if (!srcMatch3Tile.SwitchBackOnMatchFail || !dstMatch3Tile.SwitchBackOnMatchFail) { 
			// Reset the "IsTileSwitching" property for tiles that don't switch back on match fail because they finished their switch animation.
			srcMatch3Tile.IsTileSwitching = false;
			dstMatch3Tile.IsTileSwitching = false;
		}
				
		DestroyLastFoundMatches();
	}	
	protected void OnBoardPieceTileChanged(AbstractBoardPiece sender, AbstractTile newTile) {
		
		if ((sender as Match3BoardPiece).IsBlocked)
		{
			StartCoroutine(RaiseTileSpawnEventNextFrame(sender, newTile));
			return;
		}
		
		// Check if the new tile of the board piece is null.
		if (newTile != null) {
			return;
		}
		
		if (OnTileSpawnerPieceEmpty != null) {
			OnTileSpawnerPieceEmpty(this);
		}
	
//			Debug.Log(name + " => at frame: " + Time.frameCount);
		// Execute the next spawn rule from the list.
		
		if( immediateSpawnList.Count > 0 &&
		    Match3BoardRenderer.minDelayForceSpawnRules + lastImmediateRuleSpawnTime < Time.time)
		{
//				Debug.LogError("ImediateSpawnList has " + immediateSpawnList.Count + " items!");
			for(int i = 0; i < immediateSpawnList.Count; i++)
			{
//					Debug.LogError("Checking for [i] = " + i);
				for(int j = 0; j < boardPiece.eligibleSpawnList.Count; j++)
				{
//						Debug.LogError("Checking for [i][j]" + i + " " + j);
					if ( immediateSpawnList[i].ruleEntries[0].Equals(boardPiece.eligibleSpawnList[j]) )
					{
						SpawnImmediateRule(i);
						return;
					}
				}
			}
		}
//			
		if (tileSpawnRules.Count > 0) 
		{
//			tileSpawnRules[currentSpawnRuleIdx++].SpawnNewTile();
			SpawnNewTileInQueue(tileSpawnRules[currentSpawnRuleIdx++]);
			if (currentSpawnRuleIdx >= tileSpawnRules.Count) {
				currentSpawnRuleIdx = 0;
			}
		}
	}
	protected IEnumerator RaiseTileSpawnEventNextFrame(AbstractBoardPiece sender, AbstractTile newtile)
	{
		yield return null;
		
		OnBoardPieceTileChanged(sender, newtile);
	}
	public virtual void TileMoving(AbstractTile tile) { }
	public virtual void EndMoveTile(AbstractTile tile) { }
	/// <summary>
	/// Raises the tap gesture event. This event is raised by FingerGestures's TapRecognizer component.
	/// </summary>
	/// <param name='eventData'>
	/// Event data.
	/// </param>
	public void OnTapGesture(TapGesture eventData) {
		if (dragLock > 0) {
			tapSelectedTile = null;
		}
		
		// Process tap gesture only if the start selection is a board tile.
		if (eventData.StartSelection != null && eventData.StartSelection.layer == Match3Globals.Instance.layerBoardTile) 
		{
			// Check if there is no previously selected tile.
			if (tapSelectedTile == null) 
			{
//				Debug.Log("TapGesture selection started: " + eventData.StartSelection);
				tapSelectedTile = eventData.StartSelection.GetComponent<AbstractTile>();
//				Debug.Log("Tile tapped: " + tapSelectedTile);
				tapSelectedTile.RaiseEventTileTap();
			} 
			else 
			{
//				Debug.Log("TapGesture selected ended: " + eventData.StartSelection);
				AbstractTile newSelectedTile = eventData.StartSelection.GetComponent<AbstractTile>();
				
				// Tell the Match3BoardGameLogic to try and switch the first selected tile with this new selected tile.
				if ((InputFilter == null || InputFilter(tapSelectedTile, newSelectedTile, TileMoveDirection.Count)) && boardGameLogic.TryToMoveTile(tapSelectedTile, newSelectedTile) == false) 
				{
					// If the tiles couldn't be switched then make the new selected tile as the first selected tile.
					tapSelectedTile = newSelectedTile;
					newSelectedTile.RaiseEventTileTap();
				} 
				else 
				{
					// If the tiles were succesfully switched (not necessarilly matched) then reset the first selected tile.
					tapSelectedTile = null;
					//boardGameLogic.loseConditions.NewMove();
				}
			}
		}
	}
Example #52
0
	/// <summary>
	/// Raises the tile switch animation ended event after this tile finishes the switch animation with another neighbour tile.
	/// This event should be raised by the <see cref="Match3BoardGameLogic"/>.
	/// </summary>
	/// <param name='neighborTile'>
	/// Neighbour tile with which this tile did the switch.
	/// </param>
	public virtual void RaiseEventTileSwitchAnimEnded(AbstractTile neighborTile) {
		if (!IsMatched) {
			tappedFirst = false;
		}

		if (onTileSwitchAnimEnded != null) {
			onTileSwitchAnimEnded(neighborTile);
		}
	}
	public void OnTileMovingChanged(AbstractTile tile)
	{
		if (!tile.IsMoving) {
			TryCheckStableBoard();
		}
	}
Example #54
0
	public override void RaiseEventTileSwitchAnimEnded (AbstractTile neighborTile)
	{
		base.RaiseEventTileSwitchAnimEnded (neighborTile);
		isSwitching = false;
	}
	public override void RaiseEventTileSwitchAnimEnded (AbstractTile neighborTile) {
		
		// Check if this directional tile was combined with a BombTile.
		
		// isCombineWithBombEffect flag check was added to remove some unwanted behaviors where (2x bomb/directional effects would spawn)
		// TODO: Investigate further into why this is happening.
		
		if (neighborTile is BombTile && !isCombineWithBombEffect)
		{
			Match3BoardGameLogic.Instance.loseConditions.NewMove();
	
			StartCoroutine(StartCombineWithBombEffect(neighborTile as BombTile));
		}
		
		// Setup directional with directional tile combine effect.
		if (neighborTile is DirectionalDestroyTile && TappedFirst)
		{
			Match3BoardGameLogic.Instance.loseConditions.NewMove();	
			
			IsDestroying = true;
			neighborTile.IsDestroying = true;
			
			Match3Tile crossTile = match3BoardRenderer.SpawnSpecificTileAt( BoardPiece.BoardPosition.row,
													                        BoardPiece.BoardPosition.col,
																			typeof(CrossDestroyTile),
																			TileColorType.None
																  		  );
			crossTile.TileColor = TileColor;
			crossTile.DisableTileLogic();
			(crossTile as DirectionalDestroyTile).UpdateMaterial();
			
			if(neighborTile.BoardPiece.Tile == neighborTile)
			{
				neighborTile.BoardPiece.Tile = null;
			}
			
			Destroy(neighborTile.gameObject);
			Destroy(gameObject);
		}
		
		if (neighborTile is ColorBombTile && TappedFirst)
		{
			Match3BoardGameLogic.Instance.loseConditions.NewMove();	
		}
		
		// In the base classes "movedByInput" and "tappedFirst" flags are reset so we call the base at the end of the overriden code.
		base.RaiseEventTileSwitchAnimEnded(neighborTile);
	}
	public override bool TryToMoveTile(AbstractTile srcTile, AbstractTile dstTile) 
	{
		if (srcTile == dstTile || srcTile == null || dstTile == null) {
			return false;
		}

		if ( CanMoveTile(srcTile, dstTile.BoardPiece) )
		{
			Match3Tile srcMatch3Tile = srcTile as Match3Tile;
			Match3Tile dstMatch3Tile = dstTile as Match3Tile;
				
			if (OnUserStartedTilesSwitch != null) {
				OnUserStartedTilesSwitch(srcMatch3Tile, dstMatch3Tile);
			}

			srcMatch3Tile.RaiseEventTileTappedFirst();
			
			srcMatch3Tile.IsTileSwitching = true;
			dstMatch3Tile.IsTileSwitching = true;
			BoardAnimations.SwitchTilesAnim(true, srcMatch3Tile, dstMatch3Tile);
			
			return true;
		}
		
		return false;
	}
	public virtual bool CanMoveTile(AbstractTile tile, AbstractBoardPiece targetBoardPiece) 
	{
		// In case we're trying to do a switch with the same tile. (failed input or reached board margin)
		if (tile.BoardPiece == targetBoardPiece) {
//			Debug.LogWarning("[Match3BoardGameLogic] Trying to move tile " + tile.name + " in the same board piece as the tile: " + targetBoardPiece);
			return false;
		}
		
		// Safety-check in case we might try to move a tile to a board piece which has no tile on it to switch with. 
		// In case we will want this mechanic later in the game we will let the tile decide if it can move to an empty board piece or not.
		if (targetBoardPiece.Tile == null) {
//			Debug.LogError("[Match3BoardGameLogic] In method CanMoveTile: " + tile.name + " error: targetBoardPiece doesn't have any tile to switch with!");
			return false;
		}
				
		// Check if tiles can switch positions.
		return tile.CanMoveAt(targetBoardPiece) && targetBoardPiece.Tile.CanMoveAt(tile.BoardPiece);
	}
	/// <summary>
	/// Raises the drag gesture event. This event is raised by FingerGestures's DragRecognizer component.
	/// Determine the selected tile and in which direction the user dragged it and tell the <see cref="Match3BoardGameLogic"/>
	/// that we've started moving that tile in that direction.
	/// </summary>
	/// <param name='eventData'>
	/// Event data.
	/// </param>
	public void OnDragGesture(DragGesture eventData) {		
		if (dragLock > 0) {
			tapSelectedTile = null;
			return;
		}
		
		// Check if we've selected any tile.
		if (eventData.StartSelection != null && eventData.StartSelection.layer == Match3Globals.Instance.layerBoardTile) {
			if (eventData.Phase == ContinuousGesturePhase.Started) {
				// Cancel the tap selected tile if we've done a drag gesture.
				tapSelectedTile = null;
				
				AbstractTile dragSelectedTile = eventData.StartSelection.GetComponent<AbstractTile>();
				TileMoveDirection moveDirection = Match3BoardGameLogic.GetTileMoveDirection(eventData.TotalMove);
				
				if (InputFilter == null || InputFilter(dragSelectedTile, null, moveDirection)) {
//					Debug.Log("Drag event started! Start Selection: " + eventData.StartSelection + " -> totalMove = " + eventData.TotalMove);
					if (boardGameLogic.TryToMoveTile(dragSelectedTile, moveDirection)) {
						//boardGameLogic.loseConditions.NewMove();
					}
				}
			}
		}
	}
	public override bool TryToMoveTile(AbstractTile tile, TileMoveDirection moveDirection) 
	{
		//TODO: ask tile to determine if it can move to given position => trigger tile move anim => register to anim finish event => 
		// notify back the gameboard logic to check for matches => 
		// if no match -> switch back (if tile allows it) 
		// if found matches => validate match pattern -> spawn new tiles, new effects, trigger other tiles, etc -> mark for destroy matched tiles
		// -> update board state (check all tiles that should be falling and set them to fall and let them update their positions until they stop)

		BoardCoord offsetDir = tilesMoveDirections[(int)moveDirection];
		BoardCoord targetBoardPos = tile.BoardPiece.BoardPosition;

		// Offset the target board position by the tile movement direction offset and clamp the result to the border of the board.
		targetBoardPos.OffsetByAndClamp(tilesMoveDirections[(int)moveDirection], boardData.NumRows - 1, boardData.NumColumns - 1);
		
//		Debug.Log("[Match3BoardGameLogic] BeginMoveTile " + tile.name + " -> from: " + tile.BoardPiece.BoardPosition + 
//			" to " + (tile.BoardPiece.BoardPosition.row + offsetDir.row)  + ", " + (tile.BoardPiece.BoardPosition.col + offsetDir.col));
		
		return TryToMoveTile(tile, boardData[targetBoardPos].Tile);
	}