Skip to content

Instantly share code, notes, and snippets.

@kishida
Created March 8, 2025 03:36
Show Gist options
  • Save kishida/1c163475f1947a576a22149d4b4433ac to your computer and use it in GitHub Desktop.
Save kishida/1c163475f1947a576a22149d4b4433ac to your computer and use it in GitHub Desktop.
ChatGPTが作った倉庫番
import java.util.Scanner;
public class Sokoban {
private static char[][] level = {
{'#', '#', '#', '#', '#', '#', '#', '#', '#'},
{'#', '.', ' ', ' ', '$', ' ', ' ', '.', '#'},
{'#', ' ', '#', ' ', ' ', ' ', '#', ' ', '#'},
{'#', ' ', '$', ' ', '@', ' ', '$', ' ', '#'},
{'#', '#', ' ', '#', ' ', '#', ' ', '#', '#'},
{'#', ' ', '.', ' ', '$', ' ', ' ', '.', '#'},
{'#', '#', '#', '#', '#', '#', '#', '#', '#'}
};
private static int playerX, playerY;
private static char[][] originalLevel;
public static void main(String[] args) {
findPlayerPosition();
backupOriginalLevel();
Scanner scanner = new Scanner(System.in);
while (true) {
printLevel();
System.out.print("Move (WASD): ");
char move = scanner.next().charAt(0);
movePlayer(move);
if (isGameWon()) {
printLevel();
System.out.println("You win!");
break;
}
}
scanner.close();
}
private static void findPlayerPosition() {
for (int i = 0; i < level.length; i++) {
for (int j = 0; j < level[i].length; j++) {
if (level[i][j] == '@') {
playerX = i;
playerY = j;
return;
}
}
}
}
private static void backupOriginalLevel() {
originalLevel = new char[level.length][level[0].length];
for (int i = 0; i < level.length; i++) {
originalLevel[i] = level[i].clone();
}
}
private static void printLevel() {
for (char[] row : level) {
System.out.println(row);
}
}
private static void movePlayer(char direction) {
int dx = 0, dy = 0;
switch (Character.toUpperCase(direction)) {
case 'W': dx = -1; break;
case 'A': dy = -1; break;
case 'S': dx = 1; break;
case 'D': dy = 1; break;
}
int newX = playerX + dx;
int newY = playerY + dy;
if (level[newX][newY] == ' ' || level[newX][newY] == '.') {
level[playerX][playerY] = (originalLevel[playerX][playerY] == '.' ? '.' : ' ');
playerX = newX;
playerY = newY;
level[playerX][playerY] = '@';
} else if (level[newX][newY] == '$') {
int boxX = newX + dx;
int boxY = newY + dy;
if (level[boxX][boxY] == ' ' || level[boxX][boxY] == '.') {
level[playerX][playerY] = (originalLevel[playerX][playerY] == '.' ? '.' : ' ');
playerX = newX;
playerY = newY;
level[newX][newY] = '@';
level[boxX][boxY] = '$';
}
}
}
private static boolean isGameWon() {
for (int i = 0; i < level.length; i++) {
for (int j = 0; j < level[i].length; j++) {
if (originalLevel[i][j] == '.' && level[i][j] != '$') {
return false;
}
}
}
return true;
}
}
@kishida
Copy link
Author

kishida commented Mar 8, 2025

image

@kishida
Copy link
Author

kishida commented Mar 8, 2025

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment