개요
저번에 자바로 구현했던 단어 맞추기 게임을 웹페이지로 구현해보고 싶었다. 디자인은 아래 사진을 참고 했다.
플로우는 이러하다.
- 초기화
- 랜덤 단어 선택
- 랜덤 단어 길이에 따라 단어들을 담을 박스에 박스와, 1글자씩 분리해서 넣어준다.
- 넣어준 뒤 텍스트만 display 를 none으로 해준다.
- 랜덤 단어 길이에 따라 단어들을 담을 박스에 박스와, 1글자씩 분리해서 넣어준다.
- 두번째 알파벳들을 담을 박스에 알파벳들을 동적으로 넣어준다.
- 랜덤 단어 선택
- 로직
- 사용자의 인풋을 받는다.
- 사용한 알파벳은 마찬가지로 display none으로 숨겨준다.
- 입력한 알파벳이 랜덤 단어에 들어가면 그 부분은 display:"" 으로 세팅해서 보이게 해준다.
- 모든 처리가 끝난 뒤 chance를 한개씩 감소
- 승패처리
- display값이 none인 요소가 하나도 없다면 승리 처리
- chance가 0이면 패배처리
위를 토대로 구현했다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./stylesheet.css">
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</link>
</head>
<body>
<div class="game">
<h1>남은 기회: <span id="chance_cnt"></span></h1>
<div class="correct_box">
</div>
<div class="input-group">
<input type="text" class="form-control" placeholder="단어를 입력하세요." aria-label="단어를 입력하세요."
aria-describedby="button-addon2">
<button class="word-inputbtn" type="button" id="button-addon2">Button</button>
</div>
<div class="foot">
</div>
</div>
<script src="scripts.js"></script>
</body>
</html>
.game{
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.correct_box{
width:auto;
height: 80px;
background-color:rgb(199, 199, 199);
display: flex;
flex-direction:row;
align-items: center;
justify-content: center;
border-radius: 15px;
padding: 20px;
gap: 20px;
}
.word_box{
width: 50px;
height: 90px;
background-color: white;
display: flex;
align-items: center;
justify-content: center;
}
.word{
color: black;
font-weight: 900;
font-size: 4rem;
}
.input-group{
margin-top: 50px;
}
.foot{
margin-top: 50px;
width :500px;
flex-wrap: wrap;
gap:5px;
display: flex;
flex-direction: row;
align-items: center;
}
#alphabet_box{
width: 25px;
height: 45px;
background-color: rgb(255, 0, 81);
display: flex;
align-items: center;
justify-content: center;
border-radius: 3px;
}
.alphabet{
color:white;
font-weight: 900;
font-size: 1.8rem;
}
const randomWords = ["Serendipity", "Melancholy", "Quixotic", "Ephemeral", "Luminous", "Tranquil", "Perplex"]
for (var i in randomWords) {
randomWords[i] = randomWords[i].toUpperCase()
}
const rand = Math.floor(Math.random() * 6);
const randWord = randomWords[rand];
var chance = 15;
$('#chance_cnt').text(chance);
function containsInRandomWord(c) {
for (var i of randWord) {
if (i == c) return true;
}
return false
}
function outWord(c) {
var arr = document.querySelectorAll('.alphabet');
console.log(arr)
arr.forEach(x => {
if (x.textContent === c) {
x.textContent = "";
}
})
}
console.log(randWord)
$('.word-inputbtn').click(async function () {
var success = true;
var arr = document.querySelectorAll('.word');
arr.forEach(x => {
if (x.style.display != '') success = false
})
if (chance == 0 || success) return;
const input = $('.input-group .form-control').val()
var find = false
var arr = document.querySelectorAll('.alphabet');
console.log(arr)
arr.forEach(x => {
if (x.textContent == input) {
find = true
}
})
if (input.length > 1 || input.charCodeAt() < 'A'.charCodeAt() ||
input.charCodeAt() > 'Z'.charCodeAt()) {
alert('잘못된 입력입니다. A ~ Z 사이의 알파벳만 입력해주세요.')
$('.input-group .form-control').val('')
return
}
if (find == false) {
alert('이미 입력한 알파벳입니다.')
$('.input-group .form-control').val('')
return
}
if (containsInRandomWord(input)) {
var arr = document.querySelectorAll('.word');
arr.forEach(x => {
if (x.textContent == input) {
x.style.display = ''
}
})
}
outWord(input)
$('.input-group .form-control').val('')
$('#chance_cnt').text(--chance);
setTimeout(function () {
// check success
var success = true;
var arr = document.querySelectorAll('.word');
arr.forEach(x => {
if (x.style.display != '') success = false
})
if (success) {
alert("성공하셨습니다!")
return;
}
if (chance == 0) {
alert("실패하셨습니다.")
window.location.reload();
}
}, 500)
});
for (let i = 0; i < randWord.length; ++i) {
$('.correct_box').append(`
<div class='word_box'>
<p class='word'>${randWord[i]}</p>
</div>
`)
$('.correct_box .word_box .word').fadeOut()
}
for (let i = "A".charCodeAt(); i <= 'Z'.charCodeAt(); ++i) {
const test = String.fromCharCode(i);
$('.foot').append(`
<div id="alphabet_box">
<div class="alphabet">${String.fromCharCode(i)}</div>
</div>
`);
}
잘 동작한다. 티스토리를 꾸며보면서 배운 자바스크립트와 html, css가 도움이 됐다. ㅎㅎㅎ 재밌었다.
'부트캠프 > 데일리 미션' 카테고리의 다른 글
보너스 문제 (0) | 2024.07.01 |
---|---|
Lv3. 단어 맞추기 게임 (0) | 2024.06.30 |
Lv2. 스파르타 자판기 (0) | 2024.06.30 |
Lv1. 랜덤 닉네임 생성기 (0) | 2024.06.30 |