How to Create a Number Guessing Game in Batch Script
Writing simple, interactive games is one of the most effective ways to understand a new scripting language. A "Number Guessing Game" incorporates several critical programming fundamentals: generating random numbers, establishing continuous while-style loops, evaluating numeric comparisons, and accepting user input.
In this guide, we will build a classic Number Guessing Game natively within the Windows Command Prompt using a Batch script.
The Strategy: The %RANDOM% Variable
- Generate a target number between 1 and 100 using the built-in
%RANDOM%environment variable. - Initialize a "guess counter" variable to 0.
- Create an infinite loop labeled
:GuessLoop. - Prompt the user for an integer inside the loop.
- Provide feedback ("Too High" or "Too Low").
- Break the loop and display the total guesses when the user guesses the target.
Implementation Script
@echo off
setlocal EnableDelayedExpansion
title Guess The Number
color 0B
:NewGame
cls
echo ==========================================
echo WELCOME TO GUESS THE NUMBER
echo ==========================================
echo I am thinking of a number between 1 and 100.
echo Can you guess what it is?
echo.
set /a "target=(!RANDOM! %% 100) + 1"
set "attempts=0"
:GuessLoop
set "userGuess="
set /p "userGuess=Enter your guess (1-100): "
:: -------------------------------------------------------
:: Validation Step 1: Non-empty
:: -------------------------------------------------------
if not defined userGuess (
echo Please type a number.
goto GuessLoop
)
:: -------------------------------------------------------
:: Validation Step 2: Digits only (using findstr)
:: echo( is a batch trick that safely prints any value
:: No space before | so no trailing space is piped
:: -------------------------------------------------------
echo(!userGuess!| findstr /r "^[0-9][0-9]*$" >nul
if errorlevel 1 (
echo Invalid input. Please enter numbers only.
goto GuessLoop
)
:: -------------------------------------------------------
:: Validation Step 3: Range check
:: -------------------------------------------------------
if !userGuess! lss 1 (
echo Out of range. Enter a number between 1 and 100.
goto GuessLoop
)
if !userGuess! gtr 100 (
echo Out of range. Enter a number between 1 and 100.
goto GuessLoop
)
:: -------------------------------------------------------
:: Increment attempts
:: -------------------------------------------------------
set /a "attempts+=1"
:: -------------------------------------------------------
:: Evaluate the guess
:: -------------------------------------------------------
if !userGuess! gtr !target! (
echo -^> Too High! Try a lower number.
echo.
goto GuessLoop
)
if !userGuess! lss !target! (
echo -^> Too Low! Try a higher number.
echo.
goto GuessLoop
)
:: -------------------------------------------------------
:: Correct guess
:: -------------------------------------------------------
echo.
echo ==========================================
echo CONGRATULATIONS!
echo ==========================================
echo You correctly guessed the number !target!
echo It took you !attempts! attempts.
echo.
set "replay="
set /p "replay=Play again? (Y/N): "
if /i "!replay!"=="Y" goto NewGame
echo Thanks for playing!
pause
exit /b
How It Works
- Random Generation (
%%): The expressionset /a "target=(!RANDOM! %% 100) + 1"is fundamental. The modulo operator%%divides the%RANDOM%integer (0–32767) by 100 and returns the remainder (0–99). Adding 1 shifts the range to 1–100. - Numeric Comparisons (
lss/gtr): In Batch, if you try to evaluateif %userGuess% > %target%, Windows throws a syntax error because>is the file-redirection symbol. You must usegtr(Greater Than),lss(Less Than), andequ(Equal To) when evaluating numbers. - Input Validation via Digit Stripping: The script removes every digit character (0–9) from the user's input. If any characters remain after stripping, the input contained non-numeric characters and the user is re-prompted. This avoids the pitfalls of relying on
set /afor validation, which silently evaluates environment variable names and expressions rather than rejecting them.
Why Build a Guessing Game?
- Math Operators: It forces a developer to understand how to correctly evaluate integers versus strings.
- Defensive Programming: Handling human input is chaotic. A guessing game forces handling edge cases: What if they hit "Enter" without typing anything? What if they type a letter?
- Loop Management: Learning how to effectively utilize
gotostructure to simulatedo...whileloops allows for complex logic iterations required in corporate script polling.
Conclusion
Creating a Number Guessing Game provides a fantastic, low-stakes environment to master Windows Batch's math evaluations, variable scopes, and iterative loops safely. Navigating dynamic variables and guarding against unexpected user inputs transforms an otherwise mundane script command into a fully fledged, interactive local software experience.