文本 Adventure Game Logic
你将构建什么
`playGame(command, 状态)` 函数那个处理 player commands (go north, take 键, 打开 door) and 返回新 game 状态 and 描述的 什么 happened.
学习目标
- Model game 状态 as 对象
- Use conditionals 到 handle player commands
- Implement branching game logic
- 练习字符串 parsing for commands
前置要求
- 对象 and 属性 access
- 如果/else conditional 链
- 字符串方法 (拆分, toLowerCase)
步骤
- 1
定义 game 状态
创建状态对象那个 tracks player's current 空间, inventory, and 哪个 doors 是 locked. 这个状态将 是更新 as player issues commands.
代码const initialState = { room: 'entrance', inventory: [], hasKey: false, doorUnlocked: false, };预期结果
状态对象 representing 开始 game 条件.
- 2
Handle movement commands
Parse commands 如 'go north' and 更新 player's 空间 based on current 空间 and 方向. Use 映射对象到 定义空间连接.
代码const rooms = { entrance: { north: 'hallway' }, hallway: { south: 'entrance', east: 'treasure' }, treasure: { west: 'hallway' }, }; function move(state, direction) { const next = rooms[state.room]?.[direction]; if (!next) return { state, message: 'You cannot go that way.' }; return { state: { ...state, room: next }, message: `You move ${direction} to the ${next}.` }; }预期结果
move(initialState, 'north') moves player 到 hallway.
- 3
Handle take and use commands
添加 logic for 'take 键' (添加键 到 inventory) and 'use 键' (unlocks door 如果 player 有键). 这些 commands 修改状态对象.
代码function takeItem(state, item) { if (state.room === 'hallway' && item === 'key') { return { state: { ...state, inventory: [...state.inventory, 'key'], hasKey: true }, message: 'You take the key.' }; } return { state, message: 'There is no key here.' }; } function useItem(state, item) { if (item === 'key' && state.hasKey) { return { state: { ...state, doorUnlocked: true }, message: 'You unlock the door with the key.' }; } return { state, message: 'You cannot use that.' }; }预期结果
Taking 键 in hallway and using 它 unlocks door.
- 4
创建主要 command dispatcher
组合所有处理函数到 单个
playGame(command, 状态)函数那个 parses command 字符串 and dispatches 到正确处理函数.代码function playGame(command, state) { const [action, ...args] = command.toLowerCase().split(' '); const target = args.join(' '); if (action === 'go') return move(state, target); if (action === 'take') return takeItem(state, target); if (action === 'use') return useItem(state, target); return { state, message: 'Unknown command.' }; } // Test a sequence let s = initialState; let r; r = playGame('go north', s); s = r.state; console.log(r.message); r = playGame('take key', s); s = r.state; console.log(r.message); r = playGame('use key', s); s = r.state; console.log(r.message);预期结果
Three 消息: moving 到 hallway, taking 键, unlocking door.
- 5
添加输入验证
在主逻辑入口处添加输入验证:检查输入是否为有效数字、是否在允许范围内,对非法输入给出清晰提示而非崩溃。这是健壮程序的第一道防线。
代码function validateInput(value, min, max) { if (typeof value !== "number" || Number.isNaN(value)) { throw new Error(`Invalid input: ${value} is not a number`); } if (value < min || value > max) { throw new Error(`Input ${value} out of range [${min}, ${max}]`); } return value; } // Usage const input = validateInput(rawInput, 1, 100);预期结果
非法输入(非数字或超出范围)会抛出清晰的错误信息,合法输入正常通过。
提示
使用 try/catch 包裹调用处,向用户展示友好的错误提示。
自己动手试试
function playGame(command, state) {
// TODO: parse command and dispatch to handlers
return { state, message: 'Not implemented.' };
}const rooms = {
entrance: { north: 'hallway' },
hallway: { south: 'entrance', east: 'treasure' },
treasure: { west: 'hallway' },
};
function playGame(command, state) {
const [action, ...args] = command.toLowerCase().split(' ');
const target = args.join(' ');
if (action === 'go') {
const next = rooms[state.room]?.[target];
if (!next) return { state, message: 'You cannot go that way.' };
return { state: { ...state, room: next }, message: `You move ${target} to the ${next}.` };
}
if (action === 'take' && target === 'key' && state.room === 'hallway') {
return { state: { ...state, hasKey: true, inventory: [...state.inventory, 'key'] }, message: 'You take the key.' };
}
if (action === 'use' && target === 'key' && state.hasKey) {
return { state: { ...state, doorUnlocked: true }, message: 'You unlock the door.' };
}
return { state, message: 'Unknown command.' };
}你学到了什么
你 modeled game as 状态 plus command 处理函数 — 相同架构 used in 真实 games, chatbots, and interactive applications. 状态 management and command dispatch 是基本模式.
相关资源
相关练习
- Predict 如果/else 输出
练习 tracing conditional 分支.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。