You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

石头剪刀布游戏中使用break跳出循环失效问题排查

问题分析与修复

核心问题(无法响应"end"退出)

player_select <- readLines("stdin", 1)语句写在while循环外部,仅在函数启动时读取一次用户输入。循环过程中不会重新获取新输入,导致后续无论输入什么,程序都只会用第一次的输入值判断,自然无法触发break退出循环。

其他潜在问题

  • 拼写错误:胜利条件中的Sciccor应为Scissor,导致该分支永远无法匹配。
  • 结果逻辑错误:原else分支将平局和失败统一输出"Tie get 0 point",不符合规则描述。
  • 缺少分数累计功能,规则提到赢局得分但代码未实现。

修正后的完整代码

play_games <- function() {
  print("Welcome to Rock, Scissor, Paper challenge.")
  print("Games Rules : ")
  print("1. Win each match get one score.") 
  print("2. Tie each match zero score.")
  print("3. Lost each match zero score.")
  print("4. If you want to end game type end.")
  
  choices <- c("Rock", "Scissor", "Paper")
  player_score <- 0
  
  while(TRUE) {
    # 每次循环读取最新输入
    player_select <- readLines("stdin", 1)
    
    if (player_select == "end") {
      cat(sprintf("Thank you for joining! Your final score is: %d\n", player_score))
      break
    }
    
    # 校验输入合法性
    if (!player_select %in% choices) {
      print("Invalid input! Please enter Rock, Scissor, Paper or end.")
      next
    }
    
    ai_select <- sample(choices, 1)
    cat(sprintf("You chose: %s | AI chose: %s\n", player_select, ai_select))
    
    # 修正拼写错误,完善胜负判断逻辑
    if ( (player_select == "Paper" & ai_select == "Rock") ||
         (player_select == "Rock" & ai_select == "Scissor") ||
         (player_select == "Scissor" & ai_select == "Paper") ) {
      print("Win get 1 point")
      player_score <- player_score + 1
    } else if (player_select == ai_select) {
      print("Tie get 0 point")
    } else {
      print("Lost get 0 point")
    }
  }
}

play_games()

修复说明

  1. 将输入读取语句移至循环内部,确保每次循环都能获取用户最新输入,输入"end"时可正常触发退出。
  2. 修正Sciccor的拼写错误,使胜利条件正常生效。
  3. 新增输入合法性校验,避免非法输入干扰游戏逻辑。
  4. 拆分平局与失败的输出逻辑,符合规则描述。
  5. 添加分数累计功能,退出时展示最终得分。

内容的提问来源于stack exchange,提问作者PPAu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 13:25:31