자바스크립트로 간단한 게임 만들기!
부트스트랩을 이용해서 구성해봤는데 난 부트스트랩 좀 어색하다..ㅎ
[ 타이핑 게임 ]
1. start를 입력하면 게임이 시작된다.
2. 제시어는 7자 이내로 filter된 단어가 랜덤으로 제시된다.
3. 시작되는 순간 시간이 카운트된다.
4. 사용자가 입력에 성공하면 score가 올라간다.
5. 7초안에 입력하지 못하면 game over되며, 모든 점수는 초기화된다.
[ js ] - 배운 것
1. api를 사용하여 랜덤 단어를 생성했다.
배열값도 랜덤으로 가져올 수 있는 api가 있는것을 처음 알았음..
저번에 랜덤 아이디값 만들때 너무 대충한 것 같아서 고쳐봐야겠다ㅋㅋ
2. async await
async와 await는 자바스크립트의 비동기 처리 패턴 중 가장 최근에 나온 문법이다.
기존의 비동기 처리 방식인 콜백함수와 프로미스의 단점을 보완하고 개발자가 읽기 좋은 코드를 작성할 수 있게 도와준다.
1) 함수 앞에 async 라는 예약어를 붙인다.
2) 함수의 내부 로직 중 HTTP 통신을 하는 비동기 처리 코드 앞에 await를 붙인다.
=> 해당 프로미스가 끝날때 까지 기다렸다가 다음 작업을 수행한다.
휴 비동기 아직도 잘 모르겠다
const wordInput = document.querySelector("#word-input");
const currentWord = document.querySelector("#current-word");
const timeDisplay = document.querySelector("#time");
const scoreDisplay = document.querySelector("#score");
const messageDisplay = document.querySelector("#message");
let words = ["banana", "key", "car", "javascript", "cat"];
let score = 0;
let time = 0;
let timeInterval;
let isPlaying = false;
let isReady = false;
// 기본 게임 시간
const GAME_TIME = 7;
const API_URL = "https://random-word-api.herokuapp.com/word?number=100";
init();
// async await 에이싱크 어웨잇 (비동기함수)
async function init() {
const res = await fetch(API_URL);
//패치가 실행이 된 후에 값이 api에 담김
const data = await res.json();
words = data.filter((i) => i.length < 7);
isReady = true;
console.log(words);
}
// function init() {
// const res = fetch(API_URL)
// .then((res) => res.json())
// // json으로 넘겨온 값을 data라는 이름으로 받는다
// .then((data) => (words = data));
// //words 변수에 넘겨받은 data를 담아주면 됨
// console.log(res);
// //통신을 완료하지않았기 때문에 promise가 나옴
// }
wordInput.addEventListener("input", (e) => {
const typedText = e.target.value;
const currentText = currentWord.innerText;
if (typedText.toUpperCase() === currentText.toUpperCase() && isReady) {
// input받은 값과 문제의 값이 같으면 score() 점수 +1, setNewWord() 새 단어 출력
addScore();
setNewWord();
}
});
// 게임 종료
function gameover() {
console.log(gameover);
isPlaying = false;
clearInterval(timeInterval);
timeInterval = null; // 빈값 넣어서 초기화
messageDisplay.innerText = "GAME OVER~!";
// game over이기 때무네 score 초기화
score = 0;
}
// 시간 카운트 다운
function countDown() {
console.log(time);
time = time - 1;
timeDisplay.innerText = time;
if (time === 0) {
gameover();
}
}
function setNewWord() {
// 새로운 단어가 제시될때마다 게임시간을 5초로 초기화한다
time = GAME_TIME;
wordInput.value = "";
messageDisplay.innerText = "Now Playing!!";
const randomIndex = Math.floor(Math.random() * words.length);
currentWord.innerText = words[randomIndex];
if (!isPlaying) {
//isPlaying 이 false 이면 true로 다시 바꿔줌
timeInterval = setInterval(countDown, 1000);
isPlaying = true;
// 게임오버가 되면 isPlaying을 다시 false로 바꿔준다 ->gameover()함수에 추가
}
}
function addScore() {
score = score + 1;
scoreDisplay.innerText = score;
}
'공부 > javascript' 카테고리의 다른 글
2022.06.30 - javascript 30 [ day3 ] CSS Variables with JS (0) | 2022.06.30 |
---|---|
2022.06.28 - javascript 30 [ day2 ] clock (0) | 2022.06.28 |
2022.06.23 - (+계속 추가) 노마드 크롬웹앱 내 맘대로 수정하기 (0) | 2022.06.23 |
2022.06.20 - javascript 동기, 비동기, callback함수 (0) | 2022.06.21 |
2022.06.17 - weatherAPI 사용해보기 (0) | 2022.06.17 |