I have a map class, which is an Array of 100 Strings
public class map{
[...]
public void movePlayer(String entrada){
if (entrada.equalsIgnoreCase("w")){
move = -10;
}
else if (entrada.equalsIgnoreCase("s")){
move = 10;
}
else if (entrada.equalsIgnoreCase("d")){
move = 1;
}
else if (entrada.equalsIgnoreCase("a")){
move = -1;
}
for(int i = 0; i < mapa.length; i++){
if (mapa[i].equals("P")){
int moved = i+move;
mapa[moved] = "P";
}
}
}
The main looks a little like this
String[] mapa = map.getMap();
mapa[0] = "T";
mapa[99] = "P";
for (int j = 0; j<10; j++){
for(int i = 0; i < map.length; i++){
if (i == 9 || i == 19 || i == 29 || i == 39 || i == 49 || i == 59 || i == 69 || i == 79 || i == 89 || i == 99){
System.out.println(mapa[i]);
}
else{
System.out.print(mapa[i]);
}
}
System.out.print("\n");
System.out.print("Entre o movimento:");
map.movePlayer(read.nextLine());
mapa = map.getMap();
}
It runs like this: A map with random chars are printed, some are normal floors some are traps
EXAMPLE
T##_______
^__#__*^#_
##^^#_#___
_*^^^#^^#^
^^_#_^____
^#_^#___##
*#^_^_____
^###_^__^#
#_#^##^#**
##^^_##_#P
Enter movement:w
T##_______
^__#__*^#_
##^^#_#___
_*^^^#^^#^
^^_#_^____
^#_^#___##
*#^_^_____
^###_^__^#
#_#^##^#*P
##^^_##_#P
Enter movement: w
T##_______
^__#__*^#_
##^^#_#___
_*^^^#^^#^
^^_#_^____
^#_^#___##
*#^_^_____
^###_^__^P
#_#^##^#*P
##^^_##_#P
How can I make the program to print the place where the Player originally was with the previous char it had, in this case a blank space in position [99] and a "*" in position [89]? Thanks for the patience!
Instead of tracking the player inside the map, you can leave the map unchanged and just track the player's position.
int playerpos = 99;
for (int j = 0; j<10; j++){
for(int i = 0; i < map.length; i++){
if (playerpos == i)
System.out.print("P");
else
System.out.print(mapa[i]);
if (i %10 == 9){
System.out.println();
}
}
Then your movePlayer method just changes the playerpos variable.
before player's movement you need to store data from the target cell, like this
int moved = i+move;
previousChar = mapa[moved]; // store replaced symbol
mapa[moved] = "P";
so, during next move you need to restore original char in old position, it could look like this:
int moved = i+move;
mapa[i] = previousChar; // restore original symbol at current player's location
previousChar = mapa[moved]; // preserve symbol at new player's location
mapa[moved] = "P"; // move player to new location
don't forget to init previousChar before very first move
As Lashane is saying, use a variable to store the overriden char for later assignment:
public class map{
[...]
this.init(function() {
last_squarechar = INIT_SQUARECHAR
[...]
});
public void movePlayer(String entrada) {
if (entrada.equalsIgnoreCase("w")){
move = -10;
}
else if (entrada.equalsIgnoreCase("s")){
move = 10;
}
else if (entrada.equalsIgnoreCase("d")){
move = 1;
}
else if (entrada.equalsIgnoreCase("a")){
move = -1;
}
}
for(int i = 0; i < mapa.length; i++){
if (mapa[i].equals("P")){
int moved = i+move;
mapa[i] = last_squarechar
last_squarechar = mapa[moved]
mapa[moved] = "P";
}
}
}
Related
I have been working on my homework of creating a simple chess program.
The chessboard is a 2D array, named board. The pieces are all single chars like R,Q,K, and empty space is filled with a ' ' char, so a space.
public static char[][] board;
The method get should return the char or whatever is there on the coordinate (x,y).
public char get(int x, int y) {
if(x < board[0].length && x >= 0 && y < board.length && y >= 0){
return board[x][y];
}
else
return '\0';
}
And the problem is that my program of evaluating who is the winner is not working as expected.
This program checks whether the king of each team is still in the chessboard, so the board array.
It should return 0 if both are still alive, 1, if only the white king is alive, and 2 if only the black king is alive.
I have made a program, or at least tried to make one, that goes through each coordinate and checks if there is a character 'K', which represents the white king, and 'S', the black king.
I have set the boolean kingIsAlive to false, so that if there is no K or S found in the array, it remains false.
Though, my code at the bottom, with the if and else that returns 0,1 or2, has the error, that kingWhiteIsAlive is always false and kingBlackIsAlive is always false.
So, I think my program of turning the kingIsAlive boolean to true is not working at all....
The errors I got is:
White should have won => expected: <1> but was: <-1>
No one should have won => expected: <0> but was: <1>
And after a couple of hours trying, I gave up and decided to ask here.
public int decideWinner(){
boolean kingWhiteIsAlive = false;
boolean kingBlackIsAlive = false;
for(int y = 0; y < board.length;y++){
for(int x = 0;x < board[0].length;x++){
if(get(x,y) == 'K'){
kingWhiteIsAlive = true;
}
}
}
for(int j = 0; j < board.length;j++){
for(int i = 0;i < board[0].length;i++){
if(get(i,j) == 'S'){
kingBlackIsAlive = true;
}
}
}
if(kingWhiteIsAlive && kingBlackIsAlive){
return 0;
}
else if(kingWhiteIsAlive && !kingBlackIsAlive){
return 1;
}
else if(!kingWhiteIsAlive && kingBlackIsAlive){
return 2;
}
else
return -1;
}
return -1 is for a test case that there are no kings from both teams.
I've tested your code & it's running perfectly, perhaps the problem is in your board initialization?
Try to debug your code by showing the actual content of the array at the beginning of decideWinner function.
I've used this initialization for the board, if it might help.
public void initBoard() {
board = new char[8][8];
// Init pawns
for (int j = 0; j < board.length; j++) {
board[j][1] = 'P';
board[j][6] = 'P';
}
// Rooks
board[0][0] = 'R';
board[7][0] = 'R';
board[0][7] = 'R';
board[7][7] = 'R';
// Knights
board[1][0] = 'N';
board[6][0] = 'N';
board[1][7] = 'N';
board[6][7] = 'N';
// Bishops
board[2][0] = 'B';
board[5][0] = 'B';
board[2][7] = 'B';
board[5][7] = 'B';
// Queens
board[3][0] = 'Q';
board[4][7] = 'Q';
// Kings
board[4][0] = 'K'; // White
board[3][7] = 'S'; // Black
// Empty space
for (int y = 0; y < board.length; y++) {
for (int x = 2; x < 6; x++) {
board[y][x] = ' ';
}
}
}
If you find a king, you need to interrupt your search. You can do it by a break statement.
for(int y = 0; y < board.length;y++){
for(int x = 0;x < board[0].length;x++){
if(get(x,y) == 'K'){
kingWhiteIsAlive = true;
break;
}
}
}
for(int j = 0; j < board.length;j++){
for(int i = 0;i < board[0].length;i++){
if(get(i,j) == 'S'){
kingBlackIsAlive = true;
break;
}
}
}
This question already has answers here:
Continue at first loop , inside the second loop
(7 answers)
Closed 1 year ago.
For this code kata I need to continue 2 for loops at the same time. How can I do that?
public class StringMerger {
public static boolean isMerge(String s, String part1, String part2) {
StringBuilder MergedWord = new StringBuilder("");
String Whole = part1+part2;
for(int j = 0; j < Whole.length(); j++){
for(int I = 0; I < part1.length(); I++){
if((Character.compare(s.charAt(j), part1.charAt(I)) == 0) && (j == I)){
MergedWord.append(s.charAt(I)+"");
continue;
}
else
break;
}
for(int i = 0; i < part2.length(); i++){
if((Character.compare(s.charAt(j), part2.charAt(i)) == 0) && (j == i)){
MergedWord.append(part2.charAt(i) + "");
continue;
}
else
break;
}
}
return s.equals(MergedWord.toString())? true : false;
}
}
I noticed when one of the for loops continue it only continues the internal loop, but labels would continue the upper loop and would be inefficient. Could I continue 2 for loops at the same time a.k.a continue the inner and upper loop in this nested for loop?
The task is to match each character in the target string, so you only need one loop, which iterates over the characters in the string. You do need two other loop variables to track how much of the two source strings have been used up.
My solution below is looping over three things at once: the target string and the two 'part' strings. The rate it moves over the 'part' strings isn't constant, but it does progress over them monotonically.
It wasn't clear to me whether the source strings could include extra characters not used in the target string. As the example didn't show any, I assumed not.
public class MergedStringChecker {
public static void main(String[] args) {
String target = "codewars";
String part1 = "cdw";
String part2 = "oears";
for (int i = 0, p1 = 0, p2 = 0; i < target.length(); ++i) {
if (p1 < part1.length() && target.charAt(i) == part1.charAt(p1)) {
++p1;
} else if (p2 < part2.length() && target.charAt(i) == part2.charAt(p2)) {
++p2;
} else {
throw new RuntimeException("No matching characters at index " + i);
}
}
}
}
The above solution is not Unicode safe if the string contains > 16 bit code points.
Try this.
public static boolean isMerge(String s, String part1, String part2) {
int length = s.length();
int length1 = part1.length();
int length2 = part2.length();
int i1 = 0, i2 = 0;
for (int i = 0; i < length; ++i)
if (i1 < length1 && s.charAt(i) == part1.charAt(i1))
++i1;
else if (i2 < length2 && s.charAt(i) == part2.charAt(i2))
++i2;
else
return false;
return i1 == length1 && i2 == length2;
}
public static void main(String[] args) throws IOException {
System.out.println(isMerge("codewars", "cdw", "oears"));
System.out.println(isMerge("codewars", "codewars", ""));
System.out.println(isMerge("codewars", "cdw", "oearsEXTRA"));
}
output:
true
true
false
you have an error on the first part loop you must append from the part not the s char
you don't need to chek the id of the part with the inital word (remove this check (j == I) and this one (j == i)
Use counter to avoid looping many times
Try this code :
public static boolean isMerge(String s, String part1, String part2) {
StringBuilder MergedWord = new StringBuilder("");
String Whole = part1+part2;
int counter1=0;
int counter2=0;
for(int w = 0; w < Whole.length(); w++){
for(int c1 = counter1; c1 < part1.length(); c1++){
if((s.charAt(w) == part1.charAt(c1)) ){
MergedWord.append(part1.charAt(c1)+"");
counter1++;
continue;
}
else
break;
}
for(int c2 = counter2; c2 < part2.length(); c2++){
if((s.charAt(w) == part2.charAt(c2)) ){
MergedWord.append(part2.charAt(c2) + "");
counter2++;
continue;
}
else
break;
}
}
return s.equals(MergedWord.toString())? true : false;
}
below is the format of the matrix. and no diagonal combinations of letters is allowed ,only vertical and horizontal combinations are allowed.
Can anyone suggest how to calculate the number of combinations required for a particular level.
example: if i say level is 1 then , only 1 letter combination is allowed i.e. A,B,C,D,E,F,G,H,I i.e. 10 combinations
if i say level is 2 then possible combinations are AA,BB,AB,AD,BC,BE,... and so on so total 36 combinations for level 2.
Like that if input is any level number given, then how do i calculate the possible number of combinations ?
A B C
D E F
G H I
J
I tried using this formula :
(n!/(r!(n-r)!)
but it doesnt calculate properly from level 2 onwards.
note : on both sides of J no letter is present.
Please suggest.
#Thientvse
This is the code that i coded... it gives correct output...can you please tell me whether my code is correct and whether it will satisfy all test cases for this scenario
import java.util.ArrayList;
import java.util.Scanner;
public class Game {
public static int combinationCounts(int input1){
ArrayList<String> mainalternatestring = new ArrayList<String>();
ArrayList<String> mainverticalstring = new ArrayList<String>();
String sb = "ABC#DEF#GHI# J ";
String a=null,b=null,c=null,nw=null;
int mainindex = 0,counter,totalcount=10,index=0,mainindex_duplicate=0,count=1;
if(input1 > 1 && input1 <= 4){
while(mainindex != 11){
int level = 0;
counter = 0;
count=1;
char[] strtoworkon = new char[sb.length()];
index=0;
if(mainindex != 0)
mainindex = mainindex+1;
for(int j = mainindex; count!= (sb.length()-mainindex) ; j++){
if(level == input1)
break;
if(sb.charAt(j) == '#'){
level++;
if (counter == 0){
mainindex_duplicate = j;
counter = 1;
}
}
if(level <= input1){
strtoworkon[index] = sb.charAt(j);
index++;
}
count++;
}
mainindex = mainindex_duplicate;
// for sideways combinations
for(int m = 0; m <= strtoworkon.length; m++){
c = null;
if(strtoworkon[m] == ' ')
break;
if(!String.valueOf(strtoworkon).substring(m, m+(input1)).contains("#")){
c = String.valueOf(strtoworkon).substring(m, m+(input1));
if(!c.matches(".*[A-Z].*"))
break;
if(!mainalternatestring.contains(c))
mainalternatestring.add(c);
}
}
//for vertical combinations
nw = "#" + (String.valueOf(strtoworkon));
int counter1=0;
while(counter1 != 3){
c="";
for(int n = 0; n<= strtoworkon.length; n++){
if(nw.charAt(n) == '#'){
Character test = nw.charAt(n+counter1);
a = Character.toString(strtoworkon[n+counter1]).trim();
if(a.contains("#"))
break;
c = a+c;
c.trim();
}
}
if(!mainverticalstring.contains(c) && c.length() == input1)
mainverticalstring.add(c);
counter1++;
}
if(mainindex == 11)
break;
}
totalcount = totalcount + (2*mainalternatestring.size()) + (2*mainverticalstring.size());
}
return totalcount;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int output = 0;
int ip1 = Integer.parseInt(in.nextLine().trim());
output = combinationCounts(ip1);
System.out.println(String.valueOf(output));
}
}
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
visBoard[i][j] = "[ ]";
board[i][j] = 0;
check[i][j] = false;
}
}for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
System.out.print(visBoard[i][j]);
}System.out.print("\n");
}
//Getting Names
System.out.println("Player 1 - Enter your name");
play1 = sc.nextLine();
System.out.println("Player 2 - Enter your name");
play2 = sc.nextLine();
//
moves = 0;
symbol = " X ";
do{
do{
//Get Coords
System.out.println("X Coordinate");
xcoord = sc.nextInt() -1;
System.out.println("Y Coordinate");
ycoord = sc.nextInt() -1;
if(check[xcoord][ycoord] == true){
System.out.println("Not a valid move!");
}
}while(check[xcoord][ycoord] == true);
//Making move
check[xcoord][ycoord] = true;
visBoard[xcoord][ycoord] = symbol;
if(symbol.equals(" X ")){
board[xcoord][ycoord] = 1;
}else if(symbol.equals(" O ")){
board[xcoord][ycoord] = 5;
}else{
System.out.println("You've messed up James");
}
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
System.out.print(visBoard[i][j]);
}System.out.print("\n");
}
//Check if game has won
//columns
total = 0;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
total = total + board[j][i];
}if(total == 15 || total == 3){
gamewon = true;
}
}total = 0;
//rows
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
total = total + board[i][j];
}if(total == 15 || total == 3){
gamewon = true;
}
}total = 0;
//diagonals
for(int i = 0; i < 3; i++){
total = total + board[i][i];
}if(total == 15 || total == 3){
gamewon = true;
}total = 0;
diag = 2;
for(int i = 0; i < 3; i++){
total = total + board[i][diag];
diag--;
}if(total == 15 || total == 3){
gamewon = true;
}
moves++;
if(gamewon == false){
if(moves == 9){
System.out.println("Game has been drawn! No one wins!");
}else{
mod = moves % 2;
if(mod == 0){
symbol = " X ";
}else{
symbol = " O ";
}
}
}
}while(gamewon == false || moves != 9);
if(gamewon == true){
if(symbol.equals(" X ")){
System.out.println("Winner is "+play1);
}else{
System.out.println("Winner is "+play2);
}
}else{
System.out.println("Game is drawn");
}
}
}
This is a further question from a previous question I had. This game won't end until moves reaches 9 even though the while loop should stop once someone has won. The boolean will turn true, but it will continue to loop.
How do I fix this issue with keeping the while condition, and possibly without using breaks?
You need an and not an or
while(gamewon == false && moves != 9);
Reading that to yourself it says while there is no winner and we are not at move 9. However it's usually better form to code your loops to check that you haven't exceeded a bound rather than you have hit the bound exactly, and it is also nicer to simply test the boolean directly so the following is more stylish:
while(!gamewon && moves < 9);
while(gamewon == false || moves != 9)....
This tells the loop to execute while game isnt won, or moves are not 9. For it to end, BOTH conditions need to change, the game needs to be ended AND moves needs to be 9.
Change your || operator to &&. This way the game will keep going while the game is not won AND the moves is not 9. It seems a bit strange but if you can follow the logic, you'll see that you need the AND operator.
Therefore, you're looking for:
while(gamewon == false && moves != 9)
I'm coding a simple maze game in java. The program reads in a text "map" from an input file for the layout of the maze. The rules are simple: navigate the maze (represented by a 2D array) through user input and avoid the cave-ins (represented by Xs), and get to the 'P' (player) the the spot marked 'T'. Right now, I've got most of the code written, it's just a matter of getting it to work properly. I've set up most of the game to run with a while loop, with the boolean "got treasure" set to false. Once this rings true, it should end the game.
However, I haven't coded the circumstance in which the player actually gets the treasure though, so I'm wondering why my code simply spits out "Congratulations! You've found the treasure!" and nothing else. If anyone could shed some light on this, I'd be very grateful. My code is somewhat of a mess of loops, as our teacher has just gotten to methods, constructors, and creating our own classes. Here is the code I have so far:
import java.util.*;
import java.io.File;
public class MazeGame {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(new File("maze.txt"));
Scanner user = new Scanner(System.in);
int rows = scan.nextInt();
int columns = scan.nextInt();
int px = 0;
int py = 0;
String [][] maze = new String[rows][columns];
String junk = scan.nextLine();
for (int i = 0; i < rows; i++){
String temp = scan.nextLine();
String[] arrayPasser = temp.split("");
for (int j = 0; j < columns; j++){
maze[i][j] = arrayPasser[i];
}
}
boolean gotTreasure = false;
while (gotTreasure = false){
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
System.out.print(maze[i][j]);
System.out.print(" ");
}
System.out.print("\n");
}
System.out.printf("\n");
System.out.println("You may:");
System.out.println("1) Move up");
System.out.println("2) Move down");
System.out.println("3) Move left");
System.out.println("4) Move right");
System.out.println("0) Quit");
int choice = user.nextInt();
int i = 0;
if (choice == 1 && i >= 0 && i < columns){
for (int k = 0; k < rows; k++){
for (int l = 0; l < columns; l++){
if (maze[k][l].equals(maze[px][py]) && maze[px][py-1].equals("X") == false){
maze[px][py] = ".";
maze[k][l-1] = "P";
maze[px][py] = maze[k][l-1];
}else if (maze[px][py-1] == "X"){
System.out.println("Cannot move into a cave-in! Try something else.");
}else {
continue;}
}
}
}
else if (choice == 2 && i >= 0 && i < columns){
for (int k = 0; k < rows; k++){
for (int l = 0; l < columns; l++){
if (maze[k][l].equals(maze[px][py]) && maze[px][py+1].equals("X") == false){
maze[px][py] = ".";
maze[k][l+1] = "P";
maze[px][py] = maze[k][l+1];
}else if (maze[px][py+1] == "X"){
System.out.println("Cannot move into a cave-in! Try something else.");
}else {
continue;}
}
}
}
else if (choice == 3 && i >= 0 && i < columns){
for (int k = 0; k < rows; k++){
for (int l = 0; l < columns; l++){
if (maze[k][l].equals(maze[px][py]) && maze[px-1][py].equals("X") == false){
maze[px][py] = ".";
maze[k-1][l] = "P";
maze[px][py] = maze[k-1][l];
}else if (maze[px-1][py] == "X"){
System.out.println("Cannot move into a cave-in! Try something else.");
}else {
continue;}
}
}
}
else if (choice == 4 && i >= 0 && i < columns){
for (int k = 0; k < rows; k++){
for (int l = 0; l < columns; l++){
if (maze[k][l].equals(maze[px][py]) && maze[px+1][py].equals("X") == false){
maze[px][py] = ".";
maze[k+1][l] = "P";
maze[px][py] = maze[k+1][l];
}else if (maze[px+1][py] == "X"){
System.out.println("Cannot move into a cave-in! Try something else.");
}else {
continue;}
}
}
}
else if (choice == 0){
System.exit(0);
}
}
System.out.println("Congratulations, you found the treasure!");
scan.close();
user.close();
}
}
And here is the sample input file:
5 5
P.XX.
.X...
...X.
XXT..
..X..
(sigh) one equals sign instead of two. You have "while (gotTreasure = false)", which assigns the value false to gotTreasure and does not enter the loop. Change it to "while (gotTreasure == false) and it enters the loop.
For future questions: please attempt to figure out on your own what is happening, and let others know what you have tried and what specific questions you have about it. It is arguable I should just have let this go, since it is essentially a request to debug your code for you. Learn to debug yourself. If trace statements aren't getting executed, it's most likely the code at that point isn't getting executed. If a loop isn't getting entered, it is almost certainly because the conditions for entering the loop don't exist.
Learn to use a debugger - eclipse (and, I am sure, lots of other development tools) has an excellent one. Find out what a breakpoint is, how to set it and examine variables when it is hit, and figure out from there what has gone wrong.
If this is a typo ignore this, if it isnt
while (gotTreasure = false) is wrong.
you are not checking if gotTreasure is false, you are assigning it false.
to check if gotTreasure is false use == operator
while(gotTreasure==false)
lemme know if this is a type, i ll delete the answer. :)
You have a simple mistake in your while loop condition,
Instead of,
while (gotTreasure = false)
You should use,
while (gotTreasure == false)
In the first case, you are assigning false to gotTreasure and in the second you are evaluating if gotTreasure is false.
I refeactored your code, because there are a lot of bad programming-styles. Now the game should run as intended.
I used a Construktor and a lot of methods, to divide your big method in small parts. -> easier to understand.
I declared attributes (known in the whole class), so that the different methods can use this variables.
You often checked for a condition like if(variable == false). Try to use if(!variable), the exclamation mark negates the value of the variable.
Your update-Methode had a lot of redundandancies.
By adding the following switch-case-Part, I could seperate the different directions:
General code for setting directions by a userinput:
switch (choice){
case 0: System.exit(0);
case 1: xdir = 0; ydir = -1; break;
case 2: xdir = 0; ydir =1; break;
case 3: xdir = -1; ydir = 0; break;
case 4: xdir = 1; ydir = 0; break;
}
Afterwards I could calculate the new position by adding xdir to x and ydir to y. This comes handy, if you try to check if the new position is in the bounds of the array.
//1. Check if the new position is in the array.
if (x+xdir >= 0 && x+xdir <columns && y+ydir >=0 && y+ydir < rows){
Here follows the whole class:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class MazeGame2 {
Scanner scan;
Scanner user;
int rows;
int columns;
String [][] maze;
int x; //Player x-Position
int y; //Player y-Position
boolean gotTreasure;
/**
* Konstruktor for the class.
*/
public MazeGame2(){
init();
game();
scan.close();
user.close();
}
/**
* Initialisation of the maze and all attributes.
*/
public void init(){
user = new Scanner(System.in); //Scanner for Userinput
/********************************
* Scanning the maze from a file.
*/
//1. Open the file. Has to be in a try-catch-Bracket, because the file might not be there.
try{
scan = new Scanner(new File("maze.txt"));
}catch(FileNotFoundException e){
e.printStackTrace();
}
//2. Scan the dimensions of the maze.
rows = scan.nextInt();
columns = scan.nextInt();
scan.nextLine(); // So that the next Line can be scanned.
maze = new String[rows][columns];//Create the maze-Array with the right dimensions.
for (int i = 0; i < rows; i++){
String temp = scan.nextLine(); //Scan one line.
for (int j = 0; j < columns; j++){
maze[i][j] = temp.substring(j, j+1);//Put every character in the maze
if (maze[i][j].equals("P")){ //Look out for the Player-Position
x = j;
y = i;
}
}
}
gotTreasure = false;
}
/**
* Prints the Input of the maze-Array. But only if the spots are visible by the player.
*/
public void printMaze(){
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
System.out.print(maze[i][j]);
System.out.print(" ");
}
System.out.println();
}
}
/**
* Prints the possebilities to move by the player.
*/
public void printUserPossebilities(){
System.out.println();
System.out.println("You may:");
System.out.println("1) Move up");
System.out.println("2) Move down");
System.out.println("3) Move left");
System.out.println("4) Move right");
System.out.println("0) Quit");
}
/**
*
*/
public void update(int choice){
int xdir=0;
int ydir=0;
// Update the direction based on the userChoice
switch (choice){
case 0: System.exit(0);
case 1: xdir = 0; ydir = -1; break;
case 2: xdir = 0; ydir =1; break;
case 3: xdir = -1; ydir = 0; break;
case 4: xdir = 1; ydir = 0; break;
}
/**
* Update the situation based on the current direction and step.
*/
//1. Check if the new position is in the array.
if (x+xdir >= 0 && x+xdir <columns && y+ydir >=0 && y+ydir < rows){
//2. Check if a step is possible
if (maze[y+ydir][x+xdir].equals("X")){
System.out.println("Cannot move into a cave-in! Try something else.");
}else{
//3. clear the P from the old Position
maze[y][x] =".";
//4. Check if the Player is over the treasure
if (maze[y+ydir][x+xdir].equals("T")){
gotTreasure = true;
}
x = x+xdir;
y = y + ydir;
maze[y][x] = "P"; //Show the new position of the player.
}
}else{
System.out.println("That's not a possible Move.");
}
}
/**
* The game-Methode that includes the game-loop and
*/
public void game(){
while (!gotTreasure){
//System.out.print('\u000C');
printMaze();
printUserPossebilities();
int userInput = user.nextInt(); //Wait for userinput
update(userInput);
}
//System.out.print('\u000C');
printMaze();
System.out.println("Congratulations, you found the treasure!");
}
public static void main(String[] args){
MazeGame2 m = new MazeGame2();
}
}