You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#开发Dart 301游戏时如何为列表内玩家分配固定控制台前景色

实现方案

预定义固定颜色映射

首先在Game类中添加和你要求的索引顺序完全对应的颜色数组,作为全局只读字段:

private readonly ConsoleColor[] _playerColors = new[] 
{
    ConsoleColor.DarkYellow,   // 列表索引0玩家
    ConsoleColor.DarkCyan,     // 列表索引1玩家
    ConsoleColor.DarkMagenta,  // 注意修正原拼写错误:DarkMagneta应为DarkMagenta
    ConsoleColor.DarkGreen     // 列表索引3玩家
};

修改玩家遍历逻辑

你之前的方案无法固定颜色是因为每次遍历都生成随机色,没有和玩家索引做绑定,修改遍历逻辑按索引取对应颜色即可,推荐用for循环实现,逻辑最直观:

// 将原有foreach改为for循环直接获取玩家索引
for (int i = 0; i < ListOfPlayers.Count; i++)
{
    var currentPlayer = ListOfPlayers[i];
    // 按索引取对应颜色,玩家数超过4时默认用灰色,可自行修改 fallback 规则
    Console.ForegroundColor = i < _playerColors.Length ? _playerColors[i] : ConsoleColor.Gray;

    // 原有业务逻辑保持不变
    Console.WriteLine("\n\t{0} it's your turn! What numbers did your arrows hit? " +
                      "\n\tREMEMBER: Each turn includes three throws with a possible score of 1-20 for each arrow. \n", currentPlayer);
    arrowOne = GetPlayerThrow();
    arrowTwo = GetPlayerThrow();
    arrowThree = GetPlayerThrow();
    currentPlayer.AddTurn(arrowOne, arrowTwo, arrowThree);
    totalScore = currentPlayer.CalculatePoints();

    // 必须加:重置控制台颜色为默认值,避免后续非玩家输出继承玩家颜色
    Console.ResetColor();
}

兼容单人模式原有效果

如果需要保留单人模式下玩家蓝色、电脑红色的显示规则,加个简单的模式判断即可:

for (int i = 0; i < ListOfPlayers.Count; i++)
{
    var currentPlayer = ListOfPlayers[i];
    // 单人模式(玩家+电脑共2个参与者)单独处理颜色
    if (ListOfPlayers.Count == 2)
    {
        Console.ForegroundColor = i == 0 ? ConsoleColor.Blue : ConsoleColor.Red;
    }
    else
    {
        // 多人模式走预定义固定颜色映射
        Console.ForegroundColor = i < _playerColors.Length ? _playerColors[i] : ConsoleColor.Gray;
    }
    // 其余业务逻辑和重置颜色的代码保持不变
}

内容的提问来源于stack exchange,提问作者Elin Forssell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 20:24:03