
本文介绍如何基于 swing 构建可扩展的 2d 地形系统,通过面向对象建模(biome/chunk/world)解耦逻辑与 ui,并利用键控导航实现类似 minecraft 的区块切换效果,避免阻塞主线程或轮询检测。
本文介绍如何基于 swing 构建可扩展的 2d 地形系统,通过面向对象建模(biome/chunk/world)解耦逻辑与 ui,并利用键控导航实现类似 minecraft 的区块切换效果,避免阻塞主线程或轮询检测。
在 Java Swing 中实现“类 Minecraft”式的 2D 地形系统,关键不在于暴力轮询组件坐标(如 while(true) 检查 JLabel 位置),而在于以数据驱动 UI、用事件替代轮询、靠抽象隔离变化。下面将从模型设计、UI 构建到完整运行逻辑,逐步呈现一个专业、可维护的实现方案。
✅ 核心设计原则:MVC 分离与接口抽象
首先定义清晰的数据契约,而非直接操作 JPanel:
public enum Biome { FOREST, PLAINS }
public interface Chunk {
Biome getBiome();
Point getLocation(); // 世界坐标 (x, y)
}
public interface World {
Chunk getChunkAt(int x, int y);
}
public interface ChunkFactory {
Chunk createChunk(Point worldLocation);
}使用 interface 而非具体类,是为了支持未来扩展(例如添加 DESERT 生物群系、NOISE_BASED_GENERATION 工厂),并便于单元测试和依赖注入。
? 动态世界存储:基于 Map 的稀疏矩阵
传统二维数组(Chunk[][])要求预分配固定大小,而真实世界是无限且稀疏的。我们采用 HashMapMatrix 实现按需加载的稀疏矩阵:
立即学习“Java免费学习笔记(深入)”;
public interface Matrix<T> {
T get(int x, int y);
void put(T value, int x, int y);
}
public class HashMapMatrix<T> implements Matrix<T> {
private final Map<Integer, Map<Integer, T>> values = new HashMap<>();
@Override
public T get(int x, int y) {
Map<Integer, T> row = values.get(y);
return row == null ? null : row.get(x);
}
@Override
public void put(T value, int x, int y) {
values.computeIfAbsent(y, k -> new HashMap<>()).put(x, value);
}
}该结构仅在访问 (x,y) 时才生成对应 Chunk,内存占用随玩家探索范围线性增长,天然支持“无限世界”。
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
? 世界生成器:可插拔的工厂模式
DefaultChunkFactory 随机分配生物群系,但逻辑完全独立于 UI:
public class DefaultChunkFactory implements ChunkFactory {
private final List<Biome> biomes = Arrays.asList(Biome.values());
@Override
public Chunk createChunk(Point location) {
Biome biome = biomes.get((int)(Math.random() * biomes.size()));
return new DefaultChunk(biome, location);
}
}
public class DefaultChunk implements Chunk {
private final Biome biome;
private final Point location;
public DefaultChunk(Biome biome, Point location) {
this.biome = biome;
this.location = new Point(location);
}
@Override
public Biome getBiome() { return biome; }
@Override
public Point getLocation() { return location; }
}? 注意:此处
Math.random()替代了原问题中易出错的Random.nextInt(2)+1(越界风险),且避免硬编码颜色值——颜色应在视图层决定。
?️ 视图层:ChunkPane 与动态世界面板
ChunkPane 是 JPanel 的子类,仅负责渲染单个区块:
public class ChunkPane extends JPanel {
public ChunkPane(Chunk chunk) {
this.chunk = chunk;
setBackground(chunk.getBiome() == Biome.FOREST ? Color.GREEN : Color.YELLOW);
setLayout(new BorderLayout());
add(new JLabel("[" + chunk.getLocation().x + "," + chunk.getLocation().y + "]"), BorderLayout.SOUTH);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}核心控制器 SwingCraft 管理玩家位置与区块切换,完全摒弃轮询,改用 Swing 标准事件机制:
public class SwingCraft extends JPanel {
private final Matrix<ChunkPane> cache = new HashMapMatrix<>();
private final World world;
private Point playerPos = new Point(0, 0);
public SwingCraft(World world) {
this.world = world;
setLayout(new BorderLayout());
setChunk(playerPos);
// 键绑定:LEFT/RIGHT/UP/DOWN → 移动动作
InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = getActionMap();
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "up");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "down");
actionMap.put("left", new MoveAction(-1, 0));
actionMap.put("right", new MoveAction(1, 0));
actionMap.put("up", new MoveAction(0, -1));
actionMap.put("down", new MoveAction(0, 1));
}
private void setChunk(Point pos) {
ChunkPane pane = cache.get(pos.x, pos.y);
if (pane == null) {
Chunk chunk = world.getChunkAt(pos.x, pos.y);
pane = new ChunkPane(chunk);
cache.put(pane, pos.x, pos.y);
}
removeAll();
add(pane);
revalidate();
repaint();
}
private class MoveAction extends AbstractAction {
private final int dx, dy;
MoveAction(int dx, int dy) {
this.dx = dx;
this.dy = dy;
}
@Override
public void actionPerformed(ActionEvent e) {
playerPos.x += dx;
playerPos.y += dy;
setChunk(playerPos);
}
}
}✅ 运行与最佳实践要点
-
无需多线程轮询:Swing 是单线程 GUI 框架,
while(true)会冻结界面;键事件天然异步且高效。 -
中心化状态管理:玩家位置
playerPos是唯一可信源,UI 刷新由setChunk()统一触发。 -
避免
getContentPane()比较:原问题中用frame.getContentPane() == world[i][j]判断当前面板,极易因引用失效导致 bug;本方案通过playerPos直接计算目标区块,逻辑更健壮。 -
启动方式(确保在 Event Dispatch Thread 中):
EventQueue.invokeLater(() -> { JFrame frame = new JFrame("SwingCraft"); frame.add(new SwingCraft(new DefaultWorld(new DefaultChunkFactory()))); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); });
这套架构不仅解决了原始需求(3×3 网格、中心房屋、边界响应),更构建了可无限扩展的地形引擎骨架——添加新生物群系只需新增 Biome 枚举值和 ChunkPane 渲染逻辑,无需修改世界生成或导航代码。这才是 Swing 场景下真正可持续的工程实践。


















