-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextBasedMazeGame.java
More file actions
91 lines (78 loc) · 2.55 KB
/
TextBasedMazeGame.java
File metadata and controls
91 lines (78 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.util.Scanner;
public class TextBasedMazeGame {
private static int playerRow = 0; // Player's starting row
private static int playerCol = 0; // Player's starting column
private static final int MAZE_SIZE = 5; // Size of the maze (5x5 in this example)
// Representing the maze (1: wall, 0: path, P: player)
private static final char[][] maze = {
{'0', '1', '0', '1', '0'},
{'0', '0', '1', '0', '1'},
{'1', '0', '0', '1', '0'},
{'1', '1', '0', '0', '0'},
{'0', '1', '1', '0', 'P'}
};
public static void main(String[] args) {
playMazeGame();
}
private static void displayMaze() {
for (char[] row : maze) {
for (char cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
}
private static void movePlayer(char direction) {
int newRow = playerRow;
int newCol = playerCol;
switch (direction) {
case 'W':
case 'w':
newRow--;
break;
case 'S':
case 's':
newRow++;
break;
case 'A':
case 'a':
newCol--;
break;
case 'D':
case 'd':
newCol++;
break;
default:
System.out.println("Invalid input!");
return;
}
if (isValidMove(newRow, newCol)) {
// Update player's position
maze[playerRow][playerCol] = '0';
playerRow = newRow;
playerCol = newCol;
maze[playerRow][playerCol] = 'P';
} else {
System.out.println("Invalid move! Try again.");
}
}
private static boolean isValidMove(int row, int col) {
return row >= 0 && row < MAZE_SIZE &&
col >= 0 && col < MAZE_SIZE &&
maze[row][col] != '1';
}
private static void playMazeGame() {
Scanner scanner = new Scanner(System.in);
char direction;
System.out.println("Welcome to the Text-Based Maze Game!");
displayMaze();
while (maze[playerRow][playerCol] != 'P') {
System.out.print("Enter a direction (WASD): ");
direction = scanner.next().toUpperCase().charAt(0);
movePlayer(direction);
displayMaze();
}
System.out.println("Congratulations! You have reached the end of the maze!");
scanner.close();
}
}