I am trying to do a yahtzee game in R, amd I would like to show the dice on the plot part of R. like this :
I have this function how simulate a dice roll
rolls_the_dice <- function(X1 = 5){if(X1 <= 5){sample(1:6, X1, replace = TRUE)}
But I don't know how to display the score the way I described. I have two main ideas:
First:
plot(c(0, 200), c(0, 170), type = "n", xlab = "", ylab = "", axes= F, main = "")
rect(xleft = 30, xright = 80, ybottom = 0, ytop = 50)
rect(xleft = 0, xright = 50, ybottom = 100, ytop = 150)
rect(xleft = 70, xright = 120, ybottom = 100, ytop = 150)
rect(xleft = 140, xright = 190, ybottom = 100, ytop = 150)
rect(xleft = 120, xright = 170, ybottom = 0, ytop = 50)
That plot 5 rectangles, and then I have to find a way to put points in it giving the result
Second :
rect(xleft = 0, xright = 20, ybottom = 0, ytop = 20)
points(x= 10, y= 10, col="black", pch=19)
This is the face one of a dice. This idea is to create one plot per dice face, and then to pick them up giving the result. But here I don´t know how to store them. If somebody could tell me what is the best (or even just the feasable) idea.
CodePudding user response:
there's a package for that ;-)
library(magrittr)
library(tidydice)
roll_dice(times = 5, rounds = 1) %>% plot_dice()
CodePudding user response:
Here is one way of doing it in base R using lists...
#your function
rolls_the_dice <- function(X1 = 5){if(X1 <= 5){sample(1:6, X1, replace = TRUE)}}
#a list of x-y coordinates of the corners of the five dice
rects <- list(c(30, 0), c(0, 100), c(70, 100), c(140, 100), c(120, 0))
#a list of list(x, y) coordinates of the dots for numbers 1-6
dots <- list(list(0, 0),
list(c(-1, 1), c(-1, 1)),
list(c(-1, 0, 1), c(-1, 0, 1)),
list(c(-1, -1, 1, 1), c(-1, 1, -1, 1)),
list(c(-1, -1, 0, 1, 1), c(-1, 1, 0, -1, 1)),
list(c(-1, -1, -1, 1, 1, 1), c(-1, 0, 1, -1, 0, 1)))
#a function to plot a dice and a number
plot_face <- function(rects, dots){
rect(xleft = rects[1], xright = rects[1] 50,
ybottom = rects[2], ytop = rects[2] 50)
points(x = rects[1] 25 15 * dots[[1]],
y = rects[2] 25 15 * dots[[2]], col = "black", pch = 19)
}
#plot a blank area (note asp=1 to keep the dice square)
plot(c(0, 200), c(0, 170), type = "n", xlab = "", ylab = "",
axes= F, main = "", asp = 1)
#plot the five dice and five random numbers
mapply(plot_face, rects, dots[rolls_the_dice()])
CodePudding user response:
Maybe this could be also interesting for you: the 'TeachingDemos' package provides a "dice" function code