How to choose random move that takes highest value piece in chess? - java

So I have an array list of all the moves at the current board state in chess that take a piece.
ArrayList<Move> takePiece;
And all the pieces have a corresponding value:
public static final int PAWN = 1;
public static final int KNIGHT = 2;
public static final int BISHOP = 3;
public static final int ROOK = 4;
public static final int QUEEN = 5;
public static final int KING = 6;
I want to be able to select a random move from the array list that takes the highest value piece.
So if 3 different moves could take the king it would randomly choose one of the 3 moves (check and checkmate haven't been implemented).
How would i go about this?
public Move(Piece p , int x, int y, int dx, int dy, boolean t){
this.p = p;
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.t = t;
}
So this is what a move is so to check the piece value that was going to be taken i would check the piece at (dx,dy).

You have to check in your array the most valuable Piece and choose your move accordingly, to make this, you must iterate twice:
// get the max value of possible pieces that could be taken
ArrayList<Move> takePiece // here you must have all possible takes
int maxPieceValue = 0;
for (Move m : takePiece) {
if(PieceCode.charToInt(m.getChar()) > maxPieceValue)
maxPieceValue = m.getPiece.getType();
}
// get a list with best moves available
ArrayList<Move> bestMoves new ArrayList<Move>();
for (Move m : takePiece) {
if(PieceCode.charToInt(m.getChar()) > maxPieceValue)
bestMoves.add(m);
}
// choose randomly one of best moves
Random random = new Random();
Move choosenMove = bestMoves.get(random.nextInt(bestMoves.lenght));

Related

How is this snake moving?

I am trying to understand a java game code but cant move past this problem.
This is a snake and apple game. I don't understand the few lines where I have commented out with "???". I dont understand how is this snake moving. I dont understand draw and move method, especially the move method.
public class GamePanel extends JPanel implements ActionListener {
static final int SCREEN_WIDTH = 600;
static final int SCREEN_HEIGHT = 600;
static final int UNIT_SIZE = 25;
static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/(UNIT_SIZE*UNIT_SIZE);
static final int DELAY = 75;
final int x[] = new int[GAME_UNITS];
final int y[] = new int[GAME_UNITS];
int bodyParts = 6;
int applesEaten;
int appleX;
int appleY;
char direction = 'R';
boolean running = false;
Timer timer;
Random random;
public void draw (Graphics g) {
for(int i=0; i<SCREEN_HEIGHT/UNIT_SIZE; i++) {
g.drawLine(i*UNIT_SIZE, 0 , i*UNIT_SIZE, SCREEN_HEIGHT);//x1,y1,x2,y2 ,basically first point and last point
g.drawLine(0, i*UNIT_SIZE , SCREEN_WIDTH, i*UNIT_SIZE);
}
g.setColor(Color.red);
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
for (int i=0; i<bodyParts;i++) {//?????????????what does this mean ?
if(i==0) {
g.setColor(Color.green);
g.fillRect(x[i],y[i], UNIT_SIZE, UNIT_SIZE);//??
}
else {
g.setColor(new Color(45,180,0));
g.fillRect(x[i],y[i],UNIT_SIZE,UNIT_SIZE);
}
}
}
public void move () {
for(int i = bodyParts;i>0;i--) {//?????????????what does this mean ?, why i--
x[i] = x[i-1];///?????????????????????what does this mean ?
y[i] = y[i-1];/////what does this mean ?
}
switch(direction) {
case 'R':
y[0] = y[0] + UNIT_SIZE; //????????????????what is this doing ???
break;
}
Iterate through the integers from 0 to bodyParts
Draw a square of size UNIT_SIZE*UNIT_SIZE at the coordinate (x[i],y[i])
The head of the snake (first coordinate stored in x and y) is green, the rest of the body is light blue
The snake moves by altering the position of its bodyparts one by one, setting the current element's position to that of the following element, this starts from the back to avoid having to create temporary variables
After having altered the position of every bodyPart of the snake the head's position is altered as well, if direction equaled 'R', then the snake's head "goes down" by UNIT_SIZE. (it results in the snake's head going down because in Swing the top-left of the screen is the starting point, so the coordinate pair (0,0), by adding to the head's height coordinate (y) you're moving it away from the top, which is down.

Java - Libgdx -TiledMap | get screenX & screenY for every Cell in the Map

as the title says, i'm trying to get the screen coordinates for each cell in my map. is it even possible?
I'm really frustraited and can't figure it out!
I appreciate your help!
note that my map has a static position on the screen.
Another note: i have a custom class Cell that extends Actor. I made it to make my cells clickable and it looks like this:
public class Cell extends Actor {
private TiledMapTileLayer.Cell tiledMapCell;
private Texture cellTexture;
public Cell(TiledMapTileLayer.Cell tiledMapCell, Field field){
this.tiledMapCell = tiledMapCell;
this.field = field;
this.cellTexture = tiledMapCell.getTile().getTextureRegion().getTexture();
}
public TiledMapTileLayer.Cell getTiledMapCell(){
return this.tiledMapCell;
}
public Texture getCellTexture(){
return this.cellTexture;
}
public void setCellTexture(Texture texture){
this.cellTexture = texture;
this.tiledMapCell.setTile(new StaticTiledMapTile(new TextureRegion(cellTexture)));
Thanks!!
You can process like this :
In your Cell class add a new Variable to get the position of the tile.
private Vector2 pos;
Change your constructor.
public Cell(TiledMapTileLayer.Cell tiledMapCell, Field field, Vector2 pos) {
this.tiledMapCell = tiledMapCell;
this.field = field;
this.cellTexture = tiledMapCell.getTile().getTextureRegion().getTexture();
this.pos = pos;
}
In your main class get the number of tiles in the width of your map, do the same for the height and the size of a tile.
int mapWidth = tiledMapTileLayer.getWidth();
int mapHeight = tiledMapTileLayer.getHeight();
int tileSize = tiledMapTileLayer.getTileWidth();
now use a loop
// These variables will store the coordinates of each new tile. and will be changed at each loop turn.
int tempX = 0;
int tempY = 0;
for (int i = 0; i < mapWidth * mapHeight; i++) {
pos = new Vector2 (tempX + tileSize / 2, tempY + tileSize / 2);
// Create a new cell with your Cell class, pass it the position.
new Cell(TiledMapTileLayer.Cell tiledMapCell, Field field, pos)
// Increase the tempX
tempX += tileSize;
// If the first line is finish we go to the next one.
if (tempX > mapWidth * tileSize) {
tempY += tileSize;
tempX = 0;
}
}
This is the method i use cause i did not find any other way.

How to create the correct relationship between classes

I have a feeling this question is going to be something really common sense that I am overcomplicating. I am working on a random maze generation program, so given a width, height, and maximum path length, it will randomly select a start point and generate a path until the max path length is reached or it dead ends/gets stuck, then it will pick a new start point for another path and repeat until the whole grid is filled. I am just creating it for the practice.
I have 3 classes, but I guess I do not really understand how they should interact, or how I should make them interact for the best performance and such. One thing in particular, I just know is terrible practice. Since my Path and Point classes have to operate on the grid of Points that is created in the Maze class, I pass the constructors for Path and Point that Array of Points. It "works"... but I just realized that in doing that, I get a seemingly infinite loop where I create a grid, and create all the points for that grid, and in those points I pass an Array of Points, and each of those Points gets passed an Array of Points, forever.
I thought about making Path and Point extend Maze, but I do not think that is the right relationship. I googled interfaces and abstract classes to see if maybe that is what I wanted, but those did not seem right either.
Maze constructor:
public class Maze
{
private int fileNum = 0;
private Random rand = new Random();
private Point[] grid;
private int width, height;
private int pathLength;
private int curLoc;
private boolean debug, toTxt, toPng, hasValidNewHead = true;
public int frameNum = 0;
public int lastPercent = 0;
public Maze(int iWidth, int iHeight, int iPathLength, boolean d, boolean txt, boolean png)
{
width = iWidth;
height = iHeight;
pathLength = iPathLength;
grid = new Point[width * height];
debug = d;
toTxt = txt;
toPng = png;
}
Path constructor:
public class Path
{
private Random rand = new Random();
private Maze maze;
private int length, maxLength, lastDir, height, width;
private int curLoc;
private boolean generating;
private Point[] grid;
private boolean debug, toTxt, toPng;
public Path(int head, int gridWidth, int gridHeight, int ml, Point[] iGrid, Maze m, boolean d, boolean txt, boolean png)
{
maze = m;
generating = true;
lastDir = -1;
length = 1;
grid = iGrid;
curLoc = head;
height = gridHeight;
width = gridWidth;
maxLength = ml;
debug = d;
toTxt = txt;
toPng = png;
}
Point constructor:
public class Point
{
private int x, y, width, height;
private Point[] grid;
private int type, curLoc;
public Point(int iX, int iY, int w, int h, Point[] iGrid)
{
x = iX;
y = iY;
width = w;
height = h;
grid = iGrid;
curLoc = Arrays.asList(grid).indexOf(this);
type = 0;
}
Mazes are annoying to model because they're either structured around rooms or walls, you need different ones at different times, and either way, you'll end up with tricky code or redundant data and awkward record keeping.
Thad said, Paths are sequences/Lists of moves (North, South, East West), a Maze is an array (or Map) from a coordinate to a Cell/Room, and Cells have boolean walls keyed on moves, so { East: true, North: false, South, false, West: true}.
Or you could just make it an undirected graph.
All I had to do was make the Path and Point classes inner-classes in my Maze Class. That way they have all of the instance data from Maze that they need without needing to pass it through their constructors.

Finding solution to maze in java

I have a project to have a red dot inside the first box of a maze i randomly generated and the dot is supposed to follow its way through the boxes and find the end of the maze. Now if it hits a dead end, its supposed to go back to where its path started and not go back down that path, that leads to a dead end. i made it so each box represents the #1, this way when the red dot travels over the box, it increments by 1, so it can realize where its been. its always supposed to go to the lowest number possible so it can never go back to the dead ends its already been to. i am able to reach the end of the maze but i come into 2 problems.
the method i wrote that does all this work is the solve() function. I cant understand why 2 things happen...
1st thing is that when the red dot comes to a branch of dead ends, sometimes itll just go to one dead end, to a different dead end , back to the same dead end.. traveling to the same 'numbers' when im trying to have it only go towards the boxes that have 1's or just the lower numbers.
2nd thing is that once it inevitably reaches the end of the maze.. the red dot goes into the green area, where i specifically say in the while loop, it can not be in a green box.
if M[y][x] = 0, its a green box and if its = 1 its a black box. anything higher than 1 will also be inside the box.
your help is highly appreciated as ive been stuck on this problem for hours and cant seem to find out the problem.
the problem persists in the solve() method
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
import javax.swing.*;
public class mazedfs extends JFrame implements KeyListener
{
/* default values: */
private static int bh = 16; // height of a graphical block
private static int bw = 16; // width of a graphical block
private int mh = 41; // height and width of maze
private int mw = 51;
private int ah, aw; // height and width of graphical maze
private int yoff = 40; // init y-cord of maze
private Graphics g;
private int dtime = 40; // 40 ms delay time
byte[][] M; // the array for the maze
public static final int SOUTH = 0;
public static final int EAST = 1;
public static final int NORTH = 2;
public static final int WEST = 3;
public static boolean showvalue = true; // affects drawblock
// args determine block size, maze height, and maze width
public mazedfs(int bh0, int mh0, int mw0)
{
bh = bw = bh0; mh = mh0; mw = mw0;
ah = bh*mh;
aw = bw*mw;
M = new byte[mh][mw]; // initialize maze (all 0's - walls).
this.setBounds(0,0,aw+10,10+ah+yoff);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try{Thread.sleep(500);} catch(Exception e) {} // Synch with system
this.addKeyListener(this);
g = getGraphics(); //g.setColor(Color.red);
setup();
}
public void paint(Graphics g) {} // override automatic repaint
public void setup()
{
g.setColor(Color.green);
g.fill3DRect(0,yoff,aw,ah,true); // fill raised rectangle
g.setColor(Color.black);
// showStatus("Generating maze...");
digout(mh-2,mw-2); // start digging!
// digout exit
M[mh-1][mw-2] = M[mh-2][mw-1] = 1;
drawblock(mh-2,mw-1);
solve(); // this is the function you will write for parts 1 and 2
play(); // for part 3
}
public static void main(String[] args)
{
int blocksize = bh, mheight = 41, mwidth = 41; // need to be odd
if (args.length==3)
{
mheight=Integer.parseInt(args[0]);
mwidth=Integer.parseInt(args[1]);
blocksize=Integer.parseInt(args[2]);
}
mazedfs W = new mazedfs(blocksize,mheight,mwidth);
}
public void drawblock(int y, int x)
{
g.setColor(Color.black);
g.fillRect(x*bw,yoff+(y*bh),bw,bh);
g.setColor(Color.yellow);
// following line displays value of M[y][x] in the graphical maze:
if (showvalue)
g.drawString(""+M[y][x],(x*bw)+(bw/2-4),yoff+(y*bh)+(bh/2+6));
}
void drawdot(int y, int x)
{
g.setColor(Color.red);
g.fillOval(x*bw,yoff+(y*bh),bw,bh);
try{Thread.sleep(dtime);} catch(Exception e) {}
}
/////////////////////////////////////////////////////////////////////
/* function to generate random maze */
public void digout(int y, int x)
{
M[y][x] = 1; // digout maze at coordinate y,x
drawblock(y,x); // change graphical display to reflect space dug out
int dir = (int)(Math.random()*4);
for (int i=0;i<4;i++){
int [] DX = {0,0,2,-2};
int [] DY = {-2,2,0,0};
int newx = x + DX[dir];
int newy = y + DY[dir];
if(newx>=0 && newx<mw && newy>=0 && newy<mh && M[newy][newx]==0)
{
M[y+DY[dir]/2][x+DX[dir]/2] = 1;
drawblock(y+DY[dir]/2,x+DX[dir]/2);
digout(newy,newx);
}
dir = (dir + 1)%4;}
} // digout
public void solve() // This is the method i need help with.
{
int x=1, y=1;
drawdot(y,x);
while(y!=mh-1 || x!=mw-1 && M[y][x]!=0){
int min = 0x7fffffff;
int DX = 0;
int DY = 0;
if (y-1>0 && min>M[y-1][x] && M[y-1][x]!=0){
min = M[y-1][x];
DX = 0;
DY = -1;
}//ifNORTH
if (y+1>0 && min>M[y+1][x] && M[y+1][x]!=0){
min = M[y+1][x];
DY = 1;
DX = 0;
}//ifSOUTH
if (x-1>0 && min>M[y][x-1] && M[y][x-1]!=0){
min = M[y][x-1];
DX = -1;
DY = 0;
}//ifWEST
if (x+1>0 && min>M[y][x+1] && M[y][x+1]!=0){
min = M[y][x+1];
DX = 1;
DY = 0;
}//ifEAST
M[y][x]++;
drawblock(y,x);
x = x+DX;
y = y+DY;
drawdot(y,x);
}//while
// modify this function to move the dot to the end of the maze. That
// is, when the dot reaches y==mh-2, x==mw-2
} // solve
///////////////////////////////////////////////////////////////
/// For part three (save a copy of part 2 version first!), you
// need to implement the KeyListener interface.
public void play() // for part 3
{
// code to setup game
}
// for part 3 you may also define some other instance vars outside of
// the play function.
// for KeyListener interface
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) // change this one
{
int key = e.getKeyCode(); // code for key pressed
System.out.println("YOU JUST PRESSED KEY "+key);
}
} // mazedfs
////////////
// define additional classes (stack) you may need here.
The issue causing the second problem you are facing (dot moving to green box) lies in the while loop conditiony!=mh-1 || x!=mw-1 && M[y][x]!=0 . The condition evaluates to y!=mh-1 ||(x!=mw-1 && M[y][x]!=0) since && has higher precedence over the || and || just needs one of its operand to be true. In your case, y!=mh-1 is still ture at the end of maze. Hence the loop continues and the dot moves into green area. To fix the issue modify the condition as (y!=mh-1 || x!=mw-1) && M[y][x]!=0. Hope this helps.

Maze, optimal path finding using stacks

i have a program that generates a random maze. In the maze a red dot is displayed and the red dot flashes on by each block in the maze. all the blocks in the maze are == 1 and if the red dot goes through that block, it increments ++. the red dot goes in the direction towards the lowest number, that way it wont stay in an infinite loop by a dead end. once it reaches the end, ive solved the maze.
This is where im stumped, im trying to print the red dot to find the optimal route all the way back to the beginning where it started. I used a stack class that i made to record all the y and x components of where the red dot traveled. im able to traceback every where the red dot has gone but that isnt the optimal solution.
My question is how could i print the red dot tracing back in only the optimal path. My idea of solving this would be to check and see if the coordinates of a stack where visited before, if so..find the last case where it was visited and print the red dot up until that point. that way itll never deal with the dead ends it traveled.
the method solve() is what contains the traceback and solving technique for the red dot to travel through the maze and back.
Im not the greatest programmer and im still learning how to use stacks, ive been stumped for hours and dont know how to approach this. Please be kind and explain how you would do it using the stack i made. Thank you
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
import javax.swing.*;
public class mazedfs extends JFrame implements KeyListener
{
/* default values: */
private static int bh = 16; // height of a graphical block
private static int bw = 16; // width of a graphical block
private int mh = 41; // height and width of maze
private int mw = 51;
private int ah, aw; // height and width of graphical maze
private int yoff = 40; // init y-cord of maze
private Graphics g;
private int dtime = 40; // 40 ms delay time
byte[][] M; // the array for the maze
public static final int SOUTH = 0;
public static final int EAST = 1;
public static final int NORTH = 2;
public static final int WEST = 3;
public static boolean showvalue = true; // affects drawblock
// args determine block size, maze height, and maze width
public mazedfs(int bh0, int mh0, int mw0)
{
bh = bw = bh0; mh = mh0; mw = mw0;
ah = bh*mh;
aw = bw*mw;
M = new byte[mh][mw]; // initialize maze (all 0's - walls).
this.setBounds(0,0,aw+10,10+ah+yoff);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try{Thread.sleep(500);} catch(Exception e) {} // Synch with system
this.addKeyListener(this);
g = getGraphics(); //g.setColor(Color.red);
setup();
}
public void paint(Graphics g) {} // override automatic repaint
public void setup()
{
g.setColor(Color.green);
g.fill3DRect(0,yoff,aw,ah,true); // fill raised rectangle
g.setColor(Color.black);
// showStatus("Generating maze...");
digout(mh-2,mw-2); // start digging!
// digout exit
M[mh-1][mw-2] = M[mh-2][mw-1] = 1;
drawblock(mh-2,mw-1);
solve(); // this is the function you will write for parts 1 and 2
play(); // for part 3
}
public static void main(String[] args)
{
int blocksize = bh, mheight = 41, mwidth = 41; // need to be odd
if (args.length==3)
{
mheight=Integer.parseInt(args[0]);
mwidth=Integer.parseInt(args[1]);
blocksize=Integer.parseInt(args[2]);
}
mazedfs W = new mazedfs(blocksize,mheight,mwidth);
}
public void drawblock(int y, int x)
{
g.setColor(Color.black);
g.fillRect(x*bw,yoff+(y*bh),bw,bh);
g.setColor(Color.yellow);
// following line displays value of M[y][x] in the graphical maze:
if (showvalue)
g.drawString(""+M[y][x],(x*bw)+(bw/2-4),yoff+(y*bh)+(bh/2+6));
}
void drawdot(int y, int x)
{
g.setColor(Color.red);
g.fillOval(x*bw,yoff+(y*bh),bw,bh);
try{Thread.sleep(dtime);} catch(Exception e) {}
}
/////////////////////////////////////////////////////////////////////
/* function to generate random maze */
public void digout(int y, int x)
{
M[y][x] = 1; // digout maze at coordinate y,x
drawblock(y,x); // change graphical display to reflect space dug out
int dir = (int)(Math.random()*4);
for (int i=0;i<4;i++){
int [] DX = {0,0,2,-2};
int [] DY = {-2,2,0,0};
int newx = x + DX[dir];
int newy = y + DY[dir];
if(newx>=0 && newx<mw && newy>=0 && newy<mh && M[newy][newx]==0)
{
M[y+DY[dir]/2][x+DX[dir]/2] = 1;
drawblock(y+DY[dir]/2,x+DX[dir]/2);
digout(newy,newx);
}
dir = (dir + 1)%4;}
} // digout
/* Write a routine to solve the maze.
Start at coordinates x=1, y=1, and stop at coordinates
x=mw-1, y=mh-2. This coordinate was especially dug out
after the program called your digout function (in the "actionPerformed"
method).
*/
public void solve()
{
int x=1, y=1;
Stack yourstack = null;
drawdot(y,x);
while(y!=mh-2 || x!=mw-2 && M[y][x]!=0){
int min = 0x7fffffff;
int DX = 0;
int DY = 0;
if (y-1>0 && min>M[y-1][x] && M[y-1][x]!=0){
min = M[y-1][x];
DX = 0;
DY = -1;
}//ifNORTH
if (y+1>0 && min>M[y+1][x] && M[y+1][x]!=0){
min = M[y+1][x];
DY = 1;
DX = 0;
}//ifSOUTH
if (x-1>0 && min>M[y][x-1] && M[y][x-1]!=0){
min = M[y][x-1];
DX = -1;
DY = 0;
}//ifWEST
if (x+1>0 && min>M[y][x+1] && M[y][x+1]!=0){
min = M[y][x+1];
DX = 1;
DY = 0;
}//ifEAST
M[y][x]++;
drawblock(y,x);
x = x+DX;
y = y+DY;
drawdot(y,x);
yourstack = new Stack(y,x,yourstack); // creates new stack for each coordinate travelled
}//while
while(yourstack != null){
yourstack = yourstack.tail;
drawdot(yourstack.y,yourstack.x); // this will traceback every box ive been through
}//while
} // solve
class Stack{
int x;
int y;
Stack tail;
public Stack(int a, int b, Stack t){
y = a;
x=b;
tail=t;
}
}//stackclass
///////////////////////////////////////////////////////////////
/// For part three (save a copy of part 2 version first!), you
// need to implement the KeyListener interface.
public void play() // for part 3
{
// code to setup game
}
// for part 3 you may also define some other instance vars outside of
// the play function.
// for KeyListener interface
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) // change this one
{
int key = e.getKeyCode(); // code for key pressed
System.out.println("YOU JUST PRESSED KEY "+key);
}
} // mazedfs
////////////
// define additional classes (stack) you may need here.
when you trace your path back you currently just go back to your stack - but thats not the shortest path...
...whenever you can go back check the values of M around you:
byte valueOfFieldNorthOfXY = M[x][y-1]; //x/y is your current position
byte valueOfFieldWesthOfXY = M[x-1][y];
byte ...;
byte ...; //and so on...
while the first while-loop in your solve-methode simplay solves the maze by flooding it the second while-method is for going back...
and when i say flooding i mean: each time a field has been passed by the 'walker' the value of M[x][y] has been increased by 1 (when the 'walker' has walked 3x over field 5/6 then the value from M[5][6] = 3)
so when you go back from the end (#40/50) to the start (#1/1), you do this algorith:
1) i stand on x/y
2) i check the values north/east/south/west of me
2a) if i come from north, then i ignore the north field
2 ) ... and so on...
2d) if i come from west , then i ignore the west field
3) i pick that direction, where the value is the least
4) put the current field int your packPathStack and walk to
the 'best' direction
5) repeat (go back to Nr.1) until you are #1/1
example
? 4 ? //i'm standing at X (x/y)
2 x f //? are values from walls or not yet considerd
? ? ? //f is where i come from
--> i pick direction WEST(2) because thats less than NORTH(4)
implement this algorithm and you a NEW stack i call it yourPathBackStack
Stack yourPathBackStack = new Stack();
while(x != 1 && y != 1 ){ //x/y = 1/1 = start - do it until you are there (Nr. 5)
// 1) i stand on x/y
int x = yourPathBackStack.x;
int y = yourPathBackStack.y;
// 2) i check the values north/east/south/west of me
byte valueOfFieldNorthOfXY = ... ; //as seen above
// 2a) if i come from north, then i ignore the north field
if (yourstack.tail.x == x && yourstack.tail.y == y-1){
//check - i DO come from north
//make then valueOfFieldNorthOfXY very high
valueOfFieldNorthOfXY = 100; //it's the same as ignoring
}
// 2 ) ... and so on...
// 2d) if i come from west , then i ignore the west field
if (yourstack.tail.x == x-1 && ...// as seen above
// 3) i pick that direction, where the value is the least
int direction = NORTH; //lets simply start with north;
byte maxValue = 100;
if ( valueOfFieldNorthOfXY < maxValue ){ //First north
maxValue = valueOfFieldNorthOfXY;
direction = NORTH;
}
if ( valueOfFieldWestOfXY < maxValue ){ //Then east
maxValue = valueOfFieldWestOfXY ;
direction = WEST;
}
//then the also other directions
if ( value ... //as seen above
// 4) put the current field int your yourPathBackStack and walk to
// the 'best' direction
int newx = x;
int newy = y;
if (direction == NORTH){ //direction has been caclulated above
newy = newy - 1;
}
if (direc ... //with all other direction)
yourPathBackStack = new Stack(newx, newy, yourPathBackStack );
drawdot(yourPathBackStack.y,yourPathBackStack.x);
}

Categories