A * search algorithm--multi-person search, real-time collision search, the nearest destination __ algorithm

Source: Internet
Author: User
Tags abs rand

A * Road algorithm principle can refer to this article, has been written in detail http://www.cppblog.com/mythit/archive/2009/04/19/80492.aspx

This article mainly writes the real time collision which the multiple people seeks the road

First talk about how to move the nearest point to the destination without finding a way

In fact, all the points can be reached in the "close list", when all the points in the open list are traversed, if the end has not been found, the path is considered

This is the time to traverse the "close list" to find out where the shortest line distance from the point can be, see the following code in the Findnearpointfromlist function


The general idea of a multiplayer collision is

1. Find a way with a * *

2, according to the path to go, did not move a grid to detect collisions

3, if the collision, call a * re-find the road

4, if not collided, according to the original path to continue to go

5. Stop at destination


Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Using System.Threading.Tasks;
        Namespace Testastar {public class Astarnode {private Astarnode parent = null;
        private int g;
        private int h;
        private int x;

        private int y;
            Public Astarnode Parent {get {return parent;
            set {parent = value;
            } public int G {get {G;
            } set {g = value;
            } public int H {get {return h;
            set {h = value;
            } public int F {get {g + H;

        }
        }public int × {get {return x;
            set {x = value;
            The public int y {get {return y;
            } set {y = value;
            } public Astarnode (int _x, int _y) {this.x = _x;
            This.y = _y;
            This.parent = null;
            THIS.G = 0;
        this.h = 0;
        } public class Astar {private list<astarnode> openlist = new list<astarnode> ();
        Private list<astarnode> closelist = new list<astarnode> ();
        Private bool[,] mapData = null;
        private int pixelformat = 16;
        private int mapwidth = 0;
        private int mapheight = 0;
        private int endx = 0;

        private int endY = 0;
         Public bool[,] MapData {   get {return mapData;
            } public int PixelFormat {get {return pixelformat; } public int Mapwidth {get {return Mapwidt
            H
            } public int Mapheight {get {return mapheight;
            } public Astar () {} private bool IsValid (int x, int y) {
            if (x < 0 | | | x >= mapwidth) {return false;
            } if (Y < 0 | | | y >= mapheight) {return false;
        return true; } private bool InList (list<astarnode> List, int x, int y) {foreach (Astarnode node in List) {if (node). x = = x && node. Y = =Y) {return true;
        return false;
        private bool Inopenlist (int x, int y) {return inList (openlist, x, y);
        private bool Incloselist (int x, int y) {return inList (closelist, x, y);
                Private Astarnode getbestnodefromopenlist () {if (Openlist.count = 0) {
            return null;
        return openlist[0];
            private void Opentoclose (Astarnode node) {openlist.remove (node);
        Closelist.add (node);

            Private Astarnode Opentoclosewithbest () {astarnode node = getbestnodefromopenlist ();
            if (node = = null) {return null;
            } opentoclose (node);
        return node; } private void Addtoopenlist (Astarnode parent, int x, int y) {if (!isvalid (x, y)) {return;
            } if (Inopenlist (x, y) | | incloselist (x, y)) {return;
            } if (!canwalk (x, y) && parent!= null) {return;
            Astarnode node = new Astarnode (x, y); Node.

            parent = parent; if (parent = null) {node.
                G = 0; Node.
            H = 0; else {if (Math.Abs) (parent. X-x) + math.abs (parent. y-y) = = 2) {node.
                G = 14; } else {node.
                G = 10; node.
            H = Math.Abs (endx-x) * + math.abs (endy-y) * 10;
            } openlist.add (node);
           Openlist.sort (Delegate (Astarnode LHS, Astarnode RHS) {if (LHS). F < RHS.
                F) {return-1; else if (LHS. F > RHS.
                F) {return 1;
            return 0;
        }); private void Genaroundnode (Astarnode node) {//addtoopenlist node, node. X-1, node.
            Y-1); Addtoopenlist (node, node. X-1, node.
            Y); Addtoopenlist (node, node. X-1, node.

            Y + 1); Addtoopenlist (node, node. X, node.
            Y-1); Addtoopenlist (node, node. X, node.

            Y + 1); Addtoopenlist (node, node. X + 1, node.
            Y-1); Addtoopenlist (node, node. X + 1, node.
            Y); Addtoopenlist (node, node. X + 1, node.
        Y + 1); Private Astarnode findnearpointfromlist (list<astarnode> List, int x, int y) {Astarno
            de result = NULL; int mindistance = Int.

            MaxValue; foreach (AstarNode node in list {int dist = (int) math.sqrt (node. X-X) * Math.Abs (node. X-x) + math.abs (node. Y-Y) * Math.Abs (node.

                Y-Y));
                    if (Dist < mindistance) {mindistance = dist;
                result = node;
        } return result;
        public bool Canwalk (int x, int y) {return mapdata[x, y];
            public bool Canwalkpixel (int x, int y) {int px = X/pixelformat;

            int py = Y/pixelformat;
        Return Canwalk (px, py); Public list<astarnode> findpath (int _startx, int _starty, int _endx, int _endy) {thi
            S.endx = _endx;
            This.endy = _endy;
            This.openList.Clear ();
            This.closeList.Clear ();
            list<astarnode> result = new list<astarnode> (); Astarnode currnode = null;
            BOOL Findpathflag = false;

            Addtoopenlist (null, _STARTX, _starty);

                while (Openlist.count > 0) {currnode = Opentoclosewithbest ();
                if (Currnode = = null) {break; } if (currnode.x = = _endx && currnode.y = _endy) {FINDPATHF
                    lag = true;
                Break
            } genaroundnode (Currnode);
            } if (!findpathflag) {Currnode = Findnearpointfromlist (Closelist, EndX, EndY);
            } if (Currnode = = null) {return null; (true) {result.

                ADD (Currnode);
                if (currnode.x = = _startx && currnode.y = = _starty) {break; } Currnode = currnode.parent; Result.

            Reverse ();
        return result; list<astarnode> findpathpixel (int startx, int starty, int endx, int endY) {in
            t sx = Startx/pixelformat;
            int sy = Starty/pixelformat;
            int ex = Endx/pixelformat;

            int ey = Endy/pixelformat;

            list<astarnode> result = Findpath (SX, SY, EX, EY);
            if (result = = null) {return null; for (int i = 0; I < result. Count; ++i) {Result[i].
                X *= PixelFormat; Result[i].
            Y *= PixelFormat;
        return result;
        public void Enablemapdata (int x, int y, bool value) {mapdata[x, y] = value;
            public void Enablemapdatapixel (int x, int y, bool value) {int px = X/pixelformat; int py = y /PixelFormat;
        Enablemapdata (px, py, value);
        public void Syncmapdata (int x, int y) {mapdata[x, y] =!mapdata[x, y];
            public void Syncmapdatapixel (int x, int y) {int px = X/pixelformat;

            int py = Y/pixelformat;
        Syncmapdata (px, py);
            public void Enablemapdataall (bool value) {for (int w = 0; w < mapwidth; ++w)
                {for (int h = 0; h < mapheight; ++h) {mapdata[w, h] = value; }} public void Initmapdata (int _widthpixel, int _heightpixel, int _pixelfor
            MAT) {int width = _widthpixel/_pixelformat;

            int height = _heightpixel/_pixelformat;
            PixelFormat = _pixelformat;
            MapData = new bool[width, height];
            Mapwidth = width;

   Mapheight = height;         Enablemapdataall (TRUE);
 }
    }
}

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;

Using System.Windows.Forms;
        Namespace Testastar {public class Player {public int ID;
        public int X;
        public int Y;
        public int targetx;
        public int targety;
        Public list<astarnode> Paths;
        public int pathindex;
        Public Color Pathcolor;

        Public Color Showcolor;
        public void Delete (Astar Astar) {astar.enablemapdatapixel (X, Y, true); } public void Update (Astar Astar) {if (Paths!= null) {if (Path Index < Paths.count) {int tx = Paths[pathindex].
                    X int ty = Paths[pathindex].

                    Y if (Astar.canwalkpixel (TX, Ty)) {asTar.enablemapdatapixel (X, Y, true);
                        X = TX;
                        Y = Ty;
                        Astar.enablemapdatapixel (X, Y, false);
                    pathindex++;
                        else {astar.enablemapdatapixel (X, Y, true);
                        Paths = Astar.findpathpixel (X, Y, Targetx, targety);
                    Pathindex = 0;
                    } else {Astar.enablemapdatapixel (X, Y, true);
                    Paths = null;
                Pathindex = 0;
                } else {int x = Form1.rand.Next (0, Form1.mapwidth);

                int y = Form1.rand.Next (0, form1.mapheight);
                    if (Astar.canwalkpixel (x, y)) {targetx = x;
                    Targety = y; Paths = AstaR.findpathpixel (x, y, x, y);
                Pathindex = 0;
            }} public void render (Astar Astar, Graphics g) {if (Paths!= null) {for (int i = Pathindex i < Paths.count; ++i) {G.fillr Ectangle (New SolidBrush (Pathcolor), New Rectangle (paths[i). X, Paths[i]. Y, Astar. PixelFormat, Astar.
                PixelFormat)); } g.fillrectangle (New SolidBrush (Showcolor), New Rectangle (X, Y, Astar.) PixelFormat, Astar.

            PixelFormat)); g.DrawString (ID.
        ToString (), New Font ("italics", fontstyle.bold), Brushes.black, X, Y);
        } partial class Form1:form {public static int mapwidth = 640;

        public static int mapheight = 480;

        public static Random rand = new Random ((int) DateTime.Now.Ticks);
        Private Astar Astar = new Astar ();
        Private Bitmap surface = null; Private Graphics g = null;

        Private list<player> players = new list<player> ();

        Private bool[] keys = new bool[256];
            private void Init () {picturebox1.location = Point.empty;

            Picturebox1.clientsize = new System.Drawing.Size (mapwidth, mapheight);
            Surface = new Bitmap (mapwidth, mapheight);

            g = graphics.fromimage (surface);

            Astar.initmapdata (Mapwidth, Mapheight, 16); for (int i = 0; i < keys. Length;
            ++i) {Keys[i] = false;
                } private void Update () {foreach (Player p in players) {
            P.update (Astar);

            }} private void Render () {g.clear (color.white); bool[,] MapData = Astar.

            MapData; for (int w = 0; w < Astar. Mapwidth; ++W) {for (int h = 0; h < Astar.) Mapheight; ++H)
                {if (!mapdata[w, h]) {G.fillrectangle (B) Rushes. Black, New Rectangle (w * astar. PixelFormat, H * astar. PixelFormat, Astar. PixelFormat, Astar.
                    PixelFormat));  {P.render (Astar, Player p in players)}
            g);
        } pictureBox1.Image = surface;
        Public Form1 () {InitializeComponent (); } private void Form1_Load (object sender, EventArgs e) {this.
            Text = "A * Seek algorithm (dynamic collision and seek the road demonstration) A: Increase D: Reduce left key: Obstacle set Right key + number key: Corresponding numbered object Search Road";

            Init ();
            Timer Gametimer = new timer ();
            Gametimer.tick + = Gametimer_tick;
            Gametimer.interval = 100;
        Gametimer.start ();
            } void Gametimer_tick (object sender, EventArgs e) {update ();
        Render (); } private void Picturebox1_mousedown (object sender, MouseEventArgs e) {if (E.button = = System.Windows.Form
            S.mousebuttons.left) {astar.syncmapdatapixel (e.x, e.y);
                else if (E.button = = System.Windows.Forms.MouseButtons.Right) {/*endx = e.x;
                EndY = e.y;
                paths = Astar.findpathpixel (px, py, endx, EndY);
                Pathindex = 0;*/int pi = 0;
                        for (int i = 0; i < 256 ++i) {if (Keys[i]) {

                        PI = i-(int) keys.d1; if (Pi < 0 | | | Pi >= players.
                        Count) {return;

                        Player p = Players[pi];
                        P.targetx = e.x;
                        P.targety = e.y; P.paths = Astar.findpathpixEl (Players[pi]. X, Players[pi].
                        Y, e.x, e.y);

                        P.pathindex = 0;

                        PLAYERS[PI] = p;
                    Return
            }}} private void Form1_keydown (object sender, KeyEventArgs e) {

            Keys[e.keyvalue] = true;
                if (E.keycode = = KEYS.A) {Player p = new player (); P.id = players.
                Count + 1;
                p.x = 0;
                P.Y = 0;
                P.targetx = 0;
                p.targety = 0;
                P.paths = null;
                P.pathindex = 0; P.showcolor = Color.FromArgb (rand. Next (0, 255), Rand. Next (0, 255), Rand.
                Next (0, 255));

                P.pathcolor = Color.FromArgb (P.showcolor); Players.
            ADD (P); } if (E.keycode = = KEYS.D) {if players. Count > 0) {PlayeRs[players.
                    Count-1].delete (Astar); Players. RemoveAt (players.
                COUNT-1); }} private void Form1_keyup (object sender, KeyEventArgs e) {keys[e.ke
        Yvalue] = false;
 }
    }
}


Engineering Documents: Http://pan.baidu.com/s/1mg1tnKk


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.