1. The main loop and why it matters
When you write a game, there’s almost always a piece of code responsible for the program’s “heartbeat”: a repeating step like “ask → process → respond → move on”. In our game, that’s the player’s attempts. If this loop is written carefully, the game feels fair and predictable; if it’s written poorly, you get an immortal player, infinite attempts, a win “in 8 attempts out of 7”, and other plot twists that were never in the script.
From the program-structure perspective, we keep this order: first set up the settings, then generate the secret, then run the loop, and after the loop print the final result. This makes main() readable like a script.
Mini sketch (no details yet):
fun main() {
// 1) settings
// 2) secret
// 3) attempt loop
// 4) result
}
Psychologically, it helps to remember: a loop is the place where off-by-one errors are born most often. So today we’ll talk a lot not only about “how to write it”, but also about “where to put attempt++ so you don’t cry later”.
2. Attempt counter: attempt = 1 and the condition attempt <= maxAttempts
You can write the attempt loop in different ways, but for a beginner the most honest option is an explicit counter attempt. We start with attempt = 1, because people naturally count “first attempt”, not “zero-th attempt”. Then we repeat attempts while attempt <= maxAttempts. This condition is easy to read and usually matches how the rules are phrased.
In Kotlin, the while loop works like this: first we check the condition, then execute the body, then check the condition again. That’s the basic behavior of while, and it’s exactly what we need for “as long as there are attempts left — keep playing”.
Mini example: “loop skeleton” without the game:
fun main() {
val maxAttempts = 3
var attempt = 1
while (attempt <= maxAttempts) {
println("Attempt $attempt of $maxAttempts")
attempt++
}
// Attempt 1 of 3
// Attempt 2 of 3
// Attempt 3 of 3
}
Notice: attempt++ is at the end of the iteration. This looks natural, but in a real game we’ll have continue and break branches, and then the increment location becomes critical.
Table: “<= or <”
Sometimes a beginner writes attempt < maxAttempts and unexpectedly gets one fewer attempt. To avoid guessing, it helps to keep a small mapping in mind:
| What we want in plain words | Familiar math | Loop condition with attempt = 1 |
|---|---|---|
| “exactly N attempts” | |
|
| “while attempt is less than N” | |
|
3. Robust input: Int?, null, and the rule about attempts
User input is like the weather: you can hope for sunshine, but it’s better to have an umbrella. In our game, the “umbrella” is toIntOrNull() and the contract of the readGuessOrNull(min, max): Int? function. That is, we don’t crash with an exception; we get null if the input is not a number or the number is out of range. This was already done in the previous lecture, and today it’s important to plug this function into the loop correctly.
And here a game-design question appears: does invalid input count as an attempt or not? This is not a “right/wrong” choice; it’s a convention. The main thing is to pick one and express it in code so it can’t be accidentally broken.
Option A: invalid input does NOT consume an attempt
In this option, if the player enters "abc" or 9999, we print “Invalid input” and ask again, without increasing attempt.
The key trick here is continue. It interrupts the current iteration and moves to the next condition check. Kotlin supports continue and break as standard loop-control operators.
Example (a fragment of the loop):
val guess = readGuessOrNull(min, max)
if (guess == null) {
println("Invalid input. Please try again.")
continue
}
Notice the “magic” (simple, honest, no dark rituals): after continue, the code below does not run, which means we never compare null to the secret and never print “too high” for a non-existent number.
Option B: invalid input consumes an attempt
Sometimes you want stricter rules: enter nonsense — the attempt is gone. Then in the guess == null branch we do attempt++ and only then continue.
Mini example:
val guess = readGuessOrNull(min, max)
if (guess == null) {
println("Invalid input. Attempt lost.")
attempt++ // important: the attempt is consumed exactly here
continue
}
A very common logical mistake is to forget attempt++ in this option and end up with an infinite loop on invalid input. In other words, the game becomes eternal: you can type “cat” forever, and attempts will never run out. Sometimes that’s cute. But usually it’s a bug.
4. Comparing the guess and the secret: hint, win, and break
After we get a valid guess guess: Int, the fun part starts: we compare it to the secret and print a hint. In the previous lecture we already prepared these functions:
- compareGuess(guess, secret): Int, returns -1, 0, or 1;
- hintText(result): String, returns “Too low/Too high/You guessed it!”.
Today it’s important to integrate this so that:
1) the hint is always printed for valid input;
2) a win ends the loop immediately;
3) the attempt counter increases only when needed.
Mini fragment:
val result = compareGuess(guess, secret)
println(hintText(result))
if (result == 0) {
isWon = true
break
}
break exits the loop instantly. Kotlin guarantees this behavior for break/continue in loops.
There’s a subtlety you’ll feel in practice: if you do attempt++ first and only then check for a win, the final message can end up “one attempt later”. That’s why you typically record the win before incrementing the counter.
5. Where to put attempt++: the main source of off-by-one bugs
The attempt counter is a small variable with a big personality. It’s constantly trying to “drift” the wrong way: increment one extra time, fail to increment in one branch, increment before checking for a win. So now we’ll deliberately go through the “correct geometry” of attempt++ for the most popular option: invalid input does not consume an attempt.
The idea is simple: an attempt is considered spent when we had valid input, compared it to the secret, and it wasn’t a win. So it makes sense to place attempt++ at the end of a successful (non-winning) iteration.
Mini example: “the correct place”:
// guess != null, compared, not guessed
attempt++
And here’s an example of “almost correct, but pain later”:
attempt++ // incremented in advance
val guess = readGuessOrNull(min, max)
Why pain? Because if the input turns out invalid and we do continue, the attempt has already been incremented, even though under the chosen policy it should not have been. That means you accidentally switched to the policy “invalid input consumes an attempt”, but without declaring war.
6. Result after the loop: win or loss without confusion
After the loop, beginners often feel tempted: “well, if the loop ended, it means I lost”. But the loop can also end because of a win (break). So we need an explicit win indicator, for example var isWon = false.
The result block should be simple: if you won — congratulate; otherwise — show the secret. And it’s important not to confuse which attempt number counts as the “number of attempts”. If attempt increases only after failed attempts, then on a win attempt points exactly to the winning attempt number — and that’s convenient.
Example of the final output:
if (isWon) {
println("Victory! You guessed it in $attempt attempts.")
} else {
println("No attempts left. The secret number was: $secret")
}
If in your version you increment attempt somewhere else (for example, at the beginning of the loop), you’ll have to rebuild the result logic too. That’s normal programmer life: code is a contract, and if you change a clause in the contract, the consequences change.
7. Assembling into a single main()
Now we’ll assemble everything into one program. I’ll deliberately keep the code chunks small and “glueable” so you can move them step by step rather than copying one huge sheet.
Settings and game start
This block usually comes first:
import kotlin.random.Random
fun main() {
val min = 1
val max = 100
val maxAttempts = 7
val secret = generateSecret(min, max)
var attempt = 1
var isWon = false
println("I picked a number from $min to $max. You have $maxAttempts attempts.")
}
Here generateSecret(min, max) is a function from the previous lecture (with require(min <= max) and Random.nextInt(from, until)).
Main loop
This is the central fragment. Pay attention to the order: attempt status → input → null handling → comparison → hint → win → increment attempt.
while (attempt <= maxAttempts) {
println("Attempt $attempt of $maxAttempts")
val guess = readGuessOrNull(min, max)
if (guess == null) {
println("Invalid input. Enter an integer within the range.")
continue
}
val result = compareGuess(guess, secret)
println(hintText(result))
if (result == 0) {
isWon = true
break
}
attempt++
}
In this code, continue keeps the structure straight: if there is no valid input, we don’t fall through and we don’t multiply nested ifs. Using continue like this is one of the few cases where it genuinely improves readability.
Game result
After the loop — only the result:
if (isWon) {
println("Victory! You guessed the number in $attempt attempts.")
} else {
println("You lost. The secret number was: $secret")
}
If invalid input should consume an attempt
Sometimes it’s useful to see that a “policy” is not philosophy but two concrete lines of code. The whole game stays the same; only the guess == null branch changes: now we increment the attempt and continue.
Here’s the fragment that differs:
val guess = readGuessOrNull(min, max)
if (guess == null) {
println("Invalid input. Attempt lost.")
attempt++
continue
}
An important point: you don’t need to rewrite the whole loop if you change the rule. It’s good when the rule is localized in one place — that’s “maintainability”, just without big words.
Execution-flow diagram
When you’re learning programming, your brain often does this: it reads code and tries to imagine all transitions “like a movie”. That works for 5 lines, but starts slipping at 30. So it’s useful to draw a diagram once, and then use it as a reference when something doesn’t work.
flowchart TD
A[Game start: settings, secret, attempt=1] --> B{attempt <= maxAttempts?}
B -- no --> Z[Print result: win/loss]
B -- yes --> C["Print 'Attempt attempt of maxAttempts'"]
C --> D["readGuessOrNull(min, max)"]
D --> E{guess == null?}
E -- yes --> F[Input error message]
F --> B
E -- no --> G["compareGuess(guess, secret)"]
G --> H["Print hintText(result)"]
H --> I{result == 0?}
I -- yes --> J[isWon = true; break]
J --> Z
I -- no --> K[attempt++]
K --> B
If you change the policy to “invalid input consumes an attempt”, only block F changes: attempt++ appears there before returning to the condition check.
8. Typical mistakes in the main attempt loop
Mistake #1: attempt++ is not where the attempt is actually “spent”.
The most common bug looks like this: you incremented attempt at the beginning of the iteration, then got invalid input and did continue. As a result, the attempt was “burned” even though by your rules it should not have been. And vice versa: you wanted invalid input to consume an attempt, but forgot to increment attempt in that branch — and got an infinite loop on “bad” strings.
Mistake #2: the win check happens after the increment, and the final attempt count ends up 1 larger.
If you do attempt++ first and only then detect a win, the final “Victory in 4 attempts” easily turns into “in 5”, even though you won on the 4th. The fix is simple: record the win before incrementing the counter and exit the loop immediately via break.
Mistake #3: null handling is missing, and the comparison logic tries to work with a non-existent number.
Sometimes this doesn’t even show up as a crash, but as a strange architecture: the student starts inventing a “magic” value like -999 to indicate input error. It’s much cleaner to use Int? and an explicit check guess == null, and then continue, so the rest of the code works only with valid data.
Mistake #4: the loop ends, and the program always prints “loss”, even if there was a break.
This happens when the final output is tied only to the fact that the loop ended, not to the meaning of why it ended. If you exit on a win via break, the loop also ends. So you need a flag isWon (or another explicit state) that determines what result you print.
Mistake #5: inconsistent range boundaries.
Visually it looks like “the game hates me”: you enter max and it says “out of range”, or you can’t guess the number because the secret is generated as, for example, 1..99, but you think it’s 1..100. The solution is simple: min/max must be a single source of settings, and both secret generation and input validation must rely on them.
Mistake #6: continue is used in a way that makes the code harder to read.
continue is good when it helps you “exit early” from an iteration on bad input and keeps the main path straight. But if continue appears in five places, it becomes hard to read: your eyes keep jumping around. In our game, one continue in the input-error branch is usually enough.
GO TO FULL VERSION