-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
196 lines (157 loc) · 5.59 KB
/
Copy pathscript.js
File metadata and controls
196 lines (157 loc) · 5.59 KB
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
// 전역 변수 정의
const images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg', 'image6.jpg', 'image7.jpg', 'image8.jpg', 'image9.jpg', 'image10.jpg', 'image11.jpg', 'image12.jpg'];
const cards = [...images, ...images]; // 쌍을 만들기 위해 이미지를 복제
let flippedCards = [];
let matchedPairs = 0; // 정확히 일치하는 카드 쌍의 수를 추적하는 변수
let totalPairs = images.length; // 전체 카드 쌍의 수
let stopwatchInterval;
let stopwatchSeconds = 0;
let gameStarted = false;
document.addEventListener('DOMContentLoaded', () => {
updateStopwatch();
createGameGrid(); // Create the game grid once when the page loads
const startGameButton = document.getElementById('start-game-button');
const restartButton = document.getElementById('restart-button');
startGameButton.addEventListener('click', startGame);
restartButton.addEventListener('click', resetGame);
});
function createGameGrid() {
const shuffledCards = shuffle(cards);
const memoryGame = document.querySelector('.memory-game');
shuffledCards.forEach((image) => {
const newCard = createCard(image);
newCard.addEventListener('click', flipCard);
memoryGame.appendChild(newCard);
});
const gameClearMessage = document.querySelector('.game-clear-message');
gameClearMessage.style.display = 'none';
}
function shuffle(array) {
return array.sort(() => Math.random() - 0.5);
}
function createCard(image) {
const div = document.createElement('div');
div.classList.add('card');
const img = document.createElement('img');
img.src = `images/${image}`;
div.appendChild(img);
return div;
}
function startGame() {
resetStopwatch();
startStopwatch();
gameStarted = true;
}
function flipCard() {
if (flippedCards.length < 2) {
const card = this;
card.classList.add('flipped');
flippedCards.push(card);
if (flippedCards.length === 2) {
setTimeout(checkMatch, 500);
}
}
}
function checkMatch() {
const [card1, card2] = flippedCards;
if (card1.querySelector('img').src === card2.querySelector('img').src) {
card1.removeEventListener('click', flipCard);
card2.removeEventListener('click', flipCard);
matchedPairs++;
if (matchedPairs === totalPairs) {
stopStopwatch();
showGameClearMessage();
}
} else {
card1.classList.remove('flipped');
card2.classList.remove('flipped');
}
flippedCards = [];
}
function resetGame() {
const memoryGame = document.querySelector('.memory-game');
const gameClearMessage = document.querySelector('.game-clear-message');
// Stop the stopwatch without starting it
stopStopwatch();
// Reset the stopwatch seconds to 0
stopwatchSeconds = 0;
// 이전 카드에서 이벤트 리스너 제거
const existingCards = document.querySelectorAll('.card');
existingCards.forEach(card => card.removeEventListener('click', flipCard));
// 기존 카드 및 메시지 제거
memoryGame.innerHTML = '';
gameClearMessage.style.display = 'none';
matchedPairs = 0; // 정확히 일치하는 카드 쌍의 수를 초기화
updateStopwatch();
if (gameStarted) {
createGameGrid(); // Only recreate the game grid if the game has started
}
gameStarted = false; // Reset the game started flag
}
function showGameClearMessage() {
const gameClearMessage = document.querySelector('.game-clear-message');
const recordedTimeSpan = document.getElementById('recorded-time');
recordedTimeSpan.textContent = formatTime(stopwatchSeconds);
gameClearMessage.style.display = 'block';
// Add this line to update the rankings after the game is cleared
updateRankings();
}
function startStopwatch() {
stopwatchInterval = setInterval(() => {
stopwatchSeconds++;
updateStopwatch();
}, 1000);
}
function stopStopwatch() {
clearInterval(stopwatchInterval);
}
function resetStopwatch() {
stopwatchSeconds = 0;
updateStopwatch();
}
function updateStopwatch() {
const stopwatchSpan = document.getElementById('stopwatch');
stopwatchSpan.textContent = formatTime(stopwatchSeconds);
}
function formatTime(seconds) {
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
const formattedMinutes = String(minutes).padStart(2, '0');
const formattedSeconds = String(remainingSeconds).padStart(2, '0');
return `${formattedMinutes}:${formattedSeconds}`;
}
function saveToLocalStorage(userName, record) {
let rankings = JSON.parse(sessionStorage.getItem('rankings')) || [];
rankings.push({ userName, record });
rankings.sort((a, b) => a.record - b.record);
if (rankings.length > 5) {
rankings.pop();
}
sessionStorage.setItem('rankings', JSON.stringify(rankings));
}
// Add this function to retrieve rankings from localStorage
function getRankings() {
return JSON.parse(sessionStorage.getItem('rankings')) || [];
}
function registerRanking() {
const userName = prompt('유저 이름 입력:');
if (userName) {
const recordedTime = formatTime(stopwatchSeconds);
saveToLocalStorage(userName, stopwatchSeconds);
updateRankings();
alert(`랭킹 등록 완료!\n${userName}: ${recordedTime}`);
}
}
function updateRankings() {
const rankingsContainer = document.querySelector('.rankings');
rankingsContainer.innerHTML = ''; // Clear existing rankings
const rankings = getRankings();
rankings.forEach((entry, index) => {
const rank = index + 1;
const { userName, record } = entry;
const formattedRecord = formatTime(record);
const rankElement = document.createElement('div');
rankElement.textContent = `${rank}위: ${userName} ${formattedRecord}`;
rankingsContainer.appendChild(rankElement);
});
}