使用HTML5 Canvas创建简单的弹跳球游戏

发布于:2024-10-13 ⋅ 阅读:(117) ⋅ 点赞:(0)

使用HTML5 Canvas创建简单的弹跳球游戏

在本教程中,我们将一步步介绍如何使用HTML5 Canvas和JavaScript创建一个经典的弹跳球游戏。这个游戏是想要入门Web技术游戏开发的初学者的绝佳起点。

游戏概览

我们的弹跳球游戏将具有以下特点:

  • 在屏幕上弹跳的球
  • 玩家控制的挡板
  • 屏幕顶部可被击碎的砖块
  • 分数追踪
  • 胜利和失败条件

设置HTML

首先,让我们创建游戏的基本HTML结构:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>弹跳球游戏</title>
    <style>
        canvas { background: #eee; display: block; margin: 0 auto; }
    </style>
</head>
<body>
    <canvas id="gameCanvas" width="480" height="320"></canvas>
    <script>
        // 我们的游戏代码将放在这里
    </script>
</body>
</html>

设置Canvas

现在,让我们初始化我们的canvas并设置一些基本变量:

const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");

let ballRadius = 10;
let x = canvas.width / 2;
let y = canvas.height - 30;
let dx = 2;
let dy = -2;

const paddleHeight = 10;
const paddleWidth = 75;
let paddleX = (canvas.width - paddleWidth) / 2;

let rightPressed = false;
let leftPressed = false;

const brickRowCount = 3;
const brickColumnCount = 5;
const brickWidth = 75;
const brickHeight = 20;
const brickPadding = 10;
const brickOffsetTop = 30;
const brickOffsetLeft = 30;

let score = 0;

创建砖块

我们将创建一个数组来存储砖块:

const bricks = [];
for (let c = 0; c < brickColumnCount; c++) {
    bricks[c] = [];
    for (let r = 0; r < brickRowCount; r++) {
        bricks[c][r] = { x: 0, y: 0, status: 1 };
    }
}

处理用户输入

让我们添加事件监听器来处理键盘输入:

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);

function keyDownHandler(e) {
    if (e.key === "Right" || e.key === "ArrowRight") {
        rightPressed = true;
    } else if (e.key === "Left" || e.key === "ArrowLeft") {
        leftPressed = true;
    }
}

function keyUpHandler(e) {
    if (e.key === "Right" || e.key === "ArrowRight") {
        rightPressed = false;
    } else if (e.key === "Left" || e.key === "ArrowLeft") {
        leftPressed = false;
    }
}

碰撞检测

我们需要一个函数来检测球和砖块之间的碰撞:

function collisionDetection() {
    for (let c = 0; c < brickColumnCount; c++) {
        for (let r = 0; r < brickRowCount; r++) {
            const b = bricks[c][r];
            if (b.status === 1) {
                if (x > b.x && x < b.x + brickWidth && y > b.y && y < b.y + brickHeight) {
                    dy = -dy;
                    b.status = 0;
                    score++;
                    if (score === brickRowCount * brickColumnCount) {
                        alert("你赢了,恭喜!");
                        document.location.reload();
                    }
                }
            }
        }
    }
}

绘图函数

现在,让我们创建函数来绘制我们的游戏元素:

function drawBall() {
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.closePath();
}

function drawPaddle() {
    ctx.beginPath();
    ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.closePath();
}

function drawBricks() {
    for (let c = 0; c < brickColumnCount; c++) {
        for (let r = 0; r < brickRowCount; r++) {
            if (bricks[c][r].status === 1) {
                const brickX = c * (brickWidth + brickPadding) + brickOffsetLeft;
                const brickY = r * (brickHeight + brickPadding) + brickOffsetTop;
                bricks[c][r].x = brickX;
                bricks[c][r].y = brickY;
                ctx.beginPath();
                ctx.rect(brickX, brickY, brickWidth, brickHeight);
                ctx.fillStyle = "#0095DD";
                ctx.fill();
                ctx.closePath();
            }
        }
    }
}

function drawScore() {
    ctx.font = "16px Arial";
    ctx.fillStyle = "#0095DD";
    ctx.fillText(`分数: ${score}`, 8, 20);
}

主游戏循环

最后,让我们创建我们的主游戏循环:

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawBricks();
    drawBall();
    drawPaddle();
    drawScore();
    collisionDetection();
    
    if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
        dx = -dx;
    }
    if (y + dy < ballRadius) {
        dy = -dy;
    } else if (y + dy > canvas.height - ballRadius) {
        if (x > paddleX && x < paddleX + paddleWidth) {
            dy = -dy;
        } else {
            alert("游戏结束");
            document.location.reload();
        }
    }
    
    if (rightPressed && paddleX < canvas.width - paddleWidth) {
        paddleX += 7;
    } else if (leftPressed && paddleX > 0) {
        paddleX -= 7;
    }
    
    x += dx;
    y += dy;
    
    requestAnimationFrame(draw);
}

draw();

结论

就是这样!我们使用HTML5 Canvas创建了一个简单而有趣的弹跳球游戏。这个游戏展示了游戏开发中的几个关键概念,如:

  1. 游戏循环
  2. 用户输入处理
  3. 碰撞检测
  4. 在canvas上绘图
  5. 分数追踪
  6. 胜利/失败条件

你可以在这个基础游戏上进行扩展,添加如下功能:

  • 多个关卡
  • 道具
  • 音效
  • 不同类型的砖块

祝你编码愉快


网站公告

今日签到

点亮在社区的每一天
去签到