我尝试绘制这样的东西(但非常简化):
所以问题是我设置height
,width
和nob
- 炸弹的数量,我想用height*width
个单元格绘制表格,其中{ {1}} ramdomly设置炸弹(可能是例如文本'炸弹',它并不重要)。此外,对于每个空单元格,我想计算邻域中的炸弹数量,并将该数字放在该单元格的中间(当为零时 - 没有)。但我真的不知道一些"算法"为了这。我画板尺寸合适,这就是我所能做的。任何想法,帮助?
nob
答案 0 :(得分:6)
圣诞节时的一些好玩:
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")