본문 바로가기

뭐라도 공부해보자!!( 이론 )/Web

HTML, CSS, Javascript 간단하게 정리하기

반응형

 나는 HTML, CSS, Javascript를 다루어본 경험이 거의 없다. 프로그래밍을 해본 적이 없는 것이 아니지만, 대부분이 C/C++, Java, Matlab 정도고, 그마저도 과제를 위해서 사용했던 것들이 대부분이다. 요즘 간단하더라도  하나의 완성된 앱을 짜보는 것이 중요하다는 생각이 계속 들고 있다. 프로그래밍 언어를 알아도 막상 앱을 짤 줄 모르면, 그게 무슨 소용인가? 

 본론으로 돌아와서, 웹에 대해서 공부하기로 마음을 먹었다. 프론트 단에서 자주 사용하는 HTML, CSS, Javascript에 대해서 공부하기로 하였다. 각각에 대해 간단히 설명하자면 "HTML = 도면, CSS = 스타일링에 특화된 HTML, Javascript = 브라우저 단에서 실행할 수 있는 프로그래밍 언어"라고 할 수 있겠다. 이 글에서는 이론적인 부분을 자세하게 설명하기 보다는 그냥 코드에 주석을 달아서 설명하는 식으로 서술할 것이다. 사용한 코드들은 지금 보고있는 영상에서, 실습으로 다루고 있는 텍스트 기반 간단한 RPG 게임에서 사용한 코드이다. 혹시 관심이 있는 사람은 참고하기를 바란다.

 

https://www.youtube.com/watch?v=nu_pCVPKzTk&list=PLmWLfPrGt9OeacznFrhXTwDNfHK0e9dMf&index=21&t=17531s

HTML

<!--html에서 주석을 사용하는 방식-->

<!DOCTYPE html>
<html lang="en" > <!--언어 설정-->

<head> <!--헤더 부분-->
  <meta charset="UTF-8"> <!--브라우저에서 사용하는 글자들이 유니코드 계열임-->
  <title>RPG - Dragon Repeller</title> <!--페이지 제목 : 탭쪽에서 확인가능-->
  <link rel="stylesheet" href="style.css"> <!--CSS 링크-->
</head>

<body> <!--바디 부분 : 주 내용이 들어간다-->
<div id="game"> <!--div tag : 기능 자체는 특별하게 없지만, CSS 등을 사용할 때 구분해 주는 역할을 함, id는 해당 div 구분한 부분에 고유 이름을 붙혀준 것-->
  <div id="stats">
    <span class="stat">XP: <strong><span id="xpText">0</span></strong></span> <!--span : 들여쓰기, class는 묶음 역할-->
    <span class="stat">Health: <strong><span id="healthText">100</span></strong></span> <!--strong : 강조-->
    <span class="stat">Gold: <strong><span id="goldText">50</span></strong></span>
  </div>
  <div id="controls">
    <button id="button1">Go to store</button> <!--button : 말 그대로 버튼을 만들어냄-->
    <button id="button2">Go to cave</button>
    <button id="button3">Fight dragon</button>
  </div>
  <div id="monsterStats">
    <span class="stat">Monster Name: <strong><span id="monsterName"></span></strong></span>
    <span class="stat">Health: <strong><span id="monsterHealth"></span></strong></span>
  </div>
  <div id="text">Welcome to Dragon Repeller. You must defeat the dragon that is preventing people from leaving the town. You are in the town square. Where do you want to go? Use the buttons above.</div>
</div>
<script  src="script.js"></script> <!--script : 어떤 스크립를 사용할 것인가? 자바 스크립트 연동에 사용-->
</body>

</html>

CSS

/*
	적용 범위{
    	적용 내용
    } : 이런 식으로 작성도미
    
    #ID{
    	적용 내용
    }
    
    .CLASS{
    	적용 내용
    }
*/

body {
    background-color: darkblue; //background-color : 배경색
  }
  
  #text {
    background-color: black;
    color: white; //color : 글자색
    padding: 10px; //padding : 영역 안에서 글자와 바깥 테두리와의 간격
  }
  
  #game {
    max-width: 500px; //max-width : 영역의 최대 너비
    max-height: 400px; //max-height : 영역의 최대 높이 
    background-color: lightgray;
    color: white;
    margin: 0 auto; //margin : 여백
    padding: 10px;
  }
  
  #controls {
    border: 1px black solid; //border : 테두리 속성
    padding: 5px;
  }
  
  #stats {
    border: 1px black solid;
    color: black;
    padding: 5px;
  }
  
  #monsterStats {
    display: none;
    border: 1px black solid;
    color: white;
    padding: 5px;
    background-color: red;
  }
  
  .stat {
    padding-right: 10px;
  }

Javascript

//사실 HTML, CSS와 다르게 프로그래밍 언어여서 상당히 익숙함. 특징으로는 높은 자유도를 보여주지만, 
// 그 어떤 버그에 대해서도 책임을 지지 않는다.
//느낌으로 main 같은 함수 안에서 흐름을 가지고 있다기 보다는, 특정 기능이 필요하면 그 필요한 기능을 정의해 떼어쓰는 느낌
//논리 중심으로 볼 것

let xp = 0; // 변수 선언 방법 : let 변수이름 = value;
let health = 100;
let gold = 50;
let currentWeapon = 0;
let fighting;
let monterHealth;
let inventory = ["stick"];

const button1 = document.querySelector("#button1"); : id를 가진 component와 연동 시키는 방법
const button2 = document.querySelector("#button2");
const button3 = document.querySelector("#button3");
const text = document.querySelector("#text");
const xpText = document.querySelector("#xpText");
const healthText = document.querySelector("#healthText");
const goldText = document.querySelector("#goldText");
const monsterStats = document.querySelector("#monsterStats");
const monsterNameText = document.querySelector("#monsterName");
const monsterHealthText = document.querySelector("#monsterHealth");

const weapons = [ //배열의 선언 방법 : C/C++에 비해서 매우 자유로운 편(파이썬의 것과 유사)
	{
		name: "stick",
		power: 5
	},
	{
		name: "dagger",
		power: 30
	},
	{
		name: "claw hammer",
		power: 50
	},
	{
		name: "sword",
		power: 100
	}
];

const monsters = [
  {
    name: "slime",
    level: 2,
    health: 15
  },
  {
    name: "fanged beast",
    level: 8,
    health: 60
  },
  {
    name: "dragon",
    level: 20,
    health: 300
  }
];

const locations = [
    {
        name: "town square",
        "button text": ["Go to store", "Go to cave", "Fight dragon"],
        "button functions": [goStore, goCave, fightDragon],
        text: "You are in the town square. You see a sign that says \"Store.\""
    },
	{
		name: "store",
		"button text": ["Buy 10 health (10 gold)", "Buy weapon (30 gold)", "Go to town square"],
		"button functions": [buyHealth, buyWeapon, goTown],
		text: "You enter the store."
	},
	{
		name: "cave",
		"button text": ["Fight slime", "Fight fanged beast", "Go to town square"],
		"button functions": [fightSlime, fightBeast, goTown],
		text: "You enter the cave. You see some monsters."
	},
	{
		name: "fight",
		"button text": ["Attack", "Dodge", "Run"],
		"button functions": [attack, dodge, goTown],
		text: "You are fighting a monster."
	},
	{
		name: "kill monster",
		"button text": ["Go to town square", "Go to town square", "Go to town square"],
		"button functions": [goTown, goTown, easterEgg],
		text: 'The monster screams "Arg!" as it dies. You gain experience points and find gold.'
	},
	{
		name: "lose",
		"button text": ["REPLAY?", "REPLAY?", "REPLAY?"],
		"button functions": [restart, restart, restart],
		text: "You die. ☠️"
	},
	{
		name: "win",
		"button text": ["REPLAY?", "REPLAY?", "REPLAY?"],
		"button functions": [restart, restart, restart],
		text: "You defeat the dragon! YOU WIN THE GAME! 🎉"
    },
	{
		name: "easter egg",
		"button text": ["2", "8", "Go to town square?"],
		"button functions": [pickTwo, pickEight, goTown],
		text: "You find a secret game. Pick a number above. Ten numbers will be randomly chosen between 0 and 10. If the number you choose matches one of the random numbers, you win!"
	}
]


// initialize buttons
button1.onclick = goStore; //.onclick : 특정 동작이 되었을 때 함수 실행
button2.onclick = goCave;
button3.onclick = fightDragon;

function update(location) { //함수 선언 방식 function name(var){}
    monsterStats.style.display = "none"; //해당 id를 가진 component를 보이지 않게 함
	button1.innerText = location["button text"][0]; // innerText : 해당 component의 내용을 바꿈
	button2.innerText = location["button text"][1];
	button3.innerText = location["button text"][2];
	button1.onclick = location["button functions"][0];
	button2.onclick = location["button functions"][1];
	button3.onclick = location["button functions"][2];
    text.innerText = location.text;    
}

function goTown() {
    update(locations[0]);
}

function goStore() {
    update(locations[1]);
}

function goCave() {
    update(locations[2]);
}

function buyHealth() {
    if (gold >= 10) {
        gold -= 10;
        health += 10;
        goldText.innerText = gold;
    	healthText.innerText = health;       
    } else {
        text.innerText = "You do not have enough gold to buy health.";
    }

}

function buyWeapon() {
    if (currentWeapon < weapons.length - 1) {
    	if (gold >= 30) {
            gold -= 30;
            currentWeapon++;
            goldText.innerText = gold;
            let newWeapon = weapons[currentWeapon].name;
    		text.innerText = "You now have a " + newWeapon + ".";
            inventory.push(newWeapon);
            text.innerText += " In your inventory you have: " + inventory;
    	} else {
    		text.innerText = "You do not have enough gold to buy a weapon.";
    	} 
    } else {
		text.innerText = "You already have the most powerful weapon!";
        button2.innerText = "Sell weapon for 15 gold";
		button2.onclick = sellWeapon;
	}
}

function sellWeapon() {
	if (inventory.length > 1) {
		gold += 15;
		goldText.innerText = gold;
        let currentWeapon = inventory.shift();
        text.innerText = "You sold a " + currentWeapon + ".";
        text.innerText += " In your inventory you have: " + inventory;
	} else {
    	text.innerText = "Don't sell your only weapon!";
  	}
}

function fightSlime() {
	fighting = 0;
	goFight();
}

function fightBeast() {
	fighting = 1;
	goFight();    
}

function fightDragon() {
	fighting = 2;
	goFight();
}

function goFight() {
    update(locations[3]);
    monsterHealth = monsters[fighting].health;
    monsterStats.style.display = "block";
    monsterNameText.innerText = monsters[fighting].name;
	monsterHealthText.innerText = monsterHealth;
}

function attack() {
    text.innerText = "The " + monsters[fighting].name + " attacks.";
    text.innerText += " You attack it with your " + weapons[currentWeapon].name + ".";
    
    if (isMonsterHit()) {
        health -= getMonsterAttackValue(monsters[fighting].level);
    } else {
		text.innerText += " You miss.";
	}
    
    monsterHealth -= weapons[currentWeapon].power + Math.floor(Math.random() * xp) + 1;
	healthText.innerText = health;
	monsterHealthText.innerText = monsterHealth;   
	if (health <= 0) {
		lose();
	} else if (monsterHealth <= 0) {
		fighting === 2 ? winGame() : defeatMonster();
	}

	if (Math.random() <= .1 && inventory.length !== 1) {
        text.innerText += " Your " + inventory.pop() + " breaks.";
        currentWeapon--;
	}
}

function getMonsterAttackValue(level) {
    let hit = (level * 5) - (Math.floor(Math.random() * xp));
    console.log(hit);
    return hit;
}

function isMonsterHit() {
	return Math.random() > .2 || health < 20;
}


function dodge() {
    text.innerText = "You dodge the attack from the " + monsters[fighting].name + ".";
}

function defeatMonster() {
    gold += Math.floor(monsters[fighting].level * 6.7)
    xp += monsters[fighting].level;
    goldText.innerText = gold;
	xpText.innerText = xp;
    update(locations[4]);
}

function lose() {
    update(locations[5]);
}

function winGame() {
  update(locations[6]);
}

function restart() {
	xp = 0;
	health = 100;
	gold = 50;
	currentWeapon = 0;
	inventory = ["stick"];
	goldText.innerText = gold;
	healthText.innerText = health;
	xpText.innerText = xp;
	goTown();
}

function easterEgg() {
	update(locations[7]);
}

function pickTwo() {
 pick(2);
}

function pickEight() {
 pick(8);
}

function pick(guess) {
    let numbers = [];
    while (numbers.length < 10) {
        numbers.push(Math.floor(Math.random() * 11));
    }

    text.innerText = "You picked " + guess + ". Here are the random numbers:\n";

    for (let i = 0; i < 10; i++) {
        text.innerText += numbers[i] + "\n";
    }

    if (numbers.indexOf(guess) !== -1) {
        text.innerText += "Right! You win 20 gold!"
        gold += 20;
        goldText.innerText = gold;
    } else {
        text.innerText += "Wrong! You lose 10 health!"
        health -= 10;
        healthText.innerText = health
        if (health <= 0) {
          lose();
        }
    }
}
반응형