0

我正在为学校开发一个简单的吃豆人游戏。(HTML、CSS、Vanilla JavaScript)我希望能够改变游戏的主题(从空间到花卉主题)。改变背景已经可以了,但现在我希望当你从主题切换时,幽灵也能再看看。

我从 html 中的一个简单网格开始,并在 Javascript 中添加了所有功能。幽灵是在一个阵列中制作的。

<div class="grid"></div>

const grid = document.querySelector('.grid');

class Ghost {
    constructor(className, startIndex, speed) {
        this.className = className
        this.startIndex = startIndex
        this.speed = speed
        this.currentIndex = startIndex
        this.timerId = NaN
    }
}

const ghosts = [
    new Ghost('alien1', 212, 650),
    new Ghost('alien2', 212, 700),
    new Ghost('alien3', 212, 830),
    new Ghost('alien4', 212, 900)
];

 const moveGhost = ghost => {
    const directions = [-1, +1, width, -width]
    let direction = directions[Math.floor(Math.random() * directions.length)]

    ghost.timerId = setInterval(function () {
        //Check if the next box does not contains 'wall' or another ghost
        if (!squares[ghost.currentIndex + direction].classList.contains('wall') && !squares[ghost.currentIndex + direction].classList.contains('ghost')) {
            //If it does not contains one of these to, the ghost can move here
            //Delete all related ghost classes
            squares[ghost.currentIndex].classList.remove(ghost.className, 'ghost', 'scared-alien', 'flower')

            //Change the currentIndex to the next box
            ghost.currentIndex += direction

            //Draw the ghost in the nex/new box
            squares[ghost.currentIndex].classList.add(ghost.className, 'ghost')

            //If it contains 'ghost' or 'wall' move into another direction
        } else direction = directions[Math.floor(Math.random() * directions.length)]


        //If ghost is scared
        if (ghost.isScared) {
            squares[ghost.currentIndex].classList.add('scared-alien')
        }

        //If ghost is scared and bumps into
        if (ghost.isScared && squares[ghost.currentIndex].classList.contains('pac-man')) {
            squares[ghost.currentIndex].classList.remove(ghost.className, 'ghost', 'scared-alien')
            ghost.currentIndex = ghost.startIndex
            score += 100
            squares[ghost.currentIndex].classList.add(ghost.className, 'ghost')
        }
        checkForGameOver()
    }, ghost.speed)
} 

要更改主题,您必须单击一个按钮,我有这些功能;

const init = () => {
    buttonSpace.addEventListener('click', themeSpace)
    buttonFlower.addEventListener('click', themeFlower)
}

const buttonSpace = document.querySelector('.btnSpace');
const buttonFlower = document.querySelector('.btnFlower');
const body = document.getElementsByTagName('body');

const themeSpace = () => {
    body[0].style.backgroundImage = "url(../assets/back-space.jpg)";
}

const themeFlower = () => {
    body[0].style.backgroundImage = "url(../assets/back-leaves.jpg)";
}

init();

如何在单击按钮时添加类名或更改 Ghost 的类名(alien.1、alien2、...更改为 flowre1、flower 2、...)?所以我可以添加另一个css样式来改变网格上ghost的外观。

4

0 回答 0