-
1 Attachment(s)
Java Labrynth Game
Code:
import java.io.*;
import java.util.*;
public class MapToString{
public char[][] mArray;
public char WALL = (char)35;
public char PLAYER = (char)80;
public MapToString(String file){
File map = new File(file);
try{
String line;
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner(map);
for(int i = 0;scan.hasNextLine();i++){
line = scan.nextLine();
list.add(line);
}
mArray = new char[list.size()][];
for(int i=0; i<mArray.length; i++){
mArray[i] = ((String) list.get(i)).toCharArray();
System.out.println(mArray[i]);
System.out.println(mArray[1][2]);
}
//System.out.println(mArray);
}
catch(Exception e){
System.out.println("invalid file");
}
}
public static void main(String[] args){
new MapToString(get_map());
}
public static String get_map(){
System.out.println("Please enter name of map you wish to load: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = null;
try{
input = br.readLine();
//reads input
}catch (Exception e){
System.out.println("Error trying to read");
System.exit(1);
//in case of error
}
return input;
}
public char[][] getmArray(){
return mArray;
}
}
Code:
import java.io.*;
import java.util.*;
public class GameLogic{
String file = "map2.txt";
MapToString m = new MapToString(file);
private void startPosition(){
int randomHeight = getRandomHeight();
int randomWidth = getRandomWidth();
if(m.mArray[randomHeight][randomWidth] != m.WALL){
int x = randomWidth;
int y = randomHeight;
setPlayer(x,y);
}
else{
startPosition();
}
}
private char setPlayer(int i, int j){
return m.mArray[i][j];
}
private int getRandomHeight(){
Random gen = new Random();
int i = gen.nextInt(m.mArray.length);
return i;
}
private int getRandomWidth(){
Random gen = new Random();
int i = gen.nextInt(m.mArray[0].length);
return i;
}
public static void main(String[] args){
new GameLogic();
}
}
this above is 2 codes I have written, MapToString takes a text file, and converts it into a 2d array.
with GameLogic, I want to place a character "P" in a random position on the map, which isn't a #. I have written the class to get the random position, but am not sure how i can put P onto the board, without replacing the existing character.
Please help,
I have attached the txt file