Created
October 3, 2015 05:18
-
-
Save prmichaelsen/3383b2c344954d5c5d88 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.Random; | |
public class Roads { | |
public static final int TILE_SIZE = 32; | |
public static final int ROOM_HEIGHT = 1024+512; | |
public static final int ROOM_WIDTH = 1024+512; | |
public static final int ROAD_LENGTH = 3; | |
public static final int[][] DIRECTION = { | |
{0, -1}, //North | |
{1, 0}, //East | |
{0, 1}, //South | |
{-1, 0}}; //West | |
public static final Random rnd = new Random(); | |
public static int map[][] = new int[ROOM_HEIGHT/TILE_SIZE][ROOM_WIDTH/TILE_SIZE]; | |
public static int tiles[] = {1,0}; //ROAD, WALL | |
public static void buildRoad(int x, int y, int size, int dir){ | |
boolean run = true; | |
boolean can = false; | |
while(run && size > 0){ | |
ArrayList<Integer> directions = | |
new ArrayList<Integer>( | |
Arrays.asList(new Integer[]{0,1,2,3})); | |
Collections.shuffle(directions); | |
can = false; | |
//try to find a free direction | |
while(!directions.isEmpty() && can == false){ | |
if(can = checkFree(x,y,size,dir=directions.remove(0))){ | |
for(int i = 0; i < ROAD_LENGTH; i++){ | |
map[x][y]=dir+1; | |
x += DIRECTION[dir][0]; | |
y += DIRECTION[dir][1]; | |
} | |
size--; | |
} | |
} | |
run = can; | |
} | |
} | |
private static boolean checkFree(int x, int y, int size, int dir){ | |
boolean can = true; | |
for(int i = 0; i < ROAD_LENGTH+1; i++){ | |
if(inBounds(x,y)){ | |
if(map[x][y]>0) | |
can= false; | |
}else if(i < ROAD_LENGTH) | |
can= false; | |
x += DIRECTION[dir][0]; | |
y += DIRECTION[dir][1]; | |
} | |
return can; | |
} | |
private static boolean inBounds(int x, int y){ | |
if(x<0 || x>=ROOM_WIDTH/TILE_SIZE || | |
y<0 || y>=ROOM_HEIGHT/TILE_SIZE) | |
return false; | |
return true; | |
} | |
public static void main(String[] args){ | |
buildRoad(ROOM_WIDTH/TILE_SIZE/2,ROOM_HEIGHT/TILE_SIZE/2,2000,0); | |
//buildRoad(ROOM_WIDTH/TILE_SIZE/2+1,ROOM_HEIGHT/TILE_SIZE/2,500,2); | |
for(int i=0;i<ROOM_WIDTH/TILE_SIZE;i++){ | |
for(int j=0;j<ROOM_HEIGHT/TILE_SIZE;j++){ | |
System.out.print((map[i][j] > 0)? " " : "0 "); | |
} | |
System.out.println(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment