gpt4 book ai didi

flutter - 如何检查和计算骰子满屋

转载 作者:行者123 更新时间:2023-12-03 03:58:29 24 4
gpt4 key购买 nike

我正在使用Flutter + Dart用5个骰子制作类似Yahtzee的游戏。我将骰子值保留在List<int>中。检查房屋是否满员的最佳方法是什么?总和或相关的骰子是多少?

如果我只想确定我是否满屋,this solution会很好。但是我必须在事后计算总和,所以我需要知道我有多少个数字。

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

最佳答案

这是使用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或更高版本,则还可以为此创建一个漂亮的 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);
}

关于flutter - 如何检查和计算骰子满屋,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59237151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com