Click here to Skip to main content
15,889,838 members

How to use breadth first search/a* search to find the shortest path to the target?

Warrior_Knight asked:

Open original thread
I am working on a Snake AI game. I want to use BFS/A* to find the shortest path to the food. I know the coordinates of the food. There are other snakes on the board so I am trying to avoid them. I have the logic but how can I use BFS/A* to find the path? For example my snake's head's coordinate is (40,40) since i can only go left, right and up (no backwards as it is rest of my snake), how can I add these to my queue in BFS/A*? How can the BFS/A* expand? (It is 2D array type of board, nothing fancy). Output example: 1s and 4s are the snakes. 9 is the Food.

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 9 0 0 1 0 0 0 0 4 4 4 4 4 4
0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 4
0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0

Each turn new coordinates are entered so the snakes movement. Aim is to use BFS/A* to locate food so snake can move towards it. BFS/A* will be used to determine my move. Help will be appreciated.

What I have tried:

I have sorted out the coordinates. I have my board size. So my input will be
(int[][] board Size, target coordinate x, target coordinate y, snake head x, snake head y)
Tags: Java, Game Development, Search, Path

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900