Ejemplo n.º 1
0
    void Update()
    {
        if (m_tower != null)
        {
            RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, 10, m_placeable);
            if (hit.collider != null)
            {
                if (hit.collider.gameObject.GetComponent <TilePiece>().Occupied == false)
                {
                    m_currentTile = hit.collider.gameObject.GetComponent <TilePiece>();
                    if (m_priorTile == m_currentTile)
                    {
                    }
                    else
                    {
                        //selection highlighting code
                        if (m_priorTile == null)
                        {
                            m_priorTile = m_currentTile;
                        }
                        Renderer temp = hit.transform.gameObject.GetComponent <Renderer>();
                        m_actualColor = temp.material.color;
                        m_priorTile.gameObject.GetComponent <Renderer>().material.color = m_actualColor;
                        m_priorTile         = m_currentTile;
                        m_currTileColor     = Color.Lerp(m_actualColor, Color.green, 0.5f);
                        temp.material.color = m_currTileColor;
                        //Debug.Log("Target Position: " + hit.collider.gameObject.transform.position);
                    }


                    //Tower Placement Code
                    if (Input.GetMouseButtonDown(0))
                    {
                        Vector3    pos = hit.collider.transform.position;
                        GameObject tow = Instantiate(m_tower, pos, Quaternion.identity);

                        hit.collider.gameObject.GetComponent <TilePiece>().Tower          = tow;
                        m_currentTile.gameObject.GetComponent <Renderer>().material.color = m_actualColor;
                    }
                }
            }
        }
    }
Ejemplo n.º 2
0
        public MapEditor()
        {
            InitializeComponent();

            tileImages.Add(TilePiece.Grass, Properties.Resources.grass);
            tileImages.Add(TilePiece.TopLeft, Properties.Resources.tl);
            tileImages.Add(TilePiece.TopRight, Properties.Resources.tr);
            tileImages.Add(TilePiece.BottomLeft, Properties.Resources.bl);
            tileImages.Add(TilePiece.BottomRight, Properties.Resources.br);
            tileImages.Add(TilePiece.Horizontal, Properties.Resources.h);
            tileImages.Add(TilePiece.Vertical, Properties.Resources.v);
            tileImages.Add(TilePiece.Start, Properties.Resources.tl);

            car = Properties.Resources.car;

            foreach (TilePiece piece in tileImages.Keys)
            {
                Button button = new Button();
                button.Tag        = piece;
                button.Image      = tileImages[piece];
                button.ImageAlign = ContentAlignment.MiddleCenter;
                button.Size       = new Size(80, 80);
                button.Click     += new EventHandler(button_Click);

                flowLayoutPanel1.Controls.Add(button);
            }

            for (int y = 0; y < mapData.Length; y++)
            {
                mapData[y] = new TilePiece[10];
                for (int x = 0; x < mapData[0].Length; x++)
                {
                    mapData[y][x] = TilePiece.Grass;
                }
            }

            pictureBox1.MouseMove  += new MouseEventHandler(pictureBox1_MouseMove);
            pictureBox1.MouseClick += new MouseEventHandler(pictureBox1_MouseClick);
            pictureBox1.MouseLeave += new EventHandler(pictureBox1_MouseLeave);

            _selectedPiece = TilePiece.Start;
        }
Ejemplo n.º 3
0
        public MapEditor()
        {
            InitializeComponent();

            tileImages.Add(TilePiece.Grass, Properties.Resources.grass);
            tileImages.Add(TilePiece.TopLeft, Properties.Resources.tl);
            tileImages.Add(TilePiece.TopRight, Properties.Resources.tr);
            tileImages.Add(TilePiece.BottomLeft, Properties.Resources.bl);
            tileImages.Add(TilePiece.BottomRight, Properties.Resources.br);
            tileImages.Add(TilePiece.Horizontal, Properties.Resources.h);
            tileImages.Add(TilePiece.Vertical, Properties.Resources.v);
            tileImages.Add(TilePiece.Start, Properties.Resources.tl);

            car = Properties.Resources.car;

            foreach (TilePiece piece in tileImages.Keys)
            {
                Button button = new Button();
                button.Tag = piece;
                button.Image = tileImages[piece];
                button.ImageAlign = ContentAlignment.MiddleCenter;
                button.Size = new Size(80, 80);
                button.Click += new EventHandler(button_Click);

                flowLayoutPanel1.Controls.Add(button);
            }

            for (int y = 0; y < mapData.Length; y++)
            {
                mapData[y] = new TilePiece[10];
                for (int x = 0; x < mapData[0].Length; x++)
                {
                    mapData[y][x] = TilePiece.Grass;
                }
            }

            pictureBox1.MouseMove += new MouseEventHandler(pictureBox1_MouseMove);
            pictureBox1.MouseClick += new MouseEventHandler(pictureBox1_MouseClick);
            pictureBox1.MouseLeave += new EventHandler(pictureBox1_MouseLeave);

            _selectedPiece = TilePiece.Start;
        }
Ejemplo n.º 4
0
    public IEnumerator BuscaProfundidade(TilePiece curr, TilePiece end)
    {
        curr.visitado = true;

        if (curr == end)
        {
            encontrou = true;
        }

        yield return(new WaitForSeconds(0.01f));

        foreach (TilePiece v in curr.vizinhos)
        {
            if (v.visitado == false && !encontrou)
            {
                visitados += 1;
                yield return(StartCoroutine(BuscaProfundidade(v, end)));
            }
        }
    }
Ejemplo n.º 5
0
 void InstantiateBoard()
 {
     for (int x = 0; x < width; x++)
     {
         for (int y = 0; y < height; y++)
         {
             Tile tile = getTile(new TileCoord(x, y));
             int  type = tile.type;
             if (type <= 0)
             {
                 continue;
             }
             GameObject    gameTile = Instantiate(tilePiece, gameBoard);
             TilePiece     piece    = gameTile.GetComponent <TilePiece>();
             RectTransform rect     = gameTile.GetComponent <RectTransform>();
             rect.anchoredPosition = new Vector2(60 + (120 * x), -60 - (120 * (y - 7)));
             piece.Initialize(type, new TileCoord(x, y), tiles[type - 1]);
             tile.SetPiece(piece);
             ResetPiece(piece);
         }
     }
 }
Ejemplo n.º 6
0
 private void SelectTilePiece(TilePiece hitPiece)
 {
     if (firstHitTile == null)
     {
         firstHitTile = hitPiece;
         effects.PlaceTileHighlight(hitPiece.transform.position);
     }
     else
     {
         if (firstHitTile == hitPiece)
         {
             return;
         }
         Vector3[] pathway;
         if (firstHitTile != hitPiece && firstHitTile.pieceValue == hitPiece.pieceValue &&
             tileBoard.CanCoordinatesConnect(firstHitTile.tilePosition.coordinates, hitPiece.tilePosition.coordinates, out pathway))
         {
             tileBoard.RemoveTilePiece(firstHitTile);
             tileBoard.RemoveTilePiece(hitPiece);
             score         += 2;
             timeRemaining += 2;
             effects.ClearTileHighlights();
             effects.PlaceLine(pathway, true);
             effects.PlayExplosion(pathway[0]);
             effects.PlayExplosion(pathway[pathway.Length - 1]);
             if (tileBoard.tilesOnBoard == 0)
             {
                 SetGameState(GameState.GameOver);
             }
         }
         else
         {
             effects.ClearTileHighlights();
         }
         firstHitTile = null;
     }
 }
Ejemplo n.º 7
0
    private void AttemptToClick()
    {
        RaycastHit hit;
        var        ray = gameCamera.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit))
        {
            TilePiece hitPiece = hit.collider.gameObject.GetComponent <TilePiece>();
            if (hitPiece != null)
            {
                SelectTilePiece(hitPiece);
            }
            else
            {
                firstHitTile = null;
                effects.ClearTileHighlights();
            }
        }
        else
        {
            firstHitTile = null;
            effects.ClearTileHighlights();
        }
    }
Ejemplo n.º 8
0
    private bool CheckSpaceAbove()
    {
        Vector2Int gridPosAbove = new Vector2Int(CurrentGridPos.x, CurrentGridPos.y + 1);

        TilePiece blockingPiece = gameGrid.GetPieceAt(gridPosAbove);

        // All clear! Do nothing
        if (blockingPiece == null || blockingPiece.Type == PieceType.NULL)
        {
            return(true);
        }

        switch (blockingPiece.Type)
        {
        case PieceType.STATIC:
            Type = PieceType.STATIC;
            TopSpawnerManager.Instance.AddMovingPiece(this);
            GetComponent <PieceHealth>().HandlePieceAttached();

            break;
        }

        return(false);
    }
Ejemplo n.º 9
0
        public static bool CheckCollidable(Sprite a, Sprite b)
        {
            if (a.inInteriorId != Guid.Empty)
            {
                if (b.inInteriorId == Guid.Empty)
                {
                    return(false);
                }

                if (b.inInteriorId != a.inInteriorId)
                {
                    return(false);
                }
            }

            if (a is IShip)
            {
                Ship ship = (Ship)a;
                // a ship doesn't collide with its any ship's sails
                if (b.GetType().BaseType == typeof(Gusto.Models.Animated.Sail))
                {
                    return(false);
                }

                if (b is ILand)
                {
                    TilePiece t = (TilePiece)b;
                    if (!(t.shorePiece))
                    {
                        return(false);
                    }
                }

                // ship doesn't collide with interior tiles
                if (b is IInteriorTile)
                {
                    return(false);
                }

                // ship doesn't collide with its own cannon balls
                if (b.GetType().BaseType == typeof(Gusto.Models.Animated.Ammo))
                {
                    Ammo ball = (Ammo)b;
                    if (ball.teamType == ship.teamType)
                    {
                        return(false);
                    }
                }
            }

            else if (a is IPlayer)
            {
                PlayerPirate pirate = (PlayerPirate)a;
                // a player doesn't collide with its own shots
                if (b is IAmmo)
                {
                    Ammo ball = (Ammo)b;
                    if (ball.teamType == pirate.teamType)
                    {
                        return(false);
                    }
                }
                else if (b.GetType().BaseType == typeof(Gusto.Models.Animated.Tree))
                {
                    return(false);
                }
            }

            else if (a.GetType().BaseType == typeof(Gusto.Models.Animated.Tower))
            {
                BaseTower tower = (BaseTower)a;
                // a tower doesn't collide with its own shots
                if (b is IAmmo)
                {
                    Ammo ball = (Ammo)b;
                    if (ball.teamType == tower.teamType)
                    {
                        return(false);
                    }
                }
            }

            // hand items only collide when they are being used
            else if (a is IHandHeld)
            {
                HandHeld inHand = (HandHeld)a;
                if (!inHand.usingItem && !inHand.onGround)
                {
                    return(false);
                }
            }

            else if (a is IAmmo)
            {
                if (b.GetType().BaseType == typeof(Gusto.Models.TilePiece))
                {
                    return(false);
                }
                if (b.GetType().BaseType == typeof(Gusto.Models.Animated.Grass))
                {
                    return(false);
                }
            }

            else if (a is IGroundObject)
            {
                if (b is IGroundObject)
                {
                    return(false);
                }
                if (b.GetType().BaseType == typeof(Gusto.Models.TilePiece))
                {
                    return(false);
                }
                if (b is IShip)
                {
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 10
0
    private void SpawnRow()
    {
        if (levelsQueue.Count > 0)
        {
            if (clearCount >= levelsQueue.Peek().AppearAtLevel)
            {
                currentLevel = levelsQueue.Dequeue();
            }
        }

        int[] gapChoices = currentLevel.gapsPerRowList;
        int   gapsPerRow = gapChoices[Random.Range(0, gapChoices.Length)];

        List <int> emptySpots = new List <int>();

        int maxIndex = spawnWidth - gapSideBuffer;

        for (int index = gapSideBuffer; index < maxIndex; index++)
        {
            emptySpots.Add(index);
        }

        for (int count = maxIndex - 1; count > gapsPerRow; count--)
        {
            int randomIndex = Random.Range(0, emptySpots.Count);
            emptySpots.RemoveAt(randomIndex);
        }

        for (int x = 0; x < spawnWidth; x++)
        {
            bool skip = false;

            foreach (int emptySpot in emptySpots)
            {
                if (emptySpot == x)
                {
                    skip = true;
                    break;
                }
            }

            if (skip)
            {
                continue;
            }

            Vector2Int spawnPos = new Vector2Int(x, spawnHeight);

            if (gameGrid.IsTileEmpty(spawnPos))
            {
                TilePiece newPiece = Instantiate(piecePrefab);
                newPiece.Type = PieceType.STATIC;

                gameGrid.AddPieceAt(spawnPos, newPiece, out bool addWasSuccessful);

                pieces.Add(newPiece);
            }
        }

        UpdateFreeHeight();
    }
Ejemplo n.º 11
0
        public void SetGameMap(ContentManager content, GraphicsDevice graphics, SpriteBatch sb, JObject mapData)
        {
            _content  = content;
            _graphics = graphics;

            oceanWater = new OceanWater(_content, _graphics);
            // set water render target
            waterScene = new RenderTarget2D(_graphics, GameOptions.PrefferedBackBufferWidth, GameOptions.PrefferedBackBufferHeight);

            /*_graphics.SetRenderTarget(waterScene);
             * _graphics.Clear(Color.CornflowerBlue);
             * int vpCols = GameOptions.PrefferedBackBufferWidth / GameOptions.tileWidth;
             * int vpRows = GameOptions.PrefferedBackBufferHeight / GameOptions.tileHeight;
             * sb.Begin(_cam, SpriteSortMode.Texture);
             * Vector2 pos = new Vector2(0, 0);
             * for (int i = 0; i < vpRows; i++)
             * {
             *  for (int j = 0; j < vpCols; j++)
             *  {
             *      TilePiece tile = new OceanTile(0, null, null, pos, "GustoGame", content, graphics, "o1");
             *      tile.transparency = 0.6f;
             *      tile.SetTileDesignRow(RandomEvents.rand.Next(0, tile.nRows));
             *      tile.DrawTile(sb, false);
             *      pos.X += GameOptions.tileWidth;
             *  }
             *  pos.Y += GameOptions.tileWidth;
             * }
             * sb.End();
             * _graphics.SetRenderTarget(null);*/

            var worldLoc = startMapPoint;
            int index    = 0;

            for (int i = 0; i < _rows; i++)
            {
                for (int j = 0; j < _cols; j++)
                {
                    TilePiece     tile          = null;
                    List <Sprite> groundObjects = null;
                    JObject       tileDetails   = mapData[index.ToString()].Value <JObject>();

                    // region
                    string regionName = (string)tileDetails["regionName"];
                    if (!BoundingBoxLocations.RegionMap.ContainsKey(regionName))
                    {
                        BoundingBoxLocations.RegionMap[regionName] = new Region(regionName);
                    }

                    // ground object
                    if ((string)tileDetails["sittingObject"] != "null")
                    {
                        groundObjects = GetGroundObjects((string)tileDetails["sittingObject"], regionName, worldLoc, content, graphics);

                        foreach (var groundObject in groundObjects)
                        {
                            groundObject.SetTileDesignRow(RandomEvents.rand.Next(0, groundObject.nRows));
                            groundObject.location.X += RandomEvents.rand.Next(-tileWidth, tileWidth);
                            groundObject.location.Y += RandomEvents.rand.Next(-tileHeight, tileHeight);
                        }
                    }

                    // set terrain piece
                    switch (tileDetails["terrainPiece"].ToString())
                    {
                    case "o1":
                        tile = new OceanTile(index, new Point(i, j), groundObjects, worldLoc, regionName, content, graphics, "o1");
                        tile.transparency = 0.6f;
                        tile.SetTileDesignRow(RandomEvents.rand.Next(0, tile.nRows));
                        AIUtility.OceanPathWeights[i, j] = 1;
                        AIUtility.LandPathWeights[i, j]  = 0;
                        AIUtility.AllPathWeights[i, j]   = 1;
                        BoundingBoxLocations.RegionMap[regionName].RegionOceanTiles.Add(tile);
                        break;

                    case "o2":
                        tile = new OceanTile(index, new Point(i, j), groundObjects, worldLoc, regionName, content, graphics, "o2");
                        tile.transparency = 0.7f;
                        AIUtility.OceanPathWeights[i, j] = 0;
                        AIUtility.LandPathWeights[i, j]  = 1;
                        AIUtility.AllPathWeights[i, j]   = 1;
                        //BoundingBoxLocations.RegionMap[regionName].RegionOceanTiles.Add(tile); omit these since they cause no path found in A*
                        break;

                    case "oD":
                        tile = new OceanTile(index, new Point(i, j), groundObjects, worldLoc, regionName, content, graphics, "oD");
                        tile.transparency = 0.7f;
                        AIUtility.OceanPathWeights[i, j] = 0;
                        AIUtility.LandPathWeights[i, j]  = 1;
                        AIUtility.AllPathWeights[i, j]   = 1;
                        //BoundingBoxLocations.RegionMap[regionName].RegionOceanTiles.Add(tile); omit these since they cause no path found in A*
                        break;

                    case "l1":
                        tile = new LandTile(index, new Point(i, j), groundObjects, worldLoc, regionName, content, graphics, "l1");
                        AIUtility.OceanPathWeights[i, j] = 0;
                        AIUtility.LandPathWeights[i, j]  = 1;
                        AIUtility.AllPathWeights[i, j]   = 1;
                        BoundingBoxLocations.RegionMap[regionName].RegionLandTiles.Add(tile);
                        break;

                    case "l2":
                        tile = new LandTile(index, new Point(i, j), groundObjects, worldLoc, regionName, content, graphics, "l2");
                        AIUtility.OceanPathWeights[i, j] = 0;
                        AIUtility.LandPathWeights[i, j]  = 1;
                        AIUtility.AllPathWeights[i, j]   = 1;
                        BoundingBoxLocations.RegionMap[regionName].RegionLandTiles.Add(tile);
                        break;
                    }

                    worldLoc.X += tileWidth;
                    GameMapTiles.map.Add(tile);
                    index++;
                }
                worldLoc.Y += tileHeight;
                worldLoc.X  = startMapPoint.X;
            }

            // Go through again to set all columns to correct frame for land tiles
            int index2 = 0;

            foreach (var tile in GameMapTiles.map)
            {
                if (tile is ILand)
                {
                    // inner land
                    if (GameMapTiles.map[index2 + 1] is ILand && GameMapTiles.map[index2 - 1] is ILand && GameMapTiles.map[index2 + _cols] is ILand && GameMapTiles.map[index2 - _cols] is ILand)
                    {
                        tile.shorePiece   = false;
                        tile.currRowFrame = 0;
                    }
                    else
                    {
                        // land tile rounding
                        tile.shorePiece = true;

                        if (GameMapTiles.map[index2 + 1] is ILand && !(GameMapTiles.map[index2 - 1] is ILand))
                        {
                            tile.currRowFrame = 1;                                                                     // left shore
                        }
                        if (GameMapTiles.map[index2 - _cols] is ILand && !(GameMapTiles.map[index2 + _cols] is ILand)) // check above
                        {
                            tile.currRowFrame = 4;                                                                     // bottom shore
                        }
                        if (GameMapTiles.map[index2 + _cols] is ILand && !(GameMapTiles.map[index2 - _cols] is ILand)) // check below
                        {
                            tile.currRowFrame = 2;                                                                     // top shore
                        }
                        if (GameMapTiles.map[index2 - 1] is ILand && !(GameMapTiles.map[index2 + 1] is ILand))
                        {
                            tile.currRowFrame = 3; // right shore
                        }
                        if (GameMapTiles.map[index2 + 1] is ILand && !(GameMapTiles.map[index2 - 1] is ILand) && !(GameMapTiles.map[index2 - _cols] is ILand))
                        {
                            tile.currRowFrame = 5; // left top corner shore
                        }
                        if (GameMapTiles.map[index2 + 1] is ILand && !(GameMapTiles.map[index2 - 1] is ILand) && !(GameMapTiles.map[index2 + _cols] is ILand))
                        {
                            tile.currRowFrame = 8; // left bottom corner shore
                        }
                        if (GameMapTiles.map[index2 - 1] is ILand && !(GameMapTiles.map[index2 + 1] is ILand) && !(GameMapTiles.map[index2 - _cols] is ILand))
                        {
                            tile.currRowFrame = 6; // right top corner shore
                        }
                        if (GameMapTiles.map[index2 - 1] is ILand && !(GameMapTiles.map[index2 + 1] is ILand) && !(GameMapTiles.map[index2 + _cols] is ILand))
                        {
                            tile.currRowFrame = 7; // right bottom corner shore
                        }
                        tile.SetTileDesignColumn(RandomEvents.rand.Next(0, tile.nColumns));
                    }
                }

                index2++;
            }
        }
Ejemplo n.º 12
0
        public override void HandleCollision(Sprite collidedWith, Rectangle overlap)
        {
            Rectangle footSpace = new Rectangle(GetBoundingBox().Left, GetBoundingBox().Bottom - (GetBoundingBox().Height / 3), GetBoundingBox().Width, GetBoundingBox().Height / 3);

            if (collidedWith.bbKey.Equals("landTile"))
            {
                colliding = false;
                // narrow the collision to just the feet (appears more realistic)
                if (footSpace.Intersects(collidedWith.GetBoundingBox()))
                {
                    swimming = false;
                }

                // can bury item?
                TilePiece tp = (TilePiece)collidedWith;
                if (tp.canFillHole)
                {
                    foreach (var item in inventory)
                    {
                        if (item == null)
                        {
                            continue;
                        }
                        if (item.placeableVersion != null && item.placeableVersion is IStorage)
                        {
                            buryTile = tp;
                            canBury  = true;
                            break;
                        }
                    }
                }
            }

            else if (collidedWith.bbKey.Equals("interiorTile"))
            {
                colliding = false;
                swimming  = false;
            }

            else if (collidedWith.bbKey.Equals("interiorTileWall"))
            {
                if (footSpace.Intersects(collidedWith.GetBoundingBox()))
                {
                    colliding = true;
                }
            }


            else if (collidedWith is IShip)
            {
                colliding = false;
                if (!onShip)
                {
                    nearShip     = true;
                    playerOnShip = (Ship)collidedWith;
                    if (playerOnShip.sinking)
                    {
                        playerOnShip = null;
                    }
                }
            }
            else if (collidedWith.GetType().BaseType == typeof(Gusto.Models.Animated.Npc))
            {
                Npc enemy = (Npc)collidedWith;
                colliding = false;
                if (enemy.inCombat)
                {
                    showHealthBar = true;
                    health       -= enemy.damage;
                }
            }
            else if (collidedWith is IWalks || collidedWith is IGroundObject || collidedWith is IPlaceable)
            {
                colliding = false;
            }
            else if (collidedWith is IStructure)
            {
                colliding           = false;
                playerNearStructure = (Structure)collidedWith;
            }
            else if (collidedWith is IAmmo)
            {
                Ammo ball = (Ammo)collidedWith;
                showHealthBar = true;
                if (!ball.exploded)
                {
                    health -= ball.groundDamage;
                }
                return;
            }
        }
Ejemplo n.º 13
0
        public void Update(KeyboardState kstate, GameTime gameTime, Camera camera)
        {
            timeSinceLastTurnFrame += gameTime.ElapsedGameTime.Milliseconds;
            timeSinceLastWalkFrame += gameTime.ElapsedGameTime.Milliseconds;

            // check inventory
            BoundingBoxLocations.treasureLocationsList.Clear();
            List <int>           removeSolvedOrSpoiled = new List <int>();
            List <InventoryItem> addTimedItem          = new List <InventoryItem>();

            foreach (var item in inventory)
            {
                if (item == null)
                {
                    continue;
                }

                // for spoiled food
                if (item is ISpoiles)
                {
                    item.msSpoilTime += gameTime.ElapsedGameTime.Milliseconds;
                    Tuple <int, string> spoilDetails = ItemMappings.SpoilMappings[item.bbKey];

                    if (item.msSpoilTime > spoilDetails.Item1)
                    {
                        InventoryItem spoiled = ItemUtility.CreateInventoryItem(spoilDetails.Item2, teamType, regionKey, location, _content, _graphics);
                        item.msSpoilTime = 0;
                        if (item.amountStacked > 1)
                        {
                            item.amountStacked -= 1;
                        }
                        else
                        {
                            removeSolvedOrSpoiled.Add(inventory.IndexOf(item));
                        }

                        addTimedItem.Add(spoiled);
                    }
                }

                // for treasure maps
                if (item.bbKey.Equals("treasureMapItem"))
                {
                    TreasureMap map = (TreasureMap)item;
                    if (map.solved)
                    {
                        removeSolvedOrSpoiled.Add(inventory.IndexOf(item));
                    }
                    else
                    {
                        BoundingBoxLocations.treasureLocationsList.Add(map);
                    }
                }
            }
            foreach (var remove in removeSolvedOrSpoiled)
            {
                inventory[remove] = null;
            }
            foreach (var item in addTimedItem)
            {
                if (!AddInventoryItem(item))
                {
                    item.location = new Vector2(GetBoundingBox().Center.ToVector2().X, GetBoundingBox().Center.ToVector2().Y + 40);
                    item.onGround = true;

                    if (inInteriorId != Guid.Empty) // add drops to interior
                    {
                        BoundingBoxLocations.interiorMap[inInteriorId].interiorObjectsToAdd.Add(item);
                    }
                    else // add drops to world
                    {
                        ItemUtility.ItemsToUpdate.Add(item);
                    }
                }
            }

            if (showHealthBar)
            {
                timeShowingHealthBar += gameTime.ElapsedGameTime.Milliseconds;
            }
            if (timeShowingHealthBar > GameOptions.millisecondsToShowHealthBar)
            {
                showHealthBar        = false;
                timeShowingHealthBar = 0;
            }

            if (colliding)
            {
                moving = false;
            }

            // update any water wake
            wake.EmitterLocation = location;
            wake.Update(currentSpeed, (swimming && moving));

            colliding = false;
            swimming  = true;

            if (timeSinceLastTurnFrame > millisecondsPerTurnFrame)
            {
                // toggle inventory (use turn frame speed here for convenience)
                if (kstate.IsKeyDown(Keys.Tab))
                {
                    if (showInventory)
                    {
                        showInventory = false;
                    }
                    else
                    {
                        showInventory = true;
                    }
                }

                if (!onShip || playerInInterior != null)
                {
                    moving = true;
                    // player direction
                    if (kstate.IsKeyDown(Keys.W))
                    {
                        currRowFrame     = 3;
                        directionalFrame = 0;
                        if (kstate.IsKeyDown(Keys.A))
                        {
                            directionalFrame = 1;
                        }
                        else if (kstate.IsKeyDown(Keys.D))
                        {
                            directionalFrame = 7;
                        }
                    }
                    else if (kstate.IsKeyDown(Keys.S))
                    {
                        currRowFrame     = 0;
                        directionalFrame = 4;
                        if (kstate.IsKeyDown(Keys.A))
                        {
                            directionalFrame = 3;
                        }
                        else if (kstate.IsKeyDown(Keys.D))
                        {
                            directionalFrame = 5;
                        }
                    }
                    else if (kstate.IsKeyDown(Keys.A))
                    {
                        currRowFrame     = 2;
                        directionalFrame = 2;
                    }
                    else if (kstate.IsKeyDown(Keys.D))
                    {
                        currRowFrame     = 1;
                        directionalFrame = 6;
                    }
                    else
                    {
                        moving = false;
                    }
                    inHand.currRowFrame = currRowFrame;
                }
                else
                {
                    moving = false;
                }

                timeSinceLastTurnFrame -= millisecondsPerTurnFrame;
            }

            // combat
            if (!onShip || playerInInterior != null)
            {
                inHand.Update(kstate, gameTime, camera);
                if (playerInInterior != null)
                {
                    inHand.inInteriorId = playerInInterior.interiorId;
                }
                else
                {
                    inHand.inInteriorId = Guid.Empty;
                }
            }

            if (Mouse.GetState().LeftButton == ButtonState.Pressed && (!onShip || playerInInterior != null) && !showInventory)
            {
                inCombat        = true;
                inHand.inCombat = true;
                currColumnFrame = 8;
                if (inHand is IRanged)
                {
                    currColumnFrame = 9; // better frame for "holding" a ranged weapon

                    //load ammo
                    if (inHand.ammoLoaded == null)
                    {
                        foreach (var item in inventory)
                        {
                            if (item != null && item.GetType() == inHand.ammoItemType)
                            {
                                if (item.amountStacked > 0)
                                {
                                    inHand.LoadAmmo(item);
                                }
                                else
                                {
                                    inventory[inventory.IndexOf(item)] = null;
                                }
                                break;
                            }
                        }
                    }
                }
            }
            else if (inCombat)
            {
                if (timeSinceSwordSwing > millisecondsCombatSwing)
                {
                    currColumnFrame++;
                    inHand.location  = location;
                    inHand.nextFrame = true;
                    if (currColumnFrame == nColumns)
                    {
                        inCombat        = false;
                        inHand.inCombat = false;
                        currColumnFrame = 0;
                    }
                    timeSinceSwordSwing = 0;
                }
                timeSinceSwordSwing += gameTime.ElapsedGameTime.Milliseconds;
            }

            inHand.location = location;
            inHand.SetBoundingBox();


            // hop on ship
            if (nearShip && kstate.IsKeyDown(Keys.X) && !onShip && playerOnShip != null && timeSinceExitShipStart < 2000)
            {
                location = playerOnShip.GetBoundingBox().Center.ToVector2();
                onShip   = true;
                playerOnShip.playerAboard          = true;
                playerOnShip.shipSail.playerAboard = true;

                // can't control non player ships (until taken over)
                if (playerOnShip.teamType != TeamType.Player)
                {
                    playerInInterior = playerOnShip.shipInterior;
                }
            }
            // exit ship
            else if (kstate.IsKeyDown(Keys.X) && onShip)
            {
                timeSinceExitShipStart += gameTime.ElapsedGameTime.Milliseconds;
                if (timeSinceExitShipStart > 2000)
                {
                    onShip = false;
                    if (playerInInterior != null)
                    {
                        playerInInterior.showingInterior = false;
                        playerInInterior.interiorObjects.Remove(this);
                        playerInInterior = null;
                        inInteriorId     = Guid.Empty;
                    }
                    playerOnShip.playerAboard          = false;
                    playerOnShip.shipSail.playerAboard = false;
                    location.X   = playerOnShip.GetBoundingBox().Center.ToVector2().X - playerOnShip.GetBoundingBox().Width / 2 - 20;
                    location.Y   = playerOnShip.GetBoundingBox().Center.ToVector2().Y;
                    playerOnShip = null;
                }
            }
            else
            {
                timeSinceExitShipStart = 0;
            }
            nearShip = false;

            // player moves with ship when controlling
            if (onShip && playerInInterior == null)
            {
                location.X = playerOnShip.GetBoundingBox().Center.ToVector2().X;
                location.Y = playerOnShip.GetBoundingBox().Center.ToVector2().Y;
            }

            if (playerOnShip != null && playerOnShip.sinking)
            {
                onShip           = false;
                playerInInterior = null;
                playerOnShip     = null;
                inInteriorId     = Guid.Empty;
            }

            else if (moving && !inCombat)
            {
                // walking animation
                if (timeSinceLastWalkFrame > millisecondsPerWalkFrame)
                {
                    currColumnFrame++;
                    if (currColumnFrame == 7) // stop before combat frames
                    {
                        currColumnFrame = 0;
                    }
                    timeSinceLastWalkFrame = 0;
                }

                currentSpeed = new Vector2(PlayerMovementVectorMappings.PlayerDirectionVectorValues[directionalFrame].Item1,
                                           PlayerMovementVectorMappings.PlayerDirectionVectorValues[directionalFrame].Item2);

                // actual "regular" movement
                location += currentSpeed;
            }
            else
            {
                if (!inCombat)
                {
                    currColumnFrame = 0;
                }
            }

            // burying storage
            int?removeChestIndex = null;

            if (canBury && kstate.IsKeyDown(Keys.B))
            {
                timeSincePressedBury += gameTime.ElapsedGameTime.Milliseconds;
                if (timeSincePressedBury > 1000)
                {
                    // remove first chest
                    foreach (var item in inventory)
                    {
                        if (item == null)
                        {
                            continue;
                        }
                        if (item.placeableVersion != null && item.placeableVersion is IStorage)
                        {
                            removeChestIndex = inventory.IndexOf(item);
                            break;
                        }
                    }

                    // create map
                    if (removeChestIndex != null)
                    {
                        Storage         toBury   = (Storage)inventory[(int)removeChestIndex].placeableVersion;
                        TreasureMapItem mapToAdd = new TreasureMapItem(toBury, teamType, regionKey, location, _content, _graphics);
                        mapToAdd.digTileLoc       = buryTile.location;
                        mapToAdd.treasureInRegion = buryTile.regionKey;
                        mapToAdd.inInventory      = false;
                        mapToAdd.remove           = false;
                        mapToAdd.onGround         = true;
                        buryTile.currColumnFrame  = 0;
                        ItemUtility.ItemsToUpdate.Add(mapToAdd);
                        inventory[(int)removeChestIndex] = null;
                    }
                    timeSincePressedBury = 0;
                }
            }
            buryTile = null;
            canBury  = false;

            // entering/toggling interior
            if (kstate.IsKeyDown(Keys.I))
            {
                msToggleInterior += gameTime.ElapsedGameTime.Milliseconds;
                if (msToggleInterior > 1000)
                {
                    if (playerInInterior != null)
                    {
                        playerInInterior.showingInterior = false;
                        playerInInterior.interiorObjects.Remove(this);
                        inInteriorId     = Guid.Empty;
                        playerInInterior = null;

                        location = entranceLoc; // player exits where they entered

                        if (playerOnShip != null)
                        {
                            playerOnShip.playerInInterior          = false;
                            playerOnShip.shipSail.playerInInterior = false;
                        }
                    }
                    else
                    {
                        // enter an interior
                        if (onShip)  // the interior of the ship the player is in
                        {
                            playerInInterior = playerOnShip.shipInterior;
                            playerOnShip.playerInInterior          = true;
                            playerOnShip.shipSail.playerInInterior = true;
                            inInteriorId = playerInInterior.interiorId;
                        }
                        else if (playerNearStructure != null)
                        {
                            entranceLoc      = location;
                            playerInInterior = playerNearStructure.structureInterior;
                            inInteriorId     = playerInInterior.interiorId;
                        }
                    }
                    msToggleInterior = 0;
                }
            }
            playerNearStructure = null;
        }
Ejemplo n.º 14
0
        private void AIUpdate(GameTime gameTime)
        {
            // AI only works if NPC aboard
            if (shipInterior.interiorObjects.OfType <Npc>().Any())
            {
                // AI ship direction and movement
                if (timeSinceLastTurn > millisecondsPerTurn)
                {
                    if (!roaming)
                    {
                        if (regionKey.Equals("GustoMap")) // TEMP see pathFind comment below
                        {
                            regionKey = "Usopp";
                        }

                        randomRoamTile = BoundingBoxLocations.RegionMap[regionKey].RegionOceanTiles[RandomEvents.rand.Next(BoundingBoxLocations.RegionMap[regionKey].RegionOceanTiles.Count)];
                        roaming        = true;
                        TilePiece rtp         = (TilePiece)randomRoamTile;
                        Point?    gridPointTo = rtp.mapCordPoint;
                        currentPath = AIUtility.Pathfind(mapCordPoint.Value, gridPointTo.Value, PathType.Ocean); // NOTE: This freezes the game when hitting GustoMap region (because it is almost all the tiles at the moment)
                    }
                    else
                    {
                        // move to attack/follow target when in range
                        int shotRange = mountedOnShip == null ? 0 : mountedOnShip.shotRange;
                        if (shotRange > 0)
                        {
                            Tuple <Point?, float> targetInfo = AIUtility.ChooseTargetPoint(teamType, shotRange, GetBoundingBox(), inInteriorId, PathType.Ocean);
                            if (targetInfo != null)
                            {
                                // stop distance
                                var distanceToTarget = targetInfo.Item2;
                                if (distanceToTarget <= stopRange)
                                {
                                    moving          = false;
                                    shipSail.moving = false;
                                }
                                else
                                {
                                    moving          = true;
                                    shipSail.moving = true;
                                }

                                Point?targetMapCords = targetInfo.Item1;
                                // compute follow path
                                if (!following)
                                {
                                    currentPath = AIUtility.Pathfind(mapCordPoint.Value, targetMapCords.Value, PathType.Ocean);
                                    following   = true;
                                }
                            }
                            else
                            {
                                following = false;
                            }
                        }


                        // we have found the next tile in path
                        if (currentPath[0].GetBoundingBox().Intersects(GetBoundingBox()))
                        {
                            currentPath.RemoveAt(0);
                            if (currentPath.Count == 0)
                            {
                                roaming   = false;
                                following = false;
                            }
                        }

                        if (roaming)
                        {
                            currRowFrame = AIUtility.SetAIShipDirection(currentPath[0].GetBoundingBox().Center.ToVector2(), location);
                        }
                    }

                    shipSail.currRowFrame = currRowFrame;
                    timeSinceLastTurn    -= millisecondsPerTurn;
                }

                // AI shooting
                if (mountedOnShip != null)
                {
                    Vector2?shotDirection = AIUtility.ChooseTargetVector(teamType, mountedOnShip.shotRange, GetBoundingBox(), inInteriorId);
                    mountedOnShip.UpdateAIMountShot(gameTime, shotDirection);
                    // temp setting AI to use weapon slot 0
                    Vector2 weaponPosOffset = new Vector2(ShipMountTextureCoordinates.WeaponMountCords[bbKey][currRowFrame][0].Item1, ShipMountTextureCoordinates.WeaponMountCords[bbKey][currRowFrame][0].Item2);
                    mountedOnShip.location = GetBoundingBox().Center.ToVector2() + weaponPosOffset;
                }
            }
        }
Ejemplo n.º 15
0
    IEnumerator SwitchTilesRoutine(TilePiece clickedTile, TilePiece targetTile)
    {
        if (m_playerInputEnabled && !GameManager.Instance.IsGameOver)
        {
            GamePiece clickedPiece = m_allGamePieces[clickedTile.xIndex, clickedTile.yIndex];
            GamePiece targetPiece  = m_allGamePieces[targetTile.xIndex, targetTile.yIndex];

            if (targetPiece != null && clickedPiece != null)
            {
                clickedPiece.Move(targetTile.xIndex, targetTile.yIndex, swapTime);
                targetPiece.Move(clickedTile.xIndex, clickedTile.yIndex, swapTime);

                yield return(new WaitForSeconds(swapTime));

                List <GamePiece> clickePieceMatches = FindMatchesAt(clickedTile.xIndex, clickedTile.yIndex, 3, true);
                List <GamePiece> targetPieceMatches = FindMatchesAt(targetTile.xIndex, targetTile.yIndex, 3, true);
                List <GamePiece> colorMatches       = new List <GamePiece>();

                #region color bombs / power to power combo
                //matching rainbow to regular color
                if (IsColorBomb(clickedPiece) && !IsColorBomb(targetPiece))
                {
                    clickedPiece.matchValue = targetPiece.matchValue;
                    colorMatches            = FindAllMatchValue(clickedPiece.matchValue);
                    //match regular piece to rainbow piec
                }
                else if (!IsColorBomb(clickedPiece) && IsColorBomb(targetPiece))
                {
                    targetPiece.matchValue = clickedPiece.matchValue;
                    colorMatches           = FindAllMatchValue(targetPiece.matchValue);
                    //match rainbow to rainbow
                }
                else if (IsColorBomb(clickedPiece) && IsColorBomb(targetPiece))
                {
                    foreach (GamePiece piece in m_allGamePieces)
                    {
                        if (!colorMatches.Contains(piece))
                        {
                            colorMatches.Add(piece);
                        }
                    }
                    // match powerup to powerup
                }
                else if (clickedPiece is Bomb && targetPiece is Bomb)
                {
                    List <Bomb> combo = new List <Bomb>()
                    {
                        clickedPiece as Bomb, targetPiece as Bomb
                    };
                    colorMatches = GetComboPieces(combo, targetTile.xIndex, targetTile.yIndex);
                }
                #endregion

                //block move from happening if there is no match and not a rainbow piece
                if (targetPieceMatches.Count == 0 && clickePieceMatches.Count == 0 && colorMatches.Count == 0)
                {
                    clickedPiece.Move(clickedTile.xIndex, clickedTile.yIndex, swapTime);
                    targetPiece.Move(targetTile.xIndex, targetTile.yIndex, swapTime);
                }
                else
                {
                    yield return(new WaitForSeconds(swapTime));

                    //get direction and placement of bomb during swap
                    Vector2 swipeDirection = new Vector2(targetTile.xIndex - clickedTile.xIndex, targetTile.yIndex - clickedTile.yIndex);

                    List <GamePiece> piecesToClear = clickePieceMatches.Union(targetPieceMatches).ToList().Union(colorMatches).ToList();
                    //ClearAndRefillBoard(clickePieceMatches.Union(targetPieceMatches).ToList().Union(colorMatches).ToList());
                    yield return(StartCoroutine(ClearAndRefillBoardRoutine(piecesToClear)));

                    if (GameManager.Instance != null)
                    {
                        //GameManager.Instance.movesLeft--;
                        GameManager.Instance.UpdateMoves();
                    }
                }
            }
        }
    }
Ejemplo n.º 16
0
 public void ResetPiece(TilePiece piece)
 {
     piece.ResetPosition();
     update.Add(piece);
 }
Ejemplo n.º 17
0
    public IEnumerator CustoUniforme(TilePiece curr, TilePiece end)
    {
        curr.visitado = true;

        List <Tuple <int, List <TilePiece> > > rotas = new List <Tuple <int, List <TilePiece> > > ();

        rotas.Add(new Tuple <int, List <TilePiece> > (0, new List <TilePiece>()));
        rotas [0].Second.Add(curr);

        while (!encontrou)
        {
            // Seleciona a rota mais curta conhecida
            int menori = 0;
            int menor  = rotas[0].First;

            for (int i = 1; i < rotas.Count; i++)
            {
                if (rotas [i].First < menor)
                {
                    menori = i;
                    menor  = rotas [i].First;
                }
            }

            Tuple <int, List <TilePiece> > rota = rotas[menori];

            // Se a rota chega ao fim, finaliza
            if (rota.Second [rota.Second.Count - 1] == end)
            {
                encontrou = true;

                foreach (TilePiece t in rota.Second)
                {
                    t.selecionado = true;
                    custo        += t.cost;
                }

                custo -= rota.Second [0].cost;

                yield break;
            }
            // Se a rota não chega ao fim
            else
            {
                rotas.Remove(rota);

                foreach (TilePiece vizinho in rota.Second[rota.Second.Count - 1].vizinhos)
                {
                    if (!encontrou)
                    {
                        if (!vizinho.visitado)
                        {
                            vizinho.visitado = true;
                            visitados       += 1;

                            List <TilePiece> novaRota = new List <TilePiece>();
                            novaRota.AddRange(rota.Second);
                            novaRota.Add(vizinho);

                            rotas.Add(
                                new Tuple <int, List <TilePiece> > (
                                    rota.First + vizinho.cost, novaRota
                                    )
                                );
                        }
                    }
                }
            }

            yield return(new WaitForSeconds(0.01f));
        }
    }
Ejemplo n.º 18
0
    public IEnumerator AStar(TilePiece curr, TilePiece end)
    {
        List <TilePiece> openSet = new List <TilePiece> ();

        openSet.Add(curr);

        TilePiece[] cameFrom = new TilePiece[level.nodes.Count];

        for (int i = 0; i < cameFrom.Length; i++)
        {
            cameFrom[i] = null;
        }

        float[] gScore = new float[level.nodes.Count];

        for (int i = 0; i < gScore.Length; i++)
        {
            gScore[i] = 99999;
        }

        gScore[level.nodes.FindIndex(d => d == curr)] = 0;

        float[] fScore = new float[level.nodes.Count];

        for (int i = 0; i < fScore.Length; i++)
        {
            fScore[i] = 99999;
        }

        fScore[level.nodes.FindIndex(d => d == curr)] = (Vector3.Distance(curr.transform.position, end.transform.position) / 2.0f);

        while (openSet.Count > 0)
        {
            float menor  = 99999;
            int   menori = -1;

            for (int i = 0; i < openSet.Count; i++)
            {
                int id = level.nodes.FindIndex(d => d == curr);

                if (fScore [id] < menor)
                {
                    menor  = fScore [id];
                    menori = i;
                }
            }

            TilePiece current = openSet [menori];

            if (current == end)
            {
                encontrou = true;

                TilePiece t = end;

                while (t != curr)
                {
                    t.selecionado = true;
                    custo        += t.cost;
                    t             = cameFrom[level.nodes.FindIndex(d => d == t)];
                }

                yield break;
            }

            openSet.Remove(current);

            //Para cada vizinho
            foreach (TilePiece v in current.vizinhos)
            {
                // A distância do início até o vizinho
                float tentativeGScore = gScore[level.nodes.FindIndex(d => d == current)] + v.cost;

                if (tentativeGScore >= gScore [level.nodes.FindIndex(d => d == v)])
                {
                    continue;                     // Esse caminho não é melhor
                }
                // Descobriu um nodo novo
                if (!openSet.Contains(v))
                {
                    visitados += 1;
                    openSet.Add(v);
                    v.visitado = true;
                }

                // Melhor caminho até agora. Salvar o caminho
                cameFrom[level.nodes.FindIndex(d => d == v)] = current;

                gScore [level.nodes.FindIndex(d => d == v)] = tentativeGScore;

                fScore [level.nodes.FindIndex(d => d == v)] = gScore [level.nodes.FindIndex(d => d == v)]
                                                              + (Vector3.Distance(v.transform.position, end.transform.position) / 2.0f);
            }

            yield return(new WaitForSeconds(0.01f));
        }
    }
Ejemplo n.º 19
0
 void button_Click(object sender, EventArgs e)
 {
     _selectedPiece = (TilePiece)((Button)sender).Tag;
 }
Ejemplo n.º 20
0
    public void ApplyGravityToBoard()
    {
        for (int x = 0; x < width; x++)
        {
            for (int y = (height - 1); y >= 0; y--)
            {
                TileCoord pos  = new TileCoord(x, y);
                Tile      tile = getTile(pos);
                int       type = getTileType(pos);
                if (type != 0)
                {
                    continue;
                }
                for (int ny = (y - 1); ny >= -1; ny--)
                {
                    TileCoord next     = new TileCoord(x, ny);
                    int       nextType = getTileType(next);
                    if (nextType == 0)
                    {
                        continue;
                    }
                    if (nextType != -1)
                    {
                        Tile      gotten = getTile(next);
                        TilePiece piece  = gotten.getPiece();
                        tile.SetPiece(piece);
                        update.Add(piece);
                        gotten.SetPiece(null);
                    }
                    else
                    {
                        int       newType = genTile();
                        TilePiece piece;
                        TileCoord fallPnt = new TileCoord(x, (-1 - fills[x]));
                        if (dead.Count > 0)
                        {
                            TilePiece revived = dead[0];
                            revived.gameObject.SetActive(true);
                            piece = revived;

                            dead.RemoveAt(0);
                        }
                        else
                        {
                            GameObject obj = Instantiate(tilePiece, gameBoard);
                            TilePiece  n   = obj.GetComponent <TilePiece>();
                            piece = n;
                        }

                        piece.Initialize(newType, pos, tiles[newType - 1]);
                        piece.rect.anchoredPosition = getPositionFromCoord(fallPnt);
                        Tile hole = getTile(pos);
                        hole.SetPiece(piece);
                        ResetPiece(piece);
                        fills[x]++;
                    }
                    break;
                }
            }
        }
    }
Ejemplo n.º 21
0
 void SwitchTiles(TilePiece clickedTile, TilePiece targetTile)
 {
     StartCoroutine(SwitchTilesRoutine(clickedTile, targetTile));
 }
Ejemplo n.º 22
0
        private bool IsMoveValid(Point curr, Point next)
        {
            TilePiece currPiece = _boardTiles[curr.Y][curr.X];
            TilePiece nextPiece = _boardTiles[next.Y][next.X];

            // We need to allow "jumping" the corner
            if (next.X > curr.X && next.Y > curr.Y)
            {
                Point topRight = new Point(curr.X + 1, curr.Y);
                Point botLeft  = new Point(curr.X, curr.Y + 1);

                if (IsMoveValid(curr, topRight) && IsMoveValid(topRight, next))
                {
                    return(true);
                }
                if (IsMoveValid(curr, botLeft) && IsMoveValid(botLeft, next))
                {
                    return(true);
                }
            }
            else if (next.X > curr.X && next.Y < curr.Y)
            {
                Point topRight = new Point(curr.X, curr.Y - 1);
                Point botLeft  = new Point(curr.X + 1, curr.Y);

                if (IsMoveValid(curr, topRight) && IsMoveValid(topRight, next))
                {
                    return(true);
                }
                if (IsMoveValid(curr, botLeft) && IsMoveValid(botLeft, next))
                {
                    return(true);
                }
            }
            else if (next.X < curr.X && next.Y > curr.Y)
            {
                Point topRight = new Point(curr.X, curr.Y + 1);
                Point botLeft  = new Point(curr.X - 1, curr.Y);

                if (IsMoveValid(curr, topRight) && IsMoveValid(topRight, next))
                {
                    return(true);
                }
                if (IsMoveValid(curr, botLeft) && IsMoveValid(botLeft, next))
                {
                    return(true);
                }
            }
            else if (next.X < curr.X && next.Y < curr.Y)
            {
                Point topRight = new Point(curr.X - 1, curr.Y);
                Point botLeft  = new Point(curr.X, curr.Y - 1);

                if (IsMoveValid(curr, topRight) && IsMoveValid(topRight, next))
                {
                    return(true);
                }
                if (IsMoveValid(curr, botLeft) && IsMoveValid(botLeft, next))
                {
                    return(true);
                }
            }
            else if (next.X > curr.X)
            {
                switch (currPiece)
                {
                case TilePiece.Start:
                case TilePiece.TopLeft:
                case TilePiece.Horizontal:
                case TilePiece.BottomLeft:
                {
                    return(nextPiece == TilePiece.Horizontal || nextPiece == TilePiece.TopRight || nextPiece == TilePiece.BottomRight);
                }

                case TilePiece.BottomRight:
                case TilePiece.TopRight:
                case TilePiece.Vertical:
                {
                    return(false);
                }
                }
            }
            else if (next.X < curr.X)
            {
                switch (currPiece)
                {
                case TilePiece.Start:
                case TilePiece.Horizontal:
                case TilePiece.BottomRight:
                case TilePiece.TopRight:
                {
                    return(nextPiece == TilePiece.Horizontal || nextPiece == TilePiece.TopLeft || nextPiece == TilePiece.BottomLeft || nextPiece == TilePiece.Start);
                }

                case TilePiece.TopLeft:
                case TilePiece.BottomLeft:
                case TilePiece.Vertical:
                {
                    return(false);
                }
                }
            }
            else if (next.Y > curr.Y)
            {
                switch (currPiece)
                {
                case TilePiece.Start:
                case TilePiece.TopLeft:
                case TilePiece.TopRight:
                case TilePiece.Vertical:
                {
                    return(nextPiece == TilePiece.Vertical || nextPiece == TilePiece.BottomLeft || nextPiece == TilePiece.BottomRight);
                }

                case TilePiece.Horizontal:
                case TilePiece.BottomLeft:
                case TilePiece.BottomRight:
                {
                    return(false);
                }
                }
            }
            else if (next.Y < curr.Y)
            {
                switch (currPiece)
                {
                case TilePiece.BottomLeft:
                case TilePiece.BottomRight:
                case TilePiece.Vertical:
                {
                    return(nextPiece == TilePiece.Vertical || nextPiece == TilePiece.TopLeft || nextPiece == TilePiece.TopRight || nextPiece == TilePiece.Start);
                }

                case TilePiece.Start:
                case TilePiece.TopLeft:
                case TilePiece.TopRight:
                case TilePiece.Horizontal:
                {
                    return(false);
                }
                }
            }
            return(false);
        }
Ejemplo n.º 23
0
    public void GenerateGrid()
    {
        // This section of the code creates new dummy prefabs if they aren't already set up in the editor
        if (numberOfUniquePieces != piecePrefabs.Length)
        {
            TilePiece[] newPiecePrefabs = new TilePiece[numberOfUniquePieces];
            for (int a = 0; a < newPiecePrefabs.Length; a++)
            {
                if (a < piecePrefabs.Length && piecePrefabs[a] != null)
                {
                    newPiecePrefabs[a] = piecePrefabs[a];
                }
                else
                {
                    TilePiece newPiece = GameObject.Instantiate(newPiecePrefab);
                    newPiece.GetComponentInChildren <TextMeshPro>().text  = "" + a;
                    newPiece.GetComponent <MeshRenderer>().material.color = new Color(Random.Range(0, 1.0f), Random.Range(0, 1.0f), Random.Range(0, 1.0f));
                    newPiece.transform.SetParent(this.transform);
                    newPiece.gameObject.name = "Generated Prefab " + a;
                    newPiece.gameObject.SetActive(false);
                    newPiecePrefabs[a] = newPiece;
                }
            }
            piecePrefabs = newPiecePrefabs;
        }

        tileGrid = new TilePosition[gridWidth, gridHeight];
        Vector2 gridOffset = new Vector2((float)-gridWidth / 2.0f + 0.5f, (float)-gridHeight / 2.0f + 0.5f);

        for (int x = 0; x < gridWidth; x++)
        {
            for (int y = 0; y < gridHeight; y++)
            {
                tileGrid[x, y].coordinates  = new Vector2Int(x, y);
                tileGrid[x, y].position     = new Vector3(x + gridOffset.x, 0, y + gridOffset.y);
                tileGrid[x, y].currentPiece = null;
            }
        }
        // I'm not filling the whole grid.  I'm leaving the edge free and using it for connection calculations
        int totalTilesToAdd = (gridWidth - 2) * (gridHeight - 2);

        tilesOnBoard = totalTilesToAdd;

        // this section of the code builds the puzzle in a way such that it guarantees a solution
        List <Vector2Int> availablePlacements = new List <Vector2Int>();

        availablePlacements.Add(new Vector2Int(Random.Range(1, gridWidth - 2), Random.Range(1, gridHeight - 2)));
        // just a safety net, it should only loop "totalTilesToAdd" times
        int maxLoopIterations = 300;

        // this is basically the reverse of the 3 line segment check.  Instead of checking if 2 pieces connect through 3 line segments over blank grid positions,
        // this checks if the 2 pieces connect over 3 line segments with filled grid positions.  It just starts with a random pair and assumes that the user
        // will remove that pair first.
        checkBlanks = false;
        while (totalTilesToAdd > 0 && maxLoopIterations > 0)
        {
            maxLoopIterations--;
            int        r = Random.Range(0, availablePlacements.Count);
            Vector2Int firstPlacement = availablePlacements[Random.Range(0, availablePlacements.Count)];
            int        addThisPiece   = Random.Range(0, numberOfUniquePieces);
            PlacePieceOnGrid(firstPlacement.x, firstPlacement.y, addThisPiece);
            availablePlacements.Remove(firstPlacement);
            // we can only add the new check points if we find a valid pair position for the first tile, so this needs to be stored in a temporary variable.
            List <Vector2Int> newFromFirst = new List <Vector2Int>();
            if (firstPlacement.x - 1 > 0 && tileGrid[firstPlacement.x - 1, firstPlacement.y].currentPiece == null &&
                !availablePlacements.Contains(new Vector2Int(firstPlacement.x - 1, firstPlacement.y)))
            {
                newFromFirst.Add(new Vector2Int(firstPlacement.x - 1, firstPlacement.y));
            }
            if (firstPlacement.x + 1 < gridWidth - 1 && tileGrid[firstPlacement.x + 1, firstPlacement.y].currentPiece == null &&
                !availablePlacements.Contains(new Vector2Int(firstPlacement.x + 1, firstPlacement.y)))
            {
                newFromFirst.Add(new Vector2Int(firstPlacement.x + 1, firstPlacement.y));
            }
            if (firstPlacement.y - 1 > 0 && tileGrid[firstPlacement.x, firstPlacement.y - 1].currentPiece == null &&
                !availablePlacements.Contains(new Vector2Int(firstPlacement.x, firstPlacement.y - 1)))
            {
                newFromFirst.Add(new Vector2Int(firstPlacement.x, firstPlacement.y - 1));
            }
            if (firstPlacement.y + 1 < gridHeight - 1 && tileGrid[firstPlacement.x, firstPlacement.y + 1].currentPiece == null &&
                !availablePlacements.Contains(new Vector2Int(firstPlacement.x, firstPlacement.y + 1)))
            {
                newFromFirst.Add(new Vector2Int(firstPlacement.x, firstPlacement.y + 1));
            }
            // this goes through all the new available pieces (on the edge of the already placed pieces) and checks if there are 3 line segments between them
            // and the first placed tile
            List <Vector2Int> availableConnections = new List <Vector2Int>();
            for (int a = 0; a < availablePlacements.Count + newFromFirst.Count; a++)
            {
                Vector3[] pathway;
                if (a < availablePlacements.Count)
                {
                    if (CanCoordinatesConnect(firstPlacement, availablePlacements[a], out pathway))
                    {
                        availableConnections.Add(availablePlacements[a]);
                    }
                }
                else
                {
                    if (CanCoordinatesConnect(firstPlacement, newFromFirst[a - availablePlacements.Count], out pathway))
                    {
                        availableConnections.Add(newFromFirst[a - availablePlacements.Count]);
                    }
                }
            }
            if (availableConnections.Count > 0)
            {
                // we have found valid pairs and select one of them at random to connect with the first piece
                Vector2Int secondPlacement = availableConnections[Random.Range(0, availableConnections.Count)];
                PlacePieceOnGrid(secondPlacement.x, secondPlacement.y, addThisPiece);
                for (int a = 0; a < newFromFirst.Count; a++)
                {
                    if (!availablePlacements.Contains(newFromFirst[a]))
                    {
                        availablePlacements.Add(newFromFirst[a]);
                    }
                }
                availablePlacements.Remove(secondPlacement);
                if (secondPlacement.x - 1 > 0 && tileGrid[secondPlacement.x - 1, secondPlacement.y].currentPiece == null &&
                    !availablePlacements.Contains(new Vector2Int(secondPlacement.x - 1, secondPlacement.y)))
                {
                    availablePlacements.Add(new Vector2Int(secondPlacement.x - 1, secondPlacement.y));
                }
                if (secondPlacement.x + 1 < gridWidth - 1 && tileGrid[secondPlacement.x + 1, secondPlacement.y].currentPiece == null &&
                    !availablePlacements.Contains(new Vector2Int(secondPlacement.x + 1, secondPlacement.y)))
                {
                    availablePlacements.Add(new Vector2Int(secondPlacement.x + 1, secondPlacement.y));
                }
                if (secondPlacement.y - 1 > 0 && tileGrid[secondPlacement.x, secondPlacement.y - 1].currentPiece == null &&
                    !availablePlacements.Contains(new Vector2Int(secondPlacement.x, secondPlacement.y - 1)))
                {
                    availablePlacements.Add(new Vector2Int(secondPlacement.x, secondPlacement.y - 1));
                }
                if (secondPlacement.y + 1 < gridHeight - 1 && tileGrid[secondPlacement.x, secondPlacement.y + 1].currentPiece == null &&
                    !availablePlacements.Contains(new Vector2Int(secondPlacement.x, secondPlacement.y + 1)))
                {
                    availablePlacements.Add(new Vector2Int(secondPlacement.x, secondPlacement.y + 1));
                }
                totalTilesToAdd -= 2;
            }
            else
            {
                // we couldn't find a pair for the first piece so we'll just try another
                // (this shouldn't be used)
                RemoveTilePiece(tileGrid[firstPlacement.x, firstPlacement.y].currentPiece);
            }
        }

        checkBlanks = true;
        if (totalTilesToAdd <= 0)
        {
            return;
        }
        // we shouldn't get here
        Debug.LogError("FAILED TO GENERATE SOLVED PUZZLE");

        // This is the original random puzzle generation with a few pairs
        ClearGrid();
        totalTilesToAdd = 140;

        // I want to add some random pairs to the grid so that it's more solvable
        int pairsToAdd = 20;

        for (int a = 0; a < pairsToAdd; a = a + 2)
        {
            int addThisPiece = Random.Range(0, numberOfUniquePieces);
            int x            = Random.Range(1, gridWidth - 3);
            int y            = Random.Range(1, gridHeight - 3);
            while (tileGrid[x, y].currentPiece != null ||
                   tileGrid[x, y + 1].currentPiece != null ||
                   tileGrid[x + 1, y].currentPiece != null)
            {
                x = Random.Range(1, gridWidth - 3);
                y = Random.Range(1, gridHeight - 3);
            }
            PlacePieceOnGrid(x, y, addThisPiece);
            if (Random.Range(0, 1) == 0)
            {
                x = x + 1;
            }
            else
            {
                y = y + 1;
            }
            PlacePieceOnGrid(x, y, addThisPiece);
        }
        totalTilesToAdd -= pairsToAdd;


        // Here I create a list of at least one pair of every tile type and the rest is random pairs
        List <int> piecesToAdd          = new List <int>();
        int        minimumNumberOfPiece = 2;

        for (int a = 0; a < numberOfUniquePieces; a++)
        {
            piecesToAdd.Add(a);
            piecesToAdd.Add(a);
        }
        for (int a = minimumNumberOfPiece * numberOfUniquePieces; a < totalTilesToAdd; a = a + 2)
        {
            int addThisPiece = Random.Range(0, numberOfUniquePieces);
            piecesToAdd.Add(addThisPiece);
            piecesToAdd.Add(addThisPiece);
        }

        // This section fills the rest of the grid randomly from the above
        for (int x = 0; x < gridWidth; x++)
        {
            for (int y = 0; y < gridHeight; y++)
            {
                if (x != 0 && y != 0 && x != gridWidth - 1 && y != gridHeight - 1 && tileGrid[x, y].currentPiece == null)
                {
                    // selects a random piece from the dictionary and adds it to the grid
                    tileGrid[x, y].coordinates = new Vector2Int(x, y);
                    tileGrid[x, y].position    = new Vector3(x + gridOffset.x, 0, y + gridOffset.y);
                    int randomIndex = Random.Range(0, piecesToAdd.Count);
                    int randomPiece = piecesToAdd[randomIndex];
                    piecesToAdd.RemoveAt(randomIndex);
                    PlacePieceOnGrid(x, y, randomPiece);
                }
            }
        }
    }
Ejemplo n.º 24
0
    void Update()
    {
        if (gameTimer <= 0.0f)
        {
            gameOver();
        }
        if (PauseControl.GameIsPaused || !gameActive)
        {
            return;
        }
        if (StartControl.Endless)
        {
            Timer.text = '\u221E'.ToString();
        }
        else if (gameStart)
        {
            gameTimer -= Time.deltaTime;
            Timer.text = ((int)gameTimer).ToString();
        }
        multiplierTimer.value -= Time.deltaTime;
        if (multiplierTimer.value <= 0.0f)
        {
            Combo.text      = "0";
            Multiplier.text = "1x";
        }
        List <TilePiece> finishedUpdating = new List <TilePiece>();

        for (int i = 0; i < update.Count; i++)
        {
            TilePiece piece = update[i];
            if (piece == null)
            {
                continue;
            }
            if (!piece.UpdatePiece())
            {
                finishedUpdating.Add(piece);
            }
        }
        for (int i = 0; i < finishedUpdating.Count; i++)
        {
            TilePiece piece = finishedUpdating[i];
            int       x     = (int)piece.index.x;
            fills[x] = Mathf.Clamp(fills[x] - 1, 0, width);

            List <TileCoord> matches = matchFinder(piece.index, true);
            Debug.Log(matches.Count);
            if (matches.Count > 0)
            {
                source.PlayOneShot(matchSound, .25f);
                foreach (TileCoord pos in matches)
                {
                    RemovePiece(pos);
                    Tile      tile      = getTile(pos);
                    TilePiece tilePiece = tile.getPiece();
                    if (tilePiece != null)
                    {
                        tilePiece.gameObject.SetActive(false);
                        dead.Add(tilePiece);
                    }
                    tile.SetPiece(null);
                }
                multiplierTimer.value += 1.5f + (matches.Count - 3) * .5f;
                int comboVal = int.Parse(Combo.text);
                comboVal += 1 + (matches.Count - 3) / 2;
                if (comboVal > maxCombo)
                {
                    maxCombo = comboVal;
                }
                Combo.text = comboVal.ToString();
                int scoreMult = 1 + comboVal / 10;
                if (scoreMult > 5)
                {
                    scoreMult = 5;
                }
                Multiplier.text = scoreMult + "x";
                double scoreVal = double.Parse(Score.text);
                scoreVal += (matches.Count - 2) * 100 * scoreMult;
                if (scoreVal > maxScore)
                {
                    maxScore = scoreVal;
                }
                Score.text = string.Format("{0:000000000}", scoreVal);
            }
            ApplyGravityToBoard();
            update.Remove(piece);
        }
    }
Ejemplo n.º 25
0
 void button_Click(object sender, EventArgs e)
 {
     _selectedPiece = (TilePiece)((Button)sender).Tag;
 }
Ejemplo n.º 26
0
    // Update is called once per frame
    void Update()
    {
        //Selling code
        if (isSelling)
        {
            RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, 10, m_placeable);
            if (hit.collider != null)
            {
                if (hit.collider.gameObject.GetComponent <TilePiece>().Occupied == true)
                {
                    m_costPanel.SetActive(true);
                    m_currentTile = hit.collider.gameObject.GetComponent <TilePiece>();
                    if (m_priorTile == m_currentTile)
                    {
                    }
                    else
                    {
                        m_TxtCost.text = "Sell Value: " + ((int)hit.collider.gameObject.GetComponent <TilePiece>().Tower.GetComponent <Tower>().value * .75f).ToString();
                        //selection highlighting code
                        if (m_priorTile == null)
                        {
                            m_priorTile = m_currentTile;
                        }
                        Renderer temp = hit.transform.gameObject.GetComponent <Renderer>();
                        m_actualColor = temp.material.color;
                        m_priorTile.gameObject.GetComponent <Renderer>().material.color = m_actualColor;
                        m_priorTile         = m_currentTile;
                        m_currTileColor     = Color.Lerp(m_actualColor, m_sellingColor, 0.5f);
                        temp.material.color = m_currTileColor;
                    }
                    //Tower Removal Code
                    if (Input.GetMouseButtonDown(0))
                    {
                        //give money back to the player here from the tower first
                        hit.collider.gameObject.GetComponent <TilePiece>().Tower.GetComponent <Tower>().SellTower();

                        Destroy(hit.collider.gameObject.GetComponent <TilePiece>().Tower);
                        hit.collider.gameObject.GetComponent <TilePiece>().Tower          = null;
                        m_currentTile.gameObject.GetComponent <Renderer>().material.color = m_actualColor;
                        m_costPanel.SetActive(false);
                    }
                }
            }
            else
            {
                m_costPanel.SetActive(false);
            }
        }

        //Buying code
        if (m_tower != null)
        {
            m_costPanel.SetActive(true);
            m_TxtCost.text = "Cost: " + m_tower.GetComponent <Tower>().value.ToString();
            RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, 10, m_placeable);
            if (hit.collider != null)
            {
                if (hit.collider.gameObject.GetComponent <TilePiece>().Occupied == false)
                {
                    m_currentTile = hit.collider.gameObject.GetComponent <TilePiece>();
                    if (m_priorTile == m_currentTile)
                    {
                    }
                    else
                    {
                        //selection highlighting code
                        if (m_priorTile == null)
                        {
                            m_priorTile = m_currentTile;
                        }
                        Renderer temp = hit.transform.gameObject.GetComponent <Renderer>();
                        m_actualColor = temp.material.color;
                        m_priorTile.gameObject.GetComponent <Renderer>().material.color = m_actualColor;
                        m_priorTile         = m_currentTile;
                        m_currTileColor     = Color.Lerp(m_actualColor, m_buyingColor, 0.5f);
                        temp.material.color = m_currTileColor;
                    }


                    //Tower Placement Code
                    if (Input.GetMouseButtonDown(0))
                    {
                        //Implement Buy code here

                        bool iCanBuy = World.Instance.RemoveCoins(m_tower.GetComponent <Tower>().value);

                        if (iCanBuy)
                        {
                            Vector3    pos = hit.collider.transform.position + new Vector3(0.0f, 0.5f, 0.0f);
                            GameObject tow = Instantiate(m_tower, pos, Quaternion.identity);

                            hit.collider.gameObject.GetComponent <TilePiece>().Tower          = tow;
                            m_currentTile.gameObject.GetComponent <Renderer>().material.color = m_actualColor;
                        }
                    }
                }
            }
        }

        //Upgrading code
        if (isUpgrading)
        {
            RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, 10, m_placeable);
            if (hit.collider != null)
            {
                if (hit.collider.gameObject.GetComponent <TilePiece>().Occupied == true)
                {
                    m_currentTile = hit.collider.gameObject.GetComponent <TilePiece>();
                    if (m_priorTile == m_currentTile)
                    {
                    }
                    else
                    {
                        //selection highlighting code
                        if (m_priorTile == null)
                        {
                            m_priorTile = m_currentTile;
                        }
                        Renderer temp = hit.transform.gameObject.GetComponent <Renderer>();
                        m_actualColor = temp.material.color;
                        m_priorTile.gameObject.GetComponent <Renderer>().material.color = m_actualColor;
                        m_priorTile = m_currentTile;

                        //check if this tile is fully upgraded, if it is then revert it back to its normal color
                        if (!hit.collider.gameObject.GetComponent <TilePiece>().Tower.GetComponent <Tower>().fullyUpgraded)
                        {
                            m_costPanel.SetActive(true);
                            m_TxtCost.text      = "Cost: " + ((int)hit.collider.gameObject.GetComponent <TilePiece>().Tower.GetComponent <Tower>().upgradeCost).ToString();
                            m_currTileColor     = Color.Lerp(m_actualColor, m_upgradingColor, 0.5f);
                            temp.material.color = m_currTileColor;
                        }
                    }
                    //Tower Upgrade Code
                    if (Input.GetMouseButtonDown(0))
                    {
                        //upgrade the tower and subtract the gold from the player here
                        hit.collider.gameObject.GetComponent <TilePiece>().Tower.GetComponent <Tower>().UpgradeTower();
                        if (hit.collider.gameObject.GetComponent <TilePiece>().Tower.GetComponent <Tower>().fullyUpgraded)
                        {
                            m_costPanel.SetActive(false);
                        }
                        //check if this tile is fully upgraded, if it is then revert it back to its normal color
                        //m_currentTile.gameObject.GetComponent<Renderer>().material.color = m_actualColor;
                    }
                }
            }
        }
    }
Ejemplo n.º 27
0
        // logic to find correct frame of sprite from user input and update movement values
        public void Update(KeyboardState kstate, GameTime gameTime, Camera camera)
        {
            timeSinceLastTurn += gameTime.ElapsedGameTime.Milliseconds;

            if (showHealthBar)
            {
                timeShowingHealthBar += gameTime.ElapsedGameTime.Milliseconds;
            }
            if (timeShowingHealthBar > GameOptions.millisecondsToShowHealthBar)
            {
                showHealthBar        = false;
                timeShowingHealthBar = 0;
            }

            // set our map cord point (initially and when it changes TODO: fix the "optimization" using currMapCordTile neighbors below. It doesn't properly update mapCordPoint when used)
            if (currMapCordTile == null || !currMapCordTile.GetBoundingBox().Intersects(GetBoundingBox()))
            {
                foreach (var tile in BoundingBoxLocations.RegionMap[regionKey].RegionOceanTiles)
                {
                    if (GetBoundingBox().Intersects(tile.GetBoundingBox()))
                    {
                        TilePiece tp = (TilePiece)tile;
                        currMapCordTile = tp;
                        mapCordPoint    = tp.mapCordPoint;
                        break;
                    }
                }
            }

            /*else if (!currMapCordTile.GetBoundingBox().Intersects(GetBoundingBox())) // (when it has changed)
             * {
             *  List<TilePiece> neighbors = new List<TilePiece>();
             *  neighbors.Add(GameMapTiles.map[currMapCordTile.mapCordPoint.Value.X * GameMapTiles.cols + currMapCordTile.mapCordPoint.Value.Y + 1]); // right neighbor
             *  neighbors.Add(GameMapTiles.map[currMapCordTile.mapCordPoint.Value.X * GameMapTiles.cols + currMapCordTile.mapCordPoint.Value.Y - 1]); // left neighbor
             *  neighbors.Add(GameMapTiles.map[(currMapCordTile.mapCordPoint.Value.X + 1) * GameMapTiles.cols + currMapCordTile.mapCordPoint.Value.Y]); // bottom neighbor
             *  neighbors.Add(GameMapTiles.map[(currMapCordTile.mapCordPoint.Value.X - 1) * GameMapTiles.cols + currMapCordTile.mapCordPoint.Value.Y]); // top neighbor
             *  foreach (var tile in neighbors)
             *  {
             *      if (GetBoundingBox().Intersects(tile.GetBoundingBox()))
             *      {
             *          TilePiece tp = (TilePiece)tile;
             *          currMapCordTile = tp;
             *          mapCordPoint = tp.mapCordPoint;
             *          break;
             *      }
             *  }
             * }*/


            // AI logic
            if (teamType != TeamType.Player)
            {
                AIUpdate(gameTime);
            }
            // player logic
            else
            {
                PlayerUpdate(kstate, gameTime, camera);
            }

            int windDir = WeatherState.wind.getWindDirection();
            int windSp  = WeatherState.wind.getWindSpeed();

            if (moving)
            {
                // map frame to vector movement
                Tuple <float, float> bonus = SetSailBonusMovement(ShipMovementVectorMapping.ShipDirectionVectorValues, windDir, windSp, shipSail.sailSpeed, shipSail.sailIsRightColumn, shipSail.sailIsLeftColumn);
                currentShipSpeed = new Vector2((ShipMovementVectorMapping.ShipDirectionVectorValues[currRowFrame].Item1 + bonus.Item1) * percentNotAnchored,
                                               (ShipMovementVectorMapping.ShipDirectionVectorValues[currRowFrame].Item2 + bonus.Item2) * percentNotAnchored);
                location += currentShipSpeed;
                //Trace.WriteLine("X: " + location.X.ToString() + "\nY: " + location.Y.ToString() + "\n");
            }
            else
            {
                currentShipSpeed = Vector2.Zero;
            }

            // wake particles
            wake.EmitterLocation = new Vector2(location.X + ShipMountTextureCoordinates.BackOfShipCords[bbKey][currRowFrame].Item1,
                                               location.Y + ShipMountTextureCoordinates.BackOfShipCords[bbKey][currRowFrame].Item2);
            wake.Update(currentShipSpeed, moving);
            shipInterior.speed = currentShipSpeed;

            // set the sail and cannon offsets here (equal to ship location plus the offset on the texture to hit the mount)
            int sailMountX = ShipMountTextureCoordinates.SailMountCords[bbKey][shipSail.bbKey][shipSail.currRowFrame][shipSail.currColumnFrame].Item1;
            int sailMountY = ShipMountTextureCoordinates.SailMountCords[bbKey][shipSail.bbKey][shipSail.currRowFrame][shipSail.currColumnFrame].Item2;

            shipSail.location.X = location.X + sailMountX;
            shipSail.location.Y = location.Y + sailMountY;

            // ship sail update
            shipSail.Update(kstate, gameTime, windDir, windSp);

            // sinking
            if (health <= 0)
            {
                sinking               = true;
                currRowFrame          = 2;
                shipSail.currRowFrame = 2;

                timeSinceStartSinking       += gameTime.ElapsedGameTime.Milliseconds;
                sinkingTransparency          = 1 - (timeSinceStartSinking / millisecondToSink);
                shipSail.sinkingTransparency = sinkingTransparency;
                if (sinkingTransparency <= 0)
                {
                    remove = true;

                    // drop items from interior (can also include actionInv someday)
                    foreach (var obj in shipInterior.interiorObjects)
                    {
                        if (obj is IStorage || obj is IContainer)
                        {
                            obj.location.X   = location.X + RandomEvents.rand.Next(-40, 40);
                            obj.location.Y   = location.Y + RandomEvents.rand.Next(-40, 40);
                            obj.inInteriorId = Guid.Empty;
                            ItemUtility.ItemsToUpdate.Add(obj);
                        }
                    }
                    shipInterior.interiorObjects.Clear();
                }
            }

            // being boarded
            if (boardingShipInteriorId != Guid.Empty)
            {
                msBoarding    += gameTime.ElapsedGameTime.Milliseconds;
                percentBoarded = msBoarding / 8000;
                if (msBoarding > 8000)
                {
                    if (teamType != TeamType.Player) // players will initiate their boarding with controls TODO
                    {
                        NpcsBoardShip();
                    }
                }
            }
            else
            {
                msBoarding = 0;
            }

            boardingShipInteriorId = Guid.Empty;
        }
Ejemplo n.º 28
0
    public void Clear()
    {
        CurrentPiece = null;

        //DebugStatus();
    }
Ejemplo n.º 29
0
    void Awake()
    {
        nodes = new List <TilePiece> ();

        foreach (TilePiece t in transform.GetComponentsInChildren <TilePiece>())
        {
            t.vizinhos = new List <TilePiece> ();

            if (t.canGoUp)
            {
                RaycastHit[] rh = Physics.RaycastAll(t.transform.position + Vector3.forward * 2 + Vector3.up * 10, Vector3.down);

                foreach (RaycastHit hit in rh)
                {
                    TilePiece other = hit.collider.gameObject.GetComponent <TilePiece> ();
                    if (other != null)
                    {
                        if (other.canGoDown)
                        {
                            t.vizinhos.Add(other);
                        }
                        break;
                    }
                }
            }

            if (t.canGoDown)
            {
                RaycastHit[] rh = Physics.RaycastAll(t.transform.position + Vector3.back * 2 + Vector3.up * 10, Vector3.down);

                foreach (RaycastHit hit in rh)
                {
                    TilePiece other = hit.collider.gameObject.GetComponent <TilePiece> ();
                    if (other != null)
                    {
                        if (other.canGoUp)
                        {
                            t.vizinhos.Add(other);
                        }
                        break;
                    }
                }
            }

            if (t.canGoLeft)
            {
                RaycastHit[] rh = Physics.RaycastAll(t.transform.position + Vector3.left * 2 + Vector3.up * 10, Vector3.down);

                foreach (RaycastHit hit in rh)
                {
                    TilePiece other = hit.collider.gameObject.GetComponent <TilePiece> ();
                    if (other != null)
                    {
                        if (other.canGoRight)
                        {
                            t.vizinhos.Add(other);
                        }
                        break;
                    }
                }
            }

            if (t.canGoRight)
            {
                RaycastHit[] rh = Physics.RaycastAll(t.transform.position + Vector3.right * 2 + Vector3.up * 10, Vector3.down);

                foreach (RaycastHit hit in rh)
                {
                    TilePiece other = hit.collider.gameObject.GetComponent <TilePiece> ();
                    if (other != null)
                    {
                        if (other.canGoLeft)
                        {
                            t.vizinhos.Add(other);
                        }
                        break;
                    }
                }
            }

            nodes.Add(t);
        }
    }