ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

0422-Box-实现推箱子游戏

2026/8/13 12:14:36 拓冰建站 浏览量
0422-Box-实现推箱子游戏

环境

  • Time 2024-03-07
  • Zig 0.12.0-dev.3152+90c1a2c41
  • WSL-Ubuntu 22.04.3 LTS

前言

说明

参考资料:

  1. 《游戏开发:世嘉新人培训教材》

目标

使用 Zig 语言实现一个控制台的推箱子游戏。

实现游戏的更新

fn update(state: []MapItem, input: ?u8) void {const char = input orelse return;// 操作角色移动的距离const delta: isize = switch (char) {'w' => -stageWidth,'s' => stageWidth,'d' => 1,'a' => -1,else => return,};// 角色当前位置const currentIndex = for (state, 0..) |value, index| {if (value == MapItem.MAN or value == MapItem.MAN_ON_GOAL) break index;} else return;const index = @as(isize, @intCast(currentIndex)) + delta;if (index < 0 or index > stageLength) return;// 角色欲前往的目的地const destIndex = @as(usize, @intCast(index));updateMap(state, currentIndex, destIndex, delta);
}

更新游戏地图

fn updateMap(state: []MapItem, current: usize, dest: usize, delta: isize) void {if (state[dest] == .SPACE or state[dest] == .GOAL) {// 如果是空地或者目标地,则可以移动state[dest] = if (state[dest] == .GOAL) .MAN_ON_GOAL else .MAN;state[current] = if (state[current] == .MAN_ON_GOAL) .GOAL else .SPACE;} else if (state[dest] == .BLOCK or state[dest] == .BLOCK_ON_GOAL) {//  如果是箱子或者目的地上的箱子,需要考虑该方向上的第二个位置const index = @as(isize, @intCast(dest)) + delta;if (index < 0 or index > stageLength) return;const next = @as(usize, @intCast(index));if (state[next] == .SPACE or state[next] == .GOAL) {state[next] = if (state[next] == .GOAL) .BLOCK_ON_GOAL else .BLOCK;state[dest] = if (state[dest] == .BLOCK_ON_GOAL) .MAN_ON_GOAL else .MAN;state[current] = if (state[current] == .MAN_ON_GOAL) .GOAL else .SPACE;}}
}

主函数 main

pub fn main() void {// 初始化地图var state: [stageLength]MapItem = undefined;initialize(&state, stageMap);const stdin = std.io.getStdIn().reader();while (true) {// 画出游戏地图draw(&state);// 检查游戏胜利条件if (checkClear(&state)) break;std.debug.print("a:left d:right w:up s:down. command?\n", .{});// 获取用户输入const char = inputChar(stdin);// 根据输入更新游戏地图update(&state, char);}// 游戏胜利std.debug.print("Congratulation's! you win.\n", .{});
}

效果

########
# .. p #
# oo   #
#      #
########
a:left d:right w:up s:down. command?
s
########
# ..   #
# oo p #
#      #
########
a:left d:right w:up s:down. command?
s
########
# ..   #
# oo   #
#    p #
########
a:left d:right w:up s:down. command?
a
########
# ..   #
# oo   #
#   p  #
########
a:left d:right w:up s:down. command?
a
########
# ..   #
# oo   #
#  p   #
########
a:left d:right w:up s:down. command?
w
########
# .O   #
# op   #
#      #
########
a:left d:right w:up s:down. command?
s
########
# .O   #
# o    #
#  p   #
########
a:left d:right w:up s:down. command?
a
########
# .O   #
# o    #
# p    #
########
a:left d:right w:up s:down. command?
w
########
# OO   #
# p    #
#      #
########
Congratulation's! you win.

总结

使用 Zig 语言,实现了命令行的推箱子游戏。

附录

源码

https://github.com/jiangbo/game/tree/main/zig/box/box1