For some reason the code inside the if statement at line 224 does not run. When the function loose() is called outside of the if statement it works. I am unsure as to what the issue with my code is.
<!DOCTYPE html>
<html>
<head>
<title>Jordan's Space Explorer </title>
</head>
<body>
<script>
// Tells user what they are about to play.
confirm ("You are about to play Jordan's Space Explorer?")
// Prompt user for their name.
userName="Capt. "+prompt("What is your name?");
shipName=prompt("What is your ship's name?")
// Declare start locations, default star system locations, and check for encounters.
var min = -10;
var max = 10;
var locationY = Math.floor(Math.random() * (max - min + 1)) + min;
var locationX = Math.floor(Math.random() * (max - min + 1)) + min;
var locationZ = Math.floor(Math.random() * (max - min + 1)) + min;
var locationYEast;
var locationYWest;
var locationXNorth;
var locationXSouth;
var locationZAbove;
var locationZBelow;
var solLocationX = Math.floor(Math.random() * (max - min + 1)) + min;
var solLocationY = Math.floor(Math.random() * (max - min + 1)) + min;
var solLocationZ = Math.floor(Math.random() * (max - min + 1)) + min;
var spacePortLocationX = Math.floor(Math.random() * (max - min + 1)) + min;
var spacePortLocationY = Math.floor(Math.random() * (max - min + 1)) + min;
var spacePortLocationZ = Math.floor(Math.random() * (max - min + 1)) + min;
var sensors = false;
var locationName = false;
var credits = 1000
var health = 100
var shipSpeed = 1
var lasers = 10
encounters();
locationQuery();
//Go directions
function goNorth(){
locationY = locationY +shipSpeed;
console.log("You head North.");
encounters();
console.log("Y = "+locationY);
}
function goSouth(){
locationY = locationY- shipSpeed;
console.log("You head South.");
encounters();
console.log("Y = "+locationY);
}
function goEast(){
locationX = locationX+shipSpeed;
console.log("You head East");
encounters();
console.log("X = "+ locationX);
}
function goWest(){
locationX = locationX-shipSpeed;
console.log("You head West");
encounters();
console.log("X = "+locationX);
}
function goUp(){
locationZ = locationZ +shipSpeed;
console.log("You go up.");
encounters();
console.log("Z = "+locationZ);
}
function goDown(){
locationZ = locationZ-shipSpeed;
console.log("You go down.");
encounters();
console.log("Z = "+locationZ);
}
// Encounters
function encounters()
{
// Sol
if(locationX === solLocationX && locationY === solLocationY && locationZ === solLocationZ){
locationName = "Sol";
console.log(shipName + " is at " + locationName)
alert("Arrived at " + locationName);
}
// Center of Galaxy
if(locationX===0 && locationY===0 && locationZ===0)
{
locationName = "Center of Galaxy";
console.log(shipName + " is at " + locationName)
alert("Arrived at " + locationName);
}
// SpacePort
if(locationX === spacePortLocationX && locationY === spacePortLocationY && locationZ === spacePortLocationZ)
{
locationName = "SpacePort"
console.log(shipName + " is at " + locationName)
alert("Arrived at " + locationName);
}
else{locationName = "empty space."}
}
// Purchase
function makePurchase()
{
if (locationName !== "SpacePort"){alert("You are not at the SpacePort.")}
if (locationName === "SpacePort")
{
var buy = prompt(userName + ", "+"what do you purchase?","Lasers, Sensors, or Repair Ship")
var purchase = buy.toUpperCase();{
if(purchase === "LASERS" && credits>=5000){lasers=lasers+10, credits= credits-5000, alert(userName+ "'s ship," + shipName +", has had it's lasers upgraded.")}
if(purchase === "SENSORS"){alert("These are not ready at this time.")}
if(purchase === "REPAIR SHIP"){shipDamage=0, alert(shipName+" has been repaired.")}
}
}
}
// Display Credits.
function creditsRemaining(){
console.log("Credits remaining: "+ credits);
}
// Display Laser Strength.
function laserStrength(){
console.log("Laser Strength: "+ lasers);
}
// Display Health.
function healthDisplay(){
console.log(health)
}
// Find things.
// Find current location.
function locationQuery(){
console.log(userName + " your ship, "+ shipName + ", is at " +locationName);
console.log("X = " +locationX);
console.log("Y = " +locationY);
console.log("Z = " +locationZ);
}
// Find Sol.
function solQuery(){
console.log("Sol is at:")
console.log("X = " + solLocationX);
console.log("Y = " + solLocationY);
console.log("Z = " + solLocationZ);
}
// Find SpacePort.
function spacePortQuery(){
console.log("The SpacePort is at:")
console.log("X = " + spacePortLocationX);
console.log("Y = " + spacePortLocationY);
console.log("Z = " + spacePortLocationZ);
}
// GoTo
function goToSpacePort(){
locationX = spacePortLocationX
locationY = spacePortLocationY
locationZ = spacePortLocationZ
locationName = "SpacePort"
}
// Quit
function quit()
{
var quitWindow = window.open("http://192.168.7.2:3000/workspace/myScripts/jordansSpaceExplorer/game/quitPage.html","_self");
}
//Loose
function loose()
{
var looseWindow = window.open("http://192.168.7.2:3000/workspace/myScripts/jordansSpaceExplorer/game/loose.html","_self");
}
// Suicide
function suicide()
{
health = health-100;
}
// Loose Conditions.
if(health <= 0){
console.log("You have lost the game.")
loose()
}
</script>
Controls: <br>
<button onclick="goEast()">Go East</button>
<button onclick="goWest()">Go West</button>
<br>
<button onclick="goNorth()">Go North</button>
<button onclick="goSouth()">Go South</button>
<br>
<button onclick="goUp()">Go Up</button>
<button onclick="goDown()">Go Down</button>
<br>
<button onclick="creditsRemaining()">Credits</button>
<button onclick="healthDisplay()">Heath</button>
<button onclick="laserStrength()">Lasers</button>
<br>
<button onclick="locationQuery()">Where am I?</button>
<button onclick="quit()">Quit</button>
<br>
SpacePort:
<br>
<button onclick="makePurchase()">Purchase</button>
<br>
Debug: <br>
<button onclick="spacePortQuery()">Where is SpacePort?</button><br>
<button onclick="solQuery()">Where is Sol?</button><br>
<button onclick="engageSensors()">Engage Sensors</button><br>
<button onclick="goToSpacePort()">SpacePort</button><br>
<button onclick="suicide()">Suicide!</button>
<button onclick="loose()">Loose</button>
</body>
</html>
Any help would be appreciated. I am new to programming so please take this into consideration.
You can changes your if statement to something along the lines of
function checkLost() {
// Loose Conditions.
if(health <= 0){
console.log("You have lost the game.")
loose()
}
setTimeout(checkLost, 100);
}
setTimeout(checkLost, 100);
Another way is to add the logic to the method that is lowering the life of the "ship" in this case. Like in you suicide method.
The if statement isn't in any function, so it will be executed when the script loads.
At that moment, the variable health has the value 100, so it is normal it should not call the function loose().
Maybe you should have a timer to check the health, or a function that you will call in every function that modifies the health.
You could do it like this:
function suicide()
{
health = health-100;
checkHealth();
}
function checkHealth() {
// Loose Conditions.
if(health <= 0){
console.log("You have lost the game.")
loose()
}
}
Related
I am trying to make a random math quiz and I want to get new random numbers
after every click on the button.
I success to get new random numbers on every click but I still get the result of the first random numbers I got on the loading on the page
Another thing I need help to increase the score size-font every time the user enters the correct answer.
I tried to do it with 2.0em but it increases only once.
HTML
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<center>
<h1 style="font-size: 400%">Random Math Quiz</h1>
<div id="question"></div>
<input type="text" name="answer" id="answer" style="width: 250px; height: 40px; font-size: 32px;">
<br><br>
<button onclick="quiz()">Enter</button>
<br><br>
Score: <div id="score">0</div>
</center>
<script src="script.js"></script>
</body>
</html>
JavaScript
var int1 = Math.floor(Math.random() * 10) + 1;
var int2 = Math.floor(Math.random() * 10) + 1;
document.getElementById('question').innerHTML = int1 + " " + "+" + " " + int2;
var answer = int1 + int2;
var score=0;
function quiz() {
{
var uanswer = document.getElementById('answer').value;
if (uanswer == answer) {
alert("Correct");
score=(score)+1;
document.getElementById('score').innerHTML =score ;
document.getElementById("question").style.fontSize = "2.0em";
} else {
alert("OOPS Try Again!")
score= (score)-5;
document.getElementById('score').innerHTML =score ;
}
}
}
The reason your numbers do not change, is because every time you call that quiz function, you did not change the original int1 and int2. The whole javascript is only loaded once and and two numbers will only be set at a random number, once. Unless you fire a function to change the variables.
try this:
var score=0;
var int1 = Math.floor(Math.random() * 10) + 1
var int2 = Math.floor(Math.random() * 10) + 1
var answer = int1 + int2;
document.getElementById('question').innerHTML = int1 + " " + "+" + " " + int2;
function quiz() {
var user_answer = document.getElementById('answer').value;
if (user_answer == answer) {
alert("Correct");
score=(score)+1;
document.getElementById('score').innerHTML =score
} else {
alert("OOPS Try Again!")
score= (score)-5;
document.getElementById('score').innerHTML =score ;
}
// you need to reset the int1, int2, and answer by generating new numbers
int1 = Math.floor(Math.random() * 10) + 1;
int2 = Math.floor(Math.random() * 10) + 1;
answer = int1 + int2
document.getElementById('question').innerHTML = int1 + " " + "+" + " " + int2;
}
Since int1 and int2 are outside of the function they going to have the same value.
You need to generate a new random number each time you call the function quiz().
same with the font size - you changed it only once from default to 2em when you need to increase the value every time you call quiz().
var int1 = Math.floor(Math.random() * 10) + 1;
var int2 = Math.floor(Math.random() * 10) + 1;
document.getElementById('question').innerHTML = int1 + " " + "+" + " " + int2;
var answer = int1 + int2;
var score=0;
var fontSize = 1;
function quiz() {
{
var uanswer = document.getElementById('answer').value;
if (uanswer == answer) {
alert("Correct");
score=(score)+1;
document.getElementById('score').innerHTML =score ;
document.getElementById("question").style.fontSize = fontSize + 'em';
fontSize++;
int1 = Math.floor(Math.random() * 10) + 1;
int2 = Math.floor(Math.random() * 10) + 1;
answer = int1 + int2;
} else {
alert("OOPS Try Again!")
score= (score)-5;
document.getElementById('score').innerHTML =score ;
}
}
}
What about this approach? You call a function in order to reset the random values after each guess. And you store your fontSize in a variable, which you increase by 2 each time the user guesses right.
// intitial setup
var int1 = Math.floor(Math.random() * 10) + 1;
var int2 = Math.floor(Math.random() * 10) + 1;
document.getElementById('question').innerHTML = int1 + " " + "+" + " " + int2;
var answer = int1 + int2;
var score=0;
var fontSize = 2;
function quiz() {
var uanswer = document.getElementById('answer').value;
if (uanswer == answer) {
alert("Correct");
score=(score)+1;
document.getElementById('score').innerHTML =score;
document.getElementById("question").style.fontSize = fontSize + ".0em";
// increase fontSize by 2 for the next correct answer
fontSize += 2;
} else {
alert("OOPS Try Again!")
score= (score)-5;
document.getElementById('score').innerHTML =score;
}
// set new values
resetValues();
}
resetValues = () => {
int1 = Math.floor(Math.random() * 10) + 1;
int2 = Math.floor(Math.random() * 10) + 1;
document.getElementById('question').innerHTML = int1 + " " + "+" + " " + int2;
answer = int1 + int2;
score=0;
}
I am working on creating a small 5 question addition quiz that asks the user a new random addition question every time they answer the previous one. I would like to be able to have my script ask a new question every time the user clicks on the "check answer" button without having to refresh the page. Then, once the user has completed the 5 questions, I would like to be able to have a popup state they have completed the quiz and can refresh the page to start a new quiz. With my current code, the script asks a random addition question, and then once the user clicks on the "check answer" button, the user must refresh the page to get a new question. I am stuck on figuring out how to modify my current code to fit what I am trying to do. I am thinking that a while loop may be they way to go, but I don't really know how to implement it. The code that I have so far is: `
<h1>Addition Quiz!</h1>
<p>This short 5 question quiz will test your addition skills! Answer the question as the computer asks it and pat yourself on the back for each correct answer!</p>
<h3 id="mathquestion"></h3>
<input type="text" name="answerbox" id="answerbox">
<button onclick="addition()">Check Answer</button>
<script>
var minimum = 1;
var maximum = 9;
var intiger1 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
var intiger2 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
document.getElementById("mathquestion").innerHTML = intiger1 + " " + "+" + " " + intiger2;
var questionanswer = intiger1 + intiger2;
function addition() {
var useranswer = document.getElementById('answerbox').value;
if (useranswer == questionanswer) {
alert("Correct! Congrats!");
} else {
alert("Sorry, your answer is incorrect. Better luck with the next question!")
}
}
</script>`
So what you want is the part that setups your question into a new function. And run that function when the answer is right. An example:
<script>
var minimum = 1;
var maximum = 9;
var questionanswer = 0;
setupQuestion();
function setupQuestion(){
var intiger1 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
var intiger2 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
document.getElementById("mathquestion").innerHTML = intiger1 + " " + "+" + " " + intiger2;
questionanswer = intiger1 + intiger2;
}
function addition() {
var useranswer = document.getElementById('answerbox').value;
if (useranswer == questionanswer) {
alert("Correct! Congrats!");
setupQuestion();
} else {
alert("Sorry, your answer is incorrect. Better luck with the next question!")
}
}
</script>`
Just update the variable
<script>
var minimum = 1;
var maximum = 9;
var intiger1 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
var intiger2 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
document.getElementById("mathquestion").innerHTML = intiger1 + " " + "+" + " " + intiger2;
var questionanswer = intiger1 + intiger2;
function addition() {
var useranswer = document.getElementById('answerbox').value;
if (useranswer == questionanswer) {
alert("Correct! Congrats!");
} else {
alert("Sorry, your answer is incorrect. Better luck with the next question!")
}
// Updating question
intiger1 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
intiger2 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
document.getElementById("mathquestion").innerHTML = intiger1 + " " + "+" + " " + intiger2;
}
</script>
I'm working on a somewhat simply dice game but I can't get it to display the alert popup when I click the button.
I'm also trying to figure out the simplest way to check if housescore or myscore = maxscore then alert "congratulations, you win" or "sorry, you lost"
Here is my code:
var myscore = 0;
var maxScore = 100;
var housescore = 0;
function rollDice() {
var x = Math.floor(Math.random() * 6) + 1;
var y = Math.floor(Math.random() * 6) + 1;
if (x + y == 7 || 11) {
housescore = (housescore + 10);
alert("CRAPS" + " Your Score is " + "Player: " + myscore + "House: " + housescore);
} else if (x == y && x + y == isEven(n)) {
myscore = (myscore + 10);
alert("Even Up" + " Your Score is " + "Player: " + myscore + "House: " + housescore);
}
if (x == y && x + y == isOdd(n)) {
housescore = (housescore + 10);
alert("Odd Ball" + " Your Score is " + "Player: " + myscore + "House: " + housescore);
} else {
alert("You rolled a " + x + " and a " + y + " Your Score is " + "Player: " + myscore + "House: " + housescore);
}
}
function isEven(n) {
return n % 2 == 0;
}
function isOdd(n) {
return Math.abs(n % 2) == 1;
}
<input type="button" value="Roll The Dice" onClick="rollDice()" />
This is what I think you're after. I broke down your ifs to handle both cases where x == y in one branch, and used a simple mod operation to determine whether a die roll was even, and an else to handle the odd die rolls.
var myscore = 0;
var maxScore = 100;
var housescore = 0;
function rollDice() {
var x = Math.floor(Math.random() * 6) + 1;
var y = Math.floor(Math.random() * 6) + 1;
var total = x + y;
msg = "You rolled " + x + "," + y + " = " + total + "\n";
if (total == 7 || total == 11) {
housescore += 10;
msg += "CRAPS";
} else if (x == y) { // this condition contains two possible outcomes, handle both within this else if
if (x % 2 == 0) {
myscore += 10;
msg += "Even Up";
} else {
housescore += 10;
msg += "Odd Ball";
}
}
msg += " Your Score is " + "Player: " + myscore + ", House: " + housescore;
alert(msg);
}
<!DOCTYPE html>
<html>
<body>
<input type="button" value="Roll The Dice" onClick="rollDice()" />
</body>
</html>
Code like this is wrong:
if (x == y && x + y == isEven(n))
You haven't declared an n variable. And it makes no sense to compare the addition of two numbers to the true or false value that isEven() and isOdd() return. I think what you meant was:
if (x == y && isEven(x + y))
But when the two numbers are equal, adding them together will always be even, so I'm not sure what the point of that test is. Maybe you mean:
if (x == y && isEven(x))
I'm not familiar with a rule in Craps where the house or player win depending on whether equal dice are even or odd.
This is also wrong:
if (x == 7 && y == 11)
x and y are numbers from 1 to 6, so they can't be 7 or 11. In craps you add the two dice, so this should be:
if (x + y == 7 || x + y == 11)
There's little need for both isEven() and isOdd() functions -- a number is odd if it's not even.
<!DOCTYPE html>
<html>
<body>
<input type="button" value="Roll The Dice" onClick="rollDice()" />
<br />
<script type="text/javascript">
var score = 0;
var maxScore = 50;
var rolls = 0;
var maxRolls = 20;
function rollDice()
{
var x = Math.floor( Math.random() * 6 ) + 1;
var y = Math.floor( Math.random() * 6 ) + 1;
if( x == y )
{
score = getScore( x );
alert("You threw a Double " + x + " Your Score is "+ score);
}
else
{
alert("You threw a " + x + " and a " + y + " Your Score is " + score);
}
rolls++;
if (rolls == maxRolls && score < maxScore)
{
alert("Sorry You Lose!");
score = 0;
rolls = 0;
return;
}
else if (score >= maxScore)
{
alert("Congratulations You Win!");
score = 0;
rolls = 0;
return;
}
}
function getScore(x)
{
switch( x )
{
case 1:
score += 5;
break;
case 2:
score += 5;
break;
case 3:
score = 0;
break;
case 4:
score += 5;
break;
case 5:
score += 5;
break;
case 6:
score += 25;
break;
}
return score;
}
</script>
</body>
</html>
</html>
I am trying to make so when the looping of 100 hits on the character exits the loop when the life dice rolls to 0. How it currently is is all gets looped 100 times. I am not quite sure how I need to go about solving this, any tips would be helpful. My code is below.
function addChar(fname, lname, speed, agility, wep, outfit, mood) {
this.fname = fname;
this.lname = lname;
this.speed = speed;
this.agility = agility;
this.wep = wep;
this.outfit = outfit;
this.mood = mood;
this.special = function(specialMove) {
specialMove();
}
this.jumpKick = function() {
var jmpkckTimes = Math.floor(Math.random() * (100 - 33 + 1)) + 33;
document.write("He jumpkicks " + jmpkckTimes + " times. ");
if (jmpkckTimes > 70) {
document.write("He enters rage mode! ");
} else {
document.write("He does not have enough kicks for rage mode. ");
}
}
this.hits = function() {
var allHits = Math.floor(Math.random() * (100 - 33 + 1)) + 33;
document.write(" He gets attacked for " + allHits + " HP.");
}
this.lifes = function() {
var life = Math.floor(Math.random() * (3 - 0 + 1)) + 0;
if (life > 0) {
document.write(" The life dice rolls a " + life + ". You have survived! For now...");
} else {
document.write(" The life dice rolls a " + life + ". You have died!");
}
}
}
var myChar = new addChar('Johhny', 'Kicker', 10, 7, 'Ancient Greataxe', 'Barrows', 'angry');
document.write(myChar.fname + " " + myChar.lname + "'s speed is " + myChar.speed + "<br>");
document.write(myChar.fname + " " + myChar.lname + "'s agility is " + myChar.agility + "<br>");
document.write(myChar.fname + " " + myChar.lname + "'s weapon of choice is: " + myChar.wep + "<br>");
document.write(myChar.fname + " " + myChar.lname + " feels " + myChar.mood + "<br>");
document.write(myChar.fname + " " + myChar.lname + " attempts his special: ");
myChar.special(myChar.jumpKick)
for (i = 1; i < 101; i++) {
myChar.hits(myChar.allHits)
myChar.lifes(myChar.lifes)
}
function myOutfit() {
document.getElementById("demo").innerHTML = ("He is wearing " + myChar.outfit)
}
var start = Date.now();
var response = prompt("Do you think my character has what it takes?", "");
var end = Date.now();
var elapsed = (end - start) / 1000;
console.log("You took " + elapsed + " seconds" + " to type: " + response);
You need to have a way to communicate outside of the object, of what is happening inside the object.
For example, when something happens in a function, like lifes() or hits(), you should assign a value to a variable on the object to retain state. That way you can access the state from the for loop.
Example:
this.isAlive = true; // starting condition
this.lifes = function() {
var life = Math.floor(Math.random() * (3 - 0 + 1)) + 0;
this.isAlive = (life > 0);
if (this.alive) {
document.write('you survived');
} else {
document.write('you died');
}
Now in your for loop, you can access isAlive:
// loop until 100 attempts or you die, which ever comes first
for (i = 1; i < 101 && myChar.isAlive; i++) {
myChar.hits(myChar.allHits)
myChar.lifes(myChar.lifes)
}
well in general you can break out of foor loops aswell as prevent further execution of a foor loop and continue the next iteration:
for (var i = 0; i < 10; i++) {
if (i == 4) continue;
if (i == 8) break;
console.log(i);
}
this will basically print: 0, 1, 2, 3, 5, 6, 7
(as you can see it kind of skipped 4)
(it will also work in while / do while loops)
so in your case you could check if the return value of one of your functions is true or false or do some other kind of conditional checking in order to break out of the loop.
or similar to how Rob Brander wrote in his answer:
var maxTurns = 100;
var turns = 0;
while (myChar.isAlive && ++turns <= maxTurns) {
myChar.hits();
myChar.lifes();
}
console.log("character is: " + myChar.isAlive ? "alive" : "dead");
console.log("after: " + turns + " turns.");
Simple button that should be creating new <p> elements when its clicked but it isn't working and I'm not sure why as I've compared it to other code of mine.
Demo
var battle = function() {
while(monsterHP > 0){
var playerDam = Math.floor(Math.random() * ((playerAtk - monsterAtk) + 2);
$('#battle').append("<p>You have hit the monster for " + playerDam + " damage. The monster has " + (monsterHP - playerDam) + "HP left</p>");
monsterHP -= playerDam;
if(monsterHP <= 0) {
$('#battle').append("<p>You have defeated the monster</p>");
}
}
}
$('#battleButton').click(function() {
battle();
}
You have many syntax errors in your code. If you correct them (as below), then it works fine. When you write a JQuery append, you need to put a ')' after your argument. Likewise, functions need to have a '}' after them.
var playerAtk = 5;
var playerDef = 5;
var playerHP = 10;
var monsterAtk = 4;
var monsterDef = 4;
var monsterHP = 8;
var battle = function() {
while(monsterHP > 0){
var playerDam = Math.floor(Math.random() * ((playerAtk - monsterAtk) + 2));
$('#battle').append("<p>You have hit the monster for " + playerDam + " damage. The monster has " + (monsterHP - playerDam) + "HP left</p>");
monsterHP -= playerDam;
if(monsterHP <= 0) {
$('#battle').append("<p>You have defeated the monster</p>");
}
}
}
$('#battleButton').click(function() {
battle();
});