Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Hangman is a classic word game in which you need to need to guess as many possible letters in word, so you can guess the word, before running out of tries (lives).
Upon running out of tries, you are hanged!
The game can be played in R Studio, where the user inputs new letters in console, and the picture is being drawn (using library ggplot2). The picture consists of 7 false tries, so it is drawn in 7 steps.
The diagram is created using simple X, Y coordinates with groups for determining the steps:
level1 <- data.frame(x=c(1,2,3,4,5,6,7,8), y=c(1,1,1,1,1,1,1,1), group=c(1,1,1,1,1,1,1,1)) level2 <- data.frame(x=c(4,4,4,4,4), y=c(1,2,3,4,5),group=c(2,2,2,2,2)) level3 <- data.frame(x=c(4,5,6), y=c(5,5,5), group=c(3,3,3)) level4 <- data.frame(x=c(6,6), y=c(5,4), group=c(4,4)) level5 <- drawHead(c(6,3.5),1,10,5) level6 <- data.frame(x=c(6,6,5.8,6.2),y=c(3,1.5,1.5,1.5), group=c(6,6,6,6)) level7 <- data.frame(x=c(5.5,6,6.5),y=c(2,2.5,2), group=c(7,7,7)) levels <- rbind(level1,level2,level3,level4,level5,level6,level7)
Drawing itself is created by using a simple function using ggplot2 library:
drawMan <- function(st_napak) { ggplot(levels[which(levels$group<=st_napak),], aes(x=x, y=y, group=group)) + geom_path(size=2.5) + theme_void() }
The function draws the hanging man in 7 steps
All the rest of the logic is fairly simple, continue until you find the correct word, or until you are hanged. Section of the code:
beseda <- readline(prompt="Word: ") iskana_beseda <- replicate(nchar(beseda),'_') while (active == TRUE) { if (i == 0) { writeLines(paste(iskana_beseda, collapse = " ")) } crka <- readline(prompt="Enter Letter: ") izbor <- rbind(izbor, crka) #iskana_beseda if (grepl(crka, beseda) == TRUE) { cilj <- rbind(cilj, crka) iskana_beseda <- zamenjaj2(beseda, crka) #print(zamenjaj2(beseda, crka)) print(paste("Yay!","Try N:",i+1,"Wrong letters: {",(toString(paste0(cilj_n, sep=","))),"}")) if (as.character(paste(iskana_beseda, collapse = "")) == beseda) { active == FALSE Print("Bravo, win!") break } {code continues.....}
… and the rest of there code is here — >> github.
When playing, this is how it looks from my R Studio.
As always, complete code is available at Github.
Happy R-hanging
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.