一些變量問題,我學到的JavaScript編程,這樣我可以添加一些功能到我的網站。我正在嘗試在瀏覽器中製作一個簡單的二十一點遊戲,現在我不知道發生了什麼。固定在JS和JQ
我有2個函數:第一個函數randomCard()
生成一個隨機卡,第二個函數deal()
使用for循環使用第一個函數兩次,並將卡存儲到一個數組中。我寧願不把這些功能結合起來,因爲未來還有其他地方會將它們分開來更方便。我用方法手在兩個對象,用戶和經銷商上使用交易功能。
現在,這裏的問題是,當我記錄這些值到控制檯(不是終點,只是爲了測試),它們是相同的每一次,我不知道爲什麼。但是當我只記錄deal()
函數時,它們都是不同的(參見腳本的底部)。
我不出去,將不勝感激幫助,這裏是我的代碼至今。
我使用jQuery的1.11.0。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Blackjack Game</title>
</head>
<body>
<button type="submit" id="deal">Deal</button>
<p class="user">
Your cards:
</p>
<p class="dealer">
The dealers cards:
</p>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
// gives the user and dealer a DOM element
var $user_cards = $('.user');
var $dealer_cards = $('.dealer');
// hides the DOM elements until the game has started
$($user_cards).hide();
$($dealer_cards).hide();
// jQuery var for DOM element to start the game
var $deal = $('#deal');
// var to track if the deal button has been clicked
var click = 0;
function randomCard() {
// random number between 0 and 10
var j = Math.random() * 10;
// round that number into a var called card
var card = Math.round(j);
// if card is 0, assign a J Q or K by making a random number again
if (card === 0) {
//another random number
var k = Math.random() * 10;
// checks random number and assign J Q or K
if (k <= 4) {
card = 'J';
} else if (k <= 7) {
card = 'Q';
}
else {
card = 'K';
}
}
// value of the function is a single card
return card;
}
// empty array to store cards
var cards = [];
function deal() {
// var to start for loop
var i = 0;
// start for loop
for (i; i < 2; i++) {
// add a random card to the i^th index of cards
cards[i] = randomCard();
}
// value fo function is array of two cards
return cards;
}
$($deal).click(function() {
// make the game start check = 1
click++;
// check to see if the game started
if (click === 1) {
// make the button disappear when game has started
$($deal).fadeToggle('fast');
// makes the player DOM elements appear when game is started
$($user_cards).fadeToggle(2000);
$($dealer_cards).fadeToggle(2000);
}
// make an object for the user and store hand under user.hand
var user = {
hand: deal()
};
// make an object for the dealer and store hand under dealer.hand
var dealer = {
hand: deal()
};
console.log(user.hand + " " + dealer.hand);
console.log(deal());
console.log(deal());
console.log(deal());
console.log(deal());
console.log(deal());
console.log(deal());
}); // $deal.click() end
}); // document.ready() end
</script>
</body>
</html>
僅供參考,沒有理由做'$($ user_cards).hide();'。你可以做'$ user_cards.hide();'。 '.hide()'是一個jQuery對象的方法,'$ user_cards'已經是一個jQuery對象,所以你可以直接使用它。無需通過執行'$($ user_cards)'來創建另一個jQuery對象。 – jfriend00