Printing previous answers - javascript

I am creating a game where the user has to try and guess the combination of a code. I want the user to be able to see his previous attempts that he has had. However at the moment I can only get the div box's that they are in to display their most recent code.
Here is my code where the function is.
Game.countAnimals = function(playerGo){
var count = {bulls:0, cows:0};
Game.counter = 1;
for (var i = 0; i < playerGo.length; i++) {
var digPresent = playerGo.indexOf(Game.score[i]);
if (playerGo[i] == Game.score[i]) {count.bulls++;}
else if (digPresent>=0) {count.cows++;}
Game.counter++
if (count.bulls == playerGo.length && Game.counter < 7){
console.log("you have won")}
else if (count.bulls !== playerGo.length && Game.counter < 7) {
console.log("Sorry Homes")}
else if (count.bulls !== playerGo.length && Game.counter > 7 ){console.log ("you lose");}
}
$(".scoreboard1").html(count.cows);
$(".scoreboard2").html(count.bulls);

Related

Javascript battleship game - prompt not responding

I'm trying to follow along with my javascript book "headfirst javascript programming"....
the assignment is to make a simplified battleship game. It was working until I added more code... Now the prompt is not showing. Im sure im doing something wrong with the curly brackets. I just want the prompt "Ready, aim, fire! (enter a number from 0-6):" to appear when launching the browser and for it to respond to numerical inputs.
Can anyone quickly tell me why im screwing up? thank you! here is my simple code --->>>
//declare variables
var location1 = 3;
var location2 = 4;
var location3 = 5;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
//loop
while (isSunk == false) {
//get
guess = prompt("Ready, aim, fire! (enter a number from 0-6):");
if (guess < 0 || guess > 6) {
alert("Please enter a valid cell number!");
} else {
//add
guesses = guesses + 1;
//if
if (guess == location1 || guess == location2 || guess == location 3) {
alet("HIT!");
hits = hits + 1;
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS");
}
}
}
var stats = "You took " + guesses + "guesses to sink the battleship, " +
"which means your shooting accuracry was " + (3/guesses);
alert(stats);
Your lines
if (guess == location1 || guess == location2 || guess == location 3) {
and
alet("HIT!");
have errors, a extra space in location3 variable name and missing r from alert, they should be
if (guess == location1 || guess == location2 || guess == location3) {
and
alert("HIT!");

Get array values from column

If my function gets the values of one column, say column I, how can I tell it to instead get the values of the column to the right (J) instead of I:K?
function headerSearch(e, activeCell, activeRow, activeCol, data, mode, secMode, terMode) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var foundValues = [];
var forConR = data.length;
var forConC = data[0].length;
Logger.log("data[0] = " + data[0]);
for (var i = 1; i < forConR; i++) {
for (var j = 0; j < forConC; j++) {
if (activeCell != "" && activeCol == 2 && data[0][j].indexOf(mode) > -1) {
if (activeCell.getValue() == data[0][j]) {
foundValues.push(data[i][j]);
}
} else if (activeCell != "" && activeCol == 3 && data[0][j].indexOf(mode) > -1 && data[i][j] != "") {
foundValues.push(data[i][j]);
Logger.log("foundValues = " + foundValues);
}
}
}
if (foundValues != "") {
var validationRule = SpreadsheetApp.newDataValidation().requireValueInList(foundValues).build();
activeCell.offset(0, 1).setDataValidation(validationRule);
}
}
EDIT:
I tried adding foundValues.push(data[i][j+1]); which gets me out of the first column (I), but then of course adds the NEXT column (L) that I don't want either. I'm just not sure how to isolate the column index. Once I figure that out, I'm sure it's just a matter of adding +1 or something to OFFSET to the column to the right.
You have two for loops - one of them iterating through all rows, the second through all columns of data
What you want instead is to retrieve only ONE column of data rather than iterating through ALL of them
You can do it by simply dropping the second for loop and instead hardcoding the value for j
If you are itnerested in the second column of your range - the column index should be 1 (since array indices start with 0)
Without having a deeper knowledge of the purpose of your if conditions and assuming that you use them only to assess the value in column J, you can modify your code as following:
...
for (var i = 1; i < forConR; i++) {
var j = 1;
if (activeCell != "" && activeCol == 2 && data[0][j].indexOf(mode) > -1) {
if (activeCell.getValue() == data[0][j]) {
foundValues.push(data[i][j]);
}
} else if (activeCell != "" && activeCol == 3 && data[0][j].indexOf(mode) > -1 && data[i][j] != "") {
foundValues.push(data[i][j]);
Logger.log("foundValues = " + foundValues);
}
}
...
I rearranged my if statements and added one to isolate the "mode" column (B) selected. At that point, I could add j + 1 to get the following column values for the next data validation selection.
function headerSearch(e, activeCell, activeRow, activeCol, data, mode, secMode, terMode) {
var foundValues = [];
var forConR = data.length;
var forConC = data[0].length;
if (activeCell != "") {
for (var i = 1; i < forConR; i++) {
for (var j = 0; j < forConC; j++) {
if (data[0][j] == mode && data[i][j] != "") {
var modeCol = j;
}
if (activeCol == 2 && data[i][j] != "") {
if (activeCell.getValue() == data[0][j]) {
foundValues.push(data[i][j]);
}
} else if (activeCol == 3 && data[0][j].indexOf(mode) > -1 && data[i][j] != "" && data[0][modeCol + 1].indexOf(mode) > -1) {
foundValues.push(data[i][modeCol + 1]);
} else if (activeCol == 4 && data[0][j].indexOf(mode) > -1 && data[i][j] != "" && data[0][modeCol + 2].indexOf(mode) > -1) {
foundValues.push(data[i][modeCol + 2]);
}
}
}
}
if (foundValues != "") {
var validationRule = SpreadsheetApp.newDataValidation().requireValueInList(foundValues).build();
activeCell.offset(0, 1).setDataValidation(validationRule);
}
}

My HTML5 canvas game keeps blinking in between frames

I've started working on an HTML5 RPG canvas game recently, and decided to make a "text-box" sort of thing, but when once I programmed it, it started blinking between the blue and text box every other frame. What could have caused this?
Code: https://github.com/Codezters/RPG-Game-1
Important Code (I think most of the player movement stuff is irrelevant though):
function update() {
if (realm == 'overworld') {
cc.fillStyle='blue';
cc.fillRect(0,0,c.width,c.height);
cc.drawImage(bob, x, y);
// Player Walk Animations
if (direction == 'up' && idleness == false) {
if (walkstage > 0 && walkstage <4) {
document.getElementById("source").src = "IdleMoveUP1.png"
}
else if (walkstage > 3 && walkstage < 7) {
document.getElementById("source").src = "IdleUP.png"
}
else if (walkstage > 6 && walkstage < 10) {
document.getElementById("source").src = "IdleMoveUP2.png"
}
}
else if (direction == 'right' && idleness == false) {
if (walkstage > 0 && walkstage <4) {
document.getElementById("source").src = "IdleMoveRIGHT1.png"
}
else if (walkstage > 3 && walkstage < 7) {
document.getElementById("source").src = "IdleRIGHT.png"
}
else if (walkstage > 6 && walkstage < 10) {
document.getElementById("source").src = "IdleMoveRIGHT2.png"
}
}
else if (direction == 'left' && idleness == false) {
if (walkstage > 0 && walkstage <4) {
document.getElementById("source").src = "IdleMoveLEFT1.png"
}
else if (walkstage > 3 && walkstage < 7) {
document.getElementById("source").src = "IdleLEFT.png"
}
else if (walkstage > 6 && walkstage < 10) {
document.getElementById("source").src = "IdleMoveLEFT2.png"
}
}
else if (direction == 'down' && idleness == false) {
if (walkstage > 0 && walkstage <4) {
document.getElementById("source").src = "IdleMoveDOWN1.png"
}
else if (walkstage > 3 && walkstage < 7) {
document.getElementById("source").src = "IdleDOWN.png"
}
else if (walkstage > 6 && walkstage < 10) {
document.getElementById("source").src = "IdleMoveDOWN2.png"
}
}
if (idleframe == 8) {
if (direction == 'down') {
document.getElementById("source").src = "IdleDOWN.png"
idleframe = 0;
idleness = true;
}
else if (direction == 'up') {
document.getElementById("source").src = "IdleUP.png"
idleframe = 0;
idleness = true;
}
else if (direction == 'right') {
document.getElementById("source").src = "IdleRIGHT.png"
idleframe = 0;
idleness = true;
}
else if (direction == 'left') {
document.getElementById("source").src = "IdleLEFT.png"
idleframe = 0;
idleness = true;
}
if (talking == true) {
if (wordcount != textBoxTest.length) {
cc.drawImage(textBox, 0, 400);
cc.fillStyle = "white";
console.log("this is working")
cc.fillText(counted, 0, 100);
counted += textBoxTest[wordcount]
wordcount++;
}
else if (EnterToggle == true) {
EnterToggle = false;
talking = false;
}
Game so far: https://codezters.github.io/RPG-Game-1/
Solution:
I didn't need to clear the canvas when nothing was happening, so I made it clear less frequently and the problem was fixed.
The HTML is completely wrong for a start, with tags in the wrong places and obsolete elements. I mean no offense, we all have to start somewhere, but you should complete a basic course in HTML and JavaScript before attempting this. MDN is a great place to start.
You're changing the src attribute of img tags, you shouldn't be doing that at all. Use a different Image object for each file and make your code choose which image to draw instead. This ensures all images are loaded once before the game starts and not every time you change it. Loading can take place asynchronously and cause errors where the image is not ready to be drawn yet when you try to.
You also have this code:
window.onload= function() {
c=document.getElementById('gc');
document.addEventListener("keydown",keyPush)
cc=c.getContext('2d');
setInterval(update,1000/30);
};
Since you run update through setInterval, you both update and draw the game 33 times per second. You should have an independent function which takes care of drawing which is called with requestAnimationFrame(draw). This will make sure the browser only draws frames when it can, and skips drawing when the computer is having trouble keeping up. Go read the documentation on requestAnimationFrame for more info.

Text animation with p5.js and js lagging

I have the following code which uses parts of the p5.js library to animate some text in a fade in - fade out manner (which keeps looping indefinetely), i also inserted an image to make things clearer.
The problem is that after the first loop is done (when the whole text appears and then starts to disappear) i have severe lag in the browser, although it still works fine and keeps looping. Im not sure if there is a mistake in my code that threw the calculations off or if it's simply too heavy for the browser to run.
All of my vars are self explanatory, but if you have any questions or require another part of my script by all means ask me.
Any ideas that could help my case? Thank you.
//FADE animation /w Loop
if ((animType == "FADE") && (animeLoop == true)) {
if (animDirection == true) {
for (i=0; i<userText.length; i++) {
word = userText[i].html();
posXcalc = 0;
for (j=0; j<word.length; j++) {
textColor.setAlpha(charsOpacity[i][j]);
fill(textColor);
textSize(userSize);
text(word[j], userPosX + posXcalc, userPosY + (i * (userSize + userLeading)));
posXcalc = posXcalc + textWidth(word[j]);
if (charsOpacity[charsOpacity.length-1][charsOpacity[charsOpacity.length-1].length-1] < 255) {
//console.log("going");
if ((i == 0) && (j == 0) && (charsOpacity[i][j] < 255)) {charsOpacity[i][j] = charsOpacity[i][j] + speed;}
else if ((j == 0) && (i != 0)) {
temp = charsOpacity[i-1].length;
if ((charsOpacity[i-1][temp-1] > 50) && (charsOpacity[i][j] < 255)) {charsOpacity[i][j] = charsOpacity[i][j] + speed;}
}
else if (charsOpacity[i][j-1] > 50) {charsOpacity[i][j] = charsOpacity[i][j] + speed;}
}
else {animDirection = false;}
}
}
}
else {
for (i=0; i<userText.length; i++) {
word = userText[i].html();
posXcalc = 0;
for (j=0; j<word.length; j++) {
textColor.setAlpha(charsOpacity[i][j]);
fill(textColor);
textSize(userSize);
text(word[j], userPosX + posXcalc, userPosY + (i * (userSize + userLeading)));
posXcalc = posXcalc + textWidth(word[j]);
if (charsOpacity[charsOpacity.length-1][charsOpacity[charsOpacity.length-1].length-1] > 0) {
console.log("going");
if ((i == 0) && (j == 0) && (charsOpacity[i][j] > 0)) {charsOpacity[i][j] = charsOpacity[i][j] - speed;}
else if ((j == 0) && (i != 0)) {
temp = charsOpacity[i-1].length;
if ((charsOpacity[i-1][temp-1] < 200) && (charsOpacity[i][j] > 0)) {charsOpacity[i][j] = charsOpacity[i][j] - speed;}
}
else if (charsOpacity[i][j-1] < 200) {charsOpacity[i][j] = charsOpacity[i][j] - speed;}
}
else {animDirection = true;}
}
}
}
}
Okay, after a lot of trial and error i found the problem, i was missing a check in the sencond else if statement and the array was recieving values much bigger than the range of the 255 (which is the cap for the setAlpha() function) that must have create the severe lag since it had to keep adding all those values and propably recalculate the alpha inside its own function

How to show a required message next to input with Javascript? [duplicate]

This question already has an answer here:
This doesn't seem right? Javascript isn't working
(1 answer)
Closed 8 years ago.
I'm trying to make fields required but I want the error to show up next to the field it self not be alert?
You can put validation messages near inputs you wanna validate like
<span class="reqMsg">* First name is required</span>
Of course you need to hide them at first with css
.reqMsg {
color:red;
display:none;
}
Then in your form submit function you can change your relevant code to this
var valid = true;
var firstFocus = null;
for (var i = 0; i < rules.length; i++) {
if (!rules[i][1]) {
valid = false;
var parent = elem(rules[i][0]).parentNode;
parent.children[2].style.display = "inline";
if (firstFocus == null) firstFocus = parent.children[1];
}
}
if (!valid) {
firstFocus.focus();
return false;
}
return true;
You can see that it's not returning false immediately if one field is not valid. It checks all the fields then set a focus to first element of those that are not valid.
FIDDLE
Add span tag next to input tag
<span id="first-name-err"></span>
and change you javascript code as below
function alpha(e) {
var k;
document.all ? k = e.keyCode : k = e.which;
return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8);
}
var flag = true;
for (var i = 0; i < rules.length; i++) {
alert(rules[i][0]);
if (!rules[i][1]) {
var parent = elem(rules[i][0]).parentNode,
message = 'Please check your ' + (parent.textContent || parent.innerText).replace(/^\s*(.*?)\s*$/, '$1').slice(0, -1).toLowerCase() + '.';
var id = rules[i][0]+'-err';
document.getElementById(rules[i][0]+'-err').innerHTML = message;
flag = false;
}
}
return flag;
};
check this

Categories

Resources