Tic Tac Toe Winner Checker Issue - java

I am relatively new to coding and Java and for my CS-173 class, I was tasked with creating a Tic Tac Toe game. However, when it came to creating the method for determining a winner, whenever I achieved a "win", the code never ran saying I won. I do have the code to check each way to win however, I pulled it from the code in order to do some personal troubleshooting. Also, my apologies for the bad code.
public static void playGame(char[][] board, int size){
Scanner input = new Scanner(System.in);
int turn = 0;
int spaces = board.length * board.length;
boolean valid = false;
boolean winner = false;
for (int i = 0; i<spaces; i++){
int startchecker = 3;
int xcord = 0;
int ycord = 0;
do{
do{
System.out.println("Player 1 please type your coordinates with a space");
xcord = input.nextInt();
ycord = input.nextInt();
valid = isValid (board, xcord, ycord);
if(i >= spaces){
}
}while(!valid);
board[xcord][ycord] = 'X';
printBoard(board);
winner = isWinner(board);
do{
System.out.println("Player 2 please type your coordinates with a space");
xcord = input.nextInt();
ycord = input.nextInt();
valid = isValid (board, xcord, ycord);
winner = isWinner(board);
}while(!valid);
board[xcord][ycord] = 'O';
printBoard(board);
if(i >= spaces){
winner = true;
System.out.println("It is a tie!");
}
}while(!winner);
}
}
public static boolean isWinner (char[][] board){
boolean determiner = false;
int XCounter = 0;
int OCounter = 0;
int size = board.length-1;
int winner = 3;
//Check Horizontal
for(int j = 0; j > size; j++){
for(int i = 0; i > size; i++){
if(board[i][j]=='X'){
XCounter++;
}
else if(board[i][j]=='O'){
OCounter++;
}
if(XCounter == winner){
determiner = true;
System.out.println("Player 1 Wins!");
}
else if(OCounter == winner){
System.out.println("Player 2 Wins!");
determiner = true;
}
}
}
return determiner;
}

Your isWinner method does not check for all the ways to win.
I would recommend using 2 for-loops (one for horizontal lines and the other for vertical) for clarity, and 2 if-statements (outside of the loops) to check for diagonals.
For example,
for(int i=0; i<size; i++){
boolean flag = true; // Assume this line is a winning line
for(int j=0; j<size; j++){ // Check each tile to see if it has a tile
// Set the flag to false when it is not the tile you're looking for
}
}

Related

Is there any COMPACT way to check winner in a simple tic-tac-toe game?

I am coding a simple tic-tac-toe for a high-school mini project, but I need it to be within a strict data volume (not more than 112 lines). I thought checking for each row, column and cross would be long, so is there any alternative to do so (You should see a [[[HERE]]] comment)? (Btw, I already know it looks awful) Thanks in advance!
public class TTTGame {
//OPTIONS v
public static final String draw = "DRAW"; // <- Definitions for different states
public static final String circles = "CIRCLES"; // BOT
public static final String crosses = "CROSSES"; // PLAYER
public static final String getCrosses = "X"; //<- Symbols to display
public static final String getCircles = "O";
//OPTIONS ^
//DO NOT MODIFY UNDER THIS LINE (Just kidding, do whatever u want) v
public static int[][] board = {
{0,0,0},
{0,0,0},
{0,0,0},
};
public static final int empty = 0; // Definition of the values
public static final int cross = 1;
public static final int circle = 2;
public static int turns = 0; //Just here to count turns, nothing special
public static void main(String[]args) { //Main process
board[1][1] = circle;
display();
while (true) {
PlayerTurn();
if (checkStop()||checkWinner()!=null) {display();GStop();break;}
BotTurn();
if (checkStop()||checkWinner()!=null) {display();GStop();break;}
display();
turns += 1;
}
}
private static void GStop() { //Force stop the match function
System.out.println("Winner : " + checkWinner());
System.exit(1);
}
private static boolean checkStop() { //Check if match is already full / completed (Draw)
for (int x = 0; x < 3; x++)
for (int y = 0; y < 3; y++)
if (board[x][y]==empty) return false;
return true;
}
#Nullable
private static String checkWinner() { //Check Winner
// [[[ HERE ]]] ---------------
return null;
}
private static void PlayerTurn() { //Player turn
int x; Scanner c = new Scanner(System.in);
while (true) {
x = c.nextInt();
x = x-1;
if ((x>=0)&&(x < 9)) {
if (board[x / 3][x % 3] == empty) {
board[x / 3][x % 3] = cross;
break;
} else System.out.println("Already chosen");
} else System.out.println("Invalid");
}
}
private static void BotTurn() { //Bot turn -> (Modify these to change the AI behaviour, here's a very simple one);
boolean choose = true;
for (int y = 0; y < 3 ; y++)
for (int x = 0; x < 3; x++)
if (board[y][x] == empty&&choose) {
board[y][x] = circle;
choose = false;
}
}
private static void display() { //Display the board
int nn = 1;
String a = "z";
for (int y = 0; y < 3 ; y++) {
for (int x = 0; x < 3; x++) {
if (board[y][x] == 0) a = "*";
if (board[y][x] == 1) a = getCrosses;
if (board[y][x] == 2) a = getCircles;
System.out.print(a + " ");
}
System.out.print(" "); //Indications
for (int xn = 0; xn < 3; xn++) {
System.out.print(nn);
nn+=1;
System.out.print(" ");
}
System.out.println(" ");
}
}
}
How about this idea: (neither the only nor the best nor the most performant solution... just an idea)
You can use the sum of each row, diagonal and column to determine if the either player one (all 1s) or player two (all 2s) wins. Therefore you only need to set the empty field to be higher than 6.
For example let's say your board looks like this:
7 1 1 -> 7+1+1 = 9 // no one wins
2 2 2 -> 2+2+2 = 6 // player two wins, he has 3 * 2 in a row
1 7 2 -> 1+7+2 =10 // no win here
if all three numbers where 1s (sum == 3) your player one wins.
It is "cumbersome" to implement, but as I said it is just an idea:
// first we check every column
for( int x=0; x<board[y].length; x++){
int sum = 0;
for( int y=0; y<board.length; y++){
sum += board[y][x];
}
if(sum == 3 || sum == 6){
return true;
}
}
// then every row
for( int y=0; y<board.length; y++){
int sum = 0;
for( int x=0; x<board[y].length; x++){
sum += board[y][x];
}
if(sum == 3 || sum == 6){
return true;
}
}
// and finally the diagonals (if we ever reach that part)
int sum= board[0][0] + board[1][1] + board[2][2];
if(sum == 3 || sum == 6){
return true;
}
sum= board[0][2] + board[1][1] + board[2][0];
if(sum == 3 || sum == 6){
return true;
}
you could also return 1 when the sum == 3 and the first player wins or 2 when player two wins.

Assistance with Tic Tac Toe program

I've been working on for awhile but i can't seem to fix it and get it to wrong correctly. It tells me where the exception is but I don't see any problems.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at TicTacToe.displayWinner(TicTacToe.java:243)
at TicTacToe.playerMove(TicTacToe.java:151)
at TicTacToe.playGame(TicTacToe.java:303)
at TicTacToeTester.main(TicTacToeTester.java:20)
Java Result: 1
import java.util.Scanner; //Used for player's input in game
public class TicTacToe
{
//instance variables
private char[][] board; //Tic Tac Toe Board, 2d array
private boolean xTurn; // true when X's turn, false if O's turn
private Scanner input; // Scanner for reading input from keyboard
//Constants for creation of gameboard
public final int ROWS = 3; //total rows
public final int COLS = 3; //total columns
public final int WIN = 3; //amount needed to win
public TicTacToe()
{
//creates the board
board = new char[ROWS][COLS];
for(int r = 0; r < ROWS; r++)
{
for(int c = 0; c < COLS; c++)
{
board[r][c] = ' ';
}
}
//X's turn when game starts
xTurn = true;
//creates our input object for the turn player
input = new Scanner(System.in);
}
//shows game board
public void displayBoard()
{
int colNum = 0; //number of columns
int rowNum = 0; //number of rows
//creates column labels
System.out.println(" \n");
System.out.println(" Columns ");
for (int num = 0; num < COLS; num++)
{
System.out.print(" " + colNum);
colNum++;
}
//creates vertical columns and spaces between each spot
System.out.println(" \n");
for (int row = 0; row < ROWS; row++)
{
//numbers rows
System.out.print(" " + rowNum + " ");
rowNum++;
for (int col = 0; col < COLS; ++col)
{
System.out.print(board[row][col]); // print each of the cells
if (col != COLS - 1)
{
System.out.print(" | "); // print vertical partition
}
}
System.out.println();
//creates seperation of rows
if (row != ROWS - 1)
{
System.out.println(" ------------"); // print horizontal
partition
}
}
//labels row
System.out.println("Rows \n");
}
//displays turn player
public void displayTurn()
{
if (xTurn)
{
System.out.println("X's Turn");
}
else
{
System.out.println("O's Turn");
}
}
//allows you to make move
public boolean playerMove()
{
boolean invalid = true;
int row = 0;
int column = 0;
while(invalid)
{
System.out.println("Which row (first) then column (second)
would you like to \n"
+ "play this turn? Enter 2 numbers between 0-2 as \n"
+ "displayed on the board, seperated by a space to
\n"
+ "choose your position.");
row = input.nextInt();
column = input.nextInt();
//checks if spot is filled
if (row >= 0 && row <= ROWS - 1 &&
column >= 0 && column <= COLS - 1)
{
if (board[row][column] != ' ')
{
System.out.println("Spot is taken \n");
}
else
{
invalid = false;
}
}
else
{
System.out.println("Invalid position");
}
//fills spot if not taken
if (xTurn)
{
board[row][column] = 'X';
}
else
{
board[row][column] = 'O';
}
}
return displayWinner(row,column);
}
public boolean displayWinner(int lastR, int lastC)
{
boolean winner = false;
int letter = board[lastR][lastC];
//checks row for win
int spotsFilled = 0;
for (int c = 0; c < COLS; c++)
{
if(board[lastR][c] == letter)
{
spotsFilled++;
}
}
if (spotsFilled == WIN)
{
winner = true;
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
//checks columns for win
spotsFilled = 0;
for (int r = 0; r < ROWS; r++)
{
if(board[r][lastC] == letter)
{
spotsFilled++;
}
}
if (spotsFilled == WIN)
{
winner = true;
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
//checks diagonals for win
spotsFilled = 0;
for (int i = 0; i < WIN; i++)
{
if(board[i][i] == letter)
{
spotsFilled++;
}
}
if(spotsFilled == WIN)
{
winner = true;
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
//checks other diagonal
spotsFilled = 0;
for(int i = 0; i < WIN; i++)
{
if(board[i][COLS-i] == letter)
{
spotsFilled++;
}
}
if(spotsFilled == WIN)
{
winner = true;
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
return winner;
}
//checks if board is full
public boolean fullBoard()
{
int filledSpots = 0;
for(int r = 0; r < ROWS; r++)
{
for (int c = 0; c < COLS; c++)
{
if (board[r][c] == 'X' || board[r][c] == 'O')
{
filledSpots++;
}
}
}
return filledSpots == ROWS*COLS;
}
//plays game
public void playGame()
{
boolean finish = true;
System.out.println("Are your ready to start?");
System.out.println("1 for Yes or 0 for No? : ");
int choice = input.nextInt();
if (choice == 1)
{
while (finish)
{
displayBoard();
displayTurn();
if (playerMove())
{
displayBoard();
}
else if (fullBoard())
{
displayBoard();
System.out.println("Draw");
}
else
{
xTurn=!xTurn;
}
}
}
}
}
my tester
public class TicTacToeTester {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
TicTacToe tictactoe = new TicTacToe();
tictactoe.playGame();
}
}
Your Player Move method has an issue take a look at this if you notice you have commented saying "// fills spot when not taken" but you misplaced the while loop bracket and included move part inside it so it threw that exception, just close the while loop bracket before moving as follows (also follow #oblivion Creations Answer these are the two issues with your code) :-
public boolean playerMove()
{
boolean invalid = true;
int row = 0;
int column = 0;
while (invalid)
{
System.out.println("Which row (first) then column (second)" + "would you like to \n"
+ "play this turn? Enter 2 numbers between 0-2 as \n"
+ "displayed on the board, seperated by a space to" + "\n" + "choose your position.");
row = input.nextInt();
column = input.nextInt();
// checks if spot is filled
if (row >= 0 && row <= ROWS - 1 && column >= 0 && column <= COLS - 1)
{
if (board[row][column] != ' ')
{
System.out.println("Spot is taken \n");
}
else
{
invalid = false;
}
}
else
{
System.out.println("Invalid position");
}
} // close while loop here
// fills spot if not taken
if (xTurn)
{
board[row][column] = 'X';
}
else
{
board[row][column] = 'O';
}
return displayWinner(row, column);
}
The reason you are getting your exception is this section of code inside your displayWinner method:
//checks other diagonal
spotsFilled = 0;
for(int i = 0; i < WIN; i++)
{
if(board[i][COLS-i] == letter)
{
spotsFilled++;
}
}
When i = 0 then COLS-i will be 3. This is outside the bounds of your array.
There are multiple ways to solve this, one would be to increase i by 1 during comparison.
//checks other diagonal
spotsFilled = 0;
for(int i = 0; i < WIN; i++)
{
if(board[i][COLS-(i+1)] == letter)
{
spotsFilled++;
}
}
Edit: also make sure you check out Null Saints answer, as it will cause you headaches later if you don't address it now.

How to create a Battleship Warship game algorithm

I'm having trouble randomizing and adding a 2x2 ship into the game board. I need it to look like the following:
currently I can only seem to get a 1x1 ship and don't quite understand the logic for adding the 2x2 and randomizing it so that they're all connected.
also when the user inputs a '2' at the main menu I need to show the solution, meaning where the ships are. Which I also could use some help on.
Not nearly finished but please be critical when it comes to judging my code, everything helps!
Thanks in advance.
import java.util.Scanner;
public class Battleship
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int [][] board = new int [5][5];
int [][] ship = new int [4][2];
int [] shot = new int[2];
boolean done = false;
resetboard(board);
while(!done)
{
displayBoard(board);
displayMenu();
for(int ships=0 ; ships < 4 ; ships++)
{
ship[ships][0]=(int) Math.random() * 5 + 1;
ship[ships][1]=(int) Math.random() * 5 + 1;
}
int choice = getMenuInput(input);
if(choice == 1)
{
getRow(shot);
getColumn(shot);
if(fireShot(shot,ship) == true)
{
board[shot[0]][shot[1]]= 1;
}
else
{
board[shot[0]][shot[1]]= 0;
}
}
else if(choice == 2)
{
for (int x = 0; x < 5; x++)
{
for(int y = 0; y < 5; y++)
{
for(int z = 0; z < 3; z++)
{
if(board[x][y] == ship[z][0] && board[x][y] == ship[z][1] )
{
board[ship[z][0]][ship[z][1]]= 1;
}
}
}
}
displayBoard(board);
}
else if (choice == 3)
{
done = true;
System.out.println("Thanks For Playing");
}
}
}
public static void displayBoard(int [][] board)
{
System.out.println(" A B C D E");
for(int r =0; r < 5; r++)
{
System.out.print((r + 1) + "");
for(int c = 0; c < 5; c++)
{
if(board[r][c] == -1)
{
System.out.print(" -");
}
else if(board[r][c] == 0)
{
System.out.print(" X");
}
else if(board[r][c] == 1)
{
System.out.print(" *");
}
}
System.out.println("");
}
}
public static void resetboard(int[][] a)
{
for(int row=0 ; row < 5 ; row++ )
{
for(int column=0 ; column < 5 ; column++ )
{
a[row][column]=-1;
}
}
}
public static void displayMenu()
{
System.out.println("\nMenu:");
System.out.println("1. Fire Shot");
System.out.println("2. Show Solution");
System.out.println("3. Quit");
}
public static int getMenuInput(Scanner input)
{
int in = 0;
if(input.hasNextInt())
{
in = input.nextInt();
if(in>0 && in<4)
{
in = in;
}
else
{
System.out.println("Invalid Entry, Please Try Again.\n");
}
}
else
{
System.out.println("Invalid Entry, Please Try Again.\n");
input.nextInt();
}
return in;
}
public static void getRow(int [] shot)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a Row Number: ");
shot[0] = shotValid(input);
shot[0]--;
}
public static void getColumn(int [] shot)
{
Scanner input = new Scanner(System.in);
int numb = 0;
System.out.println("Enter a Column Letter: ");
String choice = input.next();
if (choice.equals("A"))
{
numb = 0;
}
else if(choice.equals("B"))
{
numb = 1;
}
else if( choice.equals("C"))
{
numb = 2;
}
else if(choice.equals("D"))
{
numb = 3;
}
else if(choice.equals("E"))
{
numb = 4;
}
else
{
System.out.println("2Invalid Entry, Please Try Again.\n");
input.nextLine();
}
shot[1] = numb;
}
public static boolean fireShot(int [] shot, int [][]ship)
{
boolean result = false;
for(int shipHit=0 ; shipHit<ship.length ; shipHit++)
{
if( shot[0]==ship[shipHit][0] && shot[1]==ship[shipHit][1])
{
result = true;
}else
{
result = false;
}
}
return result;
}
public static int shotValid(Scanner quantity)
{
int shot = 0;
boolean done = false;
while(!done)
{
if(quantity.hasNextInt())
{
shot = quantity.nextInt();
if(shot>0 && shot<6)
{
shot = shot;
done = true;
}
else
{
System.out.println("1Invalid Entry, Please Try Again.\n");
}
}
else
{
System.out.println("2Invalid Entry, Please Try Again.\n");
quantity.next();
}
}
return shot;
}
}
You want to place a single ship of size 2×2 on the board and do this:
for(int ships=0 ; ships < 4 ; ships++)
{
ship[ships][0]=(int) Math.random() * 5 + 1;
ship[ships][1]=(int) Math.random() * 5 + 1;
}
There are several errors here:
The random variables will always be 1, because the (int) conversion affects only the result of Math.random(), which is a pseudo-random floating-point number between 0 and 1 exclusively. Conversion to int truncates this to 0. Use (int) (Math.Random() * 5), which will yield a random number from 0 to 4.
You shouldn't add 1. Internally, your game uses the zero-base indices that Java uses, which is good. ()These are known to the outside as rows 1 to 5 ande columns A to E, but you take care of that in your getRow and getColumn functions.)
You place up to four independent ships of size 1×1. (This is up to four, because you might end up wit one ship in an already occupied place.)
To place a single 2×2 ship, just determine the top left corner randomply and make the other ship coordinates dependent on that:
int x = (Math.random() * 4);
int y = (Math.random() * 4);
ship[0][0] = x;
ship[0][1] = y;
ship[1][0] = x + 1;
ship[1][1] = y;
ship[2][0] = x;
ship[2][1] = y + 1;
ship[3][0] = x + 1;
ship[3][1] = y + 1;
You now have two separate data structures: The board, which is all minus ones initially, and the list of ships. Your display routine suggests that you want three different values for a cell in the board: −1 is water; 1 is an unarmed part of a ship and 0 is where a shot has been fired.
But you never set these values. You set the position of the ship before displaying, but you should probably set them straight away. You should also set the locations of shots, so that you never fire at the same cell.
You need two modes for displaying the board: The in-play mode, where the unharmed ships are displayed as water and the solution mode, which shows everything as it is. You could so this by passing a flag to the routine.
Now if you think about it, you don't really need the ship array. Just use the information in the board:
int x = (Math.random() * 4);
int y = (Math.random() * 4);
board[x][y] = 1;
board[x + 1][y] = 1;
board[x][y + 1] = 1;
board[x + 1][y + 1] = 1;
Keep a count of ships, initially 4. When you fire at water, mark the cell with 0. When you fire at a ship, mark the cell as 0 and decrement the count of ships. If the count of ships is zero, the player has won. Otherwise, redisplay the boatrd and shoot again.

(ADDED) Noughts and Crosses game. While loop

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)

Java: Programming a simple maze game

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();
}
}

Categories