我的代码是旧游戏Mastermind的一个版本,应该猜测我的密码,如果用户猜到了正确的字符,它会打印字母绿色,如果它的正确字符错误的地方,如果完全错误则打印出红色和黑色。
<!doctype.html>
<html>
<head>
<title> Mastermind </title>
<script>
var secret= 'FLGRL';
function init() {
var button = document.getElementById('startButton');
button.onclick = myButtonClick;
}
function myButtonClick() {
var userTry = document.getElementById('userGuess').value;
var ul = document.getElementById('guessList');
var li = document.createElement('li');
}
for (var i=0; i < secret.length; i++) {
var found = false;
//if user finds right character, right spot
if (userTry.charAt(i)===(secret.charAt(i))) {
//if code and guess are a match, display letter in greeting
li.innerHTML += userTry.charAt(i).fontcolor('green');
found = true;
//show user
}
//if character is in the code but in wrong
else if {
for (var j=0; j = charAt('secret'); j++) {
var found = true;
if (userTry.charAt(j)===(secret.charAt(j))){
li.innerHTML += userTry.charAt(j).fontcolor('red');
}
if (found === false) {
li.innerHTML += userTry.charAt(i). fontcolor('black');
//show user character is wrong
}
}
ul.appendChild(li);
alert(userTry);
window.onload = init;
</script>
</head>
<body>
<form>
<input type="text" id="userGuess" size="15" placeholder="Your Guess">
<input type="button" id="startButton" value="Place your Guess">
</form>
<ul id="guessList">
</ul>
</body>
</html>
答案 0 :(得分:0)
该代码有很多错误,至少是您发布的代码。一个未闭合的括号,这也是错误的
else if { Blockquote
如果没有必要或缺少条件。还有,这是什么?
for (var j=0; j = charAt('secret'); j++)
条件错误。
我已更正了这些内容,代码仍未100%校正,但:
<!doctype.html>
<html>
<head>
<title> Mastermind </title>
<script>
var secret = 'FLGRL';
function init() {
var button = document.getElementById('startButton');
button.onclick = myButtonClick;
}
var userTry;
function myButtonClick() {
userTry = document.getElementById('userGuess').value;
var ul = document.getElementById('guessList');
var li = document.createElement('li');
for (var i = 0; i < secret.length; i++) {
var found = false;
//if user finds right character, right spot
if (userTry.charAt(i) === (secret.charAt(i))) {
//if code and guess are a match, display letter in greeting
li.innerHTML += userTry.charAt(i).fontcolor('green');
found = true;
//show user
}
//if character is in the code but in wrong
else {
for (var j = 0; j < secret.length; j++) {
var found = true;
if (userTry.charAt(j) === (secret.charAt(j))) {
li.innerHTML += userTry.charAt(j).fontcolor('red');
}
if (found === false) {
li.innerHTML += userTry.charAt(i).fontcolor('black');
//show user character is wrong
}
}
}
}
ul.appendChild(li);
alert(userTry);
}
window.onload = init;
</script>
</head>
<body>
<form>
<input type="text" id="userGuess" size="15" placeholder="Your Guess">
<input type="button" id="startButton" value="Place your Guess">
</form>
<ul id="guessList">
</ul>
</body>
</html>