-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·115 lines (93 loc) · 3.08 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#! /usr/bin/env node
import readlineSync from "readline-sync";
import Enquirer from "enquirer";
class NumberGuessingGame {
constructor() {
this.enquirer = new Enquirer();
}
async main() {
console.log("数字当てゲームへようこそ!楽しんでいってください");
let digitCount;
for (;;) {
digitCount = parseInt(
readlineSync.question("挑戦する桁数を3,4,5から選んでください:"),
10,
);
if ([3, 4, 5].includes(digitCount)) {
break;
} else {
console.log("3, 4, 5のうちから桁数を指定してください");
}
}
const { level } = await this.enquirer.prompt({
type: "select",
name: "level",
message: "難易度を選択してください",
choices: ["easy", "hard"],
});
const targetNumber = this.#generateRandomNumber(digitCount);
let attempts = 0;
console.log(`${digitCount}桁の数字を推理しましょう. (難易度: ${level})`);
for (;;) {
const guess = readlineSync.question(
`推測した${digitCount}桁の数字を入力してください:`,
);
if (guess.length !== digitCount || !/^\d+$/.test(guess)) {
console.log(
`桁数が間違っています ${digitCount}桁の数字を入力してください`,
);
continue;
}
attempts++;
const detailedFeedback = this.#checkGuess(targetNumber, guess);
if (level === "easy") {
this.#displayDetailedFeedback(detailedFeedback);
} else {
this.#displayFeedback(detailedFeedback);
}
if (detailedFeedback.every((symbol) => symbol === "☆")) {
console.log(
`おめでとうございます! ${attempts}回目の回答で正解しました`,
);
break;
}
}
}
#generateRandomNumber(digitCount) {
const numberSet = Array.from({ length: 10 }, (_, index) => index);
for (let i = numberSet.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[numberSet[i], numberSet[j]] = [numberSet[j], numberSet[i]];
}
return numberSet.slice(0, digitCount).join("");
}
#checkGuess(targetNumber, guess) {
const detailedFeedback = [];
for (let i = 0; i < targetNumber.length; i++) {
const targetDigit = targetNumber[i];
const guessDigit = guess[i];
if (guessDigit === targetDigit) {
detailedFeedback.push("☆");
} else if (targetNumber.includes(guessDigit)) {
detailedFeedback.push("△");
} else {
detailedFeedback.push("✕");
}
}
return detailedFeedback;
}
#displayFeedback(detailedFeedback) {
const feedback = { "☆": 0, "△": 0, "✕": 0 };
detailedFeedback.forEach((symbol) => {
feedback[symbol]++;
});
console.log(
` 推理結果(hard) ⇒ ☆:${feedback["☆"]} △:${feedback["△"]} ✕:${feedback["✕"]}`,
);
}
#displayDetailedFeedback(detailedFeedback) {
console.log(` 推理結果(easy) ⇒ ${detailedFeedback.join(" ")}`);
}
}
const game = new NumberGuessingGame();
game.main();