//캔버스 세팅
let canvas;
let ctx;
canvas = document.createElement("canvas")
ctx = canvas.getContext("2d")
canvas.width = 400;
canvas.height = 700;
document.body.appendChild(canvas);
let backgroundImage, starshipImage, bulletImage, enemyImage;
function loadImage(){
backgroundImage = new Image();
backgroundImage.src = "images/space.jpg";
starshipImage = new Image();
starshipImage.src = "images/spaceship.png";
bulletImage = new Image();
bulletImage.src = "images/bullet.png";
enemyImage = new Image();
enemyImage.src = "images/enemy.png";
}
// 우주선 좌표
let spaceshipX = canvas.width/2-32;
let spaceshipY = canvas.height-64;
// 총알 좌표
let bulletList = []; // 총알들을 저장하는 리스트
// let bulletListOut = bulletList.shift(); // 한번씩 발사한 총알들 삭제
let gameOver = false // true이면 게임이 끝남, false이면 게임이 진행
// 방향키 누르면 이동
let keysDown={};
function setupKeyboardListener(){
document.addEventListener("keydown", function(event){
//console.log("무슨 키가 눌렷니", event.key)
keysDown[event.key] = true;
//console.log("무슨 키가 눌렷니2", keysDown);
});
document.addEventListener("keyup", function(event){
delete keysDown[event.key];
//console.log("키다운객체에 들어간 값", keysDown);
if(event.key == " "){ //총알 생성
createBullet();
}
});
}
//적군 만들기
// x,y, init, update 진행
// 적군과 총알이 만나면 우주선이 사라진다 점수 1점
//총알만들기
//1. 스페이스바를 누르면 총알 발사
//2. 총알 발사 = 총알의 y값 -- . x값은 스페이스 바를 누를때 우주선의 위치
//3. 발사된 총알들은 총알 배열에 저장을 한다.
//4. 총알들은 x,y 좌표값이 있어야 한다.
//5. 총알 배열을 가지고 render 그려준다.
/* function newEnemy(){
let e = new Enemy();
e.init();
}
*/
function update(){
if( 'ArrowRight' in keysDown){
spaceshipX += 5;
} // 우주선 오른쪽 눌렀을시 속도
if( 'ArrowLeft' in keysDown){
spaceshipX -= 5;
} // 우주선 왼쪽 눌렀을시 속도
if( 'ArrowUp' in keysDown){
spaceshipY -= 5;
} // 우주선 위쪽 눌렀을시 속도
if( 'ArrowDown' in keysDown){
spaceshipY += 5;
} // 우주선 아래쪽 눌렀을시 속도
if(spaceshipY <= 0) {
spaceshipY = 0;
} // 우주선 화면 밖으로 나가지 않도록 위쪽 고정
if(spaceshipY >= canvas.height-64){
spaceshipY=canvas.height-64;
} // 우주선 화면 밖으로 나가지 않도록 아래쪽 고정
if(spaceshipX <= 0) {
spaceshipX = 0;
} // 우주선 화면 밖으로 나가지 않도록 왼쪽 고정
if(spaceshipX >= canvas.width-64){
spaceshipX=canvas.width-64;
} // 우주선 화면 밖으로 나가지 않도록 오른쪽 고정
//총알의 y좌표 업데이트하는 함수 호출
for(let z=0; z<bulletList.length; z++){
if(bulletList[z].alive){
bulletList[z].update();
bulletList[z].meet();
}
}
//적의 y좌표 업데이트하는 함수 호출
for(let k=0; k<enemyList.length; k++){
enemyList[k].update();
}
}
function createEnemy(){
const interval = setInterval(function(){
let e = new Enemy(); // 새로운 적 생성
e.init();
},1000); // setInterval(호출하고 싶은 함수, 시간)
}
let score = 0;
function createBullet(){
//console.log("총알생성");
let b = new Bullet(); // 총알 하나 생성
b.init();
}
function Bullet(){
this.x = 0;
this.y = 0;
this.init = function(){
this.x = spaceshipX + 20;
this.y = spaceshipY;
this.alive = true; // true 이면 살아있는 총알, false이면 만난 총알
bulletList.push(this);
};
this.update = function(){
/* if(this.y <= -15){
bulletList.shift();
//console.log("안에 들어있는 총알", bulletList);
}
else */
this.y -= 7;
//console.log("새로운 총알", bulletList);
};
this.meet = function(){
for(q=0; q<enemyList.length; q++){
if(this.y <= enemyList[q].y &&
this.x >= enemyList[q].x &&
this.x <= enemyList[q].x + 40){
score++;
this.alive = false;
enemyList.splice(q,1);
console.log("점수", score);
}
}
}
}
function enemyRandomValue(min, max){
let randomNum = Math.floor(Math.random()*(max - min + 1)); // 0~1 사이 랜덤한 값을 반환
return randomNum;
}
let enemyList = [];
function Enemy(){
this.x = 0;
this.y = 0;
this.init = function(){
this.x = enemyRandomValue(0, canvas.width - 48);
this.y = 0;
enemyList.push(this);
};
this.update = function(){
this.y += 2;
if(this.y >= canvas.height-48){
gameOver = true;
console.log("게임오버");
}
};
}
function render(){
// ctx.clearRect(0, 0, canvas.width, canvas.height); // 그림 초기화
ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
ctx.drawImage(starshipImage, spaceshipX, spaceshipY);
ctx.fillText(`Score:${score}`, 20, 20);
ctx.fillstyle = "yellow";
ctx.font = "20px Arial";
for(let i=0; i<bulletList.length; i++){
if(bulletList[i].alive){
ctx.drawImage(bulletImage,bulletList[i].x, bulletList[i].y);
}
}
for(let j=0; j<enemyList.length; j++){
ctx.drawImage(enemyImage,enemyList[j].x, enemyList[j].y);
}
}
function main(){
if(!gameOver){
update(); // 좌표값을 업데이트
render(); // 그려주기
//bulletDisappear();
requestAnimationFrame(main);
}
}
/*function bulletDisappear() // 화면 밖으로 총알이 나갈경우 제외
{
if(Bullet.y <= -12){ //총알의 y좌표 업데이트하는 함수 호출
cancelAnimationFrame(main);
}
else
//총알의 y좌표 업데이트하는 함수 호출
for(let z=0; z<bulletList.length; z++){
bulletList[z].update();
}
}*/
loadImage();
setupKeyboardListener();
createEnemy();
main();