首页 > 解决方案 > 如何检查和计算骰子满屋

问题描述

我正在使用 Flutter + Dart 制作一个带有 5 个骰子的类似 Yahtzee 的游戏。我将骰子值保存在List<int>. 检查是否有满堂彩的最佳方法是什么?总和或相关骰子是多少?

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

用30if秒覆盖每个案例一种解决方案,但可能不是最好的解决方案。有没有人有更好的主意?

标签: flutterdart

解决方案


下面是一个使用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);

如您所见,我将总和和全屋检查分开,但如有必要,我也可以调整它。

扩大

如果您使用的是 Dart或更高版本,您还可以为此2.6创建一个 nice :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);
}

推荐阅读