import java.util.Scanner;
public class SokobanGame {
private char[][] gameMap;
private int playerX;
private int playerY;
private int targetCount;
private int moves;
private int bestScore;
public SokobanGame() {
gameMap = new char[][]{
{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'},
{'#', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', '#'},
{'#', ' ', 'T', ' ', ' ', '#', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', 'B', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', '#'},
{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'}
};
playerX = 3;
playerY = 3;
targetCount = 1;
moves = 0;
bestScore = Integer.MAX_VALUE;
}
public void playGame() {
Scanner scanner = new Scanner(System.in);
while (true) {
displayGameMap();
System.out.print("Enter move (W/A/S/D): ");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("W")) {
movePlayer(-1, 0);
} else if (input.equalsIgnoreCase("A")) {
movePlayer(0, -1);
} else if (input.equalsIgnoreCase("S")) {
movePlayer(1, 0);
} else if (input.equalsIgnoreCase("D")) {
movePlayer(0, 1);
} else {
System.out.println("Invalid input! Please enter W/A/S/D.");
continue;
}
if (targetCount == 0) {
System.out.println("Congratulations! You win!");
if (moves < bestScore) {
bestScore = moves;
System.out.println("New best score: " + bestScore);
}
break;
}
}
scanner.close();
}
private void displayGameMap() {
for (int i = 0; i < gameMap.length; i++) {
for (int j = 0; j < gameMap[i].length; j++) {
System.out.print(gameMap[i][j]);
}
System.out.println();
}
System.out.println("Moves: " + moves);
System.out.println("Best score: " + bestScore);
}
private void movePlayer(int dx, int dy) {
int newX = playerX + dx;
int newY = playerY + dy;
if (gameMap[newX][newY] == ' ') {
gameMap[playerX][playerY] = ' ';
gameMap[newX][newY] = 'P';
playerX = newX;
playerY = newY;
moves++;
} else if (gameMap[newX][newY] == 'T') {
gameMap[playerX][playerY] = ' ';
gameMap[newX][newY] = 'P';
playerX = newX;
playerY = newY;
targetCount--;
moves++;
} else if (gameMap[newX][newY] == 'B') {
int boxNewX = newX + dx;
int boxNewY = newY + dy;
if (gameMap[boxNewX][boxNewY] == ' ') {
gameMap[playerX][playerY] = ' ';
gameMap[newX][newY] = 'P';
gameMap[boxNewX][boxNewY] = 'B';
playerX = newX;
playerY = newY;
moves++;
}
}
}
public static void main(String[] args) {
SokobanGame game = new SokobanGame();
game.playGame();
}
}