Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 71 ยท Projects

Project: Number Guessing Game, OTP Generator and Random Numbers

Build a random number generator, a number guessing game and a one-time-password generator and validator in React Native, with testable logic, expiry and attempt limits.

Three small apps share one ingredient: randomness. A random number generator is the simplest possible screen, a guessing game turns randomness into rules, and a one-time-password (OTP) screen shows where randomness becomes a security matter. Before the apps, you need to understand what Math.random() is and is not, because that choice decides which of the three is safe to ship.

What runs on this site. The React Native screens are read-only here. The logic is plain JavaScript and runs below, together with stand-in screens that use the same state and functions with HTML.

Random numbers, correctly

Math.random() returns a decimal from 0 up to but not including 1. To get a whole number in an inclusive range you scale, floor and shift:

JavaScript
export function randomInt(min, max, random = Math.random) {
  const low = Math.ceil(min);
  const high = Math.floor(max);
  return Math.floor(random() * (high - low + 1)) + low;   // both ends included
}

Two habits make this testable. The generator takes the random function as a parameter that defaults to Math.random, so a test can pass a fixed sequence. And it handles the range arithmetic in one place, so you never write Math.round(Math.random() * 10) (which makes 0 and 10 only half as likely as the others).

Math.random() is fine for games, shuffling a list or picking a joke. It is not secure: its output can be predicted by someone who sees enough of it. For anything an attacker would profit from guessing (OTPs, tokens, password suggestions) use a cryptographically secure source. In Expo that is expo-crypto:

JavaScript
import * as Crypto from 'expo-crypto';

const bytes = Crypto.getRandomValues(new Uint32Array(1));   // secure random 32-bit integer
const secureInt = bytes[0];

To get an unbiased integer below n from it, reject values from the uneven top slice instead of using % directly (value % n favours small numbers when n does not divide 2^32 evenly):

JavaScript
export function secureInt(n, getValues) {
  const limit = Math.floor(0x100000000 / n) * n;
  let value;
  do {
    value = getValues(new Uint32Array(1))[0];
  } while (value >= limit);
  return value % n;
}

For reproducible tests and demos you also want a seeded generator that gives the same sequence for the same seed. A few lines do it (the algorithm is called mulberry32):

JavaScript
export function seeded(seed) {
  let a = seed >>> 0;
  return () => {
    a = (a + 0x6d2b79f5) >>> 0;
    let t = a;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

Project 1: the random number generator screen

State: the range inputs (as text, since they come from TextInput), the last result, and an error. The key rules: parse and validate the range before generating, and report problems in words.

JSX
export function RandomScreen() {
  const [min, setMin] = useState('1');
  const [max, setMax] = useState('100');
  const [result, setResult] = useState(null);
  const [error, setError] = useState('');

  function generate() {
    const lo = Number.parseInt(min, 10);
    const hi = Number.parseInt(max, 10);
    if (Number.isNaN(lo) || Number.isNaN(hi)) return setError('Enter two whole numbers.');
    if (lo > hi) return setError('Minimum must not be greater than maximum.');
    setError('');
    setResult(randomInt(lo, hi));
  }
  // ...two number-pad TextInputs, a Button and Text for result and error
}

Project 2: the guessing game

The computer picks a secret number; the player guesses; the app says "too low", "too high" or "correct" and counts attempts. As in the calculator, put the rules in a reducer so they can be tested without a screen.

JavaScript
export const newGame = (secret, max = 100, maxAttempts = 7) => ({
  secret, max, maxAttempts, attempts: 0, status: 'playing', message: `Guess a number from 1 to ${max}.`, history: [],
});

export function guess(game, text) {
  if (game.status !== 'playing') return game;
  const n = Number(text);
  if (text.trim() === '' || !Number.isInteger(n) || n < 1 || n > game.max) {
    return { ...game, message: `Enter a whole number from 1 to ${game.max}.` };   // no attempt used
  }
  const attempts = game.attempts + 1;
  const history = [...game.history, n];
  if (n === game.secret) return { ...game, attempts, history, status: 'won', message: `Correct! You needed ${attempts} ${attempts === 1 ? 'guess' : 'guesses'}.` };
  if (attempts >= game.maxAttempts) return { ...game, attempts, history, status: 'lost', message: `Out of guesses. The number was ${game.secret}.` };
  return { ...game, attempts, history, message: n < game.secret ? 'Too low.' : 'Too high.' };
}

Notice that an invalid guess (empty text, a decimal, out of range) uses no attempt and keeps the game in the same state with a helpful message. Seven attempts is not arbitrary: with 100 numbers, halving the range each time (binary search) always finds the answer in at most 7 guesses, so the game is fair but not trivial. A good extension is a hint that says so after the player's third guess.

Project 3: OTP generator and validator

A one-time password is a short code, valid for a few minutes and a few attempts. The rules of a sound OTP flow:

  1. Generate a code with a secure random source, always padded to the full length (007421, not 7421).
  2. Expire it: store expiresAt and check it on validation.
  3. Limit attempts: lock after 3 wrong tries, otherwise a 6-digit code (a million possibilities) can be brute-forced.
  4. Compare carefully: trim the input, accept only digits, and use a constant-time comparison.
  5. Invalidate on success: a code works once.
  6. Cool down resend requests so nobody can spam SMS messages.
JavaScript
export function createOtp(now, getInt, { length = 6, ttlMs = 5 * 60 * 1000, maxAttempts = 3 } = {}) {
  const code = String(getInt(10 ** length)).padStart(length, '0');
  return { code, expiresAt: now + ttlMs, attemptsLeft: maxAttempts, used: false };
}

export function validateOtp(otp, input, now) {
  if (otp.used) return { otp, ok: false, reason: 'This code was already used.' };
  if (now > otp.expiresAt) return { otp, ok: false, reason: 'The code has expired. Request a new one.' };
  if (otp.attemptsLeft <= 0) return { otp, ok: false, reason: 'Too many attempts. Request a new code.' };
  const clean = input.trim();
  const match = /^\d+$/.test(clean) && constantTimeEqual(clean, otp.code);
  if (match) return { otp: { ...otp, used: true }, ok: true, reason: 'Verified.' };
  const left = otp.attemptsLeft - 1;
  return { otp: { ...otp, attemptsLeft: left }, ok: false, reason: left > 0 ? `Wrong code. ${left} attempt${left === 1 ? '' : 's'} left.` : 'Too many attempts. Request a new code.' };
}

function constantTimeEqual(a, b) {
  if (a.length !== b.length) return false;
  let diff = 0;
  for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
  return diff === 0;
}

An OTP checked only on the device is a demo, not security. The code sits in app memory where a user with a debugger can read it. In a real app the server generates and sends the code (by SMS or email), the server stores the hash and the expiry, and the app only submits what the user typed. The client-side logic above shows the rules; move the same rules to your backend for production. For SMS codes, set textContentType="oneTimeCode" and autoComplete="one-time-code" on the input so the keyboard offers the code it just received (see TextInput in Depth).

Guessing game, OTP rules and a seeded generator

The scripted checks prove the rules: invalid text such as abc costs no attempt, a seeded generator is repeatable (which makes game tests possible), the OTP keeps its leading zeros, a wrong code uses an attempt, a correct code works once, and an old code expires.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which expression gives a whole number from min to max, both included?

    Scaling by (max - min + 1) and flooring gives every integer in the range the same chance. Rounding makes the end values half as likely.
  2. 2. Why should an OTP generator not use Math.random()?

    Math.random is not designed to be unpredictable. Security-sensitive values need a secure random generator.
  3. 3. A player types "abc" in the guessing game. What should happen?

    Invalid input is feedback, not a move. Charging an attempt for a typo would frustrate players.
  4. 4. Why limit OTP attempts?

    Without an attempt limit an attacker can try every code. Limits plus expiry make guessing impractical.

Summary

  • Use Math.floor(random() * (max - min + 1)) + min, pass the random function in as a parameter, and use a seeded generator for repeatable tests.
  • Math.random() is fine for games; use expo-crypto for OTPs and tokens, and avoid modulo bias.
  • Put game rules in a pure function, count only valid guesses and show clear messages.
  • A sound OTP has secure generation, padding, expiry, an attempt limit, single use and resend cooldown; real validation belongs on the server.

Next: Project: Currency Converter and GPA Calculator.