HTML5/Javascript Game



我目前正在开发一个游戏,我需要一堆随机气泡才能落下,在它下面有一个矩形,可以移动以"爆破"这些气泡。我目前有一个代码不会丢弃这些气泡。有人可以告诉我哪里出错了吗?这是我的代码:

var canvasColor;
var x,y,radius,color;
var x=50, y=30;
var bubbles= [];
var counter;
var lastBubble=0;
var steps=0, burst=0, escaped=0;
var xx=200; 
var moveRectangleRight=false;
var moveRectangleLeft=false;

function startGame()
{
    var r, g, b;
    canvasColor= '#f1f1f1';
    x=10;
    y=10;
    radius=10;
    clearScreen();
    counter=0;
    while (counter<100)
    {
        x= Math.floor(450*Math.random()+1);
        r = Math.floor(Math.random()*256);
        g = Math.floor(Math.random()*256);
        b = Math.floor(Math.random()*256);
        color='rgb('+r+','+g+','+b+')';
        bubbles[counter]=new Bubble(x,y,radius,color);
        counter+=1;
    }
    setInterval('drawEverything()',50); 
}
function Bubble(x,y,radius,color)
{   
        this.x=x;
        this.y=y;
        this.radius=radius;
        this.color=color;
        this.active=false;
}
function drawEverything()
{   
    var canvas=document.getElementById('myCanvas');
    var context= canvas.getContext('2d');
    steps+=1;
    clearScreen();
    if (steps%20==0 && lastBubble <100) {
        bubbles[lastBubble].active=true;
        lastBubble+=1;
    }
    drawRectangle();
    counter=0;
    while(counter<100)
        {
        if (bubbles[counter].active==true) {
            context.fillStyle= bubbles[counter].color;
            context.beginPath();
            context.arc(bubbles[counter].x, bubbles[counter].y,
                        bubbles[counter.radius], 0, 2*Math.PI);
            context.fill();
            bubbles[counter].y+=2;
        }
        y=bubbles[counter].y;
        x=bubbles[counter].x;
        if (y>=240 && y<=270 && x>=xx-10 && x<=xx+60)
        {
            bubbles[counter]=false;
        }

        else if (y>=450)
        {
            bubbles[counter]=false;
        }
        counter+=1;
    }
}
function clearScreen ()
{
    var canvas=document.getElementById('myCanvas');
    var context= canvas.getContext('2d');
    context.fillStyle= canvasColor;
    context.fillRect(0,0,450,300);
}

function drawRectangle()
{   var canvas, context;
    if (moveRectangleRight==true && xx<400){
        xx+=20;
    }
    if (moveRectangleLeft==true && xx>0){
        xx-=20;
    }
    canvas=document.getElementById('myCanvas');
    context= canvas.getContext('2d');
    context.fillStyle = 'blue';
    context.fillRect(xx,250,50,10);
}
function moveLeft () {
    moveRectangleLeft=true;
}
function moveRight() {
    moveRectangleRight=true;
}
function stopMove () {
    moveRectangleRight=false;
    moveRectangleLeft=false;
}

您的问题是您将counter初始化为 1 ,因此当您将项目添加到计数器时,您从 1 的索引开始,这实际上是第 2 项。因此,当您尝试访问bubbles[0] 时,它将返回 undefined。相反,counter初始化为 0

括号位于错误的位置,这解决了问题。

最新更新