随机数生成器破坏了整个脚本

时间:2019-07-19 02:48:24

标签: javascript

我正在创建一个简单的乒乓游戏,遇到了一个我无法解释的独特问题。

基本上,我可以根据需要让球移动并从墙壁上弹起。但是,我希望球的初始位置是随机的。

所以我写了一些简单的代码:

let ballX = Math.floor(random() * 100);
let ballY = Math.floor(random() * 200);

但是,这阻止了我的脚本完全运行。我运行了一个console.log,似乎它不断地生成一个随机的#。我该如何在加载时一次运行此功能,而在游戏中再也运行一次?

(function startBall() {
    setInterval(moveBall, 5);
}());


//DOM element of Left Slider
const sliderLeft = document.getElementById('left');
const lsx = document.getElementById('lsx');
const lsy = document.getElementById('lsy');
//ball position for table
const tballx = document.getElementById('ballx');
const tbally = document.getElementById('bally');



//specify starting vertical position in pixels (px)
let yPosition = 125;

//add that variable to the slider
sliderLeft.style.top = yPosition + 'px';


//this is the event listener that fires the function slider everytime the key up/down is pressed.
document.onkeydown = slider;

//slider function has a parameter of e, which stands for event.
function slider(e) {

    e = e || window.event;

    //up
    if (e.keyCode == '38') {

        if(yPosition === 5) {
        delta = 0;    
        } else {
        delta = -1;
         }
        yPosition += delta;
        sliderLeft.style.top = yPosition +'px';
    }

    //down
    else if (e.keyCode == '40') {

        if(yPosition === 245) {
            delta = 0;    
            } else {
            delta = 1;
             }

        yPosition += delta;
        sliderLeft.style.top = yPosition +'px';
    }
lsx.innerHTML = yPosition;
}

//this is the direction
ballx = 100;
bally = 200;

//this is the speed...
let ballDx = 1;
let ballDy = 1;
function moveBall() {

    //instantiate the ball
    ball = document.getElementById('ball');

    //vertical ball movement
    ballx += ballDx;
    ball.style.top = ballx + 'px';
    if(ballx > 314) ballDx = -1;
    if(ballx < 0) ballDx = 1;

    //horizontal ball movement
    bally += ballDy;
    ball.style.left = bally + 'px';
    if(bally > 515) ballDy = -1;
    if(bally < 0) ballDy = 1;

    tballx.innerHTML = ballx;
    tbally.innerHTML = bally;
}

0 个答案:

没有答案