【问题标题】:How to plot dices, that change with the result如何绘制骰子,随着结果的变化
【发布时间】:2022-01-05 04:25:23
【问题描述】:

我正在尝试在 R 中做一个 yahtzee 游戏,并且我想在 R 的情节部分显示骰子。像这样:

我有这个功能如何模拟掷骰子

rolls_the_dice <- function(X1 = 5){if(X1 <= 5){sample(1:6, X1, replace = TRUE)}

但我不知道如何按照我描述的方式显示分数。我有两个主要想法:

第一:

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)

绘制 5 个矩形,然后我必须找到一种方法在其中放置点并给出结果

第二:

rect(xleft = 0, xright = 20, ybottom = 0, ytop = 20)
points(x= 10, y= 10, col="black", pch=19)

这是一个骰子的面。这个想法是为每个骰子面创建一个图,然后将它们拾取并给出结果。但是在这里我不知道如何存储它们。 如果有人能告诉我什么是最好的(甚至只是可行的)想法。

【问题讨论】:

    标签: r plot dice


    【解决方案1】:

    有一个包 ;-)

    library(magrittr)
    library(tidydice)
    roll_dice(times = 5, rounds = 1) %>% plot_dice()
    

    【讨论】:

      【解决方案2】:

      这是使用列表在基础 R 中执行此操作的一种方法...

      #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()])
      

      【讨论】:

        【解决方案3】:

        也许这对你来说也很有趣:“TeachingDemos”包提供了一个“骰子”功能代码https://github.com/cran/TeachingDemos

        #install.packages("TeachingDemos")
        library(TeachingDemos)
        dice(5,1, plot.it=TRUE)
        

        【讨论】:

          猜你喜欢
          • 2018-06-26
          • 1970-01-01
          • 2021-12-06
          • 2019-05-19
          • 2015-01-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多