Exploring Solutions: Dice Board Game and Maze Path Problems in Java

Kushagra Ojha
6 min readJun 9, 2023

--

Introduction

In the realm of programming, solving problems and designing algorithms are essential skills. In this blog, we will delve into two intriguing problems: the Dice Board Game Problem and the Maze Path Problem. These problems require careful thinking and implementation in Java, with the added twist of allowing user input. We will explore the solutions for both problems and demonstrate how recursion can be utilized to find the answers. So, let’s roll the dice and navigate through the maze!

Dice Board Game Problem

The Dice Board Game Problem challenges us to simulate a board game where players roll dice and strive to reach a target score. To start, we prompt the user to input the number of players and the target score. We then create an array to hold the scores and a boolean array to track completed players.

Using recursion, we implement the game logic. Each player takes turns rolling the dice until one of them reaches or exceeds the target score. The random number generator simulates dice rolls, and the scores are updated accordingly. The game continues until a player wins or all players have completed their turns. The program concludes by announcing the winner and ending the game.

Implementation using recursion

import java.util.*;

class DiceBoardGameRecursion {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();

System.out.print("Enter the number of players: ");
int numPlayers = scanner.nextInt();

System.out.print("Enter the target score: ");
int targetScore = scanner.nextInt();

int[] scores = new int[numPlayers];
boolean[] completed = new boolean[numPlayers];

playGame(0, numPlayers, scores, completed, targetScore, random, scanner);

System.out.println("Game Over!");
scanner.close();
}

public static void playGame(int currentPlayer, int numPlayers, int[] scores, boolean[] completed,
int targetScore, Random random, Scanner scanner) {
if (checkAllCompleted(completed)) {
return;
}

if (completed[currentPlayer]) {
playGame((currentPlayer + 1) % numPlayers, numPlayers, scores, completed, targetScore, random, scanner);
return;
}

System.out.print("Player " + (currentPlayer + 1) + " - Press Enter to roll the dice: ");
scanner.nextLine();

int diceValue = random.nextInt(6) + 1;
scores[currentPlayer] += diceValue;

System.out.println("Player " + (currentPlayer + 1) + " rolled a " + diceValue);
System.out.println("Current Score: " + scores[currentPlayer]);

if (scores[currentPlayer] >= targetScore) {
System.out.println("Player " + (currentPlayer + 1) + " has won!");
completed[currentPlayer] = true;
}

System.out.println();

playGame((currentPlayer + 1) % numPlayers, numPlayers, scores, completed, targetScore, random, scanner);
}

public static boolean checkAllCompleted(boolean[] completed) {
for (boolean isCompleted : completed) {
if (!isCompleted) {
return false;
}
}
return true;
}
}

Implementation using loops

import java.util.*;

class DiceBoardGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();

System.out.print("Enter the number of players: ");
int numPlayers = scanner.nextInt();

System.out.print("Enter the target score: ");
int targetScore = scanner.nextInt();

int[] scores = new int[numPlayers];
boolean[] completed = new boolean[numPlayers];

while (true) {
for (int i = 0; i < numPlayers; i++) {
if (completed[i]) {
continue;
}

System.out.print("Player " + (i + 1) + " - Press Enter to roll the dice: ");
scanner.nextLine();

int diceValue = random.nextInt(6) + 1;
scores[i] += diceValue;

System.out.println("Player " + (i + 1) + " rolled a " + diceValue);
System.out.println("Current Score: " + scores[i]);

if (scores[i] >= targetScore) {
System.out.println("Player " + (i + 1) + " has won!");
completed[i] = true;
}

System.out.println();
}

boolean allCompleted = true;
for (boolean isCompleted : completed) {
if (!isCompleted) {
allCompleted = false;
break;
}
}

if (allCompleted) {
break;
}
}

System.out.println("Game Over!");
scanner.close();
}
}

Maze Path Problem

The Maze Path Problem presents a fascinating challenge of finding a path from the top-left corner to the bottom-right corner in a maze. The maze is represented by a 2D array, with 0 denoting an empty path and 1 indicating a blocked path. To solve this problem, we employ recursion and allow user input to define the maze’s dimensions and layout.

After obtaining the maze’s dimensions and layout from the user, we initiate the recursive function, findPath(). This function explores different paths within the maze, starting from the top-left corner. It checks if the current position is valid (within the maze boundaries and not blocked). If the current position is the destination, the function adds the position to the path list and returns true.

If the current position is not the destination, the function makes recursive calls to explore the next possible moves. It attempts to move down and then to the right. If any of these recursive calls return true, it means a valid path has been found. The current position is added to the path list, and the function returns true. If no valid path is found, the function returns false.

The program then displays the found path or indicates if no path exists.

Implementation using recursion

import java.util.*;

class MazePathProblemRecursion {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of rows in the maze: ");
int rows = scanner.nextInt();

System.out.print("Enter the number of columns in the maze: ");
int columns = scanner.nextInt();

int[][] maze = new int[rows][columns];

System.out.println("Enter the maze layout (0 for empty path, 1 for blocked path):");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
maze[i][j] = scanner.nextInt();
}
}

List<String> path = new ArrayList<>();
boolean foundPath = findPath(maze, 0, 0, rows, columns, path);

if (foundPath) {
System.out.println("Path Found:");
for (String step : path) {
System.out.println(step);
}
} else {
System.out.println("No path found!");
}

scanner.close();
}

public static boolean findPath(int[][] maze, int row, int col, int rows, int columns, List<String> path) {
if (row < 0 || row >= rows || col < 0 || col >= columns || maze[row][col] == 1) {
return false;
}

if (row == rows - 1 && col == columns - 1) {
path.add("(" + row + ", " + col + ")");
return true;
}

if (findPath(maze, row + 1, col, rows, columns, path)
|| findPath(maze, row, col + 1, rows, columns, path)) {
path.add("(" + row + ", " + col + ")");
return true;
}

return false;
}
}

Implementation using loops

import java.util.*;

class MazePathProblem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of rows in the maze: ");
int rows = scanner.nextInt();

System.out.print("Enter the number of columns in the maze: ");
int columns = scanner.nextInt();

int[][] maze = new int[rows][columns];

System.out.println("Enter the maze layout (0 for empty path, 1 for blocked path):");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
maze[i][j] = scanner.nextInt();
}
}

List<String> path = new ArrayList<>();
findPath(maze, 0, 0, rows, columns, path);

if (path.isEmpty()) {
System.out.println("No path found!");
} else {
System.out.println("Path Found:");
for (String step : path) {
System.out.println(step);
}
}

scanner.close();
}

public static boolean findPath(int[][] maze, int row, int col, int rows, int columns, List<String> path) {
if (row < 0 || row >= rows || col < 0 || col >= columns || maze[row][col] == 1) {
return false;
}

if (row == rows - 1 && col == columns - 1) {
path.add("(" + row + ", " + col + ")");
return true;
}

if (findPath(maze, row + 1, col, rows, columns, path) || findPath(maze, row, col + 1, rows, columns, path)) {
path.add("(" + row + ", " + col + ")");
return true;
}

return false;
}
}

Conclusion

In this blog, we have tackled two engaging problems, the Dice Board Game Problem and the Maze Path Problem, and implemented their solutions in Java using recursion. By allowing user input, we have made these problems interactive and customizable. The Dice Board Game Problem simulates a game where players aim to reach a target score, while the Maze Path Problem challenges us to navigate through a maze. Both solutions demonstrate how recursion can be leveraged to explore possibilities and find solutions.

By exploring these problems and their solutions, we have enhanced our problem-solving skills and learned how to utilize recursion effectively. These skills are invaluable in various programming scenarios. So, the next time you encounter a problem, don’t hesitate to roll the dice or navigate through the maze of possibilities!

Thanks for Reading ❤❤

--

--

Kushagra Ojha
Kushagra Ojha

Written by Kushagra Ojha

Exploit Developer | Malware Analyst | Security Researcher

No responses yet