Home > Software engineering >  How do I randomly arrange elements?
How do I randomly arrange elements?

Time:05-31

I'm in the process of creating a memory game using the R console for a specified grid dimension (n_row , n_col), possible card symbols (pch), possible card color (col) and number of players (n_players).

I want to arrange the cards randomly on the playing field (invisible for players). Each pair of equal cards should correspond to a unique combination of symbol and color. How can I do this?

Here is my current code:

memory <- function(n_row = 6, n_col = 6, pch = 1:13, col = 1:8, n_player = 2) {

 # Select starting player
 player <- sample(1:n_player, 1, replace = TRUE) 

 # Print starting message
 cat(paste0("Player", player, "starts!"))
 cat(paste0("In each move you have to choose two cards."))

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

 # Stop function if n is odd
 n <- n_row * n_col
 if(n %% 2 != 0) 
   stop("Error in memory(): n_row * n_col must be an even number.")

 # Otherwise arrange cards randomly

}

CodePudding user response:

R is a statistical programming language, dice rolling and card games are its strengths ;-). They can naturally be represented with vectors and matrices. Let's assume each card has an integer code, e.g. 1 to 12, then we just need to mix them and then re-format it as matrix:

## twelve pairs of cards
cards <- rep(1:12, each=2)

## mix the cards
mixed <- sample(cards)

## arrange it at a gameboard
gameboard <- matrix(mixed, nrow=4, ncol=6)

## show placement of cards as a matrix
gameboard

## a simple visualization
image(gameboard, col=rainbow(12))

To arrange symbols or numbers on a grid graphically, one can directly work with the vector and use %% (modulo) and %/% (integer division) to calculate the coordinates:

## arrange symbols or numbers at a grid
plot(NULL, xlim=c(0, 6), ylim=c(0, 4), axes=FALSE, xlab="", ylab="")
text(0.5   (1:24 %% 6), 0.5   (0:23 %/% 6), mixed)
box()
abline(h=seq(-0, 4), lty="dashed")
abline(v=seq(-0, 6), lty="dashed")

Memory game

CodePudding user response:

Just to answer the question of how you could mark the symbols:

n_row = 6
n_col = 6
pch = 1:13
col = 1:8

x <- setNames(expand.grid(pch, col), c("pch", "col"))
x2 <- x[sample(seq_len(nrow(x)), n_row*n_col*.5), ]
x2 <- sample(rbind(x2, x2))

# Plot
plot(NULL, xlim=c(0, n_col), ylim=c(0, n_row), axes=FALSE, xlab="", ylab="")
box(lwd = 2)
abline(h=seq(0, n_row), lty="dashed")
abline(v=seq(0, n_col), lty="dashed")
points(0.5   (1:(n_row*n_col) %% n_col), 0.5   (0:((n_row*n_col) -1) %/% n_col), 
    pch=x2$pch, col=x2$col, cex=3)

Created on 2022-05-31 by the reprex package (v2.0.1)

  • Related