Text Adventure Game Logic
What you'll build
A `playGame(command, state)` function that processes player commands (go north, take key, open door) and returns the new game state and a description of what happened.
Goals
- Model game state as an object
- Use conditionals to handle player commands
- Implement branching game logic
- Practice string parsing for commands
Prerequisites
- Objects and property access
- if/else conditional chains
- String methods (split, toLowerCase)
Steps
- 1
Define the game state
Create a state object that tracks the player's current room, inventory, and which doors are locked. This state will be updated as the player issues commands.
Codeconst initialState = { room: 'entrance', inventory: [], hasKey: false, doorUnlocked: false, };Expected result
A state object representing the starting game conditions.
- 2
Handle movement commands
Parse commands like 'go north' and update the player's room based on the current room and direction. Use a map object to define room connections.
Codeconst 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}.` }; }Expected result
move(initialState, 'north') moves the player to the hallway.
- 3
Handle take and use commands
Add logic for 'take key' (adds key to inventory) and 'use key' (unlocks the door if the player has the key). These commands modify the state object.
Codefunction 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.' }; }Expected result
Taking the key in the hallway and using it unlocks the door.
- 4
Create the main command dispatcher
Combine all handlers into a single
playGame(command, state)function that parses the command string and dispatches to the right handler.Codefunction 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);Expected result
Three messages: moving to hallway, taking the key, unlocking the door.
- 5
Add input validation
At the entry of the main logic, add input validation: check that the input is a valid number and within the allowed range, and show a clear message for invalid input instead of crashing. This is the first line of defense for a robust program.
Codefunction 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);Expected result
Invalid input (non-number or out of range) throws a clear error message; valid input passes through normally.
Hint
Wrap the call site in try/catch to show a friendly error to the user.
Try it yourself
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.' };
}What you learned
You modeled a game as state plus command handlers — the same architecture used in real games, chatbots, and interactive applications. State management and command dispatch are fundamental patterns.
Related Resources
Related Lessons
- Conditions
Conditionals route commands to the right handler.
- Objects
Objects model game state and room connections.
Related Practice
- Predict the if/else Output
Practice tracing conditional branches.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.