我正在尝试按照基于文本的游戏制作某些内容,但使用按钮而不是文本进行输入。例如,我想从页面上的3个按钮开始。当您选择其中一个按钮时,函数应该更改该问题变量,然后为下一个问题创建按钮。
问题一:
<DOCTYPE html>
<body>
<button onclick="russetPotato()">Russet</button>
<button onclick="redPotato()">Red</button>
<button onclick="sweetPotato()">Sweet</button>
</body>
<script type="text/javascript">
var seed = 0;
var soil = 0;
function russetPotato(){
seed = 1
document.write("You set seed as Russet Potato.");
}
function redPotato(){
seed = 2
document.write("You set seed as Red Potato.");
}
function sweetPotato(){
soil = 3
document.write("You set seed as Sweet Potato.");
}
</script>
</html>
现在我要做的是添加第二个问题。在种子按钮被回答后,我可以如何使土壤按钮出现而不是同时出现?
<DOCTYPE html>
<body>
<button onclick="russetPotato()">Russet</button>
<button onclick="redPotato()">Red</button>
<button onclick="sweetPotato()">Sweet</button>
<button onclick="sandySoil()">Thin Sandy Soil</button>
<button onclick="loamSoil()">Loose Loam Soil</button>
<button onclick="claySoil()">Heavy Clay Soil</button>
</body>
<script type="text/javascript">
var seed = 0;
var soil = 0;
function russetPotato(){
seed = 1
document.write("You set seed as Russet Potato.");
}
function redPotato(){
seed = 2
document.write("You set seed as Red Potato.");
}
function sweetPotato(){
soil = 1
document.write("You set seed as Sweet Potato.");
}
function sandySoil(){
soil = 1
document.write("You set soil as Thin Sandy Soil.");
}
function loamSoil(){
soil = 2
document.write("You set soil as Loose Loam Soil.");
}
function claySoil(){
soil = 3
document.write("You set soil as Heavy Clay Soil.");
}
</script>
</html>
道歉,如果这实际上非常简单。这是我第一次使用javascript / html进行实验。
答案 0 :(得分:0)
您不必创建新按钮(如果您总是使用其中的三个按钮)。无论如何,它完全取决于游戏逻辑 通常它是如何通过使用像下面的对象数组来完成的:
var stages = [
[
{btntext:"Russet", type:"seed", pts:1, text:"You set seed as Russet Potato."},
{btntext:"Red", type:"seed", pts:2, text:"You set seed as Russet Potato."},
{btntext:"Sweet", type:"soil", pts:1, text:"You set seed as Russet Potato."}
],[
{btntext:"Sand", type:"foo", pts:1, text:"You set soil as Thin Sandy Soil."},
{btntext:"Loam", type:"bar", pts:2, text:"You set soil as Loose Loam Soil."},
{btntext:"Clay", type:"bar", pts:3, text:"You set soil as Heavy Clay Soil."}
],[
{btntext:"Baz", type:"baz", pts:1, text:"You set Baz!."},
{btntext:"Foo2", type:"foo", pts:2, text:"You set Foo twice!."}
]
];
现在,如果你查看上面的数组并执行:alert(stages.length) // 3
,你会发现你可以计算3
个阶段。如果您最初将var counter = 0
设置为0
,则可以先阅读0
索引阶段,请阅读{em>选项的长度,例如var nOfBtns = stages[counter].length; // 3
有三个选项 Russet Red Sweet 。最后一个将返回2个按钮。您可以很容易地从Array和Object中提取所有需要的值:
var selectedButtonPoints = stages[counter][buttonNid].pts;
一旦玩家点击按钮并从阵列中提取所有需要的信息,您只需根据下一阶段中的项目数创建一组新按钮并增加计数器counter += 1;
只是为了给你一个想法。
此外,不推荐使用document.write。请参阅如何使用innerHTML
像一些容器一样在页面上设置一些元素:
<div id="buttons"></div> <!-- JS will populate with needed buttons -->
<div id="points"></div> <!-- JS will write here the player stats -->
<!-- etc... -->
使用JS定位这些元素,创建像function createNewButtons()
这样的函数,并使用它们用按钮和信息填充元素。