Home > Back-end >  How to keep score in rock, paper, scissors game - Kotlin/Android Studio
How to keep score in rock, paper, scissors game - Kotlin/Android Studio

Time:09-17

I'm making a rock, paper, scissors game for a class and I'm having trouble figuring out the scoring aspect. So far, I have figured out how to update the score, but can't get it to go past one. I know I'm missing something important, but I'm a bit new to this so I'm not sure where to look. Any advice would be super helpful! Thank you.

Here's my paper code:

    fun paperPressed(view:View) {
    val computerChoice = Random.nextInt(2)
    paperIcon.setColorFilter(Color.RED)
    rockIcon.setColorFilter(Color.BLACK)
    scissorsIcon.setColorFilter(Color.BLACK)
    when (computerChoice){
        0 -> aiChoice.text = "They chose rock."
        1 -> aiChoice.text = "They chose paper."
        2 -> aiChoice.text = "They chose scissors."
    }

    yourChoice.text = "You chose paper."
    when (computerChoice) {
        0 -> whoWon.text = "You won!"
        1 -> whoWon.text = "It was a tie!"
        2 -> whoWon.text = "You lost!"

    }
    var tie = 0
    var win = 0
    var lose = 0
    tie  
    win  
    lose  
    when (computerChoice) {
        0 -> winNumber.text = "$win"
        1 -> drawNumber.text = "$tie"
        2 -> lossNumber.text = "$lose"
    }
}

CodePudding user response:

the answer is simple, declare

    var tie = 0
    var win = 0
    var lose = 0

globally.

what is happening is every time you call function paperPressed the counter is reset to Zero, so declaring is globally would be a prefrable option.

like this

private var tie = 0
private var win = 0
private var lose = 0


fun paperPressed(view:View) {
    val computerChoice = Random.nextInt(2)
    paperIcon.setColorFilter(Color.RED)
    rockIcon.setColorFilter(Color.BLACK)
    scissorsIcon.setColorFilter(Color.BLACK)
    when (computerChoice){
        0 -> aiChoice.text = "They chose rock."
        1 -> aiChoice.text = "They chose paper."
        2 -> aiChoice.text = "They chose scissors."
    }

    yourChoice.text = "You chose paper."
    when (computerChoice) {
        0 -> whoWon.text = "You won!"
        1 -> whoWon.text = "It was a tie!"
        2 -> whoWon.text = "You lost!"

    }
 
    tie  
    win  
    lose  
    when (computerChoice) {
        0 -> winNumber.text = "$win"
        1 -> drawNumber.text = "$tie"
        2 -> lossNumber.text = "$lose"
    }
}

  • Related