Pathfinding algorithm: Simulate tower defense flash to make a small game

Source: Internet
Author: User

The first time I wrote a game with C. Writing algorithms on C # is indeed a challenge. If the time is too complex, the consequences will be much more obvious than C ++, so we always try to make things into O (N) or O (nlogn ). This time we implemented a path-finding algorithm.

The path search algorithm is like this: there is a square on 16 × 16.SomeThe end point. Things can only move up or down on the grid. Each grid needs to be recordedOne of the endpointsThe nearest pathAllDirection (just like the three-layer cyclic pathfinding algorithm, which finally gives the matrix ).

So I used the width-first search and a queue to solve this problem. At the beginning, it takes one second for an algorithm to write an error into an O (n2) result. After correction, the result is instantly displayed.

The algorithm is as follows:
1: add all the goal to the queue and mark it.
2: record the number of elements in the current queue.
3 ), mark this element (non-neighbor ).
4: if the number of pop-up elements is not as large as that recorded in step 1, go to step 3.
5: if the number of queues is not empty, go to 2.
6: end.
Run this algorithm to obtain the following layers:

This algorithm can be re-computed when an obstacle is added. You only need to mark the obstacle at the beginning.

C # is really the best choice for doing big jobs. It's really convenient to develop, and you don't have to worry about memory problems (becauseYesOccupies a lot of resources ).

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.