Drawing board with non-empty cells in R
I'm trying to do something like this (but very simplistic):
So, I have set height
, width
and nob
is the number of bombs, and I want to draw a table with cells height*width
where the bombs will be placed to nob
be, for example, a text "bomb", it doesn't matter). Also, for each empty cell, I want to count the number of bombs in the neighborhood and place that number in the middle of that cell (when zero is nothing). But I really have no idea about some "algorithm" for this. I paint the board with the proper size and whatever 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)
source to share
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")
source to share