Add consecutive numbering to playing field

Viewed 49

I am in the process of creating a small game using the R console, and I am trying to add consecutive numbering to my empty playing field (which should be adaptive to changes in n_row and n_col). The final output should something look like this:

Picture of playing field

Here is my current code:

n_row <- 4
n_col <- 4

# Plot empty playing field 
par(xaxs = "i", yaxs = "i") 
plot.new()
plot.window(xlim = c(0.5, 4.5), ylim = c(0.5, 4.5))
grid(nx = n_col, ny = n_row, col = "grey")
box(lwd = 2)
2 Answers

You may use mtext at= sequences derived from the par()$usr for dynamic n_row, n_col.

n_row <- 6
n_col <- 7

# Plot empty playing field (4x4)
par(xaxs = "i", yaxs = "i") 
plot.new()
plot.window(xlim = c(0.5, 4.5), ylim = c(0.5, 4.5))
grid(nx = n_col, ny = n_row, col = "grey")
box(lwd = 2)

xs <- do.call(seq, c(as.list(par()$usr[1:2]), length.out=n_col*2+1))
xs <- xs[seq_along(xs) %% 2 == 0]
mtext(seq_len(n_col), at=xs, side=1, line=1, cex=1.5)

ys <- do.call(seq, c(as.list(par()$usr[1:2]), length.out=n_row*2+1))
ys <- ys[seq_along(ys) %% 2 == 0]
mtext(seq_len(n_row), at=ys, side=2, line=1, cex=1.5, las=2)

enter image description here

Another solution, with axis function

axis(side=1, at=1:4, labels=1:4, cex.axis=2, tick=FALSE)
axis(side=2, at=1:4, labels=1:4, cex.axis=2, las=2, tick=FALSE)

enter image description here

Related