Skip to content

Commit 1a7c2a3

Browse files
committed
♳ score computation
1 parent d3b7943 commit 1a7c2a3

File tree

3 files changed

+23
-8
lines changed

3 files changed

+23
-8
lines changed

src/App/Ui/ScoreSheet/ScoreSheetContent.tsx

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
categories,
55
Category,
66
DiceValue,
7+
getScoreSheetScore,
78
ScoreSheet,
89
} from "../../../gameRules/types";
910
import { getScore } from "../../../gameRules/getScore";
@@ -72,11 +73,7 @@ export const ScoreSheetContent = ({
7273
<td />
7374
<Td style={{ border: "1px solid #ddd" }}>
7475
<div style={{ marginLeft: "auto" }}>
75-
{categories.reduce((s, c) => {
76-
const roll = scoreSheet[c];
77-
78-
return s + (roll ? getScore(c, roll) : 0);
79-
}, 0)}
76+
{getScoreSheetScore(scoreSheet)}
8077
</div>
8178
</Td>
8279
</tr>

src/gameRules/getScore.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Category, DiceValue } from "./types";
1+
import type { Category, DiceValue } from "./types";
22

33
export const getScore = (category: Category, set: DiceValue[]) => {
44
switch (category) {

src/gameRules/types.ts

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { getScore } from "./getScore";
2+
13
export const categories = [
24
"Aces",
35
"Two",
@@ -20,6 +22,15 @@ export type Category = (typeof categories)[number];
2022
export type DiceValue = 1 | 2 | 3 | 4 | 5 | 6;
2123

2224
export type ScoreSheet = Record<Category, DiceValue[] | null>;
25+
export type FinishedScoreSheet = Record<Category, DiceValue[]>;
26+
27+
export const isScoreSheet = (s: any, nDice: number): s is ScoreSheet =>
28+
s &&
29+
categories.every(
30+
(c) =>
31+
!s[c] ||
32+
(Array.isArray(s[c]) && s[c].length === nDice && s[c].every(isDiceValue))
33+
);
2334

2435
export const isDiceValue = (d: any): d is DiceValue =>
2536
d === 1 || d === 2 || d === 3 || d === 4 || d === 5 || d === 6;
@@ -29,8 +40,15 @@ export const createEmptyScoreSheet = () =>
2940
categories.map((category) => [category, null])
3041
) as ScoreSheet;
3142

32-
export const isScoreSheetFinished = (scoreSheet: ScoreSheet) =>
33-
categories.every((c) => scoreSheet[c]);
43+
export const isScoreSheetFinished = (
44+
scoreSheet: ScoreSheet
45+
): scoreSheet is FinishedScoreSheet => categories.every((c) => scoreSheet[c]);
3446

3547
export const isScoreSheetEmpty = (scoreSheet: ScoreSheet) =>
3648
!categories.some((c) => scoreSheet[c]);
49+
50+
export const getScoreSheetScore = (scoreSheet: ScoreSheet) =>
51+
categories.reduce(
52+
(sum, c) => sum + (scoreSheet[c] ? getScore(c, scoreSheet[c]) : 0),
53+
0
54+
);

0 commit comments

Comments
 (0)