I did a simple game that generates a random number and the player needs to guess the random number. The player only has 6 chances to guess and the game will be over if the player didn't get to guess the number in that 6 chances. The problem is when the player enters the RIGHT answer on the 6th chance. The system shows the imgLose
even though the answer is TRUE.
Here is the code segment:
guessCount = 1
when {
guessNumber > randomNumber -> {
status.text = "Less than ${tGuess.text}"
tGuess.text = ""
}
guessNumber < randomNumber -> {
status.text = "More than ${tGuess.text}"
tGuess.text = ""
}
guessNumber == randomNumber -> {
status.text = "You're Correct! \nThe Answer is ${randomNumber.toString()}"
btnGuess.isEnabled = false
imgWin.visibility = View.VISIBLE
var soundEffect = MediaPlayer.create(this, R.raw.wining)
soundEffect.start();
}
}
if (guessCount == guessLimit){
status.text = "The Limit is Exceeded! \nThe Answer is $randomNumber"
btnGuess.isEnabled = false
var soundEffect = MediaPlayer.create(this, R.raw.losing)
soundEffect.start();
imgLose.visibility = View.VISIBLE
}
The result with coding right now
CodePudding user response:
there's many ways to handle this, but also depends on the rest of your code.
If possible you could try to simply return
after a correct guess, if there's no other relevant code in that function.
another way is to save in a boolean whether there was a correct guess and check on that. like this for example:
var isCorrect = false
guessCount = 1
when {
guessNumber > randomNumber -> {
status.text = "Less than ${tGuess.text}"
tGuess.text = ""
}
guessNumber < randomNumber -> {
status.text = "More than ${tGuess.text}"
tGuess.text = ""
}
guessNumber == randomNumber -> {
status.text = "You're Correct! \nThe Answer is ${randomNumber.toString()}"
btnGuess.isEnabled = false
imgWin.visibility = View.VISIBLE
var soundEffect = MediaPlayer.create(this, R.raw.wining)
soundEffect.start();
isCorrect = true
}
}
if (guessCount == guessLimit && !isCorrect){
status.text = "The Limit is Exceeded! \nThe Answer is $randomNumber"
btnGuess.isEnabled = false
var soundEffect = MediaPlayer.create(this, R.raw.losing)
soundEffect.start();
imgLose.visibility = View.VISIBLE
}
and actually just changing this line should be enough, since it's only disabled on a right guess:
if (guessCount == guessLimit && btnGuess.isEnabled){