Web前端--HTML+CSS+JS实现圣诞抓礼物小游戏_snowflakes js,前端framework视频

48 阅读2分钟

效果动图演示:

查看完整视频

 代码实现:

JS部分:

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    elfImage = document.getElementById("elf");
greenGiftImage = document.getElementById("green_gift");
redGiftImage = document.getElementById("red_gift");
blueGiftImage = document.getElementById("blue_gift");
bombImage = document.getElementById("bomb");
bangImage = document.getElementById("bang");

var x = canvas.width / 2;
var y = canvas.height - 30;
var dx = 2;
var dy = -2;
const elfHeight = 70;
const elfWidth = 55;
var elfX = (canvas.width - elfWidth) / 2;
const elfSpeed = 10;
var rightPressed = false;
var leftPressed = false;
var spacePressed = false;
var spawnInterval;
var spawnTimer = 50;
var gifts = [];
var maxGift = 0;
const giftWidth = 40;
const giftHeight = 40;
var timer = 0;
var giftRotation = 0;
const TO_RADIANS = Math.PI / 180;
var score = 0;
var health = 3;
const bombChance = 5;
var elfRotation = 0;
var bangX;
var bangTime;
var snowHeight = 6;
var spawnTimeChangeInterval = 3000;
var titleColours = [];

// snowflake stuff
var snowflakes = [];
const maxSnowflakes = 80;
const snowflakeSize = 3;
const snowflakeMinSpeed = 1;
const snowflakeMaxSpeed = 4;
const snowflakeColours = ["rgba(255,255,255,0.95)", "rgba(255,255,255,0.65)", "rgba(255,255,255,0.4)"];

const gameModes = {
    TITLE: 'title',
    PLAYING: 'playing',
    GAMEOVER: 'gameover'
};

var gameMode = gameModes.TITLE;

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;
    } else if (e.code == "Space") {
        spacePressed = true;
    }
}

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

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawSnow();

    timer++;

    switch (gameMode) {
        case gameModes.TITLE:
            titleScreen();
            break;
        case gameModes.GAMEOVER:
            gameOver();
            break;
        case gameModes.PLAYING:
            gameLoop();
            break;
    }
}

function titleScreen() {
    if (timer > titleColours.length) timer = 0;

    ctx.font = "50px Arial";
    ctx.fillStyle = titleColours[timer];
    ctx.fillText(`圣诞抓礼物!`, 0, 50);
    ctx.fillStyle = "yellow";

    ctx.font = "30px Arial";
    ctx.fillText(`请按空格键开始!`, 65, 140);

    var highScore = getHighScore();
    if (highScore != -1) ctx.fillText(`High Score: ${highScore}`, 90, 220);

    drawRotatedImage(elfImage, canvas.width / 2 - elfWidth / 2, 330, elfRotation, 200);
    elfRotation += 2;
    if (elfRotation > 359) elfRotation = 0;

    if (spacePressed && timer > 5) {
        setGameMode(gameModes.PLAYING);
    }
}

function gameLoop() {
    drawSnowPerson();
    spawnGifts();
    processGifts();
    drawFloor();
    drawHUD();
    drawElf();
    drawBang();

    if (rightPressed) {
        elfX += elfSpeed;
        if (elfX + elfWidth > canvas.width) {
            elfX = canvas.width - (elfWidth + 5);
        }
    } else if (leftPressed) {
        elfX -= elfSpeed;
        if (elfX < -15) {
            elfX = -15;
        }
    }
}

function gameOver() {
    ctx.font = "50px Arial";
    ctx.fillStyle = "yellow";
    ctx.fillText(`GAME OVER!`, 80, 200);
    ctx.font = "30px Arial";
    ctx.fillText(`Final score: ${score}`, 130, 240);
    ctx.fillText('Press space to continue', 80, 280);

    if (spacePressed && timer > 5) {
        initialiseGame();
        setGameMode(gameModes.TITLE);
    }
}

function processGifts() {
    gifts.forEach((g) => {
        if (g && g.alive) {
            // draw gift
            drawGift(g);
            if (g.y > canvas.height) {
                g.alive = false;
                if (!g.bomb) score--;
            }

            // move gift
            g.y += g.speed;

            // rotate gift
            g.rotation += 5;
            if (g.rotation > 359) g.rotation = 0;

            // check for collision
            if ((g.y + (giftHeight / 2)) >= ((canvas.height - elfHeight - snowHeight) + 20) &&
                (g.y < canvas.height - snowHeight + 20)) {
                if ((elfX + 25) <= (g.x + (giftWidth / 2)) && ((elfX + 20) + (elfWidth)) >= g.x) {
                    g.alive = false;
                    if (!g.bomb) {
                        score += 5;
                    } else {
                        doBombCollision();
                    }
                }
            }
        }
    });
}

function drawGift(g) {
    switch (g.colour) {
        case 1:
            drawColouredGift(greenGiftImage, g);
            break;
        case 2:
            drawColouredGift(redGiftImage, g);
            break;
        case 3:
            drawColouredGift(blueGiftImage, g);
            break;
        case 4:
            drawRotatedImage(bombImage, g.x, g.y, 180, 45);
            break;
    }
}

function drawColouredGift(colourImage, g) {
    drawRotatedImage(colourImage, g.x, g.y, g.rotation, 35);
}

function doBombCollision() {
    health--;
    bangX = elfX;
    bangTime = 5;
    if (health == 0) {
        setHighScore();
        setGameMode(gameModes.GAMEOVER);
    }
}

function drawBang() {
    if (bangTime > 0) {


### 最后

四轮技术面+一轮hr面结束,学习到了不少,面试也是一个学习检测自己的过程,面试前大概复习了 一周的时间,把以前的代码看了一下,字节跳动比较注重算法,面试前刷了下leetcode和剑指offer, 也刷了些在牛客网上的面经。大概就说这些了,写代码去了~



祝大家都能收获大厂offer~



**篇幅有限,仅展示部分内容**

![](https://p3-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/4f7e77191f0f4a168f587c842731866c~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg55So5oi3NTc5MjMwMTY3MDI=:q75.awebp?rk3s=f64ab15b&x-expires=1773229386&x-signature=JhUNdWQNpsltbv2x1EeevfY01To%3D)



![](https://p3-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/88afcfae0fc5481786e8441541f3848a~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg55So5oi3NTc5MjMwMTY3MDI=:q75.awebp?rk3s=f64ab15b&x-expires=1773229386&x-signature=jlnSfI8%2FqISGRncWoExaZep7I1k%3D)

![](https://p3-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/c055fb894a344fc6b9176e8139230eb9~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg55So5oi3NTc5MjMwMTY3MDI=:q75.awebp?rk3s=f64ab15b&x-expires=1773229386&x-signature=eR67P8I5W5S63qmPlPx7h7hPUL4%3D)

**开源分享:https://docs.qq.com/doc/DSmRnRGxvUkxTREhO**