randomNumberGame: randomNumberGame

Description Usage Arguments Value Author(s) Examples

View source: R/pscript1.R

Description

Takes in the bounds used for the random number generation and then asks for the user to guess the random number.

Usage

1
randomNumberGame(leftbound, rightbound)

Arguments

leftbound

The least value that the random number can hold

leftbound

The greatest value that the random number can hold

Value

Has a void return type. Prints out the results instead of returning them

Author(s)

Matt Heffernan, University of Illinois at Chicago

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
randomNumberGame(1,10)
Generates a random number between 1 and 10 inclusive and asks for the user to guess it
##---- Should be DIRECTLY executable !! ----
##-- ==>  Define data, use random,
##--	or do  help(data=index)  for the standard data sets.

## The function is currently defined as
randomNumberGame <- function(leftbound, rightbound){
  if(leftbound > rightbound)
  {
    cat("Upper bound should be greater than lower bound\n")
    return()
  }
  secretNumber<-sample(leftbound:rightbound, 1)
  count <- 1
  cat("Range: ",leftbound,"-",rightbound)
  guess <- readline("Enter a guess : ");
  guess <- as.integer(guess)

  while(guess != secretNumber)
  {
    if(guess < leftbound || guess > rightbound)
    {
      cat("Your guess is outside of the valid range", leftbound,"-",rightbound,". Try Again \n")
    }
    else if(guess < secretNumber)
    {
      cat("The secret number is greater than your guess\n")
    }
    else if(guess > secretNumber)
    {
      cat("The secret number is less than your guess\n")
    }

    count <- count + 1
    guess <- readline("Enter a guess : ");
    guess <- as.integer(guess)

  }
  cat("You got it! The secret number is ", secretNumber,". It took you ",count," guesses")
}

mheffe3/MyFirstPackage documentation built on Dec. 21, 2021, 5:52 p.m.