我正在使用 R 控制臺為指定的網格維度 ( n_row, n_col) 創建記憶游戲。我想在比賽場地上隨機排列卡片(玩家看不見)。每對相等的卡片應對應于符號 ( pch) 和顏色 ( col) 的唯一組合。我怎樣才能做到這一點?
這是我當前的代碼:
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."))
# 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
}
uj5u.com熱心網友回復:
只是為了回答如何標記符號的問題:
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 <- rbind(x2, x2)[sample(seq_len(n_row*n_col)), ]
# 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)

由reprex 包于 2022-05-31 創建(v2.0.1)
uj5u.com熱心網友回復:
R 是一種統計編程語言,擲骰子和紙牌游戲是它的強項;-)。它們自然可以用向量和矩陣來表示。假設每張卡片都有一個整數代碼,例如 1 到 12,那么我們只需將它們混合,然后將其重新格式化為矩陣:
## 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))
要在網格上以圖形方式排列符號或數字,可以直接使用向量并使用%%(模) 和%/%(整數除法) 來計算坐標:
## 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")

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/484908.html
