본문 바로가기

자바스크립트

웹 게임을 만들며 배우는 자바스크립트 예제2

inf.run/TAmq

 

웹 게임을 만들며 배우는 자바스크립트 - 인프런

본 강의에서는 자바스크립트를 활용해 프로그래밍하는 연습을 할 것입니다. 웹 게임인 구구단을 시작으로 끝말잇기, 숫자 야구, 틱택토, 로또 추첨기, 가위바위보, 지뢰 찾기, 카드 짝맞추기 게�

www.inflearn.com

틱택토

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>틱택토</title>
        <style>
            td {
                border: 1px solid black;
                width: 50px;
                height: 50px;
                text-align: center;
                font-weight: bold;
                font-size: 35px;
            }
        </style>
    </head>
    <body>
        <script src="틱택토.js"></script>
    </body>
</html>
var body = document.body;
var table = document.createElement('table');
table.style.border=1;
var cells = [];
var rows = [];
var turn = 'X';
var result = document.createElement('div');



var clickEvent = function (e) {

    var clickRow = rows.indexOf(e.target.parentNode);
    var clickCell = cells[clickRow].indexOf(e.target);
    console.log(clickRow, clickCell);

    if (cells[clickRow][clickCell].textContent != '') {
    } else {
        cells[clickRow][clickCell].textContent = turn;
    }

    var full = false;
    if (cells[clickRow][0].textContent === turn 
        && cells[clickRow][1].textContent === turn
        && cells[clickRow][2].textContent === turn ) {
            full = true;
        } 

        if (cells[0][clickCell].textContent === turn 
            && cells[1][clickCell].textContent === turn
            && cells[2][clickCell].textContent === turn ) {
                full = true;
            } 

    if (clickRow - clickCell === 0) {
        if (cells[0][0].textContent === turn 
            && cells[1][1].textContent === turn
            && cells[2][2].textContent === turn ) {
                full = true;
            } 
    }    
    
    if (Math.abs(clickRow - clickCell === 2)) {
        if (cells[0][2].textContent === turn 
            && cells[1][1].textContent === turn
            && cells[2][0].textContent === turn ) {
                full = true;
            } 
    }



    if (full == true) {
        result.textContent = turn + '님의 승리';

        turn = 'X';
        cells.forEach(function (row) {
            row.forEach(function (cell) {
                cell.textContent = '';
            });
        });
    } else {
        if (turn == 'X') {
            turn = 'O';
        } else {
            turn = 'X';
        }
    }
    
}


for (var i = 1; i <= 3; i++) {
    var row = document.createElement('tr');
    rows.push(row);
    cells.push([]);
    for (var j = 1; j <= 3; j++) {
        var cell = document.createElement('td');
        cell.addEventListener('click', clickEvent);
        cells[i - 1].push(cell);
        row.appendChild(cell);
    }
    table.appendChild(row);
}
body.appendChild(table);
body.appendChild(result);

로또

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>로또</title>
        <style>
            
        </style>
    <body>
        <div>당첨 숫자</div>
        <div id="result"></div>
        <div>보너스!</div>
        <div name="bonus"></div>
        <script src="로또.Js"></script>
    </body>
</html>
var candicates = Array(45)
    .fill()
    .map(function (item, index) {
    return index + 1;
    });
console.log(candicates);

var shuffle = [];
while (candicates.length > 0) {
    var move = candicates.splice(Math.floor(Math.random() * candicates.length), 1)[0];
    shuffle.push(move);
}

console.log(shuffle);

var bonus = shuffle[shuffle.length - 1];
var choicesNumbers = shuffle.slice(0, 6).sort(function (p, c) {return p - c;});
console.log(choicesNumbers, bonus);


var result = document.getElementById('result');

function ballColor(number, result) {
    var ball = document.createElement('div');
    ball.textContent = number;
    ball.style.display='inline-block';
    ball.style.border = '1px solid black';
    ball.style.borderRadius = '10px';
    ball.style.width = '20px';
    ball.style.height = '20px';
    ball.style.textAlign = 'center';
    ball.style.marginRight = '10px';
    ball.style.fontSize = '12px';
    ball.className = '공아이디' + number;
    var backColor;
    if (number <= 10) {
        backColor = 'red';
    } else if (number <= 20) {
        backColor = 'orange';
    } else if (number <= 30) {
        backColor = 'yellow';
    } else if (number <= 40) {
        backColor = 'blue';
    } else {
        backColor = 'green';
    }
    ball.style.background = backColor;
    result.appendChild(ball);
}

setTimeout(function a(){
    ballColor(choicesNumbers[0], result);
}, 1000);
setTimeout(function a(){
    ballColor(choicesNumbers[1], result);
}, 2000);
setTimeout(function a(){
    ballColor(choicesNumbers[2], result);
}, 3000)
setTimeout(function a(){
    ballColor(choicesNumbers[3], result);
}, 4000);
setTimeout(function a(){
    ballColor(choicesNumbers[4], result);
}, 5000);
setTimeout(function a(){
    ballColor(choicesNumbers[5], result);
}, 6000);
setTimeout(function a(){
    var bonusBallDiv = document.getElementsByName('bonus')[0];
    ballColor(bonus, bonusBallDiv);
}, 7000);


가위바위보

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>가위바위보</title>
        <style>
            #computer {
                width: 150px;
                height: 243px;
                background: url('https://en.pimg.jp/023/182/267/1/23182267.jpg')
            }
        </style>
    </head>
    <body>
        <div id="computer">
        </div>
        <div>
            <button id="rock" class='btn'>바위</button>
            <button id="scissor" class='btn'>가위</button>
            <button id="paper" class='btn'>보</button>
        </div>
        <script src="가위바위보.js"></script>
    </body>
</html>
let dot = 0;
var 가위바위보 = { // 딕셔너리 자료구조
    바위 : '0',
    가위: '-142px',
    보: '-284px',
};

function choice(dot) {
    return Object.entries(가위바위보).find(function(y) {
        return y[1] === dot;
    })[0];
}

var score = {
    가위:1,
    바위: 0,
    보: -1,
}

var interval1 ;
function intervalMaker () {
    interval1 = setInterval(function () {
    if (dot == 가위바위보.바위) {
        dot = 가위바위보.가위;
    } else if (dot == 가위바위보.가위) {
        dot = 가위바위보.보;
    } else {
        dot = 가위바위보.바위;
    }
    document.querySelector('#computer').style.background = 
    'url(https://en.pimg.jp/023/182/267/1/23182267.jpg) ' + dot + ' 0';
}, 100)};

intervalMaker();

document.querySelectorAll('.btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        clearInterval(interval1);
        setTimeout(function() {
            intervalMaker();
        }, 1000);
        var me = this.textContent;
        var computerDot = choice(dot);
        var meScore = score[me];
        var computerScore = score[computerDot];
        var diffScore = meScore - computerScore;
        console.log(this.textContent, computerDot);
        var computerScore = score[computerDot];
        if(diffScore === 0) {
            console.log("비겼음");
        } else if ([-1, 2].includes(diffScore)){
            console.log("이겼음");
        } else {
            console.log("졌음");
        }
    });
});