2013-05-06 98 views
0

我正在開發我的第一個黑色傑克遊戲,並且我一直對最簡單的事情感到困惑。這個問題在我的if語句我要說的是:在21點遊戲中需要幫助if語句

if (cardsinhand < 7 && newcard != firstcard && newcard != secondcard) 

,當我按下打我按鈕,它會一遍又一遍對付我一樣卡。這是我的功能。我需要if語句中的信息爲true,然後執行,否則就不執行。

cardsinhand = 2 
firstcard = Math.floor(Math.random() * 1000 % 52) 
secondcard = Math.floor(Math.random() * 1000 % 52) 
newcard = Math.floor(Math.random() * 1000 % 52) 

function hitCard() 
{ 
    if (cardsinhand < 7 && newcard != firstcard && newcard != secondcard) 
    { 
    document.images[cardsinhand].src = "http://www.biogow/images/cards/gbCard" + newcard + ".gif" 

    cardsinhand++ 
    } 
} 

任何想法,爲什麼這不工作的權利?

回答

4

這實際上並不是您的if聲明本身的問題。看來,這樣的:

newcard = Math.floor(Math.random() * 1000 % 52) 

正在做一次而不是每次你打的時間。這意味着你一遍又一遍地得到相同的卡。

您應該在每次執行點擊操作時重新計算一張新卡。


你或許應該也考慮如何你產生卡。通常情況下,你會使用一個甲板(包含一個或多個「真正的」甲板),以便隨着卡的移除,概率發生變化,就像在現實生活中一樣。

這也可以解決使用* 1000 % 52時出現的任何歪斜問題,它傾向於喜歡卡片在「卡座」的一端。

+0

謝謝你畢竟是我的問題 – Dolbyover 2013-05-06 03:08:56

1

這是因爲你只有一次在功能體外生成newcard。你想要的是每次生成新卡調用該函數,因此該行:newcard = Math.floor(Math.random() * 1000 % 52)應該是裏面的功能,像這樣:

cardsinhand = 2 
firstcard = Math.floor(Math.random() * 1000 % 52) 
secondcard = Math.floor(Math.random() * 1000 % 52) 


function hitCard() 
{ 
    var newcard = Math.floor(Math.random() * 1000 % 52) 
    if (cardsinhand < 7 && newcard != firstcard && newcard != secondcard) 
    { 
     document.images[cardsinhand].src = "http://www.biogow/images/cards/gbCard"+newcard+".gif" 

     cardsinhand++ 
    } 
} 

也爲它的價值,如果你剛開始時你可能想用Array來存放你的手牌。當你的新卡可能成爲第一張卡時,第二張卡第三張卡時,會發生什麼情況if