用Java编写推方块游戏的代码
时间: 2023-12-04 18:04:55 浏览: 31
以下是一个简单的用Java编写的推方块游戏的代码:
```java
import java.util.Scanner;
public class PushBoxGame {
private static int[][] map = {
{1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 2, 0, 0, 1},
{1, 0, 0, 0, 3, 0, 1},
{1, 1, 1, 1, 1, 1, 1}
}; // 1表示墙,0表示空地,2表示人物,3表示箱子
private static int playerX = 4;
private static int playerY = 3;
private static int boxX = 5;
private static int boxY = 4;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
showMap();
System.out.print("请输入移动方向(w上 s下 a左 d右):");
String direction = scanner.next();
switch (direction) {
case "w":
move(-1, 0);
break;
case "s":
move(1, 0);
break;
case "a":
move(0, -1);
break;
case "d":
move(0, 1);
break;
default:
System.out.println("无效的移动方向!");
}
if (isWin()) {
System.out.println("恭喜你,通关了!");
break;
}
}
scanner.close();
}
private static void showMap() {
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[0].length; j++) {
if (i == playerX && j == playerY) {
System.out.print("2");
} else if (i == boxX && j == boxY) {
System.out.print("3");
} else {
System.out.print(map[i][j]);
}
}
System.out.println();
}
}
private static void move(int dx, int dy) {
int nextPlayerX = playerX + dx;
int nextPlayerY = playerY + dy;
if (map[nextPlayerX][nextPlayerY] == 0) { // 空地
playerX = nextPlayerX;
playerY = nextPlayerY;
} else if (map[nextPlayerX][nextPlayerY] == 3) { // 箱子
int nextBoxX = boxX + dx;
int nextBoxY = boxY + dy;
if (map[nextBoxX][nextBoxY] == 0) { // 箱子推到空地
playerX = nextPlayerX;
playerY = nextPlayerY;
boxX = nextBoxX;
boxY = nextBoxY;
}
}
}
private static boolean isWin() {
return map[boxX][boxY] == 1;
}
}
```
该代码中使用了一个二维数组来表示游戏地图,其中1表示墙,0表示空地,2表示人物,3表示箱子。在游戏进行过程中,用户输入移动方向后,程序会根据当前人物和箱子的位置,判断是否可以移动,并更新人物和箱子的位置。最后,判断箱子是否被推到终点,如果是则通关。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)