如何在R控制台开发的指定网格维度记忆游戏中实现卡片随机排列及唯一符号颜色配对?
解决R语言记忆游戏的卡片随机排列问题
嘿,我来帮你搞定这个记忆游戏里的卡片排列逻辑!咱们的核心目标是生成每对唯一符号(pch)+颜色(col)组合的卡片集合,然后随机打乱后排列成指定的网格。我会基于你现有的代码完善这部分功能,还会加一些必要的校验和游戏状态管理。
完整实现代码
memory <- function(n_row = 6, n_col = 6, pch = 1:13, col = 1:8, n_player = 2) { # 选择起始玩家 player <- sample(1:n_player, 1, replace = TRUE) # 打印起始提示信息 cat(paste0("Player ", player, " starts!\n")) cat("In each move you have to choose two cards.\n") # 当卡片总数为奇数时终止函数 n <- n_row * n_col if(n %% 2 != 0) stop("Error in memory(): n_row * n_col must be an even number.") # ------------------- 卡片排列核心逻辑 ------------------- n_pairs <- n %/% 2 # 计算需要的卡片对数 total_combinations <- length(pch) * length(col) # 可用的唯一组合总数 # 校验:确保可用组合数足够生成需要的对数 if(total_combinations < n_pairs) { stop(paste0("Error in memory(): Not enough unique pch+col combinations. ", "You need at least ", n_pairs, " combinations, but only have ", total_combinations, ".")) } # 生成所有可能的符号-颜色组合 all_combinations <- expand.grid(pch = pch, col = col) # 随机抽取n_pairs个唯一组合(每对卡片用一个) selected_pairs <- all_combinations[sample(nrow(all_combinations), n_pairs), ] # 复制每对组合,得到完整的卡片集合(因为每对要出现两次) cards <- rbind(selected_pairs, selected_pairs) # 随机打乱卡片顺序,保证排列随机 cards <- cards[sample(nrow(cards)), ] # 把卡片转换为对应维度的网格索引,方便后续游戏中定位卡片 card_grid <- matrix(1:nrow(cards), nrow = n_row, ncol = n_col) # 构建游戏状态列表,存储所有必要信息(方便后续扩展游戏逻辑) game_state <- list( card_grid = card_grid, # 卡片的网格位置索引 cards = cards, # 每张卡片的pch和col信息 revealed = matrix(FALSE, n_row, n_col), # 记录卡片是否被翻开 current_player = player, # 当前玩家 scores = setNames(rep(0, n_player), paste0("Player", 1:n_player)) # 玩家得分 ) # 返回游戏状态,方便后续游戏操作(比如翻牌、计分等) return(invisible(game_state)) }
关键步骤解释
- 组合数校验:先计算
pch和col能生成的唯一组合总数,如果比需要的卡片对数少,直接报错——毕竟咱们要保证每对卡片的符号+颜色都是独一无二的。 - 生成唯一组合对:用
expand.grid生成所有可能的符号-颜色组合,然后随机抽取需要的对数,确保每对都是唯一的。 - 复制+打乱:把选中的组合复制一次(每对卡片要出现两次),再用
sample打乱顺序,这样卡片的排列就是完全随机的。 - 游戏状态管理:把卡片信息、翻牌状态、玩家信息都存在一个列表里,后续扩展翻牌、计分逻辑时会非常方便。
测试一下
你可以这样调用函数,查看生成的卡片信息:
# 生成一个4x4的游戏 game <- memory(n_row = 4, n_col = 4) # 查看每张卡片的pch和col print(game$cards) # 查看卡片的网格布局 print(game$card_grid)
内容的提问来源于stack exchange,提问作者Amanda Bash
相关产品推荐
相关产品推荐

