-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBaseballGame.js
93 lines (78 loc) · 2.46 KB
/
BaseballGame.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
export class BaseballGame {
#computerNumber;
#restartBtnEl;
#resultEl;
#submitEl;
constructor() {
this.#creatComputerNumber();
console.log(this.#computerNumber);
this.#getDomElemet();
this.#addEventListener();
}
#getDomElemet() {
this.#submitEl = document.querySelector("#submit");
this.#restartBtnEl = document.querySelector("#game-restart-button");
this.#resultEl = document.querySelector("#result");
this.#restartBtnEl.style.display = "none";
}
#addEventListener() {
this.#restartBtnEl.addEventListener("click", this.#refresh);
this.#submitEl.addEventListener("click", this.#play);
}
#creatComputerNumber() {
const computerNumber = [];
for (let i = 0; computerNumber.length < 3; i++) {
let randomNumber = MissionUtils.Random.pickNumberInRange(1, 9);
if (!computerNumber.includes(randomNumber)) {
computerNumber.push(randomNumber);
}
}
this.#computerNumber = computerNumber;
}
#getUserNumber() {
const userNumberinput = document.getElementById("user-input").value;
const userNumberArray = Array.from(userNumberinput, Number);
if (userNumberArray.length != 3) {
alert("You need to type 3 numbers.");
} else if (this.#checkRepeatNumber(userNumberArray)) {
alert("Three different Numbers I said.");
} else {
return userNumberArray;
}
}
#checkRepeatNumber(arr) {
return new Set(arr).size !== arr.length;
}
#matchNumbers(userNum) {
const strikeNum = userNum.filter(
(item, ind) => item === this.#computerNumber[ind]
).length;
const ballNum = userNum
.filter((item, index) => item !== this.#computerNumber[index])
.filter((item) => this.#computerNumber.includes(item)).length;
return [strikeNum, ballNum];
}
#convertToMessage(matchNum) {
const [strikeNum, BallNum] = matchNum;
let message = `${strikeNum ? strikeNum + "strike" : ""} ${
BallNum ? BallNum + "Ball" : ""
}`;
if (matchNum.every((item) => item === 0)) {
message = "Nothing";
} else if (strikeNum === 3) {
this.#restartBtnEl.style.display = "block";
message = "Home Run!";
}
return message;
}
#play = (e) => {
e.preventDefault();
const userNum = this.#getUserNumber();
const matchNumber = this.#matchNumbers(userNum);
const result = this.#convertToMessage(matchNumber);
this.#resultEl.innerHTML = result;
};
#refresh() {
document.location.reload(true);
}
}