PDA

View Full Version : Random number addition script - help!



Shenshen
05-23-2006, 12:02 AM
I'm trying to do a short script for a class. The script should generate two random numbers and ask the user what the sum of the two numbers is. I'm having some trouble making it work, this is what I have so far -- I'm new to scripting at all (I'm in a game design major but I'm a writer, so this is all strange to me!). Any help would be hugely, hugely appreciated. Thanks in advance!


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Problem 2</title>
<script language="javascript" type="text/javascript">

var guess = 0
var target1 = 0;
var target2 = 0;
var correct = target1+target2
var msg = "";

target1 = Math.floor(Math.random() * 10) + 1;
target2 = Math.floor(Math.random() * 5) + 2;

guess = eval(Prompt("What is " target1 "plus" target2 "?", ""));

while (guess != correct){
guess = prompt ("What is " target1 "plus" target2 "?", "");
if (guess == correct){
alert ("Good job!");
} else {
alert ("Sorry, try again!");
} // end if
} // end while

</script>
</head>

<body>

</body>
</html>

Twey
05-23-2006, 06:17 PM
Ugh, what horrible code. A class, you say?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Problem 2</title>
<script type="text/javascript">
function NumberGame() {
this.n1 = this.n2 = this.target = this.modifier1 = this.modifier2 = 0;
this.upper1 = this.upper2 = 1;
this.won = true;
this.message = "What is %1 plus %2?";
this.fail = "Sorry, try again!";
this.succeed = "Good job!";
}
NumberGame.prototype.construct = function() {
this.n1 = Math.floor(Math.random() * (this.upper1 + 1)) + modifier1;
this.n2 = Math.floor(Math.random() * (this.upper2 + 1)) + modifier2;
this.target = this.n1 + this.n2;
this.message = this.message.replace(/%1/g, this.n1).replace(/%2/g, this.n2);
this.won = false;
}
NumberGame.prototype.play = function() {
this.construct();
while(!this.won) {
this.won = (this.target == prompt(this.message));
if(!this.won) alert(this.fail);
}
window.alert(this.succeed);
}
var game = new NumberGame();
game.upper1 = 10;
game.upper2 = 6;
game.play();
</script>
</head>
<body>
</body>
</html>