1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
| import java.awt.Color; import java.awt.Graphics; import java.util.Random;
import javax.swing.JFrame;
public class Pathsearch extends JFrame {
int curX=0; int curY=0; int SIZE_X=30; int SIZE_Y=30; int[][] passable = new int[SIZE_X][SIZE_Y]; int[][] field = new int[SIZE_X][SIZE_Y]; int scaling=10; int tx=10; int ty=40; int startX=25; int startY=25; int goalX=1; int goalY=1; public Pathsearch() {
this.setVisible(true); this.setSize(SIZE_X*10+20, SIZE_Y*10+50); setDefaultCloseOperation(3);
this.setLocationRelativeTo(null); Random ran=new Random(); for(int xx=0;xx<SIZE_X;xx++) { for(int yy=0;yy<SIZE_Y;yy++) { passable[xx][yy]=ran.nextInt(4)==0?1:0; } } this.repaint(); curX=startX; curY=startY; System.out.println(0 % 2 ); while(true) { int gx=curX; int gy=curY; double minDist=1000000; for(int x=-1;x<2;x++) { for(int y=-1;y<2;y++) { int nx=curX+x; int ny=curY+y; if(nx>=0 && nx<SIZE_X && ny>=0 && ny<SIZE_Y && !(x==0 && y==0) && !(Math.abs(x)==1 && Math.abs(y)==1)) { if(passable[nx][ny]==0) { double dx=nx-goalX; double dy=ny-goalY; double dist=Math.sqrt((dx*dx) + (dy*dy)); dist+=field[nx][ny]; if(dist<minDist) { gx=nx; gy=ny; minDist=dist; } } } } } curX=gx; curY=gy; field[gx][gy]+=50; if(curX==goalX && curY==goalY) break; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } this.repaint(); } } BufferedImage buffer=new BufferedImage(400,400,1); public void paint(Graphics g) { Graphics g2=g; g=buffer.getGraphics(); g.setColor(new Color(255,255,255)); g.fillRect(0, 0, 400, 400); g.translate(tx, ty); g.setColor(new Color(230,230,230)); for(int xx=0;xx<SIZE_X;xx++) { g.drawLine(xx*scaling, 0, xx*scaling, SIZE_Y*scaling); } for(int xx=0;xx<SIZE_Y;xx++) { g.drawLine(0, xx*scaling, SIZE_X*scaling, xx*scaling); } g.setColor(new Color(100,100,100)); for(int xx=0;xx<SIZE_X;xx++) { for(int yy=0;yy<SIZE_Y;yy++) { if(passable[xx][yy]!=0) g.fillRect(xx*scaling, yy*scaling, scaling, scaling); } } g.setColor(new Color(250,100,100)); g.fillRect(startX*scaling, startY*scaling, scaling, scaling); g.setColor(new Color(100,100,250)); g.fillRect(goalX*scaling, goalY*scaling, scaling, scaling);
g.setColor(new Color(100,250,100)); g.fillRect(curX*scaling, curY*scaling, scaling, scaling); g2.drawImage(buffer, 0, 0, null); } public static void main(String[] args) { new Pathsearch();
}
}
|