본문 바로가기

풀스택 개발/간단 개발 실습

[JS] 가위바위보 (vs PC)

 

가위, 바위, 보 중 하나를 선택하면 컴퓨터의 무작위 선택과 비교하여 승리, 패배, 무승부 결과를 표시한다.


HTML

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>가위바위보</title>
    <style>
       
    </style>
</head>

<body>
    <div class="blur-box">
        <h1>가위바위보</h1>
        <button onclick="playGame('가위')">가위</button>
        <button onclick="playGame('바위')">바위</button>
        <button onclick="playGame('보')">보</button>
        <p id="result"></p>
    </div>

    <script>
    </script>
</body>

</html>

 

 

<head>: 이 부분은 문서의 메타 정보를 포함하며, 스타일과 스크립트 파일의 링크를 설정하는 곳이다

  • <meta charset="UTF-8">: 문자 인코딩을 UTF-8로 설정하여 다양한 언어를 지원한다.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: 반응형 웹 디자인을 위해 뷰포트를 설정한다.
  • <title>가위바위보</title>: 웹 페이지의 제목을 "가위바위보"로 설정한다.
  • <style>: 문서에 적용할 CSS 스타일을 포함한다
  • <body>: 웹 페이지의 본문을 정의하며, 실제 사용자에게 표시되는 콘텐츠를 포함한다.
    • <div class="blur-box">: 게임의 주요 콘텐츠를 감싸는 블록 요소로, CSS 클래스를 통해 스타일을 적용받는다.
      • <h1>가위바위보</h1>: 페이지 제목으로 "가위바위보"를 표시한다.
      • <button onclick="playGame('가위')">가위</button>: "가위"를 선택할 수 있는 버튼. 클릭 시 playGame 함수가 호출되며, '가위'라는 값을 전달한다.
      • <button onclick="playGame('바위')">바위</button>: "바위"를 선택할 수 있는 버튼. 클릭 시 playGame 함수가 호출되며, '바위'라는 값을 전달한다.
      • <button onclick="playGame('보')">보</button>: "보"를 선택할 수 있는 버튼. 클릭 시 playGame 함수가 호출되며, '보'라는 값을 전달한다
      • <p id="result"></p>: 게임 결과를 표시하는 문단 요소. JavaScript로 결과를 이곳에 출력한다

CSS

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
    overflow: hidden;
}

body {
    font-family: Arial, sans-serif;
    background-image: url('img/일반/dark.jpg');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}

.blur-box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    padding: 20px;
    background-color: rgba(0, 0, 0, 0.6);
    border-radius: 10px;
    color: #FFFFFF;
    max-width: 80%;
    width: 400px;
    text-align: center;
    backdrop-filter: blur(10px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
}

button {
    padding: 10px 20px;
    font-size: 16px;
    background-color: #f3ff44;
    border: none;
    border-radius: 5px;
    color: #000000;
    cursor: pointer;
    transition: background-color 0.3s;
    margin: 5px;
}

button:hover {
    background-color: #32CD32;
}

.result {
    color: red;
}

 

 

  • html, body: 전체 페이지의 기본 스타일을 설정한다. 높이를 100%로 하고, 기본 마진과 패딩을 제거하며, 스크롤을 방지한다
  • body: 폰트를 설정하고, 배경 이미지와 관련된 스타일을 설정한다
  • .blur-box: 게임 UI를 감싸는 블록 요소로, 중앙에 위치시키고 반투명 배경과 블러 효과를 적용한다
  • button: 버튼의 스타일을 정의한다. 배경색, 테두리, 폰트 크기, 호버 효과 등을 설정한다
  • .result: 결과 텍스트의 색상을 빨간색으로 설정한다

JavaScript

function playGame(userChoice) {
    const choices = ['바위', '보', '가위'];
    const computerChoice = choices[Math.floor(Math.random() * 3)];

    let result;
    if (userChoice === computerChoice) {
        result = "다시 도전";
    } else if (
        (userChoice === '바위' && computerChoice === '가위') ||
        (userChoice === '보' && computerChoice === '바위') ||
        (userChoice === '가위' && computerChoice === '보')
    ) {
        result = "승리";
    } else {
        result = "패배";
    }

    document.getElementById('result').innerHTML = `당신: ${userChoice}<br>컴퓨터: ${computerChoice}<br><span class="result">${result}</span>`;
}

 

 

playGame(userChoice): 사용자의 선택을 인자로 받아 게임을 실행하는 함수이다

  • choices 배열에서 컴퓨터의 무작위 선택을 결정한다
  • 사용자와 컴퓨터의 선택을 비교하여 승리, 패배, 무승부를 판별한다
  • 결과를 HTML 문서에 표시한다 (result ID를 가진 <p> 요소에 결과를 출력)

↓ ↓코드 한 번에 보기

더보기
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>가위바위보</title>
    <style>
        html,
        body {
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }

        body {
            font-family: Arial, sans-serif;
            background-image: url('img/일반/dark.jpg');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }

        .blur-box {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            padding: 20px;
            background-color: rgba(0, 0, 0, 0.6);
            border-radius: 10px;
            color: #FFFFFF;
            max-width: 80%;
            width: 400px;
            text-align: center;
            backdrop-filter: blur(10px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
        }

        button {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #f3ff44;
            border: none;
            border-radius: 5px;
            color: #000000;
            cursor: pointer;
            transition: background-color 0.3s;
            margin: 5px;
        }

        button:hover {
            background-color: #32CD32;
        }

        .result {
            color: red;
        }
    </style>
</head>

<body>
    <div class="blur-box">
        <h1>가위바위보</h1>
        <button onclick="playGame('가위')">가위</button>
        <button onclick="playGame('바위')">바위</button>
        <button onclick="playGame('보')">보</button>
        <p id="result"></p>
    </div>

    <script>
        function playGame(userChoice) {
            const choices = ['바위', '보', '가위'];
            const computerChoice = choices[Math.floor(Math.random() * 3)];

            let result;
            if (userChoice === computerChoice) {
                result = "다시 도전";
            } else if (
                (userChoice === '바위' && computerChoice === '가위') ||
                (userChoice === '보' && computerChoice === '바위') ||
                (userChoice === '가위' && computerChoice === '보')
            ) {
                result = "승리";
            } else {
                result = "패배";
            }

            document.getElementById('result').innerHTML = `당신: ${userChoice}<br>컴퓨터: ${computerChoice}<br><span class="result">${result}</span>`;
        }
    </script>
</body>

</html>

'개발 > 간단 개발 실습' 카테고리의 다른 글

유튜브 웹 페이지 실습  (2) 2024.09.09
[React] 영화 서비스  (0) 2024.08.20
[React] 로그인 페이지 구현  (0) 2024.08.13
[JS] 단어 추측  (0) 2024.08.12
[JS] 부딪히며 만들어보는 타자 연습 (Eng Ver.)  (0) 2024.08.07