[JavaScript] 농구게임 만들기

2022. 6. 21. 17:40·개발/html, css, js
728x90
반응형

jason 값 가져오기

 

jason

{   
    "player":{
        "user":{
            "id":"윤철이",
            "name" :"이지니"
        },
        "user2":{
            "id":"윤철이2",
            "name" :"이지니2"
        },
        "user3":{
            "id":"윤철이3",
            "name" :"이지니3"
        },
        "user4":{
            "id":"윤철이4",
            "name" :"이지니4"
        }
    },
    "class":{
        "1":40,
        "2":30,
        "3":20,
        "4":10,
        "5":5
    }
}

 

JS

 

function one(){
    //2초뒤 콘솔
    setTimeout(()=>{
    console.log("첫번째");
    },2000);
}

function two(){
    console.log("두번째");
}

function three(){
    console.log("세번째");
}


// 순서 첫번째가 2초뒤에 나오고
// 두번째, 세번째가 먼저 나옴

one();
two();
three();

function use(){
    //Promise 동적으로 생성
    return new Promise((res,rej)=>{
        //setTimeout 실행하고 1초뒤에
        setTimeout(()=>{
        // console 첫번째
            console.log("끝남");
            one();
            res();
        },1000)
    })
}

use().then(function(){
    //then 결과까지 기다리고
    //two() 함수 실행
    //three() 함수 실행
    two();
    three();
})

//rej 일때
function use(){
    //Promise 동적으로 생성
    return new Promise((res,rej)=>{
        //setTimeout 실행하고 1초뒤에
        setTimeout(()=>{
        // console 첫번째
            console.log("끝남");
            one();
            rej();
        },1000)
    })
}

use().then(function(){
    //then 결과까지 기다리고
    //two() 함수 실행
    //three() 함수 실행
    two();
    three();
}).catch(function (){
    console.log("난 rej")
})

function use(data){
    //Promise 동적으로 생성
    return new Promise((res,rej)=>{
       
        setTimeout(()=>{
        if (data === 1){
            res();
        }
        else if(data === -1){
            console.log("끝남");
            one();
            rej();
        }
        },1000)
    })
}

use(-1).then(function(){
    //then 결과까지 기다리고
    //two() 함수 실행
    //three() 함수 실행
    two();
    three();
    console.log("난 res(성공)")
}).catch(function (){
    console.log("난 rej(실패)")
})

//json 파일을 데이터처럼 가져와 보기
//이제 데이터를 저장된 것을 가져와 볼거야

function loadJson(){
    // fetch 경로에 데이터를 요청한다 기본적으로 method는
    // get방식(가져오는 방식,읽기)과 post방식(참조도 되고 쓰기 및 수정도 가능)
    // 비동기 요청 방식이다.
    return fetch("01.index.json")
    // 요청을 하는데 json방식으로 받는다
    .then((res)=>res.json())
    // player 키값의 객체를 가져옴
    .then((json)=>json.player)
    // catch 실패했을때
    .catch((rej)=>{});
}

loadJson().then((user)=>{console.log(user)});

function loadJson2(){
    return fetch("01.index.json")
    .then((res)=>res.json())
    .then((json=> json.class))
    .catch((res)=> {})
}

loadJson2().then((result)=>{console.log(result)})

 

농구게임

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="02.css">
</head>
<body>
    
    <div class="scoreBoard">
        <div class="scoreboard inner">
            <span>남은 횟수</span>
            <span id="shots">10</span>
        </div>
        <div class="flex">
            <div class="play-score">
                <div class="pos">
                    <div class="score-name">박태수</div>
                    <div class="computer-score">0</div>
                </div>
            </div>
            <div class="play-score">
                <div class="pos">
                    <div class="score-name">김경환</div>
                    <div class="player-score">0</div>
                </div>
            </div>
        </div>
        <div>
            <p id="text">경환이 차례</p>
            <button id="computer">박태수 슛</button>
            <!-- disabled : 어트리뷰트 -->
            <button id="user">김경환 슛</button>
        </div>
    </div>
</body>
<script src="02.js"></script>
</html>

css

.scoreBoard{
    width: 100%;
    height: 100vh;
}
.scoreboard.inner{
    background-color: antiquewhite;
    width: 100%;
    height: 60px;
    text-align: center;
    font-size: 20px;
}
/* 바로 밑에 span  : > */
/* :first-child : 첫번째 요소만 */
/* :last-child 마지막요소만 */
/* :nth-of-type(여기에 index) index번째 요소만 */
.scoreboard.inner > span {
    display: block;
}

.play-score{
    width: 50%;
    height: 600px;
    background-color: aliceblue;
    /* 기준 */
    position: relative;
}

/* play-score의 첫번째 요소 */
.play-score:first-child{
    border-right: 1px solid red;
}


.pos{
    /* play-score 기준으로 이동 */
    position: absolute;
    top: 50%;
    left: 50%;
    /* transform : translate (x포지션, y포지션) */
    transform: translate(-50%,-50%);
    background-color: bisque;
    width: 200px;
    height: 200px;
}

.score-name{
    font-size: 25px;
    text-align: center;
    margin-top: 50px;
}

.computer-score,.player-score{
    font-size: 20px;
    text-align: center;
    margin-top: 30px;
}

/* 세로 정렬 */
.flex{
    display: flex;
}

js

//컴퓨터 score
let comScore = 0;
//플레이어 score
let userScore = 0;

let turn = false;

//게임의 횟수
let gameCount = 10;

computer.disabled = true;
function usershoot(){ 
    //turn이 true면 return으로 함수 종료
    if(turn) return;
    let shootType = Math.random() < 0.5 ? 2 : 3;
    if(shootType === 2){

        if(Math.random()<0.5){
            console.log("user : 2점 슛 성공")
            userScoreUpdate(shootType);
        }
        else{
            console.log("user : 2점 슛 실패")
        }
    }
    else {

        if(Math.random()<0.3){
            console.log("user : 3점 슛 성공")
            userScoreUpdate(shootType);
        }
        else{
            console.log("user : 3점 슛 실패")
        }

    }
    textUpdate("태수");
    //다 동착후 turn true로
    turn = true;
}

function comshoot(){
    let shootType = Math.random() < 0.5 ? 2 : 3;
    //turn이 false면 return문으로 함수 종료
    if(!turn) return;
    if(shootType === 2){

        if(Math.random()<0.5){
            console.log("com : 2점 슛 성공")
            comScoreUpdate(shootType);
        }
        else{
            console.log("com : 2점 슛 실패")
        }
    }
    else {

        if(Math.random()<0.3){
            console.log("com : 3점 슛 성공")
            comScoreUpdate(shootType);
        }
        else{
            console.log("com : 3점 슛 실패")
        }

    }
    
    textUpdate("경환")
    gameCounting();
    turn = false;

}

//요소 선택자 
//document.querySelector("요소의 클래스나 아이디 아니면 어트리뷰트 선택자")
//ID는 고유, 하나만 존재하기 때문에 user만 써줘도됨

// document.querySelector("#user").addEventListener 이벤트 함수 설정
// console.log(user);
// console.log(document.querySelector("#user")); 둘이 똑같음

//addEventListener 첫 매개변수는 이벤트 타입을 문자열로, 두번째 매개변수는 이벤트 작동시 실행할 함수
user.addEventListener("click",function(){
    //user를 click하면 실행되는 곳
    usershoot();
})

computer.addEventListener("click",function(){
    comshoot();
})

function userScoreUpdate(addScore){
    //userScore에 addScore값을 증가 시킨다.
    userScore += addScore;
    document.querySelector(".player-score").innerHTML = userScore;
}


function comScoreUpdate(addScore){
    comScore += addScore;
    document.querySelector(".computer-score").innerHTML = comScore;
}

//text를 갱신하는 함수
function textUpdate(name){
    text.innerHTML = `${name}의 차례`;
    switch (name) {
        case "경환":
            computer.disabled = true;
            user.disabled = false;
            break;

        case "태수":
            computer.disabled = false;
            user.disabled = true;
            break;
        default :
            break;

    }
}

function gameCounting(){
    gameCount--;
    
    shots.innerHTML = gameCount;
    //게임카운트 감소
    if(gameCount === 0){
        //게임의 승패를 보여주고
        if(comScore > userScore){
            text.innerHTML = "태수의 승리";
        }
        else if(userScore > comScore){
            text.innerHTML = "경환의 승리";
        }
        else{
            text.innerHTML = "무승부";
        }
    computer.disabled = true;
    user.disabled = true;
    }
    
}
728x90
반응형

'개발 > html, css, js' 카테고리의 다른 글

[30일 챌린지 Day-3] input값 적용하기  (0) 2022.07.25
[30일 챌린지 Day-2] 시계 만들기  (1) 2022.07.25
[HTML, JavaScript] 정규표현식  (0) 2022.06.21
[JS, HTML, CSS] 이벤트  (0) 2022.06.17
[HTML, CSS] 이벤트리스너  (0) 2022.06.09
'개발/html, css, js' 카테고리의 다른 글
  • [30일 챌린지 Day-3] input값 적용하기
  • [30일 챌린지 Day-2] 시계 만들기
  • [HTML, JavaScript] 정규표현식
  • [JS, HTML, CSS] 이벤트
TeTedo.
TeTedo.
  • TeTedo.
    TeTedo 개발 일기
    TeTedo.
  • 전체
    오늘
    어제
    • 분류 전체보기 (319)
      • 개발 (274)
        • Article (4)
        • 정리 (21)
        • Spring Boot (17)
        • JPA (2)
        • JAVA (6)
        • Database (4)
        • 자료구조 (11)
        • 알고리즘 (32)
        • React (20)
        • Docker (10)
        • node.js (18)
        • Devops (11)
        • Linux (4)
        • TypeScript (3)
        • Go (10)
        • HyperLedger (4)
        • BlockChain (43)
        • html, css, js (48)
        • CS (3)
        • AWS (3)
      • 모아두고 나중에 쓰기 (3)
      • 팀프로젝트 (18)
        • SNS(키보드워리어) (9)
        • close_sea (9)
      • 개인프로젝트 (1)
        • Around Flavor (1)
        • CHAM (13)
        • ethFruitShop (5)
      • 독서 (0)
        • 스프링부트와 AWS로 혼자 구현하는 웹 서비스 (0)
  • 블로그 메뉴

    • 홈
    • 개발일기
    • CS
    • 실습
    • 코딩테스트
    • 웹
    • Go
    • node.js
    • 팀플
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    js
    CSS
    프로그래머스
    하이퍼레저
    html
    node
    erc20
    명령어
    React
    블록체인
    도커
    mysql
    nodejs
    컨테이너
    30일챌린지
    ERC721
    go
    go언어
    30일 챌린지
    node.js
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
TeTedo.
[JavaScript] 농구게임 만들기
상단으로

티스토리툴바