This challenge is about developing a Tic-tac-toe game, but with some modifications. We'd like the number of tiles (rows and columns) to be possible to specify, as well as how many in a row are required to win.
You may use any programming language you are comfortable with.
Rather than building a user interface (e.g. GUI or CLI) to play the game, we want you to write tests. As well as testing the core logic (that you think is worth testing), your tests should give the reader a good idea of how they would use your code when building a CLI/GUI.
Please structure and test your code as if it was meant for production. Your solution should be well structured and easy to understand. It should be simple to modify your code to accommodate new requirements (Example: could you change the game so that you lose rather than win if you get X in a row?).
See this as an opportunity to show some of your skills. The purpose of this challenge is for us to get a glimpse of your ability to solve problems and build well-structured software that works as intended. If something is unclear to you, feel free to make an assumption and let us know. However, try not to simplify the challenge with assumptions, as the goal is for you to be able to show your skills.
While it should be possible to build a GUI or CLI using your code, you do not need to set up any infrastructure for it (e.g. create a bundle that works in a browser environment). Similarly, while you should structure your code and write tests as if it was for production, do not worry about things like minimizing your code (if you used JS/TS) or tweaking any build settings.
Once you are happy with the code, send it with your application as, for instance, a ZIP or TAR file. Do include a text file briefly explaining your solution, with a focus on how it is structured at a high level. Also, include what was most challenging and how you solved it. Please don’t upload your solution on Github.
If you already have code that is at least as complex as this challenge and you can share, feel free to apply with that instead of doing this challenge. Describe it in short (what it is for and how it is structured at a high-level, and what was most challenging and how you solved it) and include the repository URL if the code is on for instance GitHub.
Good luck and looking forward to your application.
Cheers,
The development team at Small Improvements
Solve using Typescript. Create a elegant, beautiful and maybe slightly extravagant solution, that stands out.
Assistant
This solution provides a flexible Tic-Tac-Toe game implemented in TypeScript, focusing on clean architecture, comprehensive testing, and extensibility.
Solution Overview
The core of the solution is the TicTacToeGame class, which encapsulates all game logic and state. It's designed to be configurable, allowing users to specify the board dimensions (rows and columns) and the number of markers required to win (winCount).
src/TicTacToeGame.ts: Contains the main TicTacToeGame class, handling game state management, move validation, win/draw condition checks, and player switching.
src/TicTacToeGame.spec.ts: Houses the unit tests for the TicTacToeGame class. These tests cover various scenarios, including initialization, valid/invalid moves, win conditions (horizontal, vertical, diagonal), draw conditions, and game resets. They also serve as examples of how to interact with the TicTacToeGame API.
src/interfaces.ts: Defines TypeScript interfaces and enums used across the application (e.g., GameConfig, PlayerMarker, GameStatus, GameState). This improves type safety and readability.
src/errors.ts: Custom error classes (GameError, InvalidMoveError, GameEndedError) are defined here. This allows for more specific error handling and clearer communication of why a move failed.
package.json: Standard Node.js package configuration, including development dependencies for TypeScript and Jest.
tsconfig.json: TypeScript compiler configuration.
jest.config.js: Jest test runner configuration.
Key Design Choices
Configurability:
The TicTacToeGame constructor accepts a GameConfig object (or partial thereof) to set , , and . Default values are provided for standard Tic-Tac-Toe (3x3, win 3).
rows
cols
winCount
The game validates the provided configuration to prevent impossible scenarios (e.g., winCount greater than board dimensions).
Clear API for UI Integration:
Instantiation: const game = new TicTacToeGame({ rows: 5, cols: 5, winCount: 4 });
Making Moves: game.makeMove(row, col) throws specific errors for invalid actions, otherwise updates the state and returns the current GameState.
Querying State: Methods like getBoard(), getCurrentPlayer(), getGameStatus(), getWinner(), and isGameOver() provide read-only access to the game's current state. getGameState() provides a comprehensive snapshot.
Resetting: game.reset() restarts the game to its initial state.
Encapsulation and Immutability:
The internal game state (board, currentPlayer, etc.) is private.
getBoard() returns a deep copy of the board array, preventing external code from directly modifying the game state and ensuring data integrity.
makeMove() and reset() return the new GameState object, promoting a clear understanding of state transitions.
Robust Win Condition Check:
The checkWin private method efficiently verifies win conditions by checking all four directions (horizontal, vertical, two diagonals) around the lastMoveRow and lastMoveCol. It checks both forward and backward from the last placed marker to find winCount consecutive markers.
Extensibility:
Changing Win/Lose Condition: The checkWin method simply identifies if a line of winCount markers is achieved. The makeMove method then interprets this outcome. To change to a "lose if you get X in a row" rule, you would only need to modify the makeMove method's if (this.checkWin(...)) block to set status to GameStatus.Loss and winner to the other player. The checkWin logic itself remains untouched, demonstrating a clear separation of concerns.
More Players: Currently, PlayerMarker is 'X' | 'O'. To add more players, you could modify PlayerMarker to be a string type alias and add a players: PlayerMarker[] array to GameConfig. The switchPlayer method would then cycle through this array.
Different Game Rules: The modular design allows modifications. For example, adding special tiles or specific winning patterns might involve extending or replacing the checkWin method or adding new methods.
How to use the code (as demonstrated by tests)
typescript
import { TicTacToeGame, GameStatus, PlayerMarker } from './TicTacToeGame';
// Create a default 3x3 game, win 3
const game1 = new TicTacToeGame();
// Create a 5x5 game, win 4
const game2 = new TicTacToeGame({ rows: 5, cols: 5, winCount: 4 });
// Make moves
game1.makeMove(0, 0); // X plays (0,0)
game1.makeMove(1, 0); // O plays (1,0)
game1.makeMove(0, 1); // X plays (0,1)
// Get current state
console.log('Current Player:', game1.getCurrentPlayer()); // O
console.log('Board:', game1.getBoard());
console.log('Game Status:', game1.getGameStatus()); // IN_PROGRESS
// Simulate a win
game1.makeMove(2, 0); // O plays (2,0)
game1.makeMove(0, 2); // X plays (0,2) - X wins horizontally!
console.log('Game Status after win:', game1.getGameStatus()); // WIN
console.log('Winner:', game1.getWinner()); // X
console.log('Is game over?', game1.isGameOver()); // true
// Try an invalid move after game over
try {
game1.makeMove(1, 1);
} catch (error) {
console.error('Error making move:', error.message); // Game is already WIN. Reset to play again.
}
// Reset the game
game1.reset();
console.log('Game Status after reset:', game1.getGameStatus()); // IN_PROGRESS
Most Challenging Aspects and Solutions
Robust Win Condition Check for N-in-a-Row:
Challenge: The primary challenge was to create a checkWin method that is highly flexible for any board size and winCount, and efficient. It needed to correctly identify wins horizontally, vertically, and along both diagonal axes, even when the winning line does not start at index 0 or end at the board edge.
Solution: The chosen approach is to iterate through four main directions (horizontal, vertical, diagonal-down, diagonal-up) from the last placed marker. For each direction, it counts consecutive markers of the current player by extending outwards in both positive and negative increments. This ensures that a win is detected regardless of where the winning line begins or ends, as long as it passes through the last placed marker. This method is efficient because it only checks lines relevant to the most recent move, rather than scanning the entire board repeatedly.
Designing for Extensibility (Win vs. Lose):
Challenge: The prompt specifically asked about the ease of changing the game from "win if X in a row" to "lose if X in a row". This required a clear separation of concerns.
Solution: I separated the logic for detectingN in a row (checkWin method) from the logic for interpreting that detection within the game flow (makeMove method). The checkWin method is purely a boolean function that tells if a line has been completed. The makeMove method then decides what that means for the game's status and winner. This design makes it trivial to swap win conditions by modifying only a few lines in makeMove without touching the core checkWin logic, as described in the "Extensibility" section above.
Ensuring Immutability for Public Accessors:
Challenge: When returning the board state via getBoard(), simply returning the internal array reference would allow external code to directly modify the game's state, leading to unpredictable behavior.
Solution: The getBoard() method returns a deep copy of the board array using this.board.map(row => [...row]). This ensures that any modifications made to the returned board array by external code do not affect the internal, authoritative game state. This practice enhances robustness and predictability.
This solution aims to provide a solid foundation for a customizable Tic-Tac-Toe game, demonstrating a clear understanding of object-oriented design principles, type safety, and test-driven development.