简体   繁体   English

在R中绘制具有非空单元格的板

[英]Drawing board with non-empty cells in R

I try to draw something like this (but very simplified): 我尝试绘制这样的东西(但非常简化):

在此输入图像描述

So the thing is that I set height , width and nob - number of bombs and I want to draw table with height*width cells, where there will by nob bombs ramdomly set (it could be for example text 'bomb',. it is not important). 所以事情就是我设置了heightwidthnob - 炸弹的数量,我想用height*width单元格绘制表格,其中将由nob炸弹ramdomly设置(它可能是例如文本'炸弹',它是不重要)。 Furthermore, for every empty cell I want to count number of bombs in neighborhood and put that number in the middle of that cell (when zero - nothing). 此外,对于每个空单元格,我想计算邻域中的炸弹数量,并将该数字放在该单元格的中间(当为零时 - 没有)。 But I really have no idea for some "algorithm" for this. 但我真的不知道一些“算法”。 I draw board with proper size and that's all I can do. 我画板尺寸合适,这就是我所能做的。 Any ideas, help? 任何想法,帮助?

 w <- 7
 h <- 5
 nob <- 5
 plot.new()
 plot.window(xlim=c(0,w), ylim=c(0,h))
 rect(0, 0, w, h)
 for (i in 1:h-1){
    lines(x=c(0,w), y=c(i,i))
 }
 for (j in 1:w-1){
    lines(x=c(j,j), y=c(0, h))
 }
 sample(w*h, nob)

Some nice fun for Xmas time: 圣诞节时的一些好玩:

w <- 7
h <- 5
nob <- 5
nwal <- 7
set.seed(42) #for reproducibility

m <- matrix(0, ncol=w, nrow=h)
#place the walls
m[sample(length(m), nwal)] <- 1

o <- matrix("", ncol=w, nrow=h)
#place the bombs
o[sample(which(m == 0), nob)] <- "o"

#http://stackoverflow.com/a/22573306/1412059
#there is probably an alternative using igraph
sumNeighbors <- function(z) {
  rbind(z[-1,],0) + 
    rbind(0,z[-nrow(z),]) + 
    cbind(z[,-1],0) + 
    cbind(0,z[,-ncol(z)]) +
    cbind(rbind(z[-1,-1],0),0) +
    cbind(0,rbind(z[-1,-ncol(z)],0)) +
    cbind(rbind(0,z[-nrow(z),-1]),0) +
    cbind(0,rbind(0,z[-nrow(z),-ncol(z)]))  
}

library(reshape2)
DF <- melt(m, varnames = c("x", "y"), value.name = "z")
DF <- merge(DF, melt(o, varnames = c("x", "y"), value.name = "b"))
DF <- merge(DF, melt(sumNeighbors(o == "o"), varnames = c("x", "y"), value.name = "n"))

DF$n[DF$n == 0 | DF$b == "o" | DF$z == 1] <- ""
DF$t <- paste0(DF$n, DF$b)

library(ggplot2)
ggplot(DF, aes(x=x, y=y, fill=factor(z))) +
  geom_tile(color="dark grey") +
  geom_text(aes(label=t)) +
  theme(axis.title = element_blank(),
        axis.text = element_blank(), 
        axis.ticks = element_blank(),
        panel.grid = element_blank(),
        legend.position = "none")

结果情节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM