everyone. I am making a little experiment with Javascript. I would like to make a guessing game, where the user guesses a number from 0-100 and the computer tells him/her "too low", "too high", or "correct." However, I want this to be rigged . That is, the computer should choose the longest path possible for the user to get the answer right. For example:
Right now, I just randomly say "too low" or "too high" which is problematic. For example:
How can I avoid this? The computer should prolong the game but not be illogical.
My ideas:
minValue
and maxValue
variable which keep track of the current bounds of the guess. Unfortunately, I'm not sure how to implement this well. The ideas are basically the same. However, I'm stuck on implementing them. Thank you in advance.
I would like some steps (or code) on how to implement these ideas in Javascript.
Jsfiddle (although it may not help much, there is little in it): http://jsfiddle.net/prankol57/f4JWw/
Yeah, just use two bounding variables.
maxNum= 100
minNum = 0
Example: user guesses 51
Result: computer says the number is less than 51, and sets maxNum = 50
if (guess > maxNum)
too high
else if (guess < minNum)
too low
else if (guess > ((maxNum+minNum)/2)) the computer would say the actual number is below the guess
else if (guess < ((maxNum+minNum)/2)) the computer would say the actual number is above the guess
//should only happen if the number is exactly the mean(maxNum,minNum)
else
i guess just default to the computer saying that the actual number is above the guess. it doesn't really matter either way
anyway, there's some pseudo-code that I think answers your question. In general though, I really recommend banging your head against the wall on problems like this. Understanding the logic behind an implementation is the only way to be good at what you do.
Created using @indiscrete pseudo code. :)
var min = 0;
var max = 100;
$("#guessForm").submit(function (e) {
var guess = parseInt($("#guess").val()) || 0;
var hint = checkGuess(guess);
$("<p>").addClass("guessRecord").html(hint).appendTo("#guessRecords");
$("#guess").val("");
e.preventDefault();
});
function checkGuess(guess) {
var mid = max - (Math.abs(max - min) / 2);
if (guess > mid) {
if (guess <= max) max = guess;
return "My number is less than " + guess + ".";
} else if (guess < mid) {
if (guess >= min) min = guess;
return "My number is greater than " + guess + ".";
} else {
return "Correct";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.