Kotlin 函数在给定指令后计算胜率

Kotlin function to count win rate after given instruction

我有一个 SendInstruction 函数,它向用户发送指令以按下带有标签 x 的按钮 3 秒。我有四个标签为 y、z 和 w 的按钮。

fun SendInstruction(buttonLabel:String):String{
return buttonLabel
}

我有一个计数器,如果正确发送的指令与用户单击的按钮匹配,则增加 20,如果不正确,则减少。

但是当正确 3 秒后,可以为按钮 y 发送另一条指令,否则用户必须通过按钮 x 才能转到 y,还必须通过 y 才能转到 z,必须通过 z 才能转到 w

这是我到目前为止尝试过的方法

var counter:Int = 0

GlobalScope.launch{
SendInstruction("click button x")
if(userclicked)//always true for 3 seconds
   delay(3000)//check in 3s if instructions matches user clicked
   counter +=20
   SendInstruction("click button y")
   if(userclicked)//always true for 3 s
      delay(3000)//check in 3s if instruction matches user clicked
else
   counter = 0
   //restart
}

但这就是行不通,谁能帮我解决这个问题。

您可以使用超时模式(如反向反跳捕获)来提供帮助。这是一个示例,您设置了一个点击目标和一个将在 3 秒内重置目标的协程。如果您在那段时间内单击目标,协程将被取消,您将移动到下一个目标。

private var job: Job? = null
private var target = ""
private var score = 0

fun onClick(btn: String, next: String) {
    if(btn == target) {
        advance(next)
    }
    else {
        // Handle wrong click by starting over
        reset()
    }
}

fun advance(next: String) {
    // Handle a correct click by cancelling
    // the coroutine, updating the score,
    // and setting the next target

    // Cancel the timeout
    job?.cancel()

    // Add to the score
    score += 20

    // Set the next/end case
    if(next.isEmpty()) {
        SendInstruction("you won")
    }
    else {
        updateTarget(next)
    }
}

fun updateTarget(next: String) {
    // Update the target, notify the user,
    // and start a coroutine to reset
    // the target in 3 seconds

    target = next

    SendInstruction("Click on $next")

    // Reset the target after 3 seconds
    // unless the coroutine is cancelled
    // by a correct button click first
    job = lifecycleScope.launch {
        delay(3000)
        reset()
    }
}

fun reset() {
    // Start over on a wrong click
    // or a timeout. Alternately could
    // just show "game over" and make
    // them click "Go" or something to start over
    job?.cancel()
    target = ""
    score = 0
    updateTarget("x")
}

fun start() {
    // Call to start the game, probably from onResume or when the user clicks "Go" or something 
    updateTarget("x")
}

// Call these when the specific buttons are clicked
fun onClickX() {
    onClick("x", "y")
}

fun onClickY() {
    onClick("y", "z")
}

fun onClickZ() {
    onClick("z", "w")
}

fun onClickW() {
    onClick("w", "")
}