|
| 1 | +package MapGenerator; |
| 2 | + |
| 3 | +public class CellAutomataStrategy implements Strategy { |
| 4 | + |
| 5 | + public void makeLikeNeighbours(Map map, int y, int x) { |
| 6 | + int difference = 0; //насколько больше стенок, чем полов |
| 7 | + |
| 8 | + int height = map.getHeight(); |
| 9 | + int width = map.getWidth(); |
| 10 | + |
| 11 | + for(int dx=-1; dx<2; dx++) { |
| 12 | + for (int dy=-1; dy < 2; dy++) { |
| 13 | + |
| 14 | + if(dx==0 && dy==0) continue; |
| 15 | + |
| 16 | + int Y=0, X=0; |
| 17 | + if(0 <= y+dy && y+dy < height) Y = y+dy; |
| 18 | + if(0 <= x+dx && x+dx < width) X = x+dx; |
| 19 | + if(y+dy < 0 ) Y = height+y+dy; |
| 20 | + if(y+dy >= height) Y = y+dy-height; |
| 21 | + if(x+dx < 0) X = width+x+dx; |
| 22 | + if(x+dx >= width) X = x+dx-width; |
| 23 | + |
| 24 | + difference += checkNeighbour(map, Y,X); |
| 25 | + } |
| 26 | + } |
| 27 | + if(difference >= -1 ) |
| 28 | + map.set(y, x, Parameter.WALL); |
| 29 | + else |
| 30 | + map.set(y, x, Parameter.FLOOR); |
| 31 | + } |
| 32 | + |
| 33 | + public int checkNeighbour(Map map, int y, int x) { |
| 34 | + if(map.get(y,x) == Parameter.FLOOR) |
| 35 | + return -1; |
| 36 | + if(map.get(y,x) == Parameter.WALL) |
| 37 | + return +1; |
| 38 | + else return 0; |
| 39 | + } |
| 40 | + |
| 41 | + public void mirrorCell(Map map, int h, int w) { |
| 42 | + Boolean value = map.get(h, w); |
| 43 | + map.set(map.getHeight() - 1 - h, w, value); |
| 44 | + map.set(h, map.getWidth() - 1 - w, value); |
| 45 | + map.set(map.getHeight() - 1 - h, map.getWidth() - 1 - w, value); |
| 46 | + } |
| 47 | + |
| 48 | + @Override |
| 49 | + public Map generateMap(int originalHeight, int originalWidth) { |
| 50 | + Map resultMap = new Map(originalHeight, originalWidth); |
| 51 | + |
| 52 | + int height = originalHeight/2 + originalHeight%2; |
| 53 | + int width = originalWidth/2 + originalWidth%2; |
| 54 | + |
| 55 | + for(int k=0; k< Parameter.LAYER_DEPTH; ++k) { //наложение сгенерированных карт друг на друга |
| 56 | + Map map = new Map(originalHeight, originalWidth); |
| 57 | + for (int initials = 0; initials < height * width * Parameter.INITIAL_PERCENTAGE / 100.0; initials++) { |
| 58 | + int y = (int) (Math.random() * (height-2)+1); |
| 59 | + int x = (int) (Math.random() * (width-2)+1); |
| 60 | + map.set(y, x, Parameter.WALL); |
| 61 | + } |
| 62 | + for (int i = 0; i < Parameter.AUTOMATA_DEPTH; ++i) { // глубина просчета клеток автоматом |
| 63 | + for (int h = height - 1; h >= 0; h--) { |
| 64 | + for (int w = 0; w < width; w++) { |
| 65 | + makeLikeNeighbours(map, h, w); |
| 66 | + mirrorCell(map, h, w); |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + resultMap.impose(map); |
| 71 | + } |
| 72 | + return resultMap; |
| 73 | + } |
| 74 | +} |
0 commit comments