gpt4 book ai didi

javascript - 无法正确添加变量

转载 作者:行者123 更新时间:2023-11-30 17:10:00 25 4
gpt4 key购买 nike

我有一个变量++;在 if/else 语句中(它在 else 部分)。它应该将一个人猜错的分数加 1。出于某种原因,它永远不会只加一个,每当我提交“猜测”时,它还会添加 3 到 7 之间的数字。你们能告诉我是我循环错了吗?请尝试详细解释。

编辑:我意识到了部分问题。尝试++;实际上是为每个 [var]choice 不匹配或不相等的字母循环一次。例如,如果我为“apple”输入“a”tries++;由于其他四个字符,将循环四次。那么如何让它只循环一次而不是为每个丢失的字符添加一个?

这是我的代码。

// JavaScript Document
var words = new Array("apple","orange","banana","lime","mango","lemon","avacado","pineapple","kiwi","plum","watermelon","peach");
var randomNum;
var word;
var tries = 0;

$('#guess').prop('disabled', true);

$(function(){
$('#start').click(function(){
$('#guess').prop('disabled', false);
word = "";
randomNum = Math.floor(Math.random() * words.length)
for (var i =0; i < words[randomNum].length; i++) {
word += "*";
}
console.log(words[randomNum]);
$('#word').html(word);
});

$('#guess').click(function guess(){
var choice = $('#letter').val().toLowerCase();
for (var i =0; i < word.length; i++) {
if (words[randomNum].charAt(i) == choice) {
word = word.substr(0, i) + choice + word.substr(i + 1);
}
if (words[randomNum].charAt(i) !== choice) {
tries++;
}
}

if (tries < 7) {
$('#tries').html(tries)
} else if (tries >= 7)
$('#tries').html("YOU LOSE");

$('#word').html(word);

$('#' + choice).css("background-color", "red");
});

});

最佳答案

成功了!

此问题与 for 循环 (每个字母) 内的 tries 变量有关。为了查看奇怪的行为,在您的代码中的循环内添加一个 console.log(tries);,您将看到。第一次它会增加 1 然后值会完全改变(我建议在这里进行一些调试以更准确地了解发生了什么,因为我做的非常快) .解决方案是从 for 循环上下文中增加变量以使其工作(我在提供的示例中从底部开始这样做)

顺便说一下,您似乎正在尝试实现一个“刽子手”游戏,老实说,在实现这些事情时您需要真正有条理。

我解决了您的问题,大大改进了代码,还考虑了其​​他可能的游戏场景,例如:

  • 再玩一次
  • 游戏结束
  • 返回

请看一下。只是要知道,HTML和CSS只是为这个例子做的即兴创作,需要一些改进所以只是作为引用。


更新:您在帖子的EDIT 部分输入的内容是正确的。


您可以在底部运行此脚本。

// Game variables
var GAME_WORDS = [ // List of words available when playing
'apple',
'orange',
'banana',
'lime',
'mango',
'lemon',
'avacado',
'pineapple',
'kiwi',
'plum',
'watermelon',
'peach'
],
GAME_MASKED_WORD = '', // Stores the masked word to be discovered
GAME_SELECTED_WORD = '', // Stores the readable word
GAME_PLAYER_ATTEMPTS = 0, // Stores player attempts when failing
GAME_RANDOM_NUMBER = 0, // Random number to pick a word
GAME_MAX_ATTEMPTS = 7, // Max. player attempts before a game over
GAME_UI_COMPONENTS = { // UI components declaration
start: $('#start'),
reset: $('#reset'),
back: $('#back'),
guess: $('#guess'),
msg: $('#msg'),
word: $('#word'),
letter: $('#letter')
},
GAME_UI_SECTIONS = { // UI sections declaration
menu: $('#menu'),
game: $('#game')
};

$(function() {;
var ui = GAME_UI_COMPONENTS;

// Initialize game
init();

// Start button handler
ui.start.on('click', function(e) {
start();
});

// Guess button handler
ui.guess.on('click', function(e) {
guess();
});

// Play Again button handler
ui.reset.on('click', function(e) {
reset();
start();
});

// Go Back button handler
ui.back.on('click', function(e) {
init();
});
});

/**
* Used to initialize the game for first time
*/
function init() {
var sections = GAME_UI_SECTIONS;
sections.menu.show();
sections.game.hide();
reset();
};

/**
* Used to start the game
*/
function start() {
var ui = GAME_UI_COMPONENTS,
sections = GAME_UI_SECTIONS,
words = GAME_WORDS;

sections.menu.hide();
sections.game.show();

GAME_RANDOM_NUMBER = Math.floor(Math.random() * words.length);

for (var i = 0; i < words[GAME_RANDOM_NUMBER].length; ++i) {
GAME_MASKED_WORD += '*';
}

GAME_SELECTED_WORD = words[GAME_RANDOM_NUMBER];

ui.word.html(GAME_MASKED_WORD);
ui.letter.focus();
};

/**
* Guess button handler
*/
function guess() {
var ui = GAME_UI_COMPONENTS,
words = GAME_WORDS,
matches = false,
choice;

// Clean messages each time player do a guess
showMsg('');

if (ui.letter && ui.letter.val()) {
choice = $.trim(ui.letter.val().toLowerCase());
}

if (choice) {
for (var i = 0; i < GAME_MASKED_WORD.length; ++i) {
if (words[GAME_RANDOM_NUMBER].charAt(i) === choice) {
GAME_MASKED_WORD = GAME_MASKED_WORD.substr(0, i) + choice +
GAME_MASKED_WORD.substr(i + 1);
matches = true;
}
}

if (!matches) {
++GAME_PLAYER_ATTEMPTS;
}
} else {
showMsg('Please type a letter.');
}

// Show attempts left if more than zero
if (GAME_PLAYER_ATTEMPTS > 0) {
showMsg('You have ' +
(GAME_MAX_ATTEMPTS - GAME_PLAYER_ATTEMPTS) +
' attempt(s) left.');
}

// Check game status each time doing a guess
if (isGameOver()) {
lose();
} else if (isGameWin()) {
win();
} else {
ui.word.html(GAME_MASKED_WORD);
}

ui.letter.focus();
};

/**
* Used to set all game variables from the scratch
*/
function reset() {
var ui = GAME_UI_COMPONENTS;
GAME_MASKED_WORD = '';
GAME_PLAYER_ATTEMPTS = 0;
GAME_RANDOM_NUMBER = 0;
showMsg('');
ui.guess.show();
ui.letter.val('');
ui.word.html('');
};

/**
* Handler when player lose the game
*/
function lose() {
var ui = GAME_UI_COMPONENTS;
showMsg('You Lose!');
ui.word.html(GAME_SELECTED_WORD);
ui.guess.hide();
};

/**
* Handler when player win the game
*/
function win() {
var ui = GAME_UI_COMPONENTS;
showMsg('You Win!');
ui.word.html(GAME_SELECTED_WORD);
ui.guess.hide();
};

/**
* Use to print UI messages for the player
*/
function showMsg(msg) {
var ui = GAME_UI_COMPONENTS;
ui.msg.html(msg);
};

/**
* Check game status, if player is going to lose the game
* @returns Boolean
*/
function isGameOver() {
return (GAME_PLAYER_ATTEMPTS >= GAME_MAX_ATTEMPTS);
};

/**
* Check game status, if player is going to win the game
* @returns Boolean
*/
function isGameWin() {
return (GAME_MASKED_WORD === GAME_SELECTED_WORD);
};
.btn {
cursor: pointer;
}

span#msg {
color: red;
font-weight: bold;
}

.text {
font-size: 3em;
}

input#letter {
width: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="wrapper">
<div id="menu">
<span class="text">Hangman!</span>
<br><br>
<img src="http://img3.wikia.nocookie.net/__cb20130207191137/scribblenauts/images/0/01/Hangman.png" height="200" width="120"/>
<br><br>
<input type="button" class="btn" id="start" value="Start Game"/>
</div>
<div id="game">
<span id="msg"></span>
<br><br>
Letter: <input type="text" id="letter" value="" maxlength="1"/>
<br><br>
<input type="button" class="btn" id="guess" value="Guess"/>
<input type="button" class="btn" id="reset" value="Play Again"/>
<input type="button" class="btn" id="back" value="Go Back"/>
<br><br>
Word: <div id="word" class="text"></div>
</div>
</div>

希望这对您有所帮助。

关于javascript - 无法正确添加变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27220348/

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