我不知道如何为Yahtzee游戏设置保持功能。我有6个骰子,当我单击它们时,我希望能够容纳任意数量的骰子,因此当我执行掷骰功能时,它们不会改变。另外,我希望骰子在单击时能改变图像。
我使用数组存储是否保留骰子。
我在哪里存储骰子值,以及是否持有骰子:
var dice = new Array(0,0,0,0,0,0);
var hold = new Array(0,0,0,0,0,0);
function rollDice() {
if (turn<3){
for (i = 0; i < 6; i++) {
if (hold[i] == 0) {
dice[i] = Math.floor(Math.random() * 6) + 1;
document.getElementById("die" + i).src = '/images/' + (dice[i]) + '.png';
}
}
turn = ++turn;
document.getElementById("rules").innerHTML = dice;
}
else{
document.getElementById("rules").innerHTML = "Ikke flere kast";
}
}
<div id="dice">
<img id="die0" class="dice" src="images/1.png" onclick="holdDice()">
<img id="die1" class="dice" src="images/2.png" onclick="holdDice()">
<img id="die2" class="dice" src="images/3.png" onclick="holdDice()">
<img id="die3" class="dice" src="images/4.png" onclick="holdDice()">
<img id="die4" class="dice" src="images/5.png" onclick="holdDice()">
<img id="die5" class="dice" src="images/6.png" onclick="holdDice()">
</div>
答案 0 :(得分:0)
保持功能非常简单:在我的HoldDice函数中,检查是否未保持裸片(0),然后将其设置为1进行保持,否则将其设置为0。
我还将您的内联点击更改为更现代的addeventlistener,并将骰子#作为数据属性添加到每个图像。
var dice = new Array(0,0,0,0,0,0);
var hold = new Array(0,0,0,0,0,0);
function rollDice() {
if (turn<3){
for (i = 0; i < 6; i++) {
if (hold[i] == 0) {
dice[i] = Math.floor(Math.random() * 6) + 1;
document.getElementById("die" + i).src = '/images/' + (dice[i]) + '.png';
}
}
turn = ++turn;
}
else{
document.getElementById("rules").innerHTML = "Ikke flere kast";
}
}
var imgs = document.getElementsByClassName("dice");
for(var z = 0;z<imgs.length;z++){
imgs[z].addEventListener("click",function(){
hold[this.dataset.index] = (hold[this.dataset.index] == 0) ? 1 : 0;
});
}
<div id="dice">
<img id="die0" data-index="0" class="dice" src="images/1.png">
<img id="die1" data-index="1" class="dice" src="images/2.png">
<img id="die2" data-index="2" class="dice" src="images/3.png">
<img id="die3" data-index="3" class="dice" src="images/4.png">
<img id="die4" data-index="4" class="dice" src="images/5.png">
<img id="die5" data-index="5" class="dice" src="images/6.png">
</div>