Js의 캔버스, 그리드를 이용해 그림을 그려, 퐁을 구현해 보자.
캔버스를 문서에 생성.
// 캔버스 생성.
function createCanvas() {
canvas.width = width;
canvas.height = height;
body.appendChild(canvas);
renderCanvas();
}
캔버스 배경.
context.fillStyle = 'black';
context.fillRect(0,0,width,height);
막대기 색
context.fillStyle = 'white';
플레이어 막대기 (하단)
context.fillRect(paddleBottomX, height - 20, paddleWidth, paddleHeight);
컴퓨터 막대기 (상단)
context.fillRect(paddleTopX, 10, paddleWidth, paddleHeight);
중앙라인(점선)
context.beginPath();
context.setLineDash([4]);
context.moveTo(0, 350);
context.lineTo(500, 350);
context.strokeStyle = 'grey';
context.stroke();
canvas.addEventListener('mousemove', (e) => {
playerMoved = true;
// Compensate for canvas being centered
paddleBottomX = e.clientX - canvasPosition - paddleDiff;
if (paddleBottomX < paddleDiff) {
paddleBottomX = 0;
}
if (paddleBottomX > width - paddleWidth) {
paddleBottomX = width - paddleWidth;
}
// 마우스 숨기기.
canvas.style.cursor = 'none';
});
// 둘중 하나가 승리점수를 얻은지 확인하고 얻으면 게임 종료.
function gameOver() {
if (playerScore === winningScore || computerScore === winningScore) {
isGameOver = true;
// 승자 결정.
const winner = (playerScore === winningScore) ? 'Player 1' : 'Computer';
showGameOverEl(winner);
}
}
게임오버 화면과 재도전.
function showGameOverEl(winner) {
// 캔버스 숨기고
canvas.hidden = true;
// Container
gameOverEl.textContent = '';
gameOverEl.classList.add('game-over-container');
// 제목
const title = document.createElement('h1');
title.textContent = `${winner} 이겼습니다!!`;
// 재도전 버튼
const playAgainBtn = document.createElement('button');
playAgainBtn.setAttribute('onclick', 'startGame()');
playAgainBtn.textContent = '다시 플레이 하시겠습니까?';
// 할당.
gameOverEl.append(title, playAgainBtn);
body.appendChild(gameOverEl);
}