
디렉터리 구조
.
├── game.js
├── index.html
├── sounds
│ ├── blue.mp3
│ ├── green.mp3
│ ├── red.mp3
│ ├── wrong.mp3
│ └── yellow.mp3
└── styles.css
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>Simon</title>
<link rel="stylesheet" href="styles.css" />
<link
href="https://fonts.googleapis.com/css?family=Press+Start+2P"
rel="stylesheet"
/>
</head>
<body>
<h1 id="level-title">Press A Key to Start</h1>
<div class="container">
<div lass="row">
<div type="button" id="green" class="btn green"></div>
<div type="button" id="red" class="btn red"></div>
</div>
<div class="row">
<div type="button" id="yellow" class="btn yellow"></div>
<div type="button" id="blue" class="btn blue"></div>
</div>
</div>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="./game.js"></script>
const gamePattern = [];
const buttonColours = ['red', 'blue', 'green', 'yellow'];
function nextSequence() {
const randomNumber = Math.floor(Math.random() * 4); // 0~3까지 정수 난수
const randomChosenColour = buttonColours[randomNumber];
gamePattern.push(randomChosenColour);
}
randomChosenColour 와 동일한 id를 가진 버튼 선택
// ...
$("#" + randomChosenColour).fadeIn(100).fadeOut(100).fadeIn(100);
const audio = new Audio("./sounds/" + randomChosenColour + ".mp3");
audio.play();
}
userChosenColour)userClickedPattern 배열에 사용자가 클릭한 내용 저장const userClickedPattern = [];
$(".btn").click(function() {
const userChosenColour = $(this).attr("id");
userClickedPattern.push(userChosenColour);
});
animatePress() 함수 생성, 매개변수 currentColourpressed 클래스 속성 추가하기
function clickHandler() {
const userChosenColour = $(this).attr('id');
userClickedPattern.push(userChosenColour);
playSound(userChosenColour);
animatePress(userChosenColour);
}
function animatePress(currentColour) {
$('#' + currentColour).addClass('pressed');
setTimeout(() => {
$('#' + currentColour).removeClass('pressed');
}, 100);
}
nextSequence호출<h2> 내용 변경let level = 0;
let started = false;
$(document).keypress(function () {
if (!started) {
$('#level-title').text('Level ' + level);
started = true;
nextSequence();
}
});
function nextSequence() {
level++;
$('#level-title').text('Level ' + level);
// 생략
}
1.checkAnswer(currentLevel) 함수 선언
2. 사용자 입력 패턴이 게임 패턴과 일치할 경우 nextSequence 호출
3. nextSequence 이 트리거되면 userClickedPattern 초기화
4. 오답 시 게임오버
function nextSequence() {
userClickedPattern = [];
// 생략
}
function clickHandler() {
// 생략
checkAnswer(userClickedPattern.length - 1);
}
function checkAnswer(currentLevel) {
if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {
console.log('success');
if (userClickedPattern.length === gamePattern.length) {
setTimeout(function () {
nextSequence();
}, 1000);
}
} else {
$('body').addClass('game-over');
setTimeout(function () {
$('body').removeClass('game-over');
}, 1000);
$('#level-title').text('GAME OVER, Rress Any Key to Restart');
}
}