Example #1
0
 /// <summary>
 /// Возвращает новый экземпляр EdgeTile в соответствии с настройками пользователя
 /// </summary>
 public Map.Tile.EdgeTile GetEdge()
 {
     // как покрытие юзаем тот тайл что выбран во вкладке Tiles
     Map.Tile coverTile = mapView.TileMakeNewCtrl.GetTile(Point.Empty);
     // MessageBox.Show(edgeDirection.ToString());
     return(new Map.Tile.EdgeTile(coverTile.graphicId, coverTile.Variation, (Map.Tile.EdgeTile.Direction)edgeDirection, (byte)edgeTypeID));
 }
Example #2
0
    bool CanMoveThere(Map.Tile Where)
    {
        var e = true;
        var s = Where.collider;

        if (Where == CurrentTile)
        {
            e = false;
        }
        if (Where.x > TilePosition.x && (s == Map.Tile.ColliderType.Left || CurrentTile.collider == Map.Tile.ColliderType.Right))
        {
            e = false;
        }
        if (Where.x < TilePosition.x && (s == Map.Tile.ColliderType.Right || CurrentTile.collider == Map.Tile.ColliderType.Left))
        {
            e = false;
        }
        if (Where.y > TilePosition.y && (s == Map.Tile.ColliderType.Down || CurrentTile.collider == Map.Tile.ColliderType.Up))
        {
            e = false;
        }
        if (Where.y < TilePosition.y && (s == Map.Tile.ColliderType.Up || CurrentTile.collider == Map.Tile.ColliderType.Down))
        {
            e = false;
        }
        if (s == Map.Tile.ColliderType.All)
        {
            e = false;
        }


        return(e);
    }
Example #3
0
        static Map.TileType TileTypeFromTile(Map.Tile tile, Tileset tileset)
        {
            var  tilesetTile = tile.FrontTileIndex == 0 ? tileset.Tiles[tile.BackTileIndex - 1] : tileset.Tiles[tile.FrontTileIndex - 1];
            bool obstacle    = tile.FrontTileIndex == 0 ? tileset.Tiles[tile.BackTileIndex - 1].BlockMovement
                : tileset.Tiles[tile.BackTileIndex - 1].BlockMovement || tileset.Tiles[tile.FrontTileIndex - 1].BlockMovement;

            if (tilesetTile.Sleep)
            {
                return(Map.TileType.Bed);
            }
            if (tilesetTile.SitDirection != null)
            {
                return(Map.TileType.ChairUp + (int)tilesetTile.SitDirection.Value);
            }
            if (tilesetTile.Invisible)
            {
                return(Map.TileType.Invisible);
            }
            if (obstacle)
            {
                return(Map.TileType.Obstacle);
            }

            // TODO

            return(Map.TileType.Free);
        }
Example #4
0
        public List <Map.Tile> GetTargets(Map.Tile node, int range)
        {
            List <Map.Tile> targets = new List <Map.Tile>();



            for (int x = -range; x <= range; x++)
            {
                for (int y = -range; y <= range; y++)
                {
                    if (x == 0 && y == 0)
                    {
                        continue;
                    }

                    int checkX = Mathf.RoundToInt(node.transform.position.x) + x;
                    int checkY = Mathf.RoundToInt(node.transform.position.y) + y;

                    if (checkX >= 0 && checkX < mytileMap.tiles[0].tiles.Length && checkY >= 0 && checkY < mytileMap.tiles.Length)
                    {
                        targets.Add(mytileMap.GetTileAt(new Vector2((float)checkX, (float)checkY)));
                    }
                }
            }
            if (targets.Contains(node))
            {
                targets.Remove(node);
            }

            return(targets);
        }
Example #5
0
 public void Teleport(Map.Tile where)
 {
     if (CurrentTile != null)
     {
         CurrentTile.OnQuitting();
     }
     CurrentTile = where;
     CurrentTile.Enter(this);
 }
Example #6
0
        /// <summary>
        /// Write the sector data to the provided Map instance, using the provided co-ordinates on the map as the top left
        /// of the sector, rotated by the provided rotation.
        /// </summary>
        public void WriteToMap(Map map, IntVector2 top_left, IntVector2.Rotation rotation)
        {
            IntVector2 read_position = new IntVector2(0, 0);

            for (read_position.y = 0; read_position.y < Height; ++read_position.y)
            {
                for (read_position.x = 0; read_position.x < Width; ++read_position.x)
                {
                    Map.Tile   tile           = m_tiles[read_position.x, read_position.y];
                    IntVector2 write_position = read_position.Rotated(rotation) + getRotatedWriteTranslation(rotation);
                    map.SetTile(write_position.x + top_left.x, write_position.y + top_left.y, tile);
                }
            }
        }
Example #7
0
        public void SuperAttack(Action onFinish)
        {
            Map.Tile actualTile = mytileMap.GetTileAt(new Vector2(Mathf.Round(transform.position.x), Mathf.Round(transform.position.y)));

            List <Map.Tile> targets = GetTargets(actualTile, 2);

            foreach (Map.Tile tile in targets)
            {
                if (tile.Character != null)
                {
                    tile.Character.DealDamage(attack);
                }
            }
            onFinish();
        }
Example #8
0
        /// <summary>
        /// Возвращает новый экземпляр EdgeTile в соответствии с настройками пользователя
        /// </summary>
        public Map.Tile.EdgeTile GetEdge()
        {
            // как покрытие юзаем тот тайл что выбран во вкладке Tiles
            var tile = mapView.GetNearestTile(mapView.mouseLocation);

            Map.Tile coverTile = mapView.TileMakeNewCtrl.GetTile(tile);

            var edgeDir = (Map.Tile.EdgeTile.Direction)edgeDirection;

            if ((chkAutoVariation.Checked) && (!chkAutoEdge.Checked))
            {
                edgeDir = GetRandomVariation(edgeDir);
            }

            return(new Map.Tile.EdgeTile(coverTile.graphicId, coverTile.Variation, edgeDir, (byte)edgeTypeID));
        }
Example #9
0
    public virtual void Move(Map.Tile where)
    {
        var v = Vector.Distance(where.Position, CurrentTile.Position);


        if (where.Actor != null || !CanMoveThere(where))
        {
            CantMove(where.Position);
            return;
        }



        Path.Clear();
        CreatePath(where);
        return;
    }
Example #10
0
        public void Attack(Action onFinish)
        {
            Map.Tile actualTile = mytileMap.GetTileAt(new Vector2(Mathf.Round(transform.position.x), Mathf.Round(transform.position.y)));

            List <Map.Tile> targets = GetTargets(actualTile, 1);

            foreach (Map.Tile tile in targets)
            {
                if (tile.Character != null)
                {
                    tile.Character.DealDamage(attack);
                    Debug.Log("take this");
                }
            }
            Debug.Log("Attack in your balls");
            onFinish();
        }
Example #11
0
        private Bitmap TileGenTexture(Map.Tile tile, bool transparent = false)
        {
            if (tile == null)
            {
                return(null);
            }
            int index = (int)ThingDb.FloorTiles[tile.graphicId].Variations[tile.Variation];
            // duplicate tile image
            Bitmap image = (Bitmap)mapRenderer.VideoBag.GetBitmap(index).Clone();

            if (image == null)
            {
                return(null);
            }
            // paint edges
            if (EditorSettings.Default.Draw_PreviewTexEdges)
            {
                for (int i = 0; i < tile.EdgeTiles.Count; i++)
                {
                    var          edge     = (Map.Tile.EdgeTile)tile.EdgeTiles[i];
                    ThingDb.Tile edgeEdge = ThingDb.EdgeTiles[edge.Edge];
                    ThingDb.Tile edgeTile = ThingDb.FloorTiles[edge.Graphic];
                    byte         dirNum   = (byte)edge.Dir;
                    // fix for MudEdge

                    if (dirNum < edgeEdge.Variations.Count)
                    {
                        int indexedge = (int)edgeEdge.Variations[(byte)edge.Dir];
                        int indextile = (int)edgeTile.Variations[edge.Variation];

                        mapRenderer.VideoBag.ApplyEdgeMask(image, indexedge, indextile);
                    }
                }
            }

            if (transparent)
            {
                var bmpShader = new BitmapShader(image);
                bmpShader.LockBitmap();
                bmpShader.MakeSemitransparent();
                image = bmpShader.UnlockBitmap();
            }

            return(image);
        }
Example #12
0
 /// <summary>
 /// Turns the data in the map_data array into actual world objects.
 /// </summary>
 private void writeMapToWorld()
 {
     for (int x = 0; x < m_map.Width; ++x)
     {
         for (int y = 0; y < m_map.Height; ++y)
         {
             Map.Tile tile = m_map.GetTile(x, y);
             if (m_tilePrefabs.ContainsKey(tile))
             {
                 Vector3 new_tile_pos = new Vector3(
                     m_environment.Bounds.min.x + TileSize * (x + 0.5f),
                     0,
                     m_environment.Bounds.min.z + TileSize * (y + 0.5f)
                     );
                 GameObject new_tile = Instantiate(m_tilePrefabs[tile], new_tile_pos, m_tilePrefabs[tile].transform.rotation) as GameObject;
                 new_tile.transform.parent = m_environment.transform;
             }
         }
     }
 }
Example #13
0
        /// <summary>
        /// Construct a Sector instance from a serialised text representation.
        /// </summary>
        /// <param name="tile_string"></param>
        public Sector(string tile_string)
        {
            ContainsEntrance  = false;
            ContainsExit      = false;
            ContainsObjective = false;

            //Iterate through each row of the data...
            string[] tile_rows = tile_string.Split(
                new String[] { "\r\n", Environment.NewLine },
                Height,
                StringSplitOptions.None
                );

            if (tile_rows.Length != Height)
            {
                throw new Exception(string.Format("Sector data contains {0} rows. Expected {1}", tile_rows.Length, Height));
            }

            for (int y = 0; y < Height; ++y)
            {
                string row = tile_rows[y];
                if (row.Length != Width)
                {
                    throw new Exception(
                              string.Format("Sector data contains {0} tiles on row {1}. Expected {2}", row.Length, y, Width)
                              );
                }
                //... and each character of each row.
                for (int x = 0; x < Width; ++x)
                {
                    Map.Tile tile = (Map.Tile)row[x];

                    //Update Contains booleans.
                    ContainsEntrance  |= tile == Map.Tile.Entrance;
                    ContainsExit      |= tile == Map.Tile.Exit;
                    ContainsObjective |= tile == Map.Tile.Objective;

                    m_tiles[x, y] = tile;
                }
            }
        }
Example #14
0
        public void Attack(Action onFinish)
        {
            sonidoAtacar.Play();

            if (anim != null)
            {
                anim.SetTrigger("J");
                Map.Tile actualTile = mytileMap.GetTileAt(new Vector2(Mathf.Round(transform.position.x), Mathf.Round(transform.position.y)));

                List <Map.Tile> targets = GetTargets(actualTile, 1);
                foreach (Map.Tile tile in targets)
                {
                    if (tile.Character != null)
                    {
                        tile.Character.DealDamage(attack);
                    }
                }

                onFinish();
            }
        }
Example #15
0
        public void UpdateListView(object sender, EventArgs e)
        {
            // force update data
            edgeDirection = 0;
            edgeTypeID    = GetSelTileTypeIndex();
            listEdgeImages.VirtualListSize = 0;
            List <uint> variations = ThingDb.EdgeTiles[edgeTypeID].Variations;

            listEdgeImages.VirtualListSize = variations.Count;
            // not yet created
            if (listEdgeImages.LargeImageList == null)
            {
                listEdgeImages.LargeImageList = new ImageList();
            }
            // clear ImageList
            ImageList imglist = listEdgeImages.LargeImageList;

            foreach (Image img in imglist.Images)
            {
                img.Dispose();
            }
            imglist.Images.Clear();
            imglist.ImageSize = new Size(46, 46);
            // update ImageList showing edge type selected by user
            Map.Tile coverTile   = mapView.TileMakeNewCtrl.GetTile(Point.Empty, true);
            int      coverSprite = (int)coverTile.Variations[coverTile.Variation];
            int      varns       = variations.Count;

            if (mapView.TileMakeNewCtrl.edgeBox.Items.Count > 0)
            {
                mapView.TileMakeNewCtrl.edgeBox.SelectedIndex = comboEdgeType.SelectedIndex;
            }

            for (int varn = 0; varn < varns; varn++)
            {
                Bitmap edge = new Bitmap(46, 46);
                videoBag.ApplyEdgeMask(edge, (int)variations[varn], coverSprite);
                imglist.Images.Add(edge);
            }
        }
Example #16
0
 public static void Load(DataLoadScript loader, ModInfo modinfo)
 {
     foreach (Func <DataStructure.Map.Tile> tileload in loader.TileList)
     {
         Map.Tile tile = tileload();
         tile.modInfo = modinfo;
         StaticUse.mainstorage.TileStorage.Add(tile);
         _ = tile.sprite;
     }
     foreach (Func <DataStructure.Map.Material> materialload in loader.MaterialList)
     {
         Map.Material material = materialload();
         material.modInfo = modinfo;
         StaticUse.mainstorage.MaterialStorage.Add(material);
     }
     foreach (Func <DataStructure.Map.BaseChunk> basechunkload in loader.BaseChunkList)
     {
         Map.BaseChunk basechunk = basechunkload();
         basechunk.modInfo = modinfo;
         StaticUse.mainstorage.BaseChunkStorage.Add(basechunk);
     }
 }
Example #17
0
 public TileContainer(Map.Tile tile1, Point pos)
 {
     Data     = tile1;
     Position = pos;
 }
Example #18
0
        public void Update(Point mousePt)
        {
            bool iWalls = (MapInterface.CurrentMode >= EditMode.WALL_PLACE && MapInterface.CurrentMode <= EditMode.WALL_CHANGE);
            bool iTiles = (MapInterface.CurrentMode >= EditMode.FLOOR_PLACE && MapInterface.CurrentMode <= EditMode.EDGE_PLACE);
            bool iObjs  = (MapInterface.CurrentMode == EditMode.OBJECT_SELECT);

            // Search for walls/tiles/objects under cursor

            statusLocation = String.Format(FORMAT_COORDINATES, mousePt.X, mousePt.Y);
            statusMapItem  = "";
            statusPolygon  = "";

            // Wall tracking
            if (iWalls)
            {
                var      wallPt = MapView.GetNearestWallPoint(mousePt);
                Map.Wall wall   = map.Walls.ContainsKey(wallPt) ? map.Walls[wallPt] : null;
                statusLocation = String.Format(FORMAT_COORDINATES, wallPt.X, wallPt.Y);

                if (wall != null)
                {
                    statusMapItem = String.Format(FORMAT_WALL_INFO, wall.Material, wall.Variation);
                }



                if (prevWall != wall)
                {
                    prevWall         = wall;
                    updateStatusbars = true;
                }
            }
            else
            {
                prevWall = null;
            }



            // Tile tracking
            if (iTiles)
            {
                var      tilePt = MapView.GetNearestTilePoint(mousePt);
                Map.Tile tile   = map.Tiles.ContainsKey(tilePt) ? map.Tiles[tilePt] : null;
                statusLocation = String.Format(FORMAT_COORDINATES, tilePt.X, tilePt.Y);

                if (tile != null)
                {
                    statusMapItem = String.Format(FORMAT_TILE_INFO, tile.Graphic, tile.Variation);
                    edgeCount     = tile.EdgeTiles.Count;
                    if (tile.EdgeTiles.Count > 0)
                    {
                        statusMapItem += String.Format(FORMAT_EDGE_COUNT, tile.EdgeTiles.Count);

                        foreach (Map.Tile.EdgeTile edge in tile.EdgeTiles)
                        {
                            statusMapItem += String.Format(FORMAT_EDGE_INFO, ThingDb.FloorTileNames[edge.Graphic], edge.Variation, edge.Dir, ThingDb.EdgeTileNames[edge.Edge]);
                        }
                    }
                }

                if (prevTile != tile)
                {
                    prevTile         = tile;
                    updateStatusbars = true;
                }
                if (prevEdge != edgeCount && tile != null)
                {
                    prevEdge         = tile.EdgeTiles.Count;
                    updateStatusbars = true;
                }
            }
            else
            {
                prevTile = null;
            }



            // Object tracking
            if (iObjs)
            {
                Map.Object obj = MapInterface.ObjectSelect(mousePt);
                if (obj == null)
                {
                    return;
                }

                statusMapItem = String.Format(FORMAT_OBJECT_INFO, obj.Name, obj.Extent);



                if (prevObj != obj)
                {
                    prevObj          = obj;
                    updateStatusbars = true;
                }
            }
            else
            {
                prevObj = null;
            }


            // Polygon tracking
            Map.Polygon ins   = null;
            var         ptFlt = new PointF(mousePt.X, mousePt.Y);
            int         i     = -1;

            foreach (Map.Polygon poly in map.Polygons)
            {
                i++;
                if (poly.IsPointInside(ptFlt))
                {
                    statusPolygon = poly.Name;
                    ins           = poly;

                    if (MainWindow.Instance.mapView.PolygonEditDlg.Visible && !MainWindow.Instance.mapView.PolygonEditDlg.LockedBox.Checked && MapInterface.CurrentMode == EditMode.POLYGON_RESHAPE && (MainWindow.Instance.mapView.PolygonEditDlg.SelectedPolygon != MainWindow.Instance.mapView.PolygonEditDlg.SuperPolygon || MainWindow.Instance.mapView.PolygonEditDlg.SelectedPolygon == null))
                    {
                        MainWindow.Instance.mapView.PolygonEditDlg.listBoxPolygons.SelectedIndex = i;
                        MainWindow.Instance.mapView.PolygonEditDlg.SelectedPolygon = ins;
                        //System.Windows.Forms.MessageBox.Show("ON:");
                    }
                    break;
                }
            }

            /*
             * if (ins == null)
             * {
             *
             *  MainWindow.Instance.mapView.PolygonEditDlg.listBoxPolygons.ClearSelected();
             *  MainWindow.Instance.mapView.PolygonEditDlg.SelectedPolygon = null;
             *   // System.Windows.Forms.MessageBox.Show("OFF:");
             * }
             */
            if (prevPoly != ins)
            {
                prevPoly         = ins;
                updateStatusbars = true;
            }
        }
Example #19
0
            /// <summary>
            /// Attempts to get the best location to move to. Returns Objects.Location.Invalid if unsuccessful.
            /// </summary>
            /// <param name="setting">The setting to use.</param>
            /// <param name="tileCollection">The tiles that are visible on screen.</param>
            /// <param name="creaturesOnScreen">The creatures that are visible on screen.</param>
            /// <returns></returns>
            public Objects.Location GetBestLocation(Target.Setting setting, Map.TileCollection tileCollection,
                                                    IEnumerable <Objects.Creature> creaturesOnScreen, Stack <Objects.Location> backtrackedLocations = null)
            {
                if (this.Creature == null)
                {
                    return(null);
                }
                Map.Tile playerTile = tileCollection.GetTile(count: this.Parent.Client.Player.ID),
                         targetTile = tileCollection.GetTile(count: this.Creature.ID);
                if (playerTile == null || targetTile == null)
                {
                    return(null);
                }
                Map.TileCollection             adjacentTiles = tileCollection.GetAdjacentTileCollection(targetTile);
                List <Objects.PathFinder.Node> pfNodes       = null;
                int closest = 15;

                Objects.Location bestLocation = Objects.Location.Invalid;
                switch (setting.FightStance)
                {
                case Enums.FightStance.FollowDiagonalOnly:
                    if (playerTile.WorldLocation.IsAdjacentDiagonalOnly(targetTile.WorldLocation))
                    {
                        break;
                    }
                    int closestNonDiagonal = 15;
                    Objects.Location bestNonDiagonalLocation = Objects.Location.Invalid;
                    foreach (Map.Tile tile in adjacentTiles.GetTiles())
                    {
                        if (!tile.IsWalkable())
                        {
                            continue;
                        }
                        //if (!tile.WorldLocation.IsAdjacentDiagonalOnly(targetTile.WorldLocation)) continue;
                        pfNodes = playerTile.WorldLocation.GetTilesToLocation(this.Parent.Client,
                                                                              tile.WorldLocation, tileCollection, this.Parent.PathFinder, true).ToList <Objects.PathFinder.Node>();
                        if (pfNodes.Count > 0)
                        {
                            if (this.Parent.CurrentSettings.AllowDiagonalMovement &&
                                playerTile.WorldLocation.IsAdjacentDiagonalOnly(targetTile.WorldLocation))
                            {
                                continue;
                            }

                            if (pfNodes.Count - 1 < closest &&
                                tile.WorldLocation.IsAdjacentDiagonalOnly(targetTile.WorldLocation))
                            {
                                closest      = pfNodes.Count - 1;
                                bestLocation = tile.WorldLocation;
                            }
                            else if (pfNodes.Count - 1 < closestNonDiagonal &&
                                     tile.WorldLocation.IsAdjacentNonDiagonalOnly(targetTile.WorldLocation))
                            {
                                closestNonDiagonal      = pfNodes.Count - 1;
                                bestNonDiagonalLocation = tile.WorldLocation;
                            }
                        }
                    }
                    if (!bestLocation.IsValid())
                    {
                        bestLocation = bestNonDiagonalLocation;
                    }
                    break;

                case Enums.FightStance.FollowStrike:
                    if (playerTile.WorldLocation.IsAdjacentNonDiagonalOnly(targetTile.WorldLocation))
                    {
                        break;
                    }
                    foreach (Map.Tile tile in adjacentTiles.GetTiles())
                    {
                        if (!tile.WorldLocation.IsAdjacentNonDiagonalOnly(targetTile.WorldLocation))
                        {
                            continue;
                        }
                        pfNodes = playerTile.WorldLocation.GetTilesToLocation(this.Parent.Client,
                                                                              tile.WorldLocation, tileCollection, this.Parent.PathFinder, true).ToList <Objects.PathFinder.Node>();
                        if (pfNodes.Count > 0 && pfNodes.Count - 1 < closest &&
                            (!this.Parent.CurrentSettings.AllowDiagonalMovement ||
                             playerTile.WorldLocation.IsAdjacentDiagonalOnly(targetTile.WorldLocation)))
                        {
                            closest      = pfNodes.Count - 1;
                            bestLocation = tile.WorldLocation;
                        }
                    }
                    break;

                case Enums.FightStance.DistanceFollow:
                case Enums.FightStance.DistanceWait:
                    // map creature tiles and the path nodes to them from the player
                    Dictionary <Map.Tile, List <Objects.PathFinder.Node> > creatureTiles =
                        new Dictionary <Map.Tile, List <Objects.PathFinder.Node> >();
                    // add the current target
                    creatureTiles.Add(targetTile,
                                      this.Creature.GetTilesToCreature(tileCollection, this.Parent.PathFinder).ToList <Objects.PathFinder.Node>());
                    // check whether to add other monsters as well
                    if (this.Parent.CurrentSettings.ConsiderAllMonstersWhenKeepingAway)
                    {
                        foreach (Objects.Creature c in creaturesOnScreen)
                        {
                            Map.Tile t = tileCollection.GetTile(count: c.ID);
                            if (t != null && !creatureTiles.ContainsKey(t))
                            {
                                creatureTiles.Add(t,
                                                  c.GetTilesToCreature(tileCollection, this.Parent.PathFinder).ToList <Objects.PathFinder.Node>());
                            }
                        }
                    }

                    // check if the player needs to move
                    // also set the player's location as default location to return
                    bool needToMove = false;
                    bestLocation = playerTile.WorldLocation;
                    foreach (var keypair in creatureTiles)
                    {
                        // check if creature can reach the player
                        if (keypair.Value.Count == 0)
                        {
                            continue;
                        }

                        if (keypair.Value.Count < setting.DistanceRange ||
                            (setting.FightStance == Enums.FightStance.DistanceFollow && keypair.Value.Count > setting.DistanceRange))
                        {
                            needToMove = true;
                        }
                    }
                    if (!needToMove)
                    {
                        break;
                    }

                    int      bestRange = 1;
                    Map.Tile bestTile  = playerTile;
                    // calculate distance to the player's tile
                    foreach (var keypair in creatureTiles)
                    {
                        pfNodes = keypair.Value;
                        if (pfNodes.Count == 0)
                        {
                            continue;
                        }
                        int count = pfNodes.Count;
                        bestRange += Math.Abs(setting.DistanceRange - count) * (count < setting.DistanceRange ? 2 : 1);
                    }

                    if (backtrackedLocations != null && backtrackedLocations.Count > 0)
                    {
                        Objects.Location peekLoc = backtrackedLocations.Peek();
                        if (peekLoc.IsOnScreen(playerTile.WorldLocation))
                        {
                            bestLocation = peekLoc;
                            break;
                        }
                    }
                    // calculate and set
                    foreach (Map.Tile t in tileCollection.GetAdjacentTileCollection(playerTile).GetTiles())
                    {
                        if (t == null || !t.IsWalkable())
                        {
                            continue;
                        }
                        if (this.Parent.CurrentSettings.AllowDiagonalMovement &&
                            playerTile.WorldLocation.IsAdjacentDiagonalOnly(t.WorldLocation))
                        {
                            continue;
                        }

                        // calculate distance for creatures
                        int distance = 0;
                        foreach (var keypair in creatureTiles)
                        {
                            pfNodes = keypair.Key.WorldLocation.GetTilesToLocation(this.Parent.Client, t.WorldLocation,
                                                                                   tileCollection, this.Parent.PathFinder, true).ToList <Objects.PathFinder.Node>();
                            if (pfNodes.Count == 0)
                            {
                                continue;
                            }
                            int count = pfNodes.Count - 1;
                            distance += Math.Abs(setting.DistanceRange - count) * (count < setting.DistanceRange ? 2 : 1);
                        }

                        // get next tile in same general direction
                        bool good       = false;
                        int  directionX = playerTile.WorldLocation.X - t.WorldLocation.X,
                             directionY = playerTile.WorldLocation.Y - t.WorldLocation.Y;
                        foreach (Map.Tile nextTile in tileCollection.GetAdjacentTileCollection(t).GetTiles())
                        {
                            if (nextTile == null || !nextTile.IsWalkable())
                            {
                                continue;
                            }
                            if (t.WorldLocation.X - nextTile.WorldLocation.X != directionX &&
                                t.WorldLocation.Y - nextTile.WorldLocation.Y != directionY)
                            {
                                continue;
                            }
                            if (nextTile == playerTile)
                            {
                                continue;
                            }

                            good = true;
                            break;
                        }
                        if (!good)
                        {
                            continue;
                        }

                        // check of tile is better than previous tile
                        if (bestRange > distance)
                        {
                            bestRange    = distance;
                            bestLocation = t.WorldLocation;
                        }
                    }
                    break;

                case Enums.FightStance.FollowEconomic:
                    break;
                }
                return(bestLocation);
            }
Example #20
0
            /// <summary>
            /// Attempts to get the best setting for this target. Also sets CurrentSettingIndex. Returns null if unsuccessful.
            /// </summary>
            /// <param name="creaturesOnScreen">A collection of creatures visible on screen.</param>
            /// <param name="playersOnScreen">A collection of players visible on screen.</param>
            /// <param name="tileCollection">A collection of tiles visible on screen.</param>
            /// <param name="setCreature">Whether to set this target's Creature.</param>
            /// <returns></returns>
            public Target.Setting GetBestSetting(IEnumerable <Objects.Creature> creaturesOnScreen,
                                                 IEnumerable <Objects.Creature> playersOnScreen, Map.TileCollection tileCollection,
                                                 bool setCreature)
            {
                // check if there are any settings to use
                bool found = false;

                foreach (Target.Setting s in this.GetSettings())
                {
                    if (s.UseThisSetting)
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    return(null);
                }

                // set up the player's tile and other variables
                Map.Tile playerTile = tileCollection.GetTile(count: this.Parent.Client.Player.ID);
                if (playerTile == null)
                {
                    return(null);
                }
                List <Objects.Creature> creatures = new List <Objects.Creature>(),
                                        players   = new List <Objects.Creature>();

                foreach (Objects.Creature c in creaturesOnScreen)
                {
                    if (c.Name.ToLower() == this.Name.ToLower())
                    {
                        creatures.Add(c);
                    }
                }
                foreach (Objects.Creature p in playersOnScreen.ToArray())
                {
                    if (p.ID != this.Parent.Client.Player.ID)
                    {
                        players.Add(p);
                    }
                }

                // calculate best setting
                int bestCount = 0, bestIndex = 0, index = 0;

                Target.Setting   bestSetting = null;
                Objects.Creature bestCreature = null;
                foreach (Target.Setting setting in this.GetSettings())
                {
                    if (!setting.UseThisSetting)
                    {
                        continue;
                    }
                    int count = 0,
                        bestCreatureDistance      = setting.Range + 1;
                    Objects.Creature tempCreature = null;
                    foreach (Objects.Creature c in creatures)
                    {
                        if (!c.IsVisible)
                        {
                            continue;
                        }
                        Map.Tile creatureTile = tileCollection.GetTile(count: c.ID);
                        if (creatureTile == null)
                        {
                            continue;
                        }
                        if (!playerTile.WorldLocation.IsOnScreen(creatureTile.WorldLocation))
                        {
                            continue;
                        }
                        if (this.Parent.CurrentSettings.FriendlyMode && players.Count > 0 && !c.HasAttackedMeRecently(4000))
                        {
                            continue;
                        }
                        if (setting.MustBeShootable && !c.IsShootable(tileCollection))
                        {
                            continue;
                        }
                        var pfNodes = c.GetTilesToCreature(tileCollection, this.Parent.PathFinder)
                                      .ToList <Objects.PathFinder.Node>();
                        if (setting.MustBeReachable && pfNodes.Count == 0)
                        {
                            continue;
                        }
                        if ((pfNodes.Count > 0 ? pfNodes.Count : playerTile.WorldLocation.DistanceTo(creatureTile.WorldLocation)) > setting.Range)
                        {
                            continue;
                        }
                        count++;

                        if (setCreature)
                        {
                            int distance = pfNodes.Count > 0 ?
                                           pfNodes.Count :
                                           (int)playerTile.WorldLocation.DistanceTo(creatureTile.WorldLocation);
                            if (distance < bestCreatureDistance)
                            {
                                bestCreatureDistance = distance;
                                tempCreature         = c;
                            }
                        }
                    }

                    if (count == 0 || count < setting.Count)
                    {
                        continue;
                    }
                    if (count > bestCount)
                    {
                        bestCount    = count;
                        bestSetting  = setting;
                        bestIndex    = index;
                        bestCreature = tempCreature;
                    }

                    index++;
                }
                this.CurrentSettingIndex = bestSetting != null ? bestIndex : -1;
                if (bestSetting != null && bestCreature != null)
                {
                    this.Creature = bestCreature;
                }
                return(bestSetting);
            }
Example #21
0
 public TileDrawData(Map.Tile tile, Bitmap tex)
 {
     Texture = tex;
     Tile    = tile;
 }
Example #22
0
            private void Run()
            {
                while (true)
                {
                    try
                    {
                        this.ResetEvent.Wait();
                        if (this.TargetExecutedBegin != null)
                        {
                            this.TargetExecutedBegin(this.CurrentTarget);
                        }

                        Objects.Client   client      = this.Parent.Client;
                        Objects.Creature oldCreature = null;

                        while (!this.Cancel)
                        {
                            this.ResetEventCacheUpdated.WaitOne();

                            if (this.Cancel)
                            {
                                break;
                            }

                            // get best setting
                            Target.Setting setting = this.CurrentTarget.GetBestSetting(this.CachedCreatures,
                                                                                       this.CachedPlayers, this.CachedTiles, true);
                            if (setting == null)
                            {
                                break;
                            }

                            // check if we should revert to older creature if sticky is on
                            // or if new creature is in no better position
                            if (oldCreature != null &&
                                oldCreature != this.CurrentTarget.Creature &&
                                oldCreature.IsVisible &&
                                client.Player.Location.IsOnScreen(oldCreature.Location))
                            {
                                if (this.Parent.CurrentSettings.StickToCreature)
                                {
                                    this.CurrentTarget.Creature = oldCreature;
                                }
                                else
                                {
                                    int oldDist = (int)client.Player.Location.DistanceTo(oldCreature.Location),
                                        newDist = this.CurrentTarget.Creature != null ?
                                                  (int)client.Player.Location.DistanceTo(this.CurrentTarget.Creature.Location) :
                                                  100;
                                    if (oldDist < newDist + 2)
                                    {
                                        this.CurrentTarget.Creature = oldCreature;
                                    }
                                }
                            }
                            oldCreature = this.CurrentTarget.Creature;

                            Objects.Location playerLoc = client.Player.Location,
                                             targetLoc = this.CurrentTarget.Creature.Location;

                            #region targeting checks and whatnot
                            // check if the creature is dead
                            if (this.CurrentTarget.Creature.IsDead)
                            {
                                break;
                            }

                            // check if creature is about to become a corpse
                            if (this.CurrentTarget.Creature.IsVisible &&
                                this.CurrentTarget.Creature.HealthPercent == 0)
                            {
                                continue;
                            }

                            // check if creature is still on screen, stop attacking and looping if so
                            if (!playerLoc.IsOnScreen(targetLoc))
                            {
                                this.CancelAttack();
                                break;
                            }

                            // check if creature if reachable and/or shootable
                            // stop attacking and break if settings says they must be
                            if ((setting.MustBeReachable && !this.CurrentTarget.Creature.IsReachable(this.CachedTiles, this.Parent.PathFinder)) ||
                                (setting.MustBeShootable && !this.CurrentTarget.Creature.IsShootable(this.CachedTiles)))
                            {
                                this.CancelAttack();
                                break;
                            }

                            // check if player is attacking the wrong target
                            if (client.Player.Target != this.CurrentTarget.Creature.ID)
                            {
                                this.CurrentTarget.Creature.Attack();
                                Thread.Sleep(100);
                            }

                            // set fight stance+mode and move accordingly
                            Map.Tile playerTile   = this.CachedTiles.GetTile(count: client.Player.ID),
                                     creatureTile = this.CachedTiles.GetTile(count: this.CurrentTarget.Creature.ID);
                            if (playerTile == null || creatureTile == null)
                            {
                                this.CancelAttack();
                                break;
                            }
                            switch (setting.FightStance)
                            {
                            case Enums.FightStance.Stand:
                                if (client.Player.FightStance != Enums.FightStance.Stand)
                                {
                                    client.Player.FightStance = Enums.FightStance.Stand;
                                }
                                break;

                            case Enums.FightStance.Follow:
                                if (client.Player.FightStance != Enums.FightStance.Follow)
                                {
                                    client.Player.FightStance = Enums.FightStance.Follow;
                                }
                                break;

                            case Enums.FightStance.FollowDiagonalOnly:
                            case Enums.FightStance.DistanceFollow:
                            case Enums.FightStance.DistanceWait:
                            case Enums.FightStance.FollowStrike:
                                if (client.Player.FightStance != Enums.FightStance.Stand)
                                {
                                    client.Player.FightStance = Enums.FightStance.Stand;
                                }
                                if (client.Player.IsWalking)
                                {
                                    break;
                                }
                                Objects.Location bestLoc = this.CurrentTarget.GetBestLocation(setting, this.CachedTiles, this.CachedCreatures);
                                if (bestLoc.IsValid() && client.Player.GoTo != bestLoc)
                                {
                                    client.Player.GoTo = bestLoc;
                                }
                                break;
                            }

                            // shoot rune or spell
                            if (client.Player.HealthPercent >= this.Parent.CurrentSettings.MinimumHealthToShoot &&
                                this.CurrentTarget.Creature.HealthPercent > 0)
                            {
                                ushort runeID = 0;
                                if ((runeID = setting.GetRuneID()) != 0)
                                {
                                    Objects.Item rune = client.Inventory.GetItem(runeID);
                                    if (rune != null)
                                    {
                                        if (!this.StopwatchExhaust.IsRunning ||
                                            this.StopwatchExhaust.ElapsedMilliseconds >= this.Parent.CurrentSettings.Exhaust)
                                        {
                                            if (setting.RuneIsAoE()) // todo: test this
                                            {
                                                Map.Tile aoeTile = this.Parent.GetAreaEffectTile(setting.GetAreaEffect(),
                                                                                                 this.CachedTiles, this.CurrentTarget.Creature);
                                                if (aoeTile != null)
                                                {
                                                    rune.UseOnTile(aoeTile);
                                                    this.StopwatchExhaust.Restart();
                                                }
                                            }
                                            else if (this.CurrentTarget.Creature.IsShootable(this.CachedTiles))
                                            {
                                                rune.UseOnBattleList(this.CurrentTarget.Creature);
                                                this.StopwatchExhaust.Restart();
                                            }
                                        }
                                    }
                                }
                                else if (!string.IsNullOrEmpty(setting.Spell))
                                {
                                    // todo: add aoe spells
                                    if (playerLoc.IsAdjacentNonDiagonalOnly(targetLoc))
                                    {
                                        Enums.Direction direction = Enums.Direction.Down;
                                        int             diffX     = playerLoc.X - targetLoc.X,
                                                        diffY = playerLoc.Y - targetLoc.Y;
                                        if (diffX > 0)
                                        {
                                            direction = Enums.Direction.Left;
                                        }
                                        else if (diffX < 0)
                                        {
                                            direction = Enums.Direction.Right;
                                        }
                                        else if (diffY > 0)
                                        {
                                            direction = Enums.Direction.Up;
                                        }
                                        else if (diffY < 0)
                                        {
                                            direction = Enums.Direction.Down;
                                        }
                                        if (client.Player.Direction != direction)
                                        {
                                            client.Packets.Turn(direction);
                                            for (int i = 0; i < 6; i++)
                                            {
                                                Thread.Sleep(50);
                                                if ((Enums.Direction)client.Player.Direction == direction)
                                                {
                                                    break;
                                                }
                                            }
                                        }
                                        if (client.Player.Direction == direction &&
                                            (!this.StopwatchExhaust.IsRunning || this.StopwatchExhaust.ElapsedMilliseconds > this.Parent.CurrentSettings.Exhaust))
                                        {
                                            client.Packets.Say(setting.Spell);
                                            this.StopwatchExhaust.Restart();
                                        }
                                    }
                                }
                            }
                            #endregion
                        }

                        if (this.TargetExecutedEnd != null)
                        {
                            this.TargetExecutedEnd(this.CurrentTarget);
                        }
                        this.ResetEvent.Reset();
                        this.Cancel = false;
                    }
                    catch (Exception ex)
                    {
                        if (this.ErrorOccurred != null)
                        {
                            this.ErrorOccurred(ex);
                        }
                    }
                }
            }
Example #23
0
        public DataStorage data;//this is ref
        public void Initialize()
        {
            load.MaterialList.Add(() =>
            {
                Map.Material material       = new Map.Material();
                material.CodeName           = @"material/none";
                material.Name["KOR"]        = "없음";
                material.Name["ENG"]        = "None";
                material.Explanation["KOR"] = "재료 없음";
                material.Explanation["ENG"] = "No Material";
                return(material);
            });
            load.MaterialList.Add(() =>
            {
                Map.Material material       = new Map.Material();
                material.CodeName           = @"material/wood";
                material.Name["KOR"]        = "나무";
                material.Name["ENG"]        = "Wood";
                material.Explanation["KOR"] = "불에 잘타는 나무";
                return(material);
            });

            //Material load end

            load.TileList.Add(() =>
            {
                Map.Tile tile           = new Map.Tile();
                tile.CodeName           = @"tile/floor/empty";
                tile.Name["KOR"]        = "빈칸";
                tile.Name["ENG"]        = "Empty";
                tile.Explanation["KOR"] = "설명";
                tile.Explanation["ENG"] = "explain";
                tile.DeathHelp["KOR"]   = "이타일효과로 뒤졌을때 뜨는 도움말";
                tile.DeathHelp["ENG"]   = "help when died by this tile";
                tile.ImagePath          = @"graphic\tile\floor\empty.png";
                tile.Priority           = Drawable.EPriority.Floor;
                tile.Attribute.Add("PlayerPassable", true);
                tile.Attribute.Add("LightPassable", true);
                tile.Event.Add("Update", () =>
                {
                });
                tile.Event.Add("PlayerOnTile", () =>
                {
                });

                return(tile);
            });
            load.TileList.Add(() =>
            {
                Map.Tile tile           = new Map.Tile();
                tile.CodeName           = @"tile/floor/grass";
                tile.Name["KOR"]        = "잔디";
                tile.Explanation["KOR"] = "설명";
                tile.DeathHelp["KOR"]   = "이타일효과로 뒤졌을때 뜨는 도움말";
                tile.ImagePath          = @"graphic\tile\floor\grass.png";
                tile.Priority           = Drawable.EPriority.Floor;
                tile.Attribute.Add("PlayerPassable", true);
                tile.Attribute.Add("LightPassable", true);
                return(tile);
            });

            //Tile load end
        }
Example #24
0
        public bool Move(int x, int y, uint ticks, TravelType travelType, out bool eventTriggered,
                         bool displayOuchIfBlocked       = true, CharacterDirection?prevDirection = null,
                         bool updateDirectionIfNotMoving = true) // x,y in tiles
        {
            eventTriggered = false;

            if (player.MovementAbility == PlayerMovementAbility.NoMovement)
            {
                return(false);
            }

            bool canMove = true;
            var  map     = Map.Map;
            int  newX    = Position.X + x;
            int  newY    = Position.Y + y;

            Map.Tile tile = null;

            if (!map.IsWorldMap)
            {
                // Don't leave the map.
                if (newX < 0 || newY < 0 || newX >= map.Width || newY >= map.Height)
                {
                    canMove = false;
                }
                else
                {
                    tile = Map[(uint)newX, (uint)newY];
                }
            }
            else
            {
                while (newX < 0)
                {
                    newX += map.Width;
                }
                while (newY < 0)
                {
                    newY += map.Height;
                }

                tile = Map[(uint)newX, (uint)newY];
            }

            if (canMove)
            {
                var tileset = mapManager.GetTilesetForMap(map);
                canMove = tile.AllowMovement(tileset, travelType);

                if (!canMove && travelType == TravelType.Swim && tile.AllowMovement(tileset, TravelType.Walk))
                {
                    canMove = true; // go on land
                }
                if (!travelType.IgnoreEvents())
                {
                    // check if there is a place, teleport, riddlemouth, chest
                    // or door event at the new position
                    var mapEventId = Map[(uint)newX, (uint)newY]?.MapEventId;

                    if (mapEventId > 0 && game.CurrentSavegame.IsEventActive(map.Index, mapEventId.Value - 1))
                    {
                        var  trigger         = EventTrigger.Move;
                        bool lastEventStatus = false;

                        bool HasSpecialEvent(Event ev, out EventType?eventType)
                        {
                            eventType = null;

                            if (ev.Type == EventType.EnterPlace ||
                                (ev is TeleportEvent teleportEvent && teleportEvent.Transition != TeleportEvent.TransitionType.WindGate) ||
                                ev.Type == EventType.Riddlemouth ||
                                (ev.Type == EventType.Chest && Map.Map.IsWorldMap) ||
                                (ev is DoorEvent doorEvent && game.CurrentSavegame.IsDoorLocked(doorEvent.DoorIndex)))
                            {
                                eventType = ev.Type;
                                return(true);
                            }

                            if (ev.Next == null)
                            {
                                return(false);
                            }

                            if (ev is ConditionEvent conditionEvent)
                            {
                                ev = conditionEvent.ExecuteEvent(map, game, ref trigger, (uint)Position.X,
                                                                 (uint)Position.Y, game.CurrentTicks, ref lastEventStatus, out bool aborted, out _);

                                if (aborted || ev == null)
                                {
                                    return(false);
                                }
                            }

                            if (ev.Next == null)
                            {
                                return(false);
                            }

                            return(HasSpecialEvent(ev.Next, out eventType));
                        }

                        var mapAtNewPosition = Map.GetMapFromTile((uint)newX, (uint)newY);

                        if (HasSpecialEvent(mapAtNewPosition.EventList[(int)mapEventId.Value - 1], out var type))
                        {
                            if ((type != EventType.Teleport || !travelType.BlockedByTeleport()) &&
                                EventExtensions.TriggerEventChain(mapAtNewPosition, game, EventTrigger.Move, (uint)x, (uint)y, ticks,
                                                                  mapAtNewPosition.EventList[(int)mapEventId.Value - 1]))
                            {
                                eventTriggered = true;
                                return(false);
                            }
                            else
                            {
                                canMove = false;
                            }
                        }
                    }
                }

                if (canMove && tile.Type == Data.Map.TileType.Water && travelType.BlockedByWater())
                {
                    canMove = false;
                }
            }

            if (canMove)
            {
                var oldMap  = map;
                int scrollX = 0;
                int scrollY = 0;
                prevDirection ??= Direction;
                var newDirection       = CharacterDirection.Down;
                var lastPlayerPosition = new Position(player.Position);

                if (x > 0 && (map.IsWorldMap || (newX >= 6 && Map.ScrollX < Map.Map.Width - RenderMap2D.NUM_VISIBLE_TILES_X)))
                {
                    scrollX = 1;
                }
                else if (x < 0 && (map.IsWorldMap || (newX <= map.Width - 7 && Map.ScrollX > 0)))
                {
                    scrollX = -1;
                }

                if (y > 0 && (map.IsWorldMap || (newY >= 5 && Map.ScrollY < Map.Map.Height - RenderMap2D.NUM_VISIBLE_TILES_Y)))
                {
                    scrollY = 1;
                }
                else if (y < 0 && (map.IsWorldMap || (newY <= map.Height - 6 && Map.ScrollY > 0)))
                {
                    scrollY = -1;
                }

                if (y > 0)
                {
                    newDirection = CharacterDirection.Down;
                }
                else if (y < 0)
                {
                    newDirection = CharacterDirection.Up;
                }
                else if (x > 0)
                {
                    newDirection = CharacterDirection.Right;
                }
                else if (x < 0)
                {
                    newDirection = CharacterDirection.Left;
                }

                player.Direction = newDirection;

                Map.Scroll(scrollX, scrollY);

                if (oldMap == Map.Map)
                {
                    bool frameReset = NumFrames == 1 || newDirection != prevDirection;
                    var  prevState  = CurrentState;

                    MoveTo(oldMap, (uint)newX, (uint)newY, ticks, frameReset, null);

                    if (travelType == TravelType.Walk)
                    {
                        Map.TriggerEvents(this, EventTrigger.Move, (uint)newX,
                                          (uint)newY, mapManager, ticks, game.CurrentSavegame);
                    }

                    if (oldMap == Map.Map) // might have changed by map change events
                    {
                        if (!frameReset && CurrentState == prevState)
                        {
                            SetCurrentFrame((CurrentFrame + 1) % NumFrames);
                        }

                        player.Position.X = Position.X;
                        player.Position.Y = Position.Y;

                        tile    = Map[(uint)player.Position.X, (uint)player.Position.Y];
                        Visible = travelType != TravelType.Walk || tile.Type != Data.Map.TileType.Invisible;

                        game.PlayerMoved(false, lastPlayerPosition);
                    }
                }
                else
                {
                    // adjust player position on map transition
                    var position = Map.GetCenterPosition();

                    MoveTo(Map.Map, (uint)position.X, (uint)position.Y, ticks, false, player.Direction);

                    if (travelType == TravelType.Walk)
                    {
                        Map.TriggerEvents(this, EventTrigger.Move, (uint)position.X,
                                          (uint)position.Y, mapManager, ticks, game.CurrentSavegame);
                    }

                    if (Map.Map.Type == MapType.Map2D)
                    {
                        player.Position.X = Position.X;
                        player.Position.Y = Position.Y;

                        // Note: For 3D maps the game/3D map will handle player position updating.

                        tile    = Map[(uint)player.Position.X, (uint)player.Position.Y];
                        Visible = travelType != TravelType.Walk || tile.Type != Data.Map.TileType.Invisible;

                        game.PlayerMoved(true, null, true, oldMap);
                    }
                }
            }
            else
            {
                if (displayOuchIfBlocked)
                {
                    game.DisplayOuch();
                }

                if (updateDirectionIfNotMoving)
                {
                    // If not able to move, the direction should be adjusted
                    var newDirection = Direction;

                    if (y > 0)
                    {
                        newDirection = CharacterDirection.Down;
                    }
                    else if (y < 0)
                    {
                        newDirection = CharacterDirection.Up;
                    }
                    else if (x > 0)
                    {
                        newDirection = CharacterDirection.Right;
                    }
                    else if (x < 0)
                    {
                        newDirection = CharacterDirection.Left;
                    }

                    if (newDirection != Direction)
                    {
                        MoveTo(Map.Map, (uint)Position.X, (uint)Position.Y, ticks, true, newDirection);
                        player.Direction = newDirection;
                        game.CurrentSavegame.CharacterDirection = newDirection;
                        UpdateAppearance(game.CurrentTicks);
                    }
                }
            }

            return(canMove);
        }
Example #25
0
        /* private void chkSnapFull_CheckedChanged(object sender, EventArgs e)
        {
            SnapGrid = false;
            SnapHalfGrid = chkSnapFull.Checked;
        }*/
        //
        // Add tiles to the screen
        //
        private void AddTile(Point tilePt)
        {
            if (CurrentMode == Mode.MAKE_FLOOR)
            {
                int tileGraph = (((ThingDb.Tile)(tileGraphic.SelectedItem)).Id);
                Map.Tile tile = Map.Tiles.ContainsKey(tilePt) ? Map.Tiles[tilePt] : null;
                if (tile == null && !threeFloorBox.Checked)
                {
                    ushort variation = CreateVariation(tilePt, (ushort)(tileVar.SelectedIndex-1), (byte)tileGraph);
                    ArrayList newblends = new ArrayList();
                    if (!chkAutoEdge.Checked)
                    {
                        for (int ve = 0; ve < blendDialog.Blends.Count; ve++)
                        {
                            Map.Tile.EdgeTile old = (Map.Tile.EdgeTile)blendDialog.Blends[ve];
                            Map.Tile.EdgeTile tr = new Map.Tile.EdgeTile(old.Graphic, (ushort)CreateVariation(tilePt, (ushort)old.Variation, (byte)old.Graphic), old.Dir, old.Edge);
                            newblends.Add(tr);
                        }
                    }
                    tile = new Map.Tile(
                        tilePt,
                        (byte)tileGraph,//tileGraphic.SelectedIndex,
                        variation,
                        newblends
                        );
                    unsafe
                    {
                        Map.Tiles.Add(tilePt, tile);
                        if (chkAutoEdge.Checked)
                        {
                            AutoEdge(tilePt);
                        }
                        IntPtr ptr = Marshal.StringToHGlobalAnsi(tile.Graphic);
                        MainWindow.myMap.AddTile(ptr.ToPointer(), tilePt.Y, tilePt.X, tile.Variation);
                        tilePt.X++;
                        //tileDrag = tilePt;  // Re-enable to allow tile dragging again
                        //dragging = true;
                    }

                }
                else if(threeFloorBox.Checked == true)
                {
                    unsafe
                    {
                        Point pat = new Point();
                        int i = 0;

                        int cols = 3;//ThingDb.FloorTiles[(byte)tileGraphic.SelectedIndex].numCols;
                        int rows = 3;//ThingDb.FloorTiles[(byte)tileGraphic.SelectedIndex].numRows;
                        for (pat = tilePt; i < rows; i++, pat.X--, pat.Y++)
                        {
                            for (int j = 0; j < cols; j++)
                            {
                                Point pat2 = new Point();
                                pat2 = pat;
                                pat2.X += j * 1;
                                pat2.Y += j * 1;
                                //pat2.X -= 1;
                                pat2.Y -= 2;
                                ushort variation = CreateVariation(pat2, (ushort)(tileVar.SelectedIndex-1), (byte)tileGraph);
                                ArrayList newblends = new ArrayList();
                                if (!chkAutoEdge.Checked)
                                {
                                    for (int ve = 0; ve < blendDialog.Blends.Count; ve++)
                                    {
                                        Map.Tile.EdgeTile old = (Map.Tile.EdgeTile)blendDialog.Blends[ve];
                                        Map.Tile.EdgeTile tr = new Map.Tile.EdgeTile(old.Graphic, (ushort)CreateVariation(pat2, (ushort)old.Variation, (byte)old.Graphic), old.Dir, old.Edge);
                                        newblends.Add(tr);
                                    }
                                }
                                tile = new Map.Tile(
                                    new Point(pat2.X, pat2.Y),
                                    (byte)tileGraph,//tileGraphic.SelectedIndex,
                                    variation,
                                    newblends
                                    );
                                IntPtr ptr = Marshal.StringToHGlobalAnsi(tile.Graphic);
                                if (!Map.Tiles.ContainsKey(tile.Location))
                                {
                                    Map.Tiles.Add(tile.Location, tile);
                                    if (chkAutoEdge.Checked)
                                    {
                                        AutoEdge(tile.Location);
                                    }
                                    MainWindow.myMap.AddTile(ptr.ToPointer(), pat2.Y, pat2.X, variation);
                                }
                            }
                        }
                    }
                }
            }
        }
Example #26
0
 public TileContainer(Map.Tile tile1)
 {
     Data = tile1;
 }
Example #27
0
    public static void Main(Client client)
    {
        Random rand = new Random();

        ushort[] waterIDs = new ushort[] { 4597, 4598, 4599, 4600, 4601, 4602, 4609, 4610, 4611, 4612 };

        while (true)
        {
            Thread.Sleep(rand.Next(600, 1200));

            // sanity checks
            if (!client.Player.Connected)
            {
                continue;
            }
            if (client.Player.Cap <= 7)
            {
                continue;
            }

            // get fishing rod
            Item fishingRod = client.Inventory.GetItem(client.ItemList.Tools.FishingRod);
            if (fishingRod == null)
            {
                continue;
            }

            // get fishy tiles
            var fishyTiles = client.Map.GetTilesWithObject(490).GetTiles().ToList();             // 7.4
            //var fishyTiles = client.Map.GetTilesWithObjects(waterIDs).GetTiles().ToList();
            // you can also use i.e. client.Map.GetTilesWithObjects(new ushort[] { 123, 124, 155 });
            // if there are more than one fishy tile
            if (fishyTiles.Count == 0)
            {
                continue;
            }

            // get random fisgy tile
            var      playerLoc = client.Player.Location;
            Map.Tile tile      = null;
            for (int i = 0; i < fishyTiles.Count; i++)
            {
                tile = fishyTiles[rand.Next(fishyTiles.Count)];
                if (!playerLoc.IsOnScreen(tile.WorldLocation) || tile.GetObjects().ToList().Count > 1)
                {
                    continue;
                }
                break;
            }
            if (tile == null)
            {
                continue;
            }

            // use fishing rod on fishy tile
            fishingRod.UseOnLocation(tile.WorldLocation);
            Thread.Sleep(rand.Next(250, 500));
            client.Inventory.GroupItems();
            Thread.Sleep(500);
        }
    }
Example #28
0
    public void CreatePath(Map.Tile where, Vector from)
    {
        Path.Clear();
        int x = (int)(where.x - from.x);
        int y = (int)(where.y - from.y);

        UnityEngine.Debug.Log(Name + ": Creating Path : from " + from.ToString() + " to " + where.Position.ToString() + " Offset: {" + x + " " + y + "}");


        var a = 1;
        var b = 1;

        if (x < 0)
        {
            a = -1;
        }
        if (y < 0)
        {
            b = -1;
        }
        Map e;

        if (GameManager.BattleMode)
        {
            e = GameManager.CurrentBattle.map;
        }
        else
        {
            e = GameManager.Map;
        }

        if (Math.Abs(x) > Math.Abs(y) || e.AtPos(from + Vector.up * b).Actor != null)
        {
            for (int i = 1; i <= Math.Abs(x); i++)
            {
                if (from + Vector.up * i * b == from)
                {
                    continue;
                }
                Path.Enqueue(from + Vector.right * i * a);
            }
            // y +1
            for (int i = 1; i <= Math.Abs(y); i++)
            {
                Path.Enqueue(from + Vector.right * x + Vector.up * i * b);
            }
        }
        else
        {
            for (int i = 1; i <= Math.Abs(y); i++)
            {
                if (from + Vector.up * i * b == from)
                {
                    continue;
                }
                Path.Enqueue(from + Vector.up * i * b);
            }
            //x + 1
            for (int i = 1; i <= Math.Abs(x); i++)
            {
                Path.Enqueue(from + Vector.up * y + Vector.right * i * a);
            }
        }
    }
Example #29
0
        private void btnWaypointsInsert_Click(object sender, EventArgs e)
        {
            if (!Client.Player.Connected || Client.Player.Health == 0)
            {
                return;
            }
            if (comboboxWaypointsOffset.SelectedIndex < 0 || comboboxWaypointsType.SelectedIndex < 0 || listboxWaypoints.SelectedIndex < 0)
            {
                return;
            }
            Modules.Cavebot.Waypoint.Types type;
            switch (comboboxWaypointsType.Text)
            {
            case "Node":
                type = Modules.Cavebot.Waypoint.Types.Node;
                break;

            case "Walk":
                type = Modules.Cavebot.Waypoint.Types.Walk;
                break;

            case "Rope":
                type = Modules.Cavebot.Waypoint.Types.Rope;
                break;

            case "Shovel":
                type = Modules.Cavebot.Waypoint.Types.Shovel;
                break;

            case "Machete":
                type = Modules.Cavebot.Waypoint.Types.Machete;
                break;

            case "Pick":
                type = Modules.Cavebot.Waypoint.Types.Pick;
                break;

            case "Ladder":
                type = Modules.Cavebot.Waypoint.Types.Ladder;
                break;

            case "Script":
                type = Modules.Cavebot.Waypoint.Types.Script;
                break;

            default:
                type = Modules.Cavebot.Waypoint.Types.Node;
                break;
            }
            int diffX = 0, diffY = 0;

            switch (comboboxWaypointsOffset.SelectedIndex)
            {
            case 0:
                break;

            case 1:
                diffY = -1;
                break;

            case 2:
                diffX = 1;
                break;

            case 3:
                diffY = 1;
                break;

            case 4:
                diffX = -1;
                break;
            }
            int index = listboxWaypoints.SelectedIndex;

            if (type == Modules.Cavebot.Waypoint.Types.Script)
            {
                Objects.Location loc = new Objects.Location(this.Client.Player.X + diffX,
                                                            this.Client.Player.Y + diffY, this.Client.Player.Z);
                Modules.Cavebot.Waypoint wp = new Modules.Cavebot.Waypoint(this.Client.Modules.Cavebot, loc, Modules.Cavebot.Waypoint.Types.Script);
                this.Client.Modules.Cavebot.InsertWaypoint(wp, index);
            }
            else
            {
                Modules.Cavebot.Waypoint wp = new Modules.Cavebot.Waypoint(this.Client.Modules.Cavebot,
                                                                           new Objects.Location(this.Client.Player.X + diffX, this.Client.Player.Y + diffY, this.Client.Player.Z), type);
                if (type == Modules.Cavebot.Waypoint.Types.Node && numericSettingsNodeRadius.Value > 0)
                {
                    ushort             pX = this.Client.Player.X, pY = this.Client.Player.Y;
                    byte               pZ = this.Client.Player.Z, radius = (byte)numericSettingsNodeRadius.Value;
                    Map.TileCollection tiles      = this.Client.Map.GetTilesOnScreen();
                    Map.Tile           playerTile = tiles.GetTile(count: this.Client.Player.ID);
                    if (playerTile == null)
                    {
                        MessageBox.Show("Could not find player tile"); return;
                    }
                    List <Objects.Location> nodeLocations = new List <Objects.Location>();
                    for (ushort x = (ushort)(pX - radius); x < pX + radius; x++)
                    {
                        for (ushort y = (ushort)(pY - radius); y < pY + radius; y++)
                        {
                            if (x == pX && y == pY)
                            {
                                continue;
                            }
                            Map.Tile tile = tiles.GetTile(new Objects.Location(x, y, pZ));
                            if (tile == null)
                            {
                                continue;
                            }
                            if (tile.IsWalkable())
                            {
                                nodeLocations.Add(tile.WorldLocation);
                            }
                        }
                    }
                    wp.NodeLocations.AddRange(nodeLocations);
                }
                this.Client.Modules.Cavebot.InsertWaypoint(wp, index);
            }
        }
Example #30
0
            private void Run()
            {
                while (true)
                {
                    try
                    {
                        this.ResetEvent.Wait();
                        if (this.WaypointExecutedBegin != null)
                        {
                            this.WaypointExecutedBegin(this.CurrentWaypoint);
                        }

                        bool success  = false,
                             firstRun = true;
                        Objects.Location currentSubNode = Objects.Location.Invalid;

                        while (!this.Cancel)
                        {
                            this.ResetEventTilesUpdated.WaitOne();

                            if (this.Cancel)
                            {
                                break;
                            }

                            Objects.Player   player    = this.Parent.Client.Player;
                            Objects.Location playerLoc = player.Location;

                            if (player.Z != this.CurrentWaypoint.Location.Z)
                            {
                                break;
                            }

                            if (firstRun)
                            {
                                firstRun = false;
                            }
                            else
                            {
                                if (this.Parent.Client.Window.StatusBar.GetText() == Enums.StatusBar.ThereIsNoWay)
                                {
                                    this.Parent.Client.Window.StatusBar.SetText(string.Empty);
                                    success = false;
                                    break;
                                }
                            }

                            bool isOnScreen     = playerLoc.IsOnScreen(this.CurrentWaypoint.Location),
                                 doBreak        = false;
                            var tilesToLocation = isOnScreen ?
                                                  playerLoc.GetTilesToLocation(this.Parent.Client,
                                                                               this.CurrentWaypoint.Location, this.CachedTiles, this.Parent.PathFinder)
                                                  .ToList <Objects.PathFinder.Node>() :
                                                  new List <Objects.PathFinder.Node>();

                            switch (this.CurrentWaypoint.Type)
                            {
                            case Waypoint.Types.Walk:
                                #region walk
                                if (playerLoc == this.CurrentWaypoint.Location)
                                {
                                    doBreak = true;
                                    success = true;
                                    break;
                                }
                                if (isOnScreen && tilesToLocation.Count == 0)
                                {
                                    doBreak = true;
                                    success = false;
                                    break;
                                }
                                if (!player.IsWalking || player.GoTo != this.CurrentWaypoint.Location)
                                {
                                    player.GoTo = this.CurrentWaypoint.Location;
                                }
                                #endregion
                                break;

                            case Waypoint.Types.Node:
                                #region node
                                if (playerLoc == this.CurrentWaypoint.Location)
                                {
                                    doBreak = true;
                                    success = true;
                                    break;
                                }
                                if (isOnScreen && tilesToLocation.Count == 0)
                                {
                                    doBreak = true;
                                    success = false;
                                    break;
                                }

                                // check if the player is already walking to a node
                                if (player.IsWalking)
                                {
                                    int range = this.Parent.CurrentSettings.NodeRadius;
                                    Objects.Location currentGoTo = player.GoTo;
                                    bool             found       = false;
                                    for (int x = -range; x <= range; x++)
                                    {
                                        for (int y = -range; y <= range; y++)
                                        {
                                            Objects.Location subNode = this.CurrentWaypoint.Location.Offset(x, y);
                                            if (currentGoTo != subNode)
                                            {
                                                continue;
                                            }
                                            // check distance to node
                                            if (isOnScreen)
                                            {
                                                var tilesToSubNode = playerLoc.GetTilesToLocation(this.Parent.Client,
                                                                                                  subNode, this.CachedTiles, this.Parent.PathFinder, true).ToArray();
                                                if (tilesToSubNode.Length <= this.Parent.CurrentSettings.NodeSkipRange)
                                                {
                                                    success = true;
                                                    doBreak = true;
                                                    break;
                                                }
                                            }
                                            found = true;
                                            break;
                                        }
                                        if (found)
                                        {
                                            break;
                                        }
                                    }
                                    if (found)
                                    {
                                        break;
                                    }
                                }
                                else if (playerLoc.DistanceTo(this.CurrentWaypoint.Location) <= this.Parent.CurrentSettings.NodeSkipRange)
                                {
                                    success = true;
                                    doBreak = true;
                                    break;
                                }

                                // find new node to walk to
                                if (isOnScreen)
                                {
                                    Map.Tile tile = this.CachedTiles.GetTile(this.CurrentWaypoint.Location);
                                    if (tile == null)
                                    {
                                        doBreak = true;
                                        success = false;
                                        break;
                                    }
                                    Map.TileCollection nearbyTiles = this.CachedTiles.GetNearbyTileCollection(tile,
                                                                                                              this.Parent.CurrentSettings.NodeRadius);
                                    Objects.Location loc = tilesToLocation.Count != 0 ?
                                                           tile.WorldLocation :
                                                           Objects.Location.Invalid;
                                    List <Map.Tile> goodTiles = new List <Map.Tile>();
                                    foreach (Map.Tile nearbyTile in nearbyTiles.GetTiles())
                                    {
                                        bool isReachable = playerLoc.CanReachLocation(this.Parent.Client,
                                                                                      nearbyTile.WorldLocation, this.CachedTiles, this.Parent.PathFinder);
                                        if (isReachable)
                                        {
                                            goodTiles.Add(nearbyTile);
                                        }
                                    }
                                    if (goodTiles.Count > 0)
                                    {
                                        loc = goodTiles[new Random().Next(goodTiles.Count)].WorldLocation;
                                    }

                                    if (loc.IsValid())
                                    {
                                        player.GoTo = loc;
                                    }
                                    else
                                    {
                                        doBreak = true;
                                        success = false;
                                        break;
                                    }
                                }
                                else if (this.Parent.CurrentSettings.UseAlternateNodeFinder)
                                {
                                    int              range = this.Parent.CurrentSettings.NodeRadius;
                                    Random           rand  = new Random();
                                    Objects.Location loc   = this.CurrentWaypoint.Location;
                                    for (int x = -range; x <= range; x++)
                                    {
                                        for (int y = -range; y <= range; y++)
                                        {
                                            Objects.Location subNode = this.CurrentWaypoint.Location.Offset(
                                                rand.Next(-range, range + 1), rand.Next(-range, range + 1));
                                            if (!this.Parent.Client.Modules.MapViewer.IsWalkable(subNode))
                                            {
                                                continue;
                                            }
                                            loc = subNode;
                                            break;
                                        }
                                        if (loc != this.CurrentWaypoint.Location)
                                        {
                                            break;
                                        }
                                    }
                                    player.GoTo = loc;
                                }
                                else     // use stored subnodes
                                {
                                    Objects.Location loc = this.CurrentWaypoint.Location;
                                    if (this.CurrentWaypoint.NodeLocations.Count > 0)
                                    {
                                        int index = -1, newIndex = new Random().Next(-1, this.CurrentWaypoint.NodeLocations.Count);
                                        if (newIndex != index)
                                        {
                                            loc = this.CurrentWaypoint.NodeLocations[newIndex];
                                        }
                                    }
                                    player.GoTo = loc;
                                }
                                #endregion
                                break;

                            case Waypoint.Types.Machete:
                            case Waypoint.Types.Pick:
                            case Waypoint.Types.Rope:
                            case Waypoint.Types.Shovel:
                                #region tools
                                // check if we're adjacent to the waypoint
                                if (playerLoc.IsAdjacentTo(this.CurrentWaypoint.Location))
                                {
                                    Objects.Item tool = null;
                                    switch (this.CurrentWaypoint.Type)
                                    {
                                    case Waypoint.Types.Machete:
                                        tool = this.Parent.Client.Inventory.GetItem(this.Parent.Client.ItemList.Tools.Machete);
                                        break;

                                    case Waypoint.Types.Pick:
                                        tool = this.Parent.Client.Inventory.GetItem(this.Parent.Client.ItemList.Tools.Pick);
                                        break;

                                    case Waypoint.Types.Rope:
                                        tool = this.Parent.Client.Inventory.GetItem(this.Parent.Client.ItemList.Tools.Rope);
                                        break;

                                    case Waypoint.Types.Shovel:
                                        tool = this.Parent.Client.Inventory.GetItem(this.Parent.Client.ItemList.Tools.Shovel);
                                        break;
                                    }
                                    if (tool == null)
                                    {
                                        doBreak = true;
                                        success = false;
                                        break;
                                    }
                                    Map.Tile tile = this.CachedTiles.GetTile(this.CurrentWaypoint.Location);
                                    if (tile == null)
                                    {
                                        success = false;
                                        doBreak = true;
                                        break;
                                    }
                                    Map.TileObject topItem = tile.GetTopUseItem(true);
                                    if (this.CurrentWaypoint.Type != Waypoint.Types.Rope)
                                    {
                                        tool.UseOnTileObject(topItem);
                                        success = true;
                                        doBreak = true;
                                    }
                                    else
                                    {
                                        if (topItem.StackIndex != 0)
                                        {
                                            // find a non-blocking adjacent tile
                                            var adjacentTiles = this.CachedTiles.GetAdjacentTileCollection(tile).GetTiles()
                                                                .ToList <Map.Tile>();
                                            Map.Tile bestTile = tile;
                                            foreach (Map.Tile t in adjacentTiles.ToArray())
                                            {
                                                if (!t.IsWalkable())
                                                {
                                                    adjacentTiles.Remove(t);
                                                }
                                            }
                                            if (adjacentTiles.Count > 0)
                                            {
                                                bestTile = adjacentTiles[new Random().Next(adjacentTiles.Count)];
                                            }
                                            topItem.Move(bestTile.ToItemLocation());
                                        }
                                        else
                                        {
                                            tool.UseOnTileObject(topItem);
                                            for (int i = 0; i < 3; i++)
                                            {
                                                Thread.Sleep(100);
                                                if (player.Z != this.CurrentWaypoint.Location.Z)
                                                {
                                                    doBreak = true;
                                                    success = true;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    break;
                                }
                                else if (isOnScreen)
                                {
                                    Map.Tile tile = this.CachedTiles.GetTile(this.CurrentWaypoint.Location);
                                    if (tile == null)
                                    {
                                        success = false;
                                        doBreak = true;
                                        break;
                                    }
                                    Map.TileCollection adjacentTiles = this.CachedTiles.GetAdjacentTileCollection(tile);
                                    Objects.Location   bestLoc       = Objects.Location.Invalid;
                                    int distance = int.MaxValue;
                                    foreach (Map.Tile adjTile in adjacentTiles.GetTiles())
                                    {
                                        if (!adjTile.IsWalkable())
                                        {
                                            continue;
                                        }

                                        var tilesToAdjTile = playerLoc.GetTilesToLocation(this.Parent.Client,
                                                                                          adjTile.WorldLocation, this.CachedTiles, this.Parent.PathFinder, true)
                                                             .ToArray <Objects.PathFinder.Node>();

                                        if (tilesToAdjTile.Length == 0)
                                        {
                                            continue;
                                        }
                                        if (tilesToAdjTile.Length < distance)
                                        {
                                            bestLoc  = adjTile.WorldLocation;
                                            distance = tilesToAdjTile.Length;
                                        }
                                    }
                                    if (bestLoc.IsValid())
                                    {
                                        player.GoTo = bestLoc;
                                    }
                                    else
                                    {
                                        doBreak = true;
                                        success = false;
                                        break;
                                    }
                                }
                                else if (!player.IsWalking)
                                {
                                    player.GoTo = this.CurrentWaypoint.Location;
                                }
                                #endregion
                                break;

                            case Waypoint.Types.Ladder:
                                #region ladder
                                if (player.IsWalking)
                                {
                                    break;
                                }

                                if (isOnScreen)
                                {
                                    Map.Tile tile = this.CachedTiles.GetTile(this.CurrentWaypoint.Location);
                                    if (tile == null)
                                    {
                                        doBreak = true;
                                        success = false;
                                        break;
                                    }

                                    if (playerLoc.DistanceTo(this.CurrentWaypoint.Location) < 2)
                                    {
                                        Map.TileObject topItem = tile.GetTopUseItem(false);
                                        if (topItem == null)
                                        {
                                            doBreak = true;
                                            success = false;
                                            break;
                                        }
                                        for (int i = 0; i < 3; i++)
                                        {
                                            topItem.Use();
                                            Thread.Sleep(300);
                                            if (player.Z != this.CurrentWaypoint.Location.Z)
                                            {
                                                doBreak = true;
                                                success = true;
                                                break;
                                            }
                                        }
                                        break;
                                    }
                                    // find suitable loc to walk to
                                    int distance             = int.MaxValue;
                                    Objects.Location bestLoc = Objects.Location.Invalid;
                                    foreach (Map.Tile adjTile in this.CachedTiles.GetAdjacentTileCollection(tile).GetTiles())
                                    {
                                        if (!adjTile.IsWalkable())
                                        {
                                            continue;
                                        }
                                        var tilesToAdjTile = playerLoc.GetTilesToLocation(this.Parent.Client,
                                                                                          adjTile.WorldLocation, this.CachedTiles, this.Parent.PathFinder, true)
                                                             .ToArray <Objects.PathFinder.Node>();
                                        if (tilesToAdjTile.Length == 0)
                                        {
                                            continue;
                                        }
                                        if (tilesToAdjTile.Length < distance)
                                        {
                                            distance = tilesToAdjTile.Length;
                                            bestLoc  = adjTile.WorldLocation;
                                        }
                                    }
                                    if (bestLoc.IsValid())
                                    {
                                        player.GoTo = bestLoc;
                                    }
                                    else
                                    {
                                        doBreak = true;
                                        success = false;
                                    }
                                    break;
                                }
                                else
                                {
                                    player.GoTo = this.CurrentWaypoint.Location;
                                }
                                #endregion
                                break;
                            }

                            if (doBreak)
                            {
                                break;
                            }
                        }

                        if (this.WaypointExecutedEnd != null)
                        {
                            this.WaypointExecutedEnd(this.CurrentWaypoint, success);
                        }
                        this.ResetEvent.Reset();
                    }
                    catch (Exception ex)
                    {
                        if (this.ErrorOccurred != null)
                        {
                            this.ErrorOccurred(ex);
                        }
                    }
                }
            }
Example #31
0
 public TileContainer(Map.Tile tile1, int x, int y)
 {
     Data     = tile1;
     Position = new Point(x, y);
 }
Example #32
0
        private void mapPanel_MouseUp(object sender, MouseEventArgs e)
        {
            Point pointClicked = new Point(e.X, e.Y);
            if (e.Button.Equals(MouseButtons.Right))
            {
                KeyStates.MRight = false;
            }
            else if (e.Button.Equals(MouseButtons.Left))
            {
                if (SelectedObject != null && CurrentMode == Mode.SELECT && KeyStates.MLeft)
                {
                    if (SnapGrid)//snap to grid when grid is on
                        pointClicked = new Point((int)Math.Round((decimal)(pointClicked.X / squareSize)) * squareSize, (int)Math.Round((decimal)(pointClicked.Y / squareSize)) * squareSize);

                    if (SnapHalfGrid)//snap to half grid when grid is on
                        pointClicked = new Point((int)Math.Round((decimal)((pointClicked.X / (squareSize)) * squareSize) + squareSize / 2), (int)Math.Round((decimal)((pointClicked.Y / (squareSize)) * squareSize) + squareSize / 2));

                    SelectedObject.Location = pointClicked;
                    dragging = false;
                }
                KeyStates.MLeft = false;
            }
            else if (e.Button.Equals(MouseButtons.Middle))
            {
                KeyStates.WheelClick = false;
            }

            if (dragging && wallDrag != null && CurrentMode == Mode.MAKE_WALL)
            {
                pointClicked = GetNearestWallPoint(pointClicked);
                int length = (int)(Distance(wallDrag, wallMouseLocation)); // X and Y should be same length
                length = (int)Math.Sqrt((length * length) / 2);
                if (pointClicked.X >= wallDrag.X && pointClicked.Y < wallDrag.Y)
                    for (int i = 1; i < length; i++)
                    {
                        Point newPoint = new Point(wallDrag.X + i, wallDrag.Y - i);
                        Map.Wall newWall = wallSelector.NewWall(newPoint);
                        newWall.Facing = Map.Wall.WallFacing.NORTH;
                        if (!Map.Walls.ContainsKey(newPoint))
                            Map.Walls.Add(newPoint, newWall);
                    }

                else if (pointClicked.X >= wallDrag.X && pointClicked.Y >= wallDrag.Y)
                    for (int i = 1; i < length; i++)
                    {
                        Point newPoint = new Point(wallDrag.X + i, wallDrag.Y + i);
                        Map.Wall newWall = wallSelector.NewWall(newPoint);
                        newWall.Facing = Map.Wall.WallFacing.WEST;
                        if (!Map.Walls.ContainsKey(newPoint))
                            Map.Walls.Add(newPoint, newWall);
                    }
                else if (pointClicked.X < wallDrag.X && pointClicked.Y < wallDrag.Y)
                    for (int i = 1; i < length; i++)
                    {
                        Point newPoint = new Point(wallDrag.X - i, wallDrag.Y - i);
                        Map.Wall newWall = wallSelector.NewWall(newPoint);
                        newWall.Facing = Map.Wall.WallFacing.WEST;
                        if (!Map.Walls.ContainsKey(newPoint))
                            Map.Walls.Add(newPoint, newWall);
                    }
                else if (pointClicked.X < wallDrag.X && pointClicked.Y >= wallDrag.Y)
                    for (int i = 1; i < length; i++)
                    {
                        Point newPoint = new Point(wallDrag.X - i, wallDrag.Y + i);
                        Map.Wall newWall = wallSelector.NewWall(newPoint);
                        newWall.Facing = Map.Wall.WallFacing.NORTH;
                        if (!Map.Walls.ContainsKey(newPoint))
                            Map.Walls.Add(newPoint, newWall);
                    }
                dragging = false;
            }
            else if (dragging && tileDrag != null && CurrentMode == Mode.MAKE_FLOOR)
            {
                Point tilePt = GetNearestTilePoint(mouseLocation);
                Point topLeftPt;
                //int variation = 0;
                int w = tilePt.X - tileDrag.X, h = tilePt.Y - tileDrag.Y;
                if (w < 0)
                    topLeftPt = new Point(tileDrag.X + w, 0);
                else
                    topLeftPt = new Point(tileDrag.X, 0);
                if (h < 0)
                    topLeftPt = new Point(topLeftPt.X, tileDrag.Y + h);
                else
                    topLeftPt = new Point(topLeftPt.X, tileDrag.Y);
                int varCount = ThingDb.FloorTiles[tileGraphic.SelectedIndex].Variations.Count; //-1 because needs to start at 0
                int varSqrt = (int)Math.Sqrt(varCount);
                for (int i = 0; i <= h; i++) // i = y
                {
                    for (int k = (i - (((int)(i / varSqrt)) * varSqrt)); k <= w + (i - (((int)(i / varSqrt)) * varSqrt)); k++) // k = x
                    {
                        tilePt = GetNearestTilePoint(new Point((topLeftPt.X + (k - (i - (((int)(i / varSqrt)) * varSqrt)))) * squareSize, (topLeftPt.Y + i) * squareSize));
                        //variation = CreateVariation(tilePt, (ushort)tileVar.SelectedIndex, (byte)tileGraphic.SelectedIndex);
                        Map.Tile tile = new Map.Tile(tilePt, (byte)tileGraphic.SelectedIndex, CreateVariation(tilePt, (ushort)tileVar.SelectedIndex, (byte)tileGraphic.SelectedIndex));
                        if (!Map.Tiles.ContainsKey(tilePt) && tilePt.X >= 0 && tilePt.Y >= 0 && tilePt.X <= 255 && tilePt.Y <= 255)
                        {
                            unsafe
                            {
                               // col = Color.FromArgb();
                                IntPtr ptr = Marshal.StringToHGlobalAnsi(tile.Graphic);
                                Map.Tiles.Add(tilePt, tile);
                                MainWindow.myMap.AddTile(ptr.ToPointer(), tilePt.Y, tilePt.X, CreateVariation(tilePt, (ushort)tileVar.SelectedIndex, (byte)tileGraphic.SelectedIndex));
                            }
                        }
                    }
                }
            }

            dragging = false;
            mapPanel.Invalidate();
        }