如何检查和计算骰子满屋

时间:2019-12-08 15:52:38

标签: flutter dart

我正在使用Flutter + Dart制作带有5个骰子的Yahtzee式游戏。我将骰子值保存在List<int>中。最好的方法是检查房子是否满员,总和或相关的骰子是多少?

如果我只想确定我是否有完整的房子,this solution会很好。但是我之后必须计算总和,所以我需要知道我有多少个数字。

让30个if覆盖每种情况 是一种解决方案,但可能不是最好的解决方案。有谁有更好的主意吗?

2 个答案:

答案 0 :(得分:0)

这是使用List / Iterable方法的简单Dart实现:

bool fullHouse(List<int> dice) {
  final counts = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0};

  dice.forEach((n) => counts[n]++);

  return counts.containsValue(3) && counts.containsValue(2);
}

int diceSum(List<int> dice) => dice.reduce((v, e) => v + e);

如您所见,我将总和和全屋支票分开,但如有必要,我也可以进行调整。

扩展名

如果您使用的是飞镖2.6或更高版本,则还可以为此创建一个不错的extension

void main() {
  print([1, 1, 2, 1, 2].fullHouseScore);
}

extension YahtzeeDice on List<int> {
  int get fullHouseScore {
    if (isFullHouse) return diceSum;
    return 0;
  }

  bool get isFullHouse {
    final counts = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0};

    forEach((n) => counts[n]++);

    return counts.containsValue(3) && counts.containsValue(2);
  }

  int get diceSum => reduce((v, e) => v + e);
}

测试

这是测试功能的简单用法:

int checkFullHouse(List<int> dice) {
  if (fullHouse(dice)) {
    final sum = diceSum(dice);
    print('Dice are a full house. Sum is $sum.');
    return sum;
  } else {
    print('Dice are not a full house.');
    return 0;
  }
}

void main() {
  const fullHouses = [
    [1, 1, 1, 2, 2],
    [1, 2, 1, 2, 1],
    [2, 1, 2, 1, 1],
    [6, 5, 6, 5, 5],
    [4, 4, 3, 3, 3],
    [3, 5, 3, 5, 3],
  ],
      other = [
    [1, 2, 3, 4, 5],
    [1, 1, 1, 1, 2],
    [5, 5, 5, 5, 5],
    [6, 5, 5, 4, 6],
    [4, 3, 2, 5, 6],
    [2, 4, 6, 3, 2],
  ];

  print('Testing dice that are full houses.');
  fullHouses.forEach(checkFullHouse);

  print('Testing dice that are not full houses.');
  other.forEach(checkFullHouse);
}

答案 1 :(得分:0)

为什么不只使用链接的解决方案?

bool isFullHouse(List<int> diceResults) {
  String counterString = diceResults.map((i) => i.toString()).join();
  return RegExp('20*3|30*2').hasMatch(counterString);
}

int getDiceSum(List<int> diceResults) {
  int sum = 0;
  for (int i = 0; i < 6; i++) {
    sum += [0, 0, 2, 0, 3, 0][i] * (i + 1);
  }
  return sum;
}

// elsewhere
dice = [0, 0, 2, 0, 3, 0]; // example result
if (isFullHouse(dice)) {
  int score = getDiceSum(dice);
  // Do something with sum
}