酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

我的世界Java程序

以下是一个简单的使用Java实现类似“我的世界”基础功能的示例代码,这里实现的是一个简单的方块世界,玩家可以在这个世界里移动和查看所在位置的方块信息。 ```java import java.util.Scanner; // 定义方块类 class Block { private String type; // 构造函数,初始化方块类型 public Block(String type) { this.type = type; } // 获取方块类型的方法 public String getType() { return type; } } // 定义世界类,管理方块世界 class World { private Block[][] blocks; private int width; private int height; // 构造函数,初始化世界的宽度和高度,并填充方块 public World(int width, int height) { this.width = width; this.height = height; blocks = new Block[width][height]; // 用草方块填充世界 for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { blocks[x][y] = new Block("Grass"); } } } // 获取指定位置的方块 public Block getBlock(int x, int y) { if (x >= 0 && x < width && y >= 0 && y < height) { return blocks[x][y]; } return null; } // 获取世界的宽度 public int getWidth() { return width; } // 获取世界的高度 public int getHeight() { return height; } } // 定义玩家类,管理玩家的位置和移动 class Player { private int x; private int y; private World world; // 构造函数,初始化玩家位置和所在世界 public Player(int x, int y, World world) { this.x = x; this.y = y; this.world = world; } // 玩家向上移动 public void moveUp() { if (y > 0) { y--; } } // 玩家向下移动 public void moveDown() { if (y < world.getHeight() - 1) { y++; } } // 玩家向左移动 public void moveLeft() { if (x > 0) { x--; } } // 玩家向右移动 public void moveRight() { if (x < world.getWidth() - 1) { x++; } } // 获取玩家当前位置的方块 public Block getCurrentBlock() { return world.getBlock(x, y); } // 获取玩家的x坐标 public int getX() { return x; } // 获取玩家的y坐标 public int getY() { return y; } } // 主类,包含程序入口 public class SimpleMinecraft { public static void main(String[] args) { // 创建一个宽度为10,高度为10的世界 World world = new World(10, 10); // 创建一个玩家,初始位置为(0, 0) Player player = new Player(0, 0, world); Scanner scanner = new Scanner(System.in); while (true) { // 显示玩家当前位置和所在方块类型 System.out.println("You are at position (" + player.getX() + ", " + player.getY() + ")"); System.out.println("The block here is: " + player.getCurrentBlock().getType()); System.out.println("Enter 'w' to move up, 's' to move down, 'a' to move left, 'd' to move right, 'q' to quit:"); String input = scanner.nextLine(); // 根据用户输入进行相应操作 switch (input) { case "w": player.moveUp(); break; case "s": player.moveDown(); break; case "a": player.moveLeft(); break; case "d": player.moveRight(); break; case "q": System.out.println("Quitting the game..."); scanner.close(); return; default: System.out.println("Invalid input. Please try again."); } } } } ``` 代码说明 1. `Block`类:表示方块,每个方块有一个类型,如“Grass”。 2. `World`类:管理方块世界,包含一个二维数组`blocks`来存储方块信息,提供了获取指定位置方块的方法。 3. `Player`类:管理玩家的位置和移动,玩家可以在世界中上下左右移动。 4. `SimpleMinecraft`类:包含程序入口`main`方法,创建世界和玩家,通过用户输入控制玩家移动。 额外注意的逻辑点 1. 边界检查:在玩家移动时,需要检查是否超出世界边界,避免数组越界异常。 2. 用户输入验证:在获取用户输入时,需要验证输入的合法性,避免程序因无效输入而崩溃。 3. 资源管理:使用`Scanner`读取用户输入时,在程序结束时要记得关闭`Scanner`,避免资源泄漏。 [2025-06-15 11:13:55 | AI写代码神器 | 1271点数解答]

相关提问