JAVA SCRIPT
펭귄폭탄마 게임 만들기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>펭귄폭탄마</title>
<style>
.box {
width: 500px;
height: 500px;
border: 2px solid black;
background-image: url("../images/penguin-game/village.png");
overflow: hidden;
}
img {
width: 50px;
}
</style>
</head>
<body>
<h1>펭귄폭탄마</h1>
<div class="box" id="box">
<img src="../images/penguin-game/penguin.png" id="peng">
</div>
<script src="js/펭귄폭탄마_teacher.js"></script>
</body>
</html>
let xindex = 0;
let yindex = 0;
document.addEventListener("keydown", function(e) {
console.log("누르는중" + e.key);
const peng = document.getElementById("peng");
const boom = document.createElement("img");
if(e.key == "ArrowRight") {
xindex += 10; // 오른쪽 방향키 누를 때마다 누적
peng.style.transform = `translate3d(${xindex}px, ${yindex}px, 0)`;
} else if(e.key == "ArrowLeft") {
xindex -= 10;
peng.style.transform = `translate3d(${xindex}px, ${yindex}px, 0`;
} else if(e.key == "ArrowDown") {
yindex += 10;
peng.style.transform = `translate3d(${xindex}px, ${yindex}px, 0)`;
} else if(e.key == "ArrowUp") {
yindex -= 10;
peng.style.transform = `translate3d(${xindex}px, ${yindex}px, 0)`;
} else if(e.key == 'x') {
const box = document.getElementById("box");
boom.setAttribute("src", "../images/penguin-game/boom.png");
boom.style.transform = `translate3d(${xindex}px, ${yindex}px, 0)`;
boom.style.position = "absolute";
box.append(boom);
}
setTimeout(function() {
boom.setAttribute("src", "../images/penguin-game/boom2.png");
}, 2000);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>15_함수</title>
</head>
<body>
<h1>기본적인 함수의 선언, 정의, 호출</h1>
<pre>
function 함수명([매개변수]) { // 함수 선언
// 함수 정의
}
함수명(); // 함수 호출
</pre>
<!-- 함수 호출-->
<div id="btn1" onclick="clickCount(this)">0</div>
<hr>
<h1>익명 함수 (이름이 없는 함수)</h1>
<pre>
function([매개변수]) { // 함수 선언
// 함수 정의
}
- 이름이 없는 함수이기 때문에 필요할 때 마음대로 호출 불가능
- 이벤트 핸들러와 같이 바로 동작하는 함수가 필요한 경우 사용
</pre>
<hr>
<h1>즉시 실행 함수</h1>
<pre>
(function([매개변수]) {
// 함수 정의
})();
- 익명 함수의 한 종류로써
함수가 정의되자마자 바로 실행되는 함수
</pre>
<hr>
<!-- 제일 중요 ! -->
<h1>화살표 함수</h1>
<pre>
익명함수의 표현식을 간단히 표현한 표기법 (es6)
작성법 1. 기본 형태 ([매개변수]) => { 함수정의 }
익명함수 : function() {}
화살표함수 : () => {}
익명함수 : function(num) { return num * 2 }
화살표함수 : (num) => { return num * 2 }
작성법 2. 매개변수가 "하나" 인 경우 () 생략 가능
익명함수 : function(e) { e,target... }
화살표함수 : e => { e,target... }
* 매개변수가 없을 경우는 "무조건" () 작성
작성법 3. 함수 정의 부분이 return [식 또는 값] 으로만 작성되어 있는 경우
{}, return 생략 가능
익명함수 : function(num) { return num * 10 }
화살표함수 : num => num * 10;
** return 되는 값이 객체(object)인 경우는 불가능
num => {price: num*1000, n:1000} (X)
num => { return {price: num*1000, n:1000} }
</pre>
<button id="btn2-1">기본 형태</button>
<button id="btn2-2">매개변수 1개</button>
<button id="btn2-3">{}, return 생략</button>
<button id="btn2-4">this 사용 불가</button>
<script src="js/15_함수.js"></script>
</body>
</html>
// 기본 함수
function clickCount(btn) { // 함수 선언
btn.innerText = Number(btn.innerText) + 1; // 함수 정의
}
document.addEventListener("click", function() {
// 익명함수
})
// 기본 함수
function test1() {
console.log("기본함수");
}
test1(); // 호출
// 즉시실행 함수
(function() {
console.log("즉시 실행 함수");
})();
// --------------------------------------------------------
// 화살표 함수(Arrow Function)
// 1. 기본형태 : () => {}
document.getElementById("btn2-1").addEventListener("click", () => {
alert("화살표 함수 기본 형태입니다"); // alert창에 화살표 함수 기본 형태입니다 내용 뜸.
});
// 2. 매개변수 1개 : 매개변수 => {}
document.getElementById("btn2-2").addEventListener("click", e => {
e.target.style.backgroundColor = "yellow";
})
// 3. {}, return 생략
document.getElementById("btn2-3").addEventListener("click", () => {
// 익명 함수
printConsole( function(num) {return num * 10} )
// 화살표 함수
printConsole( num => num * 5 );
})
function printConsole(fn) { // 매개변수로 함수가 전달됨
console.log( fn(2) ); // 20 // 10
}
// this 사용 불가
// 1) 익명함수는 this 사용 가능
document.getElementById("btn2-4").addEventListener("click", function() {
this.style.backgroundColor = "red";
})
// 2) 화살표함수는 this 사용 불가
document.getElementById("btn2-4").addEventListener("click", (e) => {
// 화살표 함수에서 this는 창 자체를 나타내는 객체(window)이다.
console.log(this);
e.target.style.color = "white";
})
0 클릭 시, 숫자가 1씩 증가
기본 형태 버튼 클릭 시, alert 창 뜸
매개변수 1개 버튼 클릭 시, 노란색으로 변경
{}, return 생략 버튼 클릭 시,
this 사용 불가 버튼 클릭 시,
랜덤 로또 번호 생성하기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>로또생성기_teacher</title>
<style>
.lottobox {
display: flex;
justify-content: center;
align-items: center;
}
.lotto {
width: 40px;
height: 40px;
border: 1px solid black;
border-radius: 50%;
padding: 20px;
font-size: 30px;
text-align: center;
}
#createLotto {
margin-top: 20px;
margin-left: 900px;
}
</style>
</head>
<body>
<div id="container" class="lottobox">
<div class="lotto"></div>
<div class="lotto"></div>
<div class="lotto"></div>
<div class="lotto"></div>
<div class="lotto"></div>
<div class="lotto"></div>
</div>
<button id="createLotto">로또 번호 생성</button>
<script>
document.getElementById("createLotto").addEventListener("click", () => {
// #container 자식 div 6개 선택
const numbers = document.querySelectorAll("#container > div");
// 로또 번호를 저장할 배열 선언
const lotto = [];
while(lotto.length < 6) {
// 1~45 난수 생성
const random = Math.floor( Math.random() * 45 + 1 );
// 생성된 난수가 배열에 있는지 검사
if( lotto.indexOf(random) == -1 ) {
lotto.push(random);
} // 중복 X
}
// lotto에 저장된 난수 오름차순 정렬
lotto.sort( function(a,b) { return a-b; } );
// numbers의 인덱스별로 lotto 인덱스에 저장된 값 출력
for(let i = 0; i < lotto.length; i++) {
numbers[i].innerText = lotto[i];
}
});
</script>
</body>
</html>
[ 결과 ]