How do I mark every position the player has been to in a maze game (2D array)?
Fantastic news! We've Found the answer you've been seeking!
Question:
How do I mark every position the player has been to in a maze game (2D array)?
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 implement 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: 1-- 'U' for up 2-- 'D' for down 3-- 'L' for left 4-- 'R' for right 5-- 'Q' for quit Have fun playing the maze game and best of luck to you :)"); while(true){ System.out.print(" Enter 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(playerRow0 && 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
Related Book For
Posted Date: