如果条件java脚本

时间:2018-02-18 09:40:00

标签: javascript if-statement

我无法解决这个问题我认为如果条件不满意(更新分数并重新加载页面)。该计划的Demo。当我运行程序时,当管道x cordinate越过代理x坐标时,分数变量不会更新,并且页面应该作为代理重新加载,并且管道坐标在任何时候都会相互干扰。我在这里发布javascript部分。可以在github上找到存储库。

var cvs = document.getElementById("gamepad");

var ctx = cvs.getContext("2d");

// load images

var agent = new Image();
var fg = new Image();
var pipeSouth = new Image();
var cloud = new Image();

agent.src = "images/rick.png";
fg.src = "images/track.png";
pipeSouth.src = "images/pipeSouth.png";
cloud.src = "images/cloud.png"



// some variables
var constant;

var bX = 100;
var bY = 130;
var base = bY;
var score = 0;

document.addEventListener("keydown",moveUp);

function moveUp(){
    bY -= 100;
    setTimeout(land,500);
}

function land() {
    bY = base;
}


function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}

// pipe coordinates

constant = 150;

var pipe = [];
var cld = [];

pipe[0] = {
    px : cvs.width,
    py : constant
};


cld[0] = {
    cx : cvs.width,
    cy : 0
};

function draw(){

    ctx.fillStyle = "#5c94fa";
    ctx.fillRect(0, 0, cvs.width, cvs.height);

    for (var j = 0; j < cld.length; j++) {

            ctx.drawImage(cloud,cld[j].cx,cld[j].cy,80,80);
            cld[j].cx-=1;

            if( cld[j].cx == 100 ){
                cld.push({
                    cx : cvs.width,
                    cy : getRandomArbitrary(cvs.height/3,cvs.height/2)
                }); 

        }
        }

    for(var i = 0; i < pipe.length; i++){


        ctx.drawImage(pipeSouth,pipe[i].px,pipe[i].py);
        ctx.drawImage(fg,pipe[i].px,cvs.height-fg.height/2,fg.width,fg.height/2);

        pipe[i].px-=10;  // this should be such that if condition for equality should be
        //satisfied with cvs.weidth (canvas width) 

        if( pipe[i].px == 200 ){
            pipe.push({
                px : cvs.width,
                py : getRandomArbitrary(cvs.height/3,cvs.height-fg.height)
                /*py : Math.floor(Math.random()*cvs.height/2)*/
            }); 
        }

        if(pipe[i].x < bX){
            score+=1;
        }    

        // detect collision

        if( pipe[i].x < bX + 50 || pipe[i].y > bY +100){
            location.reload(); // reload the page
        }

    }

    ctx.drawImage(agent,bX,bY,50,100);

    ctx.fillStyle = "#000";
    ctx.font = "20px Verdana";
    ctx.fillText("Score : "+score,10,20);

    requestAnimationFrame(draw);
}

draw();

2 个答案:

答案 0 :(得分:0)

这是一个简单的错字,你使用属性&#39; x&#39;并且&#39; y&#39;但是您将属性定义为&#39; px&#39;和&#39; py。所以pipe [i] .x是((lst_act x t curr) + 1)

答案 1 :(得分:0)

更改

if(pipe[i].x < bX){
            score+=1;
            scor.play();
        }   

if(pipe[i].px < bX){
            score+=1;
            scor.play();
        }   

进行此更改后,分数会更新。确保在所有地方使用适当的属性。