我是JavaScript的新手,我将这个色彩猜谜游戏作为一项任务。我的脚本如下。我尝试了许多不同的方法,但我无法让它发挥作用。
总之,我有两个问题。
脚本在下面。如果您运行该程序,它将显示用户猜测的答案(仅用于测试)。如果用户猜测正确,则页面颜色将为该颜色。任何帮助将不胜感激。
<DOCTYPE! HTML>
<HTML>
<HEAD>
<TITLE>Color Guessing Game</TITLE>
</HEAD>
<body onload="do_game()">
<script type="text/javascript">
var target;
var target_index;
var guess_input;
var finished = false;
var guess_input_text;
var guesses = 0
var color= ["Blue","Coral","Cyan","Fuchsia","Gold","Lavender","Lime","Red","Tan"];
var myBody=document.getElementsByTagName("body")[0];
var check_color = colors.indexOf(guess_input);
function do_game(){
var random_number_integer = colors[Math.floor(Math.random() * colors.length-1)];
target = random_number_integer;
alert(target);
while (!finished) {
guess_input_text = prompt("I am thinking of one these colors: \n\n\n" +
colors.toString() +
"\n\n\n What color am I thinkning of?");
guess_input = guess_input_text;
guesses += 1;
finsihed = check_guess();
}
}
function check_guess() {
if (guess_input == null){
alert("Type in a color.");
return false;
}
if (guess_input > target){
alert("Your input is alphabetically lower than mine!" +
"\n\nPlease Try Again.\n\n");
return false;
}
if (guess_input < target){
alert("Your input is alphabetically higher than mine!" +
"\n\nPlease Try Again.\n\n");
return false;
}
alert("Yes!!!, the correct color was: " + target +
"\n\n\n The Number of guesses:" + guesses +
"\n\n\nGood Job\n\n\n");
myBody.style.background=guess_input;
return true;
}
</script>
</body>
</HTML>
答案 0 :(得分:0)
// check whether the array or string empty
function is_empty(obj){
if (obj == null || (obj == '' && obj.length == 0)){
return true;
}
else {
return false;
}
}
// check whether this elem is included in arr
function is_included(elem, arr){
if (is_empty(arr) || is_empty(elem) || arr.toString().indexOf(elem) == -1){
return false;
}
else {
return true;
}
}
&#13;
答案 1 :(得分:0)
答案1:使用indexOf:(Docs)