Closed TheCanasian23 closed 2 years ago
We can't edit a screen shot. Use the code block option (look for the <> icon) and insert your code into the issue. Then also give a concrete problem of what doesn't work means and we can try to help you.
Also, you do not want to use as variable names words that have special meaning in a language. time
is a built in function in R. Try a different name
`hangman=function(word, guess){ x=nchar(word) sprintf("The word is %d letters long",x) sprintf("You have %d number of incorrect guesses.", guess) copy=word counter = 0 while (guess!=0){ letter=readline(prompt="Please enter the letter you would like to check:") position=list() let=FALSE for (a in range(nchar(copy))){ if (substr(copy,a,a)==letter){ append(position,a+1) sub(substr(copy,a,a),"",copy) let=TRUE counter=counter+1 } } print(position) if (counter==(nchar(word))){ return(print("You win! The word was:", word)) } if (let==FALSE){ guess=guess-1 } } return(print("You lose! The word was:",word)) }
times=function(maxx){ maxx = readline(prompt="Please enter the maximum number of incorrect guesses as a positive integer:") maxx = as.integer(maxx); hangman("hello",maxx) } ` So the file will take the maximum number of incorrect guesses and letter you want to guess, but it's not correctly check if the letter is right or not. It also not printing how long the word is, how many incorrect guesses you have to start, and an error occurs from the return print statement saying "invalid printing digits -2137483648"
Your problems are traceable to a few things.
sprintf
at the top of your code you then failed to use it correctly later when you kept typing print
when you meant sprintf
, and you did not include the proper formatting characters. hangman=function(targetWord = "hello", guess){
x=nchar(targetWord)
sprintf("The word is %d letters long",x)
sprintf("You have %d number of incorrect guesses.", guess)
copyTargetWord = targetWord
displayCorrectGuesses = rep("_",x)
print(displayCorrectGuesses)
position = list()
counter = 0
while (guess!=0){
letter=readline(prompt="Please enter the letter you would like to check:")
let=FALSE
for (a in seq(nchar(copyTargetWord))){
if (substr(copyTargetWord,a,a)==letter){
displayCorrectGuesses[a] <- letter
sub(substr(copyTargetWord,a,a),"",copyTargetWord)
print(copyTargetWord)
let=TRUE
counter=counter+1
}
}
print(displayCorrectGuesses)
if (counter==(nchar(targetWord))){
return(sprintf("You win! The word was: %s", targetWord))
}
if (let==FALSE){
guess=guess-1
}
}
return(sprintf("You lose! The word was: %s",targetWord))
}
Try hangman("psychology", 5)
I usually write in python so I might be missing some brackets or my logic might not work for r. I honestly don't know why it doesn't work