Leave a rating/review
For the next item on our nice to haves on our programming todo list, you’ll add the ability for the player to restart the game. To do this, we’re going to need a new method we can call to restart the game. Let’s go implement this functionality now.
Create a new method called startNewGame() right below the pointsForCurrentRound() method.
private fun startNewGame() {
}
Then reset all the game related variables to their defaults:
...
totalScore = 0
currentRound = 1
sliderValue = 50
targetValue = Random.nextInt(1, 100)
...
Next set all textviews and the seekbar’s progress to their defaults. I’ll go ahead and paste them in since we have them before:
binding.gameScoreTextView?.text = totalScore.toString()
binding.gameRoundTextView?.text = currentRound.toString()
binding.targetTextView.text = targetValue.toString()
binding.seekBar.progress = sliderValue
Cool!!! Now, if you notice, we’re setting the targetValue to a random value once again. And that signals that we have a code smell and we could refactor this random generator into a method. I’ll create it right below the differenceAmount method Go ahead and add the following code:
private fun newTargetValue() = Random.nextInt(1, 100)
Call it to set the targetValue variable inside the startNewGame method.
Then set the targetValue to use it inside the click listener of the alert dialog’s positive button.
And also do the same thing for the targetValue declaration up in the MainActivity class.
Now that we have the startNewGame method ready, its time to make use of it.
You’ll use it in two places.
First, you will call it when the start over button is clicked.
Enter the following code right below the click listener for the hit me button:
binding.startOverButton?.setOnClickListener {
startNewGame()
}
The second place you will use this method is inside the onCreate method of the MainActivity.
You will do this because we want to trigger a new game whenever the app launches.
Go ahead and call it right below the setContentView function:
startNewGame()
Now if you notice, we have the code that sets the text of the target and game round textviews.
Go ahead and remove those code because the startNewGame() method already does that.
Cool!!! You’re done with the restart game feature.
Run your app to try it out.
Clicking on the stat over button restart the game and you can see a new target value is generated. Let’s play one round.
You can see we’re currently at round 2. Then go ahead and tap the start over button.
The game restarts with all the values set to their defaults as expected.