2013-10-22 30 views
0

我對這種令人難以置信的語言有點新鮮,我正在嘗試創建一個函數,讓我慢慢地揭示戰鬥的方式去。我可以儘早編寫函數,然後在setTimeout中聲明函數,而不必重寫它,因爲這看起來似乎沒有用。這裏是我做的不太好的代碼:我可以在setTimeout中預先定義一個函數,所以我不會在括號中調用它

var health=100; 
var ehealth=100; 
var atk; 
var eatk; 

function attack(x){ 
    x=Math.floor(Math.random()*11); 
    atk=x; 
    ehealth=ehealth-atk 
    document.write('Enemy Health:' + '   ' + ehealth + '   ') 
} 

function eattack(x){ 
    x=Math.floor(Math.random()*11); 
    eatk=x; 
    health=health-eatk 
    document.write('Health:' + '   ' + health) 
} 

function dead(){ 
    if(health<=0){ 
     document.write('You Lose'); 
    }else{ 
     if(ehealth<=0){ 
      document.write('You Win'); 
     } 
    } 
} 

function battle(){ 
    document.write('Enemy Health:' + '&nbsp; &nbsp;' + ehealth + '&nbsp; &nbsp; Health: &nbsp; &nbsp;' + health + '<br/>\n') 
    while(health>=0&&ehealth>=0){ 
     setTimeout(attack(0),400) 
     setTimeout(eattack(0),400) 
     document.write("<br/>\n"); 
     dead(); 
    } 
} 

幫助!

+0

你可以像[setTimeout(attack,400,0)]那樣在[call]中包含額外的參數(https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout),但是它不受所有瀏覽器的支持。 – RobG

回答

1

調用它像這樣:

setTimeout(function() { 
    attack(0); 
}, 400); 

如果你這樣做:

setTimeout(attack(0), 400); 

它會立即評估attack(0),它會嘗試使用的attack(0)輸出作爲回調函數(這是不是你想要的)。

+0

:D你不可思議的人... – Clarinetking

相關問題