簡體   English   中英

HTML5 / Javascript游戲

[英]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 ,所以當您將項目添加到counter時,您從索引1開始,該索引實際上是第二個項目。 因此,當您嘗試訪問bubbles[0] ,它將返回undefined。 而是將counter初始化為0

支架放置在錯誤的位置,這解決了問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM