gpt4 book ai didi

javascript - JS帮助: While Loop

转载 作者:行者123 更新时间:2023-11-28 07:50:29 24 4
gpt4 key购买 nike

帮助:我对 JS 有点陌生,需要函数方面的帮助。我需要修改这个函数,使其仅在分数 < 20 时运行,我还想做一个变体,你划船 4 次,然后就不能再滚动了。

<html>
<head>
<font face="verdana">
<title>The Game Of Pig</title>
<body background="h.jpg">
<center>
<table border="1">
<script>
alert("Welcome to the Game of Pig!");
function roll() {
return Math.floor(Math.random() * 6) + 1;
}
function game() {
var die = document.getElementById("die"),
score = document.getElementById("score"),
d,
d = roll();
die.innerHTML = d;
if (d !== 1) {
score.innerHTML = parseInt(score.innerHTML, 10) + d;
}
if (d === 1) {
score.innerHTML = 0;
}
}

</script>
</head>
<body>
<form>

<h1>Dice Roll</h1>
<br>
<br>
<br>
<br>
<div style="width:200px;height:108px;border:4px solid black;">
<h2>Total: <span id="score">0</span></h2>

<div>
<span id="die">0</span>
</div>
<input type="button" value="Roll" id="roll" onclick="game();">
</center>
</form>
</body>
</font>
</html>

最佳答案

不需要解析回dom元素的内容。在全局范围内使用变量。他们将在游戏调用之间保持其值(value)。

var die, score = 0, attempts = 0;
var die_div = document.getElementById("die");
var score_div = document.getElementById("score");

function game() {
var d = roll();
if(score + d > 20) return;
if(attempts > 3) return;
die_div.innerHTML = d;
score = (d=== 1)?0:(score+d);
score_div.innerHTML = score;
attempts++;
}

关于javascript - JS帮助: While Loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26877888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com