我很喜歡Javascript並試圖製作二十一點遊戲。JavaScript數組中的對象
數組和對象:
card = {}, //every card is an object having 3 properties: suit, number and points
playerCards = [], //an array containing player cards (objects)
dealerCards = [], //an array containing dealer cards (objects)
我也是手動創建用於測試目的某些卡,如:
card = {
suit : "spade",
number : "queen",
points : 10
};
playerCards.push(card);
以後,我的功能來隨機創建新卡,並檢查它是否已經在使用:
function makeCard() {
"use strict";
var uK;
for (;;) {
createCard(card, suit, number, points); // creates a new card, code below
checkCard(card, playerCards, dealerCards, uC); // checkes if card is already in use and returns uC = 1 if "yes" and uC = 0 if "not" (working)
if (uK === 0) {
break;
}
}
return card;
}
下面是createCard()的代碼:
function createCard(card, suit, number, points) {
"use strict";
var i = Math.floor(Math.random() * 4);
card.suit = suit[i];
i = Math.floor(Math.random() * 13);
card.number = number[i];
card.points = points[i];
return card;
}
它可以工作,但是當它創建新卡時,它會替換手動添加到playerCards/dealerCards數組中的最後一個卡。我可以通過創建一個毫無意義的示例卡來防止它,並且不會將其添加到數組中(然後這個將被替換),但它看起來不正確。所以我該怎麼做?
在此先感謝!
哪裏調用'createCard'並將結果添加到數組中? –
您可能只是在操縱現有的卡片對象,您應該改爲創建一個新的對象。 – runspired
二十一點不使用套裝,所以你可以簡化你的代碼。 – dcaswell