App 24 — 24 Apps You Can Make Today
Lights Out Game
The classic puzzle game — a 5×5 grid of lights where every tap toggles a cell and its neighbors.
- ios
Lights Out is a classic puzzle. A grid of lights — some on, some off. Tap a cell and it toggles, but so do all its neighbors. The goal is to turn every light off. The final app in the book, and the most complete game in it.
What you'll build
A 5×5 (or 4×4) grid of toggle-able cells. Tap a cell and it, plus its left, right, up, and down neighbors, flip their state. A win message appears when all cells are off. A Reset button generates a new puzzle.
Key concepts
2D grid state — Store the grid as a flat array of Bool values. true = on, false = off.
let size = 5
@State var grid: [Bool] = Array(repeating: false, count: 5 * 5)
Toggle with neighbor effect — When a cell is tapped, flip it and all valid neighbors.
func tap(row: Int, col: Int) {
for (dr, dc) in [(0,0), (-1,0), (1,0), (0,-1), (0,1)] {
let r = row + dr, c = col + dc
guard r >= 0, r < size, c >= 0, c < size else { continue }
grid[r * size + c].toggle()
}
}
Win detection — The puzzle is solved when no cell is true.
var isSolved: Bool { !grid.contains(true) }
LazyVGrid — The same grid layout from Pixel Paint (App 13), now with game logic attached.
Generating solvable puzzles — Start from a solved state and apply random taps to guarantee the puzzle is solvable.
func newGame() {
grid = Array(repeating: false, count: size * size)
for _ in 0..<(size * size) {
tap(row: Int.random(in: 0..<size), col: Int.random(in: 0..<size))
}
}
Putting it all together
Lights Out combines arrays, grid layout, game logic, and win detection — patterns from throughout the book. It's a fitting finale: a real, playable, complete game in a few dozen lines of Swift.
Download and run it
Open the Playgrounds file from GitHub, hit Run, and solve the puzzle.