ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Rock-Paper-Scissors 만들기) 2. Javascript 완성하기
    HTML & CSS & JAVASCRIPT 2021. 1. 24. 18:14

     

     

     

    버튼 누름에 따라서 사용자의 게임결과 변화 만드는 것이 주된 목적이다.

     

    1. 계산 결과에 따라서 점수판 변경하기

    2. 승리여부에 따른 멘트 변경하기

    3. 승리 여부 빛으로 나타내기

     

     

     

     

    1. index. html

    끝에 자바스크립트 script문장을 추가했다. 

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Rock  Paper Scissors Game</title>
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <header>
            <h1>Rock Paper Scissors</h1>
        </header>
    
        <div class="score-board">
            <div id = "user-label" class="badge">user</div>
            <div id = "computer-label" class="badge">comp</div>
            <span id = "user-score">0</span>
            <span id = "computer-score">0</span>
        </div>
    
        <div class="result">
            <p>Paper covers rock. You win!</p>
        </div>
    
        <div class="choices">
            <div class="choice" id = "r">
                <img src="images/rock.png" alt="">
            </div>
            <div class="choice" id = "p">
                <img src="images/paper.png" alt="">
            </div>
            <div class="choice" id = "s">
                <img src="images/scissors.png" alt="">
            </div>
        </div>
    
        <p id="action-message">Make your move.</p>
        <script src="app.js" charset="utf-8"></script>
    </body>
    </html>

     

     

     

    2. styles.css

    결과에 따라서 빛을 추가하기 위해서 glow 영역을 마지막에 추가했다. (!important대신에 맨 아래에 추가했음)

    @import url('https://fonts.googleapis.com/css2?family=Asap:wght@500;700&display=swap');
    
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    
    body {
        background-color: #003049;
    
    }
    header {
        background: white;
        padding: 20px;
    
        
    }
    
    
    
    header > h1 {
        color: #003049;
        text-align: center;
        font-family: Asap, sans-serif;
    }
    
    .score-board {
        margin: 20px auto;/*위아래 20px, 양옆 center*/
        border: 3px solid white;
        border-radius: 4px;
        text-align: center;
        width: 200px;
        color: white;
        font-size: 46px;
        padding: 15px 20px;/*박스 안에서 패딩주기*/
        font-family: Asap, sans-serif;
        position: relative; /*user-labe,computer-label 이후 남은 영역 상대적으로 사용*/
    
    }
    
    .badge {
        background: #e63946;
        color: white;
        font-size: 14px;
        padding: 2px 10px;
        font-family: Asap, sans-serif;
    }
    
    #user-label {
        position : absolute;
        top: 30px;
        left: -25px;
    }
    
    #computer-label {
        position : absolute;
        top: 30px;
        right: -30px;
    }
    
    .result {
        font-size: 40px;
        color: white;
        font-weight: bold;
        font-family: Asap,sans-serif;
        
    }
    
    .result > p{
        text-align: center;
    }
    
    .choices {
        margin-top: 50px;
        text-align: center;
    }
    .choice {
        border : 4px solid white;
        border-radius: 50%;
        margin: 0 20px;/*아이콘 끼리 사이에 공간 주기*/
        padding: 10px; /*동그라미안에 아이콘 테두리 사이에 주기*/
        display: inline-block; /*horiaontal 배치*/
        transition: all 0.3s ease;/*마우스 가져자 댔을때 변하는 속도 느리게 */
        
    }
    
    .choice:hover {
        cursor: pointer;
        background: #2a9d8f;
    
    }
    
    #action-message {
        text-align: center;
        color: white;
        font-family: Asap, sans-serif;
        font-weight: bold;
        font-size: 20px;
        margin-top: 20px;
    }
    
    
    /*자바스크립트는 아니지만 이기고 졌을 때 기능을 추가하고 싶다*/
    .red-glow {
        border: 4px solid #e63946;
        box-shadow: 0 0 10px #e76f51;
    }
    
    .green-glow {
        border: 4px solid #b9e769;
        box-shadow: 0 0 10px #83e377;
    }
    
    .gray-glow {
        border: 4px solid #6d6875;
        box-shadow: 0 0 10px #2b2d42;
    
    }
    

     

     

     

    2.app.js

    변수를 설정하고 함수를 구현해서 게임 결과에 따른 변경과 기능을 추가했다. 

    let userScore = 0;/*얘네는 게임의 결과에 따라서 변하는 값이라서 let으로 둔다 */
    let computerScore = 0;
    const userScore_span = document.getElementById("user-score");/* variables  span tag라고 알려주는 것이다. */ 
    const computerScore_span = document.getElementById("computer-score");
    const scoreBoard_div = document.querySelector(".score-board");/*클래스 쿼리 셀렉터 */
    const result_p = document.querySelector(".result > p"); /*result 안의 p tag를 변경할 것이다. */
    const rock_div = document.getElementById("r");/*id 파트 Getelementbyid */
    const paper_div = document.getElementById("p");
    const scissors_div = document.getElementById("s");
    
    
    function getComputerChoice() {
        const choices = ['r','p','s'];
        const randomNumber = Math.floor(Math.random()*3);/*0~2까지 숫자 랜덤으로(정수로) 추출*/
        return choices[randomNumber];
    }
    
    function convertToWord(letter){
        if(letter ==="r") return "ROCK";
        if(letter ==="r") return "PAPER";
        return "SCISSORS"
    }
    
    function win(user,computer){
        const smallUserWord = "user".fontsize(3).sup();/*sup은 맨 위로 올리자는 것 */
        const smallCompWord = "comp".fontsize(3).sup();
        const userChoice_div = document.getElementById(user);/*결과에 따라서 불빛을 줄것이다. */
        userScore++;
        userScore_span.innerHTML = userScore; /*점수 업데이트*/
        computerScore_span.innerHTML = computerScore;
    
        result_p.innerHTML = `${convertToWord(user)}${smallUserWord} beats ${convertToWord(computer)}${smallCompWord}. You win!🔥`; /*es6문법이다 */
    
        userChoice_div.classList.add('green-glow'); /*이겼을때는 그린색 빛을 주고 싶다) 그리고 시간이 지나면 원래대로 하얗게 돌아오도록 할거다 -> settimeout*/
        setTimeout(() => userChoice_div.classList.remove('green-glow'),500);
    
    }
    
    
    function lose(user, computer){
        const smallUserWord = "user".fontsize(3).sup();/*sup은 맨 위로 올리자는 것 */
        const smallCompWord = "comp".fontsize(3).sup();
        const userChoice_div = document.getElementById(user);/*결과에 따라서 불빛을 줄것이다. */
        computerScore++;
        userScore_span.innerHTML = userScore; /*점수 업데이트*/
        computerScore_span.innerHTML = computerScore;
    
        result_p.innerHTML = `${convertToWord(computer)}${smallCompWord} beats ${convertToWord(computer)}${smallUserWord}. You lose!💩`; 
    
        userChoice_div.classList.add('red-glow'); /*졌을때는 빨간색 빛을 주고 싶다) 그리고 시간이 지나면 원래대로 하얗게 돌아오도록 할거다 -> settimeout*/
        setTimeout(() =>  userChoice_div.classList.remove('red-glow') ,500);
    }
    
    function draw(user, computer){
        const smallUserWord = "user".fontsize(3).sup();/*sup은 맨 위로 올리자는 것 */
        const smallCompWord = "comp".fontsize(3).sup();
        const userChoice_div = document.getElementById(user);/*결과에 따라서 불빛을 줄것이다. */
    
        result_p.innerHTML = `${convertToWord(user)}${smallUserWord} is equal to ${convertToWord(computer)}${smallCompWord}. It was draw!🤟`; 
    
        userChoice_div.classList.add('gray-glow'); /*비겼을때는 회색 빛을 주고 싶다) 그리고 시간이 지나면 원래대로 하얗게 돌아오도록 할거다 -> settimeout*/
        setTimeout(function() { userChoice_div.classList.remove('gray-glow') },500);   /*람다식으로 하면 화살표 추가하고 함수 지우고 {}지워서 한줄에 표현 가능 */
    }
        
    
    function game(userChoice) {
        const computerChoice = getComputerChoice();/*game이 호출될 때마다 컴퓨터에서 랜덤으로 불러낼 것이다. */
        switch(userChoice + computerChoice){ /*둘다 문자다 */
            case "rs":
            case "pr":
            case "sp":
                win(userChoice,computerChoice);
                break;
            case "sr":
            case "rp":
            case "ps":
                lose(userChoice,computerChoice);
                break;
            case "rr":
            case "ss":
            case "pp":
                draw(userChoice,computerChoice);
                break;
        }
    }
    
    function main(){
    
    
        /*버튼을 눌렀을 떄 이벤트를 알려준다.  */
        rock_div.addEventListener('click',() => game("r")); /*얘도 람다식으로 바꾼 것 */
    
        paper_div.addEventListener('click',function(){
            game("p");
        })
    
        scissors_div.addEventListener('click',function(){
            game("s");
        })
    
    }
    
    
    main();

     

     

    사진으로 보면,

    제일 기본 화면

     

     

     

     

     

    마우스를 가져다 대면 동그라미 안의 색이 변한다. 

     

     

    이기면 파란 불이 들어오고 멘트가 변화한다. (스코어도 올라가고 있다.)

     

     

    비기면 멘트변하고 회색불이 들어온다. 

     

     

     

     

    지면 빨간불이 들어오고 멘트가 변한다. (각각의 빛은 모두 시간이 지나면 사라지도록 settimeout을 사용하였다.)

     

     

     

     

     

     

     

     

     

     

Designed by Tistory.