How to resolve the algorithm 21 game step by step in the R programming language

Published on 12 May 2024 09:40 PM
#R

How to resolve the algorithm 21 game step by step in the R programming language

Table of Contents

Problem Statement

21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly 21. The running total starts at zero. One player will be the computer. Players alternate supplying a number to be added to the running total.

Write a computer program that will:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm 21 game step by step in the R programming language

Source code in the r programming language

game21<-function(first = c("player","ai","random"),sleep=.5){
  state = 0
  finished = F
  turn = 1
  if(length(first)==1 && startsWith(tolower(first),"r")){
    first = rbinom(1,1,.5)
  }else{
    first = (length(first)>1 || startsWith(tolower(first),"p"))
  }
  while(!finished){
    if(turn>1 || first){
      cat("The total is now",state,"\n");Sys.sleep(sleep)
      while(T){
        player.move = readline(prompt = "Enter move: ")
        if((player.move=="1"||player.move=="2"||player.move=="3") && state+as.numeric(player.move)<=21){
          player.move = as.numeric(player.move)
          state = state + player.move
          break
        }else if(tolower(player.move)=="exit"|tolower(player.move)=="quit"|tolower(player.move)=="end"){
          cat("Goodbye.\n")
          finished = T
          break
        }else{
          cat("Error: invaid entry.\n")
        }
      }
    }
    if(state == 21){
      cat("You win!\n")
      finished = T
    }
    if(!finished){
      cat("The total is now",state,"\n");Sys.sleep(sleep)
      while(T){
        ai.move = sample(1:3,1)
        if(state+ai.move<=21){
          break
        }
      }
      state = state + ai.move
      cat("The AI chooses",ai.move,"\n");Sys.sleep(sleep)
      if(state == 21){
        cat("The AI wins!\n")
        finished = T
      }
    }
    turn = turn + 1
  }
}


game21()


game21(first = "ai")


  

You may also check:How to resolve the algorithm Prime decomposition step by step in the AArch64 Assembly programming language
You may also check:How to resolve the algorithm Jacobsthal numbers step by step in the Maxima programming language
You may also check:How to resolve the algorithm Hello world/Graphical step by step in the AWK programming language
You may also check:How to resolve the algorithm Fractal tree step by step in the Icon and Unicon programming language
You may also check:How to resolve the algorithm FizzBuzz step by step in the MUMPS programming language