I'm making a maze game that uses a 2D array to represent the game board. I currently have the console outputting "P" wherever the player's current position is. However, I would like to change every element in the array that the player has "visited" and display that to show their path. How would I do this? Do I need to make a second, duplicate array so I can make changes to that?
Here's my code:
import java.util.Scanner;
public class MazeGame {
private static char[][] maze = {
{'1','1','1','0','1','1','0','0','0','1','1','1','1'},
{'1','0','1','1','1','0','1','1','1','1','0','0','1'},
{'0','0','0','0','1','0','1','0','1','0','1','0','0'},
{'1','1','1','1','1','1','1','0','1','0','1','1','1'},
{'1','0','0','0','0','0','1','1','1','1','0','0','1'},
{'1','1','1','1','1','1','1','0','1','1','1','1','1'},
{'1','0','1','0','0','0','0','1','0','0','0','0','1'},
{'1','1','1','1','1','1','1','1','1','1','1','1','1'}
};
private static int playerRow = 0, playerCol = 0;
private static int moves = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
printMaze();
System.out.println("Welcome to the maze! Your goal is to make it from your starting position, the top left corner of the maze, to the end position, the bottom right corner of the maze. 1s represent spaces that you can move to, 0s represent walls that you can not move to, and Ps represent places that you have already been. To begin, enter an input: \n1-- 'U' for up\n2-- 'D' for down\n3-- 'L' for left\n4-- 'R' for right\n5-- 'Q' for quit\nHave fun playing the maze game and best of luck to you :)");
while (true) {
System.out.print("\nEnter a move (U/D/L/R/Q): ");
String move = input.nextLine();
if (move.charAt(0) == 'Q' || move.charAt(0) == 'q') {
System.out.println("Thanks for playing and have a wonderful day!");
System.exit(0);
}
if (move.length() == 1) {
if (move.charAt(0) == 'U' || move.charAt(0) == 'u') {
if (playerRow > 0 && maze[playerRow - 1][playerCol] != '0') {
playerRow--;
moves++;
} else {
System.out.println("Invalid move.");
}
} else if (move.charAt(0) == 'D' || move.charAt(0) == 'd') {
if (playerRow < maze.length - 1 && maze[playerRow + 1][playerCol] != '0') {
playerRow++;
moves++;
} else {
System.out.println("Invalid move. Please enter a valid move from the list below: \n1-- 'U' for up\n2-- 'D' for down\n3-- 'L' for left\n4-- 'R' for right\n5-- 'Q' for quit");
}
} else if (move.charAt(0) == 'L' || move.charAt(0) == 'l') {
if (playerCol > 0 && maze[playerRow][playerCol - 1] != '0') {
playerCol--;
moves++;
} else {
System.out.println("Invalid move.");
}
} else if (move.charAt(0) == 'R' || move.charAt(0) == 'r') {
if (playerCol < maze[0].length - 1 && maze[playerRow][playerCol + 1] != '0') {
playerCol++;
moves++;
} else {
System.out.println("Invalid move.");
}
} else {
System.out.println("Invalid move.");
}
} else {
System.out.println("Invalid move.");
}
printMaze();
if (playerRow == maze.length - 1 && playerCol == maze[0].length - 1) {
System.out.println("\nCongratulations, you have won the game in " + moves + " moves!");
break;
}
}
}
private static void printMaze() {
for (int i = 0; i < maze.length; i++) {
for (int j = 0; j < maze[0].length; j++) {
if (i == playerRow && j == playerCol) {
System.out.print("P ");
} else {
System.out.print(maze[i][j] + " ");
}
}
System.out.println();
}
}
}
In your case, you can straight away write P on location the player is before moving him to other part. As your conditions are maze[playerRow][playerCol + 1] != '0' it does not matter if there is 1 or P, it will be still accessible field.
maze[playerRow][playerCol] = 'P'
playerCol++;
moves++;
Yuo can add this line maze[playerRow][playerCol] = '*'; before you do the move up/down/left/right action.
In case the user enters an invalid move, it will not matter since the printMaze() method will overwrite the * with P for the current player coordinates, given by playerRow and playerCol.
if (move.length() == 1) {
maze[playerRow][playerCol] = '*';
I have been trying to figure out how to write the code to reset my program/ clear the board so tic tac toe can be played again. It is supposed to have a prompt that asks "do you want to play again" after a win/tie. It's the final part I am trying to figure out.
Board:
public class Board {
private char[][] board;
public Board() {
char[][] temp = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
board = temp;
}
public void printBoard() {
for (char[] row : board) {
for (char cell : row) {
System.out.printf("| %c ", cell);
}
System.out.println();
}
}
public boolean isCellAvailable(int number) {
if (1 <= number && number <= 9) {
int row = (number - 1) / 3;
int col = (number - 1) % 3;
if (board[row][col] == 'X' || board[row][col] == 'O') return false;
else return true;
}
return false;
}
public void place(int number, char marker) {
int row = (number - 1) / 3;
int col = (number - 1) % 3;
board[row][col] = marker;
}
public boolean isWinner() {
if (board[0][0] == board[0][1] && board[0][1] == board[0][2]) return true;
else if (board[1][0] == board[1][1] && board[1][1] == board[1][2]) return true;
else if (board[2][0] == board[2][1] && board[2][1] == board[2][2]) return true;
else if (board[0][0] == board[1][0] && board[1][0] == board[2][0]) return true;
else if (board[0][1] == board[1][1] && board[1][1] == board[2][1]) return true;
else if (board[0][2] == board[1][2] && board[1][2] == board[2][2]) return true;
else if (board[0][0] == board[1][1] && board[1][1] == board[2][2]) return true;
else if (board[0][2] == board[1][1] && board[1][1] == board[2][0]) return true;
return false;
}
}
Driver:
import java.util.Scanner;
class Driver {
public static void main(String[] args) {
Board board = new Board();
Scanner scanner = new Scanner(System.in);
board.printBoard();
int moves = 0;
while (true) {
while (true) {
System.out.print("Player 1: Enter your move: ");
int cell = scanner.nextInt();
if (board.isCellAvailable(cell)) {
board.place(cell, 'X');
board.printBoard();
moves += 1;
break;
} else {
System.out.println("Cell not available.");
}
}
if (board.isWinner()) {
System.out.println("Player 1 wins.");
break;
}
if (moves == 9) {
System.out.println("Draw. Game ended.");
break;
}
while (true) {
System.out.print("Player 2: Enter your move: ");
int cell = scanner.nextInt();
if (board.isCellAvailable(cell)) {
board.place(cell, 'O');
board.printBoard();
moves += 1;
break;
} else {
System.out.println("Cell not available.");
}
}
if (board.isWinner()) {
System.out.println("Player 2 wins.");
break;
}
}
}
}
You need another loop in order to manage the Play again option. If the player wants to play again, a new Board() is created and the moves are reseted as well. Something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
Board board = new Board();
board.printBoard();
int moves = 0;
while(true){
while (true) {
System.out.print("Player 1: Enter your move: ");
int cell = scanner.nextInt();
if (board.isCellAvailable(cell)) {
board.place(cell, 'X');
board.printBoard();
moves += 1;
break;
} else {
System.out.println("Cell not available.");
}
}
if (board.isWinner()) {
System.out.println("Player 1 wins.");
break;
}
if (moves == 9) {
System.out.println("Draw. Game ended.");
break;
}
while (true) {
System.out.print("Player 2: Enter your move: ");
int cell = scanner.nextInt();
if (board.isCellAvailable(cell)) {
board.place(cell, 'O');
board.printBoard();
moves += 1;
break;
} else {
System.out.println("Cell not available.");
}
}
if (board.isWinner()) {
System.out.println("Player 2 wins.");
break;
}
}
System.out.println("Do you want to play again? Press 1, otherwise press 0")
int option = scanner.nextInt();
if(option == 0) break;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I created a TicTacToe game and I can't figure out why it won't display the last letter when someone wins. Like if you get 3 in a row it will display only the 2 letters but won't display the winning letter if that makes any sense.
TicTacToe Class Code:
import java.util.Scanner;
import javax.swing.JFrame;
public class TicTacToe {
public static void main(String [] args) {
Board board = new Board();
Rules winner = new Rules();
Scanner input = new Scanner(System.in);
int slot;
int swap = 1;
System.out.print("Player 1 Name: ");
String player1 = input.next();
System.out.print('\f');
System.out.print("Player 2 Name: ");
String player2 = input.next();
System.out.print('\f');
System.out.print(player1 + ", Choose X or O: ");
String letter = input.next();
System.out.print('\f');
String player1Letter;
String player2Letter;
if (letter.equalsIgnoreCase("x")) {
player1Letter = "X";
player2Letter = "O";
} else {
player1Letter = "O";
player2Letter = "X";
}
System.out.println("This is how each number is set on the board");
System.out.println();
System.out.println(" 1 | 2 | 3 ");
System.out.println("-------------");
System.out.println(" 4 | 5 | 6 ");
System.out.println("--------- ---");
System.out.println(" 7 | 8 | 9 ");
System.out.println();
System.out.println("Each number represents the slot number. For example if you wanted to");
System.out.println("Place an 'X' or an 'O' in the very middle, you would choose slot 5");
System.out.println();
while (true) {
System.out.print("Type 'begin' to begin: ");
String begin = input.next();
if (begin.equalsIgnoreCase("begin")) {
break;
} else if (!begin.equalsIgnoreCase("begin")) {
System.out.println();
System.out.println("Incorrect Syntax");
}
}
while (true) {
System.out.print('\f');
System.out.println(" " + board.getPosition(1) + " | " + board.getPosition(2) + " | " + board.getPosition(3) + " ");
System.out.println("----------------");
System.out.println(" " + board.getPosition(4) + " | " + board.getPosition(5) + " | " + board.getPosition(6) + " ");
System.out.println("----------------");
System.out.println(" " + board.getPosition(7) + " | " + board.getPosition(8) + " | " + board.getPosition(9) + " ");
System.out.println();
System.out.print("Choose A Slot: ");
slot = input.nextInt();
if (swap == 1 || swap == 3 || swap == 5 || swap == 7 || swap == 9 || swap == 11) {
board.setPosition(slot, player1Letter);
swap++;
} else if (swap == 2 || swap == 4 || swap == 6 || swap == 8 || swap == 10 || swap == 12) {
board.setPosition(slot, player2Letter);
swap++;
}
if (winner.isWinner(board) == true) {
if (swap == 1 || swap == 3 || swap == 5 || swap == 7 || swap == 9 || swap == 11) { //swap%2 == 1
System.out.println();
System.out.print(player2 + " Wins!");
break;
}
if (swap == 2 || swap == 4 || swap == 6 || swap == 8 || swap == 10 || swap == 12) {
System.out.println();
System.out.print(player1 + " Wins!");
break;
} else if (winner.isWinner(board) == false) {
System.out.println();
System.out.print("Tie Game");
break;
}
}
}
if (winner.isWinner(board) == true) {
JFrame frame = new JFrame();
frame.setSize(150, 250);
frame.setTitle("A Simley Face");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FaceComponent component = new FaceComponent();
frame.add(component);
frame.setVisible(true);
}
}
}
Board Class Code:
public class Board
{
private String position;
String topLeft= "1";
String topMiddle= "2";
String topRight= "3";
String middleLeft= "4";
String middleMiddle= "5";
String middleRight= "6";
String bottomLeft= "7";
String bottomMiddle= "8";
String bottomRight= "9";
public String getPosition(int pos)
{
if (pos == 1)
{
return topLeft;//varible of position 1
}
else if (pos == 2)
{
return topMiddle;//varible of position 2
}
else if (pos == 3)
{
return topRight;//varible of position 3
}
else if (pos == 4)
{
return middleLeft;//varible of position 4
}
else if (pos == 5)
{
return middleMiddle;//varible of position 5
}
else if (pos == 6)
{
return middleRight;//varible of position 6
}
else if (pos == 7)
{
return bottomLeft;//varible of position 7
}
else if (pos == 8)
{
return bottomMiddle;//varible of position 8
}
else if (pos == 9)
{
return bottomRight;//varible of position 9
}
return position;
}
public String setPosition(int pos, String value)
{
if (pos == 1)
{
topLeft = value;
}
else if (pos == 2)
{
topMiddle = value;
}
else if (pos == 3)
{
topRight = value;
}
else if (pos == 4)
{
middleLeft = value;
}
else if (pos == 5)
{
middleMiddle = value;
}
else if (pos == 6)
{
middleRight = value;
}
else if (pos == 7)
{
bottomLeft = value;
}
else if (pos == 8)
{
bottomMiddle = value;
}
else if (pos == 9)
{
bottomRight = value;
}
return position;
}
}
Rules Class Code:
public class Rules
{
private String winner;
private String threeInARow;
public boolean isWinner(Board threeInARow)
{
String pos1 = threeInARow.getPosition(1);
String pos2 = threeInARow.getPosition(2);
String pos3 = threeInARow.getPosition(3);
String pos4 = threeInARow.getPosition(4);
String pos5 = threeInARow.getPosition(5);
String pos6 = threeInARow.getPosition(6);
String pos7 = threeInARow.getPosition(7);
String pos8 = threeInARow.getPosition(8);
String pos9 = threeInARow.getPosition(9);
if (pos1.equals(pos2) && pos2.equals(pos3))
{
return true;
}
else if (pos4.equals(pos5) && pos5.equals(pos6))
{
return true;
}
else if (pos7.equals(pos8) && pos8.equals(pos9))
{
return true;
}
else if (pos1.equals(pos4) && pos4.equals(pos7))
{
return true;
}
else if (pos2.equals(pos5) && pos5.equals(pos8))
{
return true;
}
else if (pos3.equals(pos6) && pos6.equals(pos9))
{
return true;
}
else if (pos1.equals(pos5) && pos5.equals(pos9))
{
return true;
}
else if (pos3.equals(pos5) && pos5.equals(pos7))
{
return true;
}
else
{
return false;
}
}
}
FaceComponent class Code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import javax.swing.JComponent;
public class FaceComponent extends JComponent
{
public void paintComponent(Graphics g)
{
// Recover Graphics2D
Graphics2D g2 = (Graphics2D) g;
// Draw the head
Ellipse2D.Double head = new Ellipse2D.Double(5, 10, 100, 150);
g2.draw(head);
// Draw the eyes
g2.setColor(Color.BLACK);
Rectangle eye = new Rectangle(25, 70, 15, 15);
g2.fill(eye);
eye.translate(50, 0);
g2.fill(eye);
// Draw the mouth
Line2D.Double mouth = new Line2D.Double(30, 110, 80, 110);
g2.setColor(Color.RED);
g2.draw(mouth);
// Draw the greeting
g2.setColor(Color.BLUE);
g2.drawString("YOU ARE A WINNER", 5, 175);
}
}
why it won't display the last letter when someone wins.
This is happening because in your main method, after you have received the user input, you are changing the location selected by user to to letter of the player. Then you are going on to check if the player is a winner or not. If the player is not a winner then you go on to draw the board and wait for the next player input. But if the player is a winner then you simply display the message and exit the loop without redrawing the board.
The solution is you could draw the board again inside the if condition of checking the winner then display the message and exit the loop.
I would suggest that you declare a method say draw board in your class TicTacToe as shown below:
private void drawBoard(Board board){
System.out.print('\f');
System.out.println(" " + board.getPosition(1) + " | " + board.getPosition(2) + " | " + board.getPosition(3) + " ");
System.out.println("----------------");
System.out.println(" " + board.getPosition(4) + " | " + board.getPosition(5) + " | " + board.getPosition(6) + " ");
System.out.println("----------------");
System.out.println(" " + board.getPosition(7) + " | " + board.getPosition(8) + " | " + board.getPosition(9) + " ");
System.out.println();
}
Now change your while loop for drawing the board and getting user input from:
while (true) {
System.out.print('\f');
System.out.println(" " + board.getPosition(1) + " | " + board.getPosition(2) + " | " + board.getPosition(3) + " ");
System.out.println("----------------");
System.out.println(" " + board.getPosition(4) + " | " + board.getPosition(5) + " | " + board.getPosition(6) + " ");
System.out.println("----------------");
System.out.println(" " + board.getPosition(7) + " | " + board.getPosition(8) + " | " + board.getPosition(9) + " ");
System.out.println();
System.out.print("Choose A Slot: ");
slot = input.nextInt();
if (swap == 1 || swap == 3 || swap == 5 || swap == 7 || swap == 9 || swap == 11) {
board.setPosition(slot, player1Letter);
swap++;
} else if (swap == 2 || swap == 4 || swap == 6 || swap == 8 || swap == 10 || swap == 12) {
board.setPosition(slot, player2Letter);
swap++;
}
if (winner.isWinner(board) == true) {
if (swap == 1 || swap == 3 || swap == 5 || swap == 7 || swap == 9 || swap == 11) { //swap%2 == 1
System.out.println();
System.out.print(player2 + " Wins!");
break;
}
if (swap == 2 || swap == 4 || swap == 6 || swap == 8 || swap == 10 || swap == 12) {
System.out.println();
System.out.print(player1 + " Wins!");
break;
} else if (winner.isWinner(board) == false) {
System.out.println();
System.out.print("Tie Game");
break;
}
}
}
to :
while (true) {
drawBoard(board); //Replace with draw board
System.out.print("Choose A Slot: ");
slot = input.nextInt();
if (swap == 1 || swap == 3 || swap == 5 || swap == 7 || swap == 9 || swap == 11) {
board.setPosition(slot, player1Letter);
swap++;
} else if (swap == 2 || swap == 4 || swap == 6 || swap == 8 || swap == 10 || swap == 12) {
board.setPosition(slot, player2Letter);
swap++;
}
if (winner.isWinner(board) == true) {
drawBoard(board); // Add the draw board.
if (swap == 1 || swap == 3 || swap == 5 || swap == 7 || swap == 9 || swap == 11) { //swap%2 == 1
System.out.println();
System.out.print(player2 + " Wins!");
break;
}
if (swap == 2 || swap == 4 || swap == 6 || swap == 8 || swap == 10 || swap == 12) {
System.out.println();
System.out.print(player1 + " Wins!");
break;
} else if (winner.isWinner(board) == false) {
System.out.println();
System.out.print("Tie Game");
break;
}
}
}
public boolean isWinner(char player)
{
if (board[0] == player && board[1] == player && board[2] == player ||
board[3] == player && board[4] == player && board[5] == player ||
board[6] == player && board[7] == player && board[8] == player ||
board[0] == player && board[3] == player && board[6] == player ||
board[1] == player && board[4] == player && board[7] == player ||
board[2] == player && board[5] == player && board[8] == player )
return true;
return false;
}
/* check to see if the player x is the winner or
the player y is the winner or the cat is the winner
or the game is not over yet and then display the result
you need to write conditional statments*/
public void displayResults()
{
if (isWinner = true)
System.out.print("CONGRATUTIONS " + player + " YOU WON!");
}
Hey I was wondering if anyone could help me on how to pass the the "isWinner" result into "displayResults" if statement. This is for a tic-tac-toe game that we got assigned if this is one of the parts I need help on.
Running under the assumption that player is an accessible char object...
public void displayResults()
{
if (isWinner(player))
System.out.print("CONGRATULATIONS " + player + " YOU WON!");
// ^^^^
// Fix your typo too
}
First of all, isWinner should return true or false, not 1 or 0.
Second of all,
if (isWinner = true)
should be
if (isWinner(player))
assuming player is a char that represents a player, since that's what isWinner() requires.
First off, I'm pretty green when it comes to java. So, I'm making a rock paper scissors game with 2 classes and an object connecting the two. For some unknown reason, when I use the object, it cannot find the method im pointing to. The error is "cannot find symbol" and is in the first class where it is game.RockPaperScissors();
public class RPSRunner {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
char response;
//add in a do while loop after you get the basics up and running
out.print("type in your prompt [R,P,S] :: ");
String player = keyboard.nextLine();
RockPaperScissors game = new RockPaperScissors();
do {
game. **RockPaperScissor **(player);
} while (player == r || p || s);
}
}
and
public class RockPaperScissors {
String playChoice;
String compChoice;
Random random = new Random();
int rand = 0;
public RockPaperScissors() {
playChoice = " ";
compChoice = " ";
}
public RockPaperScissors(String player) {
setPlayers(player);
}
public void setPlayers(String player) {
playChoice = player;
rand = random.nextInt(3);
if (rand == 0) {
compChoice = "r";
}
if (rand == 1) {
compChoice = "p";
}
if (rand == 2) {
compChoice = "s";
}
System.out.println("player had " + playChoice);
System.out.println("computer had " + compChoice);
}
public String determineWinner() {
String winner = "";
if ((compChoice == "r") && (playChoice == "p")) ;
{
winner = "!Player wins << Paper covers Rock>>!";
}
if ((compChoice == "r") && (playChoice == "s")) ;
{
winner = "! Computer wins << Rock breaks Scissors >>!";
}
if ((compChoice == "p") && (playChoice == "r")) ;
{
winner = "! Computer wins << Paper covers Rock>>!";
}
if ((compChoice == "p") && (playChoice == "s")) ;
{
winner = "!Player wins << Scissors cuts paper >>!";
}
if ((compChoice == "s") && (playChoice == "p")) ;
{
winner = "! Computer wins << Scissors cuts paper >>!";
}
if ((compChoice == "s") && (playChoice == "r")) ;
{
winner = "!Player wins << Rock breaks Scissors >>!";
}
if (compChoice == playChoice) ;
{
winner = " !Tie << Both the computer and player have selected " + compChoice + " >>!";
}
return winner;
}
public String toString() {
String output = "";
return output;
}
}
Change
public RockPaperScissors(String player)
To
public void RockPaperScissors(String player)
The former is a constructor while the latter is a method. Also,there seems to be numerous other problems in your code(like the condition of the do...while loop,using == to compare Strings etc)