TIL-no.12 Javascript 숫자 맞추기 게임 만들기

sanghun Lee·2020년 6월 24일
0

Today I Learned

목록 보기
10/66

랜덤으로 생성된 숫자를 맞춰주는 프로그램을 만들어 자기소개 사이트에 넣기로 했다
아래는 사이트 주소

https://sanghunlee-711.github.io/wecode1stweek/PROJECTS.html

1. Html layout만들기

먼저 random으로 선정된 숫자와 대조시키기위해 사용자 임의기입을 위한 input tag를 생성했고 각자 id 와 class를 넣었다.

<label for = "guessField">Enter a guess</label>
<input type = "text" id = "guessField" class = "guessField">
<input type ="submit" value = "Submit guess" 
                      class = "guessSubmit" id = "submitguess">
  • label은 폼의 양식에 이름붙이는 태그이다. 주요속성은 for 이며 check를 위해 사용[사실 저렇게 클래스랑 value Id 를 남발하는 이유를 모르겠다]

2. 변수설정하기

변수 y 😒

Math 객체를 이용하여 random한 숫자를 불러오게 시켰다.

Math.random()를 이용하여 0과 1 사이의 난수를 받아 그것의 *10을 하면 0~9사이의 값이 나올것이고
거기에 +1 을 한뒤 floor를사용하면 1~10사이의 값이 나오게 된다.

*Math.floor(x): 인수보다 작거나 같은 수 중에서 가장 큰 정수를 반환합니다.

const y = Math.floor(Math.random()*10+1);

변수 x 👍

x 변수는 querySelector()를 이용하여 guessField class에 있는 input tag 내에 사용자가 기입 할 value값을 가져오는 것으로 만들었다.

value설명 참조

*document.querySelector(): 문서 내에서 주어진 선택자를 만족하는 첫 번째 Element를 반환합니다.
-> css 의 선택자라고 생각하면 편할듯.

const x = document.querySelector(".guessField").value;

3. 조건문 작성

조건문은 간단하게 변수두개의 일치 및 크기비교를 통해 alert를 띄우는것으로 작성되었고
내부에 template line 작성법을 적용해보았다.(별의미가 없음)

if(x == y)
{
    alert(`Congratulation you guess right way!! The number is ${x} !`);
}

 
else if(x > y)
{

    alert("Sorry try a smaller number");
}
else
{

    alert("Sorry try a greater number");
}

4. click시 function 작동시키기

querySelector를 통해 id sumbitguess인 submit 타입의 input form 클릭시 함수가 작동하도록 만들었다.

document.querySelector("#submitguess").onclick = function(){
};

onclick 참조

5.Wrap-up

클릭시 value값을 가져오기 위해 function 내부에 const x를 넣었음

const y = Math.floor(Math.random()*10+1);

const guess = 1;

document.querySelector("#submitguess").onclick = function(){
    const x = document.querySelector(".guessField").value;

if(x == y)
{
    alert(`Congratualtion you guess right way The number is ${x} ! `);
}
else if(x > y)
{

    alert("Sorry try a smaller number");
}
else
{

    alert("Sorry try a greater number");
}
    };

추후에 CSS로 좀 예쁘게 만들어야할 것 같다.

참고:www.geeksforgeeks.org

profile
알고리즘 풀이를 담은 블로그입니다.

0개의 댓글