我正在从这个页面做一个简单的石头、剪刀、布、蜥蜴和斯波克问题https://retosdeprogramacion.com/semanales2023
我创建了一个函数调用 whoWins(),如果玩家 1 获胜,它基本上返回下一个字符串“P1”,如果玩家 2 获胜则返回“P2”或“Tie”……你知道在什么情况下 XD
fun whoWins(game: Array<String>): String {
var chooseP1 = game.get(0)
var chooseP2 = game.get(1)
println("Choose is ok : $chooseP1 and the type is: "+ chooseP1::class.simpleName)
println("Choose is ok : $chooseP2 and the type is: "+ chooseP2::class.simpleName)
var rules: MutableMap<String, ArrayList<String>> = mutableMapOf(
"rock" to arrayListOf("scissors", "lizard"),
"scissors" to arrayListOf("paper", "lizard"),
"lizard" to arrayListOf("spock", "paper"),
"paper" to arrayListOf("spock", "rock"),
"spock" to arrayListOf("scissors", "rock")
)
if (chooseP1 == chooseP2) return "Tie"
println("\nhere for some reason it returns null, HELP! "+ rules[chooseP1]+"\n")
rules[chooseP1]?.forEach {
if (it == chooseP2) {
return "P1"
}
}
return "P2"
}
出于某种原因,当我尝试使用 var 访问地图时,系统返回 null,
现在为了保存我游戏的不同回合,问题使用数组,但是当我访问方法时
whoWins()
系统总是返回“P2”,但是当我使用函数中直接声明的字符串方法时它起作用了好的,这是我的主要功能
fun main(args: Array<String>) {
var game1 = mapOf<String, Array<String>>( "round1" to arrayOf("🗿rock", "scissors️"), "round2" to arrayOf("scissors️", "rock🗿"), "round3" to arrayOf("📄paper", "scissors️") )
var game2 = arrayOf( arrayOf("🗿rock", "scissors️"), arrayOf("scissors️", "rock🗿"), arrayOf("📄paper", "scissors️"), arrayOf("🗿spock", "scissors️"), arrayOf("lizard️", "spock"), arrayOf("📄spock", "rock️") )
println("the var ${game1.get("round1")!!.get(0)} type is: "+game1.get("round1")!!.get(0)::class.simpleName)
println("Game 1 " + whoWins(game1.get("round1")!!))
println("Game 2 " + whoWins(game2.get(0)!!))
println("But the function is working fine: " + whoWins(arrayOf("rock", "scissors")))
/*
for (game in game2){
if(whoWins(game.get(0),game.get(1)) == "P1"){
pointsP1++
}else{
pointsP2++
}
}
println(
if (pointsP1 == pointsP2) "Tie"
else if (pointsP1 > pointsP2) "Player 1"
else "Player 2"
)
*/
}
在这种情况下,函数应该在这种特定情况下返回“P1”,但这里是输出
the var 🗿rock type is: StringChoose is ok : 🗿rock and the type is: StringChoose is ok : scissors️ and the type is: String
here for some reason it returns null, HELP! null
Game 1 P2Choose is ok : 🗿rock and the type is: StringChoose is ok : scissors️ and the type is: String
here for some reason it returns null, HELP! null
Game 2 P2Choose is ok : rock and the type is: StringChoose is ok : scissors and the type is: String
here for some reason it returns null, HELP! [scissors, lizard]
But the function is working fine: P1
所以...我真的不知道发生了什么,提前致谢
我已经在
HashMap
选项中尝试使用 Map
、MutableMap
和 whoWins()