代码

guess <- function() {
  # Guess game: guess a number between 1 and 1000
  
  # generate random number between 1 and 1000
  num <- as.integer(runif(1, 1, 1000))
  # save guess history
  guess.log <- c()
  # input the number
  guess.input <- function() {
    guess.num <- suppressWarnings(
      as.integer(readline("guess an integer: "))
      )
    # check the input 
    while (is.na(guess.num) | guess.num < 1 | guess.num > 1000) {
      cat("Input Error\n", 
          "Please input an integer between 1 to 1000!\n\n")
      guess.num <- suppressWarnings(
        as.integer(readline("Guess an integer: "))
        )
    }
    return(guess.num)
  }
  
  # Start game information
  cat("Guess Game\n\n")
  cat("Guess an integer from 1 to 1000.\n\n")
  
  # guessing...
  guess.num <- guess.input()
  # log the guess number
  guess.log <- c(guess.log, guess.num)
  
  while (guess.num != num) {
    # do not get the right number
    if (guess.num < num) {
      cat("Too Small !")
    } else {
      cat("Too large !")
    }
    guess.num <- guess.input()
    guess.log <- c(guess.log, guess.num)
  }
  
  # get the right number !
  cat("Bingo ! You got the number", num, "in", length(guess.log), "time(s) !")
  # plot the guess log
  plot(guess.log, main = "Guess log", type = "b", 
       ylim = c(1, 1000), ylab = "number")
}

演示

guess()
## Guess Game
## 
## Guess an integer from 1 to 1000.
## 
## guess an integer: 500
## Too Small !
## guess an integer: 750
## Too Small !
## guess an integer: 875
## Too large !
## guess an integer: 812
## Too large !
## guess an integer: 781
## Too large !
## guess an integer: 765
## Too large !
## guess an integer: 757
## Too large !
## guess an integer: 753
## Bingo ! You get the number 753 in 8 time(s) !

点评

此时,老师的心已化作七彩祥云。。。童鞋,这门课你来上[捂脸][捂脸][捂脸]:)

好吧!稍作点评。首先从撰写规范上,值得赞一下,不知有没有读过 Google’s R Style Guide,总之,读起来很清晰明了!可以判断作者有一定的编程基础,而且水平还很了得呢。

另外,用到了我没有讲过的函数:as.integer()suppresswarnings()is.na()等,说明作者对程序的自学能力很强。Whileif 的嵌套使用也很灵活。最后,作为游戏的总结,把游戏者每次猜的的数字画成图形,以可视化完美收官!

课后,很多同学都玩了这个游戏,大家可以试一下。几个人一起玩的话,可以通过猜中所需次数判断午饭谁买单啦!