Lesson 14. Capstone: Simulating a lock and key

 

In this capstone exercise you’re going to build a lock and key system. Each lock will have its own key that’s unique to it. The lock will hold some secret data and only return the data if accessed with the correct key. You’ll then build a game where you generate three locks and give the player only one key and one chance to unlock a prize!

14.1. Creating the lock and key system

You’ll start by designing the lock API. You want to have a function called lock which accepts a single parameter that’s the data you’re locking up. It should then return a unique key (key as in key to a lock) and an unlock function that reveals the secret if invoked with the correct key. So the high-level API is basically { key, unlock } = lock(secret).

The secret can be any single datum. Both lock and unlock are functions, but you need to figure out what data type key is going to be.

A good solution would be a randomly generated string. But strings aren’t exactly unique; it’s possible they may overlap or even be guessable. You can use a complex string that’s hard to guess or rarely overlaps like a SHA-1, but that would take a lot of effort or require installing a library. You already have a data type that’s easy to generate and guaranteed to be unique, the Symbol. So you’ll use that:

14.2. Creating a Choose the Door game

Summary