flutter - 如何检查和计算骰子满屋
问题描述
我正在使用 Flutter + Dart 制作一个带有 5 个骰子的类似 Yahtzee 的游戏。我将骰子值保存在List<int>
. 检查是否有满堂彩的最佳方法是什么?总和或相关骰子是多少?
如果我只想确定我是否有一个完整的房子,这个解决方案会很好。但是我必须在之后计算总和,所以我需要知道我有多少个数字。
用30if
秒覆盖每个案例是一种解决方案,但可能不是最好的解决方案。有没有人有更好的主意?
解决方案
下面是一个使用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);
}
推荐阅读
- javascript - 如何从另一个组件访问不同 .ts 文件中使用的自定义 html 元素?
- xamarin - Azure SignalR 不适用于几种类型的手机
- php - 如何在php中创建一个分配新键的数组
- javascript - 这有什么奇怪的:JSON 解析错误:意外的标识符“隧道”
- jpa - 休眠@OneToMany where discriminatorValue = 'SOMETHING'
- python - 如何使“class1 * class2”表现得像“class2 * class1”?
- extendscript - 通过extendscript改变bg,将一张图片导入到After Effects项目的“背景合成”中
- jquery - 在 Jquery 中查找并附加相关类
- python - 我想打开网站中的每个项目以使用 selenium 和 python 进行抓取
- vuejs2 - 鼠标悬停在儿童身上时会触发 V-on mouseout