Javascript Check variable.Then gain ++ per second - javascript

I have a problem i want to check a variable.If its 0 then gain ++ after 1.5s.If its 10 then gain ++ after .4s.Its complicated.It doesnt really work.My code so far:
if(road == 1){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1400);}
else if(road == 2){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1300);}
else if(road == 3){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1200);}
else if(road == 4){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1100);}
else if(road == 5){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1000);}
else if(road == 6){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},900);}
else if(road == 7){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},800);}
else if(road == 8){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},600);}
else if(road == 9){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},400);}
else if(road == 10){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},200);}
else{setInterval(function(){stamina++;document.getElementById("stamina").innerHTML = stamina;},1500);}
And the code to build a road is this:
function build_road() {
if ((wood + tavern) >= 29 && stone > 4 && road < 10) {
road++;
document.getElementById("road_count").innerHTML = road;
wood = (wood + tavern) - 20;
stone = stone - 5;
document.getElementById("wood").innerHTML = wood;
document.getElementById("stone").innerHTML = stone;
exp = exp + 20;
var x = document.getElementById("PROGRESS");
x.setAttribute("value", exp);
x.setAttribute("max", max);
if (exp == 100) {
exp = 0;
level++;
document.getElementById("level").innerHTML = level;
}
alert("Congratulations,You've create a Road,Now you gain stamina slightly faster.");
}
else {
alert("You need: 30Wood,5Stone .Maximum 10 Roads.")
}
}

Make reusable functions (it's often a good practice, when you a difficulties with a piece of code, to break it into small functions):
var staminaIncreaseTimer = null;
function configureStaminaIncrease(delay) {
if (staminaIncreaseTimer !== null)
clearInterval(staminaIncreaseTimer);
staminaIncreaseTimer = setInterval(function () {
increaseStamina();
}, delay);
}
function increaseStamina() {
stamina += 1;
document.getElementById("stamina").innerHTML = stamina;
}
Solution with an array (suggested by Jay Harris)
var roadIndex = road-1;
var ROAD_DELAYS = [1400, 1300, 1200, /*...*/];
var DEFAULT_DELAY = 1500;
if (roadIndex < ROAD_DELAYS.length) {
configureStaminaIncrease(ROAD_DELAYS[roadIndex]);
} else {
configureStaminaIncrease(DEFAULT_DELAY);
}
Solution with a switch instead of you if-elseif mess:
switch (road) {
case 1:
configureStaminaIncrease(1400);
break;
case 2:
configureStaminaIncrease(1300);
break;
case 3:
configureStaminaIncrease(1200);
break;
//and so on...
default:
configureStaminaIncrease(1500);
}

Related

Javascript: Global Variables Aren't Defined In Other Functions

I have three variables that I need to put in the innerHTML of four spans. The variables I use are seconds, accurateclick, and inaccurateclick. The process I use to get these variables is fine. The problem is I can't figure out how to bring them over to another function. I will make a replica of what I have. This will be a simpler version.
var x;
var y;
var z;
function A(){
x = 1;
y = 2;
z = 3;
B();
}
function B(){
var a = "";
var b = "";
var c = "";
var d = "";
a += x;
b += y;
c += z;
d += (x + y + z);
}
What would happen is, instead of a being equal to 1, b being equal to 2, and c being equal to 3, they would all equal to undefined. I don't know why that is happening when x, y, and z are global variables. I thought they should change when set to a different value.
Here is my actual code:
var seconds;
var accurateclicks;
var inaccurateclicks;
var windowheight = window.innerHeight;
var windowwidth = window.innerWidth;
var colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Purple"];
var randomcolor = colors[Math.floor(Math.random()*colors.length)];
function BeginGameLoad(){
var BottomLabel1 = document.getElementById("bl1");
var BeginGameContainer = document.getElementById("BGC1");
var RightClick = false;
BottomLabel1.addEventListener("mousedown", BL1MD);
BottomLabel1.addEventListener("mouseup", BL1MU);
BottomLabel1.style.cursor = "pointer";
window.addEventListener("resize", BeginGameResize);
window.addEventListener("contextmenu", BeginGameContextMenu);
function BeginGameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function BL1MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
var randomcolor = colors[Math.floor(Math.random()*colors.length)];
BottomLabel1.style.color = randomcolor;
RightClick = false;
}
}
function BL1MU(){
if(RightClick == false){
window.location.href = "Game.html";
GameLoad();
}
else{
RightClick = false;
}
}
if(windowheight < 600)
{
BeginGameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
BeginGameContainer.style.width = "800px";
}
function BeginGameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
BeginGameContainer.style.height = "600px";
}
if(windowheight > 600)
{
BeginGameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
BeginGameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
BeginGameContainer.style.width = "100%";
}
}
}
function GameLoad(){
var LeftPanel2 = document.getElementById("lp2");
var LeftColorPanel2 = document.getElementById("lcp2");
var TopPanel2 = document.getElementById("tp2");
var TopLabel2 = document.getElementById("tl2");
var RightPanel2 = document.getElementById("rp2")
var RightLabel2 = document.getElementById("rl2");
var GameContainer = document.getElementById("GC2");
var MiddleLabelTwo = document.getElementById("mltwo3");
var MiddleLabelThree = document.getElementById("mlthree3");
var MiddleLabelFour = document.getElementById("mlfour3");
var MiddleLabelFive = document.getElementById("mlfive3");
var clickedRightName = false;
var clickedRightColor = false;
var clickedRightNameColor = false;
var RightClick = false;
var ClickedLeftColorPanel = false;
var ClickedRightLabel = false;
var ClickedTopLabel = false;
var Timer;
TopPanel2.addEventListener("mouseup", TP2MU);
TopLabel2.addEventListener("mousedown", TL2MD);
TopLabel2.addEventListener("mouseup", TL2MU);
TopLabel2.style.cursor = "pointer";
LeftPanel2.addEventListener("mouseup", LP2MU);
LeftColorPanel2.addEventListener("mouseup", LCP2MU);
LeftColorPanel2.addEventListener("mousedown", LCP2MD);
LeftColorPanel2.style.cursor = "pointer";
RightPanel2.addEventListener("mouseup", RP2MU);
RightLabel2.addEventListener("mouseup", RL2MU);
RightLabel2.addEventListener("mousedown", RL2MD);
RightLabel2.style.cursor = "pointer";
window.addEventListener("resize", GameResize);
window.addEventListener("contextmenu", GameContextMenu);
function AddSeconds(){
seconds++;
}
function GameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function TL2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else if(clickedRightName == true && clickedRightColor == true && clickedRightNameColor == true){
TopLabel2.style.color = randomcolor;
RightClick = false;
}
}
function TP2MU(){
if(ClickedTopLabel == false){
inaccurateclicks++;
}
else{
ClickedTopLabel = false;
}
}
function TL2MU(){
ClickedTopLabel = true;
if(clickedRightName == true && clickedRightColor == true && clickedRightNameColor == true && RightClick == false){
clearInterval(Timer);
accurateclicks++;
window.location.href = "EndGame.html";
EndGameLoad();
}
else if (!clickedRightName == true && !clickedRightColor == true && !clickedRightNameColor == true && RightClick == false){
clearInterval(Timer);
Timer = setInterval(AddSeconds, 1000);
seconds = 0;
accurateclicks = 0;
inaccurateclicks = 0;
TopLabel2.innerHTML = randomcolor;
RightClick = false;
}
else{
inaccurateclicks++;
}
RightClick == false
}
function LCP2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
RightClick = false;
}
}
function LCP2MU(){
ClickedLeftColorPanel = true;
if(clickedRightColor == false && TopLabel2.innerHTML != "Click Here To Start" && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2.toLowerCase() == LeftColorPanel2.style.backgroundColor){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2.toLowerCase() != LeftColorPanel2.style.color){
LeftColorPanel2.style.backgroundColorr = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2.toLowerCase() != LeftColorPanel2.style.backgroundColor){
LeftColorPanel2.style.backgroundColor = randomcolor2;
accurateclicks++;
}
if (LeftColorPanel2.style.backgroundColor == randomcolor.toLowerCase()){
clickedRightColor = true;
LeftColorPanel2.style.cursor = "auto";
}
randomcolor2 = null;
RightClick = false;
}
else if(clickedRightColor == true && RightClick == false){
inaccurateclicks++;
}
}
function LP2MU(){
if(ClickedLeftColorPanel == false){
inaccurateclicks++;
}
else{
ClickedLeftColorPanel = false;
}
}
function RL2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
RightClick = false;
}
}
function RL2MU(){
ClickedRightLabel = true;
if(clickedRightName == false && TopLabel2.innerHTML != "Click Here To Start" && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2 == RightLabel2.innerHTML){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2 != RightLabel2.innerHTML){
RightLabel2.innerHTML = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2 != RightLabel2.color){
RightLabel2.innerHTML = randomcolor2;
accurateclicks++;
}
if (RightLabel2.innerHTML == randomcolor){
clickedRightName = true;
}
randomcolor2 = null;
}
else if(clickedRightName == true && clickedRightNameColor == false && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2.toLowerCase() == RightLabel2.style.color){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2.toLowerCase() != RightLabel2.style.color){
RightLabel2.style.color = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2.toLowerCase() != RightLabel2.style.color){
RightLabel2.style.color = randomcolor2;
accurateclicks++;
}
if (RightLabel2.style.color == randomcolor.toLowerCase()){
clickedRightNameColor = true;
RightLabel2.style.cursor = "auto";
}
randomcolor2 = null;
}
else if(clickedRightName == true && clickedRightNameColor == true && RightClick == false){
inaccurateclicks++;
}
}
function RP2MU(){
if(ClickedRightLabel == false){
inaccurateclicks++;
}
else{
ClickedLeftColorPanel = false;
}
}
if(windowheight < 600)
{
GameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
GameContainer.style.width = "800px";
}
function GameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
GameContainer.style.height = "600px";
}
if(windowheight > 600)
{
GameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
GameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
GameContainer.style.width = "100%";
}
}
}
function EndGameLoad(){
var BottomLabel3 = document.getElementById("bl3");
var EndGameContainer = document.getElementById("EGC3");
var MiddleLabelTwo = document.getElementById("mltwo3");
var MiddleLabelThree = document.getElementById("mlthree3");
var MiddleLabelFour = document.getElementById("mlfour3");
var MiddleLabelFive = document.getElementById("mlfive3");
var RightClick = false;
BottomLabel3.addEventListener("mousedown", BL3MD);
BottomLabel3.addEventListener("mouseup", BL3MU);
BottomLabel3.style.cursor = "pointer";
window.addEventListener("resize", EndGameResize);
MiddleLabelTwo.innerHTML += seconds;
MiddleLabelThree.innerHTML += accurateclicks;
MiddleLabelFour.innerHTML += inaccurateclicks;
MiddleLabelFive.innerHTML += seconds + accurateclicks + inaccurateclicks;
window.addEventListener("contextmenu", EndGameContextMenu);
function EndGameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function BL3MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true
}
else{
randomcolor = colors[Math.floor(Math.random()*colors.length)];
BottomLabel3.style.color = randomcolor;
RightClick = false;
}
}
function BL3MU(){
if(RightClick == false){
MiddleLabelTwo.innerHTML = "Time (Seconds): "
MiddleLabelThree.innerHTML = "Accurate Clicks: "
MiddleLabelFour.innerHTML = "Inaccurate Clicks: "
MiddleLabelFive.innerHTML = "Score: "
window.location.href = "Game.html";
}
}
if(windowheight < 600)
{
EndGameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
EndGameContainer.style.width = "800px";
}
function EndGameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
EndGameContainer.style.height = "600px";
}
if(windowheight > 600)
{
EndGameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
EndGameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
EndGameContainer.style.width = "100%";
}
}
}
Whenever I run it, it works up to this point
MiddleLabelTwo.innerHTML += seconds;
MiddleLabelThree.innerHTML += accurateclicks;
MiddleLabelFour.innerHTML += inaccurateclicks;
MiddleLabelFive.innerHTML += seconds + accurateclicks + inaccurateclicks;
It says seconds, accurateclicks, and inaccurateclicks are all undefined. I don't know why this would happen given that they were defined in the previous function [Game()].
try writing,
x = 1;
y = 2;
z = 3;
function A() {
B();
}
function B() {
var a = "";
var b = "";
var c = "";
var d = "";
a += x;
b += y;
c += z;
d += (x + y + z);
console.log(a, b, c, d);
}
A();
Reason: 'var' defines variables locally!
You did make two html files and this caused the js file to reload. This is why the global variables are declared again and are renewed to undefined.The solution is to work with one html file and to only reload the body.
My syntax was right, but as #Julie mentioned, the variables were being reloaded. How to get JS variable to retain value after page refresh? this helped me solve my problem.

Tic Tac Toe with Minimax and Javascript

I am attempting to create a Tic Tac Toe game using Javascript as part of my learning on FreeCodeCamp and after my 5th attempt still haven't managed to get it to work. I think i'm doing the correct thing, but the computer AI is still making very stupid decisions and loosing.
Here is my entire AI function, which can be called using a console log to see the recommended move from the AI. However when i hard code values for moves already taken and ask for the next move, it doesn't pick what i would expect.
/*
Attempt to inplement a Tic Tac Toe minimax game
5th attempt, so hopefully this time it works!
*/
var util = require("util");
//These are all the winning square sequences, as string to make various things easier
var validRows = [
['00','01','02'], // left column
['10','11','12'], // middle column
['20','21','22'], // right column
['00','10','20'], // top row
['01','11','21'], // middle row
['02','12','22'], // bottom row
['00','11','22'], // Diag TL to BR
['20','11','02'] // Diag BL to TR
];
//Our scoring arrays for evaulating moves
var max1 = ['100','010','001'];
var min1 = ['200','020','002'];
var max2 = ['110','011'];
var min2 = ['220','022'];
var max3 = ['111'];
var min3 = ['222'];
//All the valid squares
var validSquaresFactory = ['00','10','20','01','11','21','02','12','22'];
//Store all the moves somewhere
//var computerMoves = ['10','22'];
//var userMoves = ['00','02'];
//Store all the moves somewhere
var computerMoves = ['11','22'];
var userMoves = ['00','01'];
function Board(minOrMax,computerMoves,userMoves){
this.computer = computerMoves;
this.user = userMoves;
this.minOrMax = minOrMax;
this.remaining = this.genRemaining();
this.complete = this.genComplete();
var results = this.getScore();
this.score = results[0];
this.winOrLoose = results[1];
}
Board.prototype.genRemaining = function(){
//Create an array of all moves taken
var takenMoves = this.computer.concat(this.user);
//Calculate all remaining squares
var validSquares = validSquaresFactory.filter(function(object){
return takenMoves.indexOf(object) === -1;
});
return validSquares;
}
Board.prototype.genComplete = function(){
return ((this.computer.length + this.user.length) === 9);
}
Board.prototype.flipMinOrMax = function(){
return (this.minOrMax === 'max') ? 'min' : 'max'
}
Board.prototype.genArrays = function(minOrMax,square){
var tempUser = this.user.slice(0);
var tempComputer = this.computer.slice(0);
if(minOrMax === 'min'){
tempUser.push(square);
} else {
tempComputer.push(square);
}
return [tempComputer,tempUser];
}
Board.prototype.generateBoards = function(minOrMax){
var boards = [];
var that = this;
this.remaining.forEach(function(remainingSquare){
var moves = that.genArrays(minOrMax,remainingSquare);
boards.push(new Board(minOrMax,moves[0],moves[1]));
})
//console.log(boards);
return boards;
}
Board.prototype.getScore = function(){
var that = this;
var winOrLoose = false;
var returnScore = validRows.reduce(function(storage,row,index,array){
var score = row.reduce(function(storage1,square){
if (that.computer.indexOf(square) !== -1) {
storage1 += '1';
} else if (that.user.indexOf(square) !== -1) {
storage1 += '2';
} else {
storage1 += '0';
}
return storage1;
},'')
var finalScore = 0;
if(max1.indexOf(score) != -1){
finalScore = 1;
} else if(min1.indexOf(score) != -1){
finalScore = -1;
} else if(max2.indexOf(score) != -1){
finalScore = 10;
} else if(min2.indexOf(score) != -1){
finalScore = -10;
} else if(max3.indexOf(score) != -1){
winOrLoose = true;
finalScore = 100;
} else if(min3.indexOf(score) != -1){
winOrLoose = false;
finalScore = -100;
}
storage.push(finalScore);
return storage;
},[])
var condensedReturnScore = returnScore.reduce(function(storage,score){
return storage+score;
})
return [condensedReturnScore,winOrLoose];
}
function generateMove(){
var board = new Board('max',computerMoves,userMoves);
var scores = [];
var boards = board.generateBoards('max');
boards.forEach(function(board){
scores.push(testMove(board,4));
});
scores = scores.map(function(score,index){
return [board.remaining[index],score];
});
var returnValue = scores.reduce(function(storage,score){
return (score[1].score > storage[1].score) ? score : storage;
});
return [returnValue[0],returnValue[1].score];
}
function testMove(masterBoard,count){
count --;
var boards = [];
boards = masterBoard.generateBoards(generateMinOrMax(masterBoard.minOrMax));
//console.log('/////////Master Board/////////');
//console.log(masterBoard);
//console.log(boards);
//console.log('//////////////////////////////');
boards = boards.map(function (move) {
if (move.complete === true || count === 0 || move.winOrLoose === true){
return move;
} else {
var returnScore = testMove(move,count);
return returnScore;
}
});
returnBoard = boards.reduce(function(storage,board,index,array){
if(board.minOrMax === 'max'){
return (board.score > storage.score) ? board : storage;
} else {
return (board.score < storage.score) ? board : storage;
}
});
return returnBoard;
}
function generateMinOrMax(minOrMax){
return (minOrMax === 'max') ? 'min' : 'max'
}
I've checked the scoring function and from what i can see it is returning the expected score for any move i try, but because of the shear number of possibilities calculated it's very hard to debug efficiently.
Any help/pointers on this would be most appreciated as i have really hit a brick wall with this, can't see the forrest for the trees e.t.c
If you would like to test this with the GUI, it's on codepen at - http://codepen.io/gazzer82/pen/yYZmvJ?editors=001
So after banging my head against this for day, as soon as i posted this i found the issues. Firstly using the wrong variable for minormax in my reduce function, so it wasn't flipping correctly and not setting the winOrLoose value correctly for a score of -100. Here is the corrected version.
*
Attempt to inplement a Tic Tac Toe minimax game
5th attempt, so hopefully this time it works!
*/
var util = require("util");
//These are all the winning square sequences, as string to make various things easier
var validRows = [
['00','01','02'], // left column
['10','11','12'], // middle column
['20','21','22'], // right column
['00','10','20'], // top row
['01','11','21'], // middle row
['02','12','22'], // bottom row
['00','11','22'], // Diag TL to BR
['20','11','02'] // Diag BL to TR
];
//Our scoring arrays for evaulating moves
var max1 = ['100','010','001'];
var min1 = ['200','020','002'];
var max2 = ['110','011'];
var min2 = ['220','022'];
var max3 = ['111'];
var min3 = ['222'];
//All the valid squares
var validSquaresFactory = ['00','10','20','01','11','21','02','12','22'];
//Store all the moves somewhere
//var computerMoves = ['10','22'];
//var userMoves = ['00','02'];
//Store all the moves somewhere
var computerMoves = ['00','20','01'];
var userMoves = ['10','11','02'];
//01,21,22 - 01//
function Board(minOrMax,computerMoves,userMoves){
this.computer = computerMoves;
this.user = userMoves;
this.minOrMax = minOrMax;
this.remaining = this.genRemaining();
this.complete = this.genComplete();
var results = this.getScore();
this.score = results[0];
this.winOrLoose = results[1];
}
Board.prototype.genRemaining = function(){
//Create an array of all moves taken
var takenMoves = this.computer.concat(this.user);
//Calculate all remaining squares
var validSquares = validSquaresFactory.filter(function(object){
return takenMoves.indexOf(object) === -1;
});
return validSquares;
}
Board.prototype.genComplete = function(){
return ((this.computer.length + this.user.length) === 9);
}
Board.prototype.flipMinOrMax = function(){
return (this.minOrMax === 'max') ? 'min' : 'max'
}
Board.prototype.genArrays = function(minOrMax,square){
var tempUser = this.user.slice(0);
var tempComputer = this.computer.slice(0);
if(minOrMax === 'min'){
tempUser.push(square);
} else {
tempComputer.push(square);
}
return [tempComputer,tempUser];
}
Board.prototype.generateBoards = function(minOrMax){
var boards = [];
var that = this;
this.remaining.forEach(function(remainingSquare){
var moves = that.genArrays(minOrMax,remainingSquare);
boards.push(new Board(minOrMax,moves[0],moves[1]));
})
//console.log(boards);
return boards;
}
Board.prototype.getScore = function(){
var that = this;
var winOrLoose = false;
var returnScore = validRows.reduce(function(storage,row,index,array){
var score = row.reduce(function(storage1,square){
if (that.computer.indexOf(square) !== -1) {
storage1 += '1';
} else if (that.user.indexOf(square) !== -1) {
storage1 += '2';
} else {
storage1 += '0';
}
return storage1;
},'')
var finalScore = 0;
if(max1.indexOf(score) != -1){
finalScore = 1;
} else if(min1.indexOf(score) != -1){
finalScore = -1;
} else if(max2.indexOf(score) != -1){
finalScore = 10;
} else if(min2.indexOf(score) != -1){
finalScore = -10;
} else if(max3.indexOf(score) != -1){
winOrLoose = true;
finalScore = 100;
} else if(min3.indexOf(score) != -1){
winOrLoose = true;
finalScore = -100;
}
storage.push(finalScore);
return storage;
},[])
var condensedReturnScore = returnScore.reduce(function(storage,score){
return storage+score;
})
return [condensedReturnScore,winOrLoose];
}
function generateMove() {
var board = new Board('max', computerMoves, userMoves);
if (board.remaining.length === 1) {
return [board.remaining[0], 0];
} else {
var scores = [];
var boards = board.generateBoards('max');
boards.forEach(function (board) {
scores.push(testMove(board, 4));
});
scores = scores.map(function (score, index) {
return [board.remaining[index], score];
});
var returnValue = scores.reduce(function (storage, score) {
return (score[1].score > storage[1].score) ? score : storage;
});
return [returnValue[0], returnValue[1].score];
}
}
function testMove(masterBoard,count){
count --;
var boards = [];
boards = masterBoard.generateBoards(generateMinOrMax(masterBoard.minOrMax));
boards = boards.map(function (move) {
if (move.complete === true || count <= 0 || move.winOrLoose === true){
return move;
} else {
var returnScore = testMove(move,count);
return returnScore;
}
});
returnBoard = boards.reduce(function(storage,board,index,array){
if(generateMinOrMax(masterBoard.minOrMax) === 'max'){
return (board.score > storage.score) ? board : storage;
} else {
return (board.score < storage.score) ? board : storage;
}
});
return returnBoard;
}
function generateMinOrMax(minOrMax){
return (minOrMax === 'max') ? 'min' : 'max'
}
function getScore(user,computer,minOrMax){
var that = this;
that.computer = computer;
that.user = user;
that.minOrMax = minOrMax;
var returnScore = validRows.reduce(function(storage,row,index,array){
var score = row.reduce(function(storage1,square){
if (that.computer.indexOf(square) !== -1) {
storage1 += '1';
} else if (that.user.indexOf(square) !== -1) {
storage1 += '2';
} else {
storage1 += '0';
}
return storage1;
},'')
var finalScore = 0;
if(max1.indexOf(score) != -1){
finalScore = 1;
} else if(min1.indexOf(score) != -1){
finalScore = -1;
} else if(max2.indexOf(score) != -1){
finalScore = 10;
} else if(min2.indexOf(score) != -1){
finalScore = -10;
} else if(max3.indexOf(score) != -1){
finalScore = 100;
} else if(min3.indexOf(score) != -1){
finalScore = -100;
}
storage.push(finalScore);
return storage;
},[])
var condensedReturnScore = returnScore.reduce(function(storage,score){
if(that.minOrMax === 'max'){
return (score >= storage) ? score : storage;
} else {
return (score <= storage) ? score : storage;
}
})
return condensedReturnScore;
}

Translating jQuery to javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm new to SO and to JS. I want to translate this code to pure JS but I'm really struggling. May someone help me please?
$(document).ready(function(){
var displayFix = function(num) {
if (num.length > 9) {
total.text(num.substr(0,9));
}
};
var number = "";
var newNumber = "";
var operator = "";
var total = $(".display");
total.text("0");
$(".numbers span").not(".clear, .dot").click(function(){
number += $(this).text();
total.text(number);
displayFix(number);
});
$(".dot").click(function() {
if ( number.length == 0)
{ number = "0.";
} else {
number += $(this).text();
total.text(number);
displayFix(number);
};
});
$(".operators span").not(".igual").click(function(){
operator = $(this).text();
newNumber = number;
number = "";
total.text("0");
});
$(".clear").click(function(){
number = "";
total.text("0");
newNumber = "";
});
$(".igual").click(function(){
if (operator === "+"){
number = (parseFloat(newNumber,10) + parseFloat(number,10)).toString(10);
} else if (operator === "-"){
number = (parseFloat(newNumber,10) - parseFloat(number,10)).toString(10);
} else if (operator === "/"){
number = (parseFloat(newNumber,10) / parseFloat(number,10)).toString(10);
} else if (operator === "*"){
number = (parseFloat(newNumber,10) * parseFloat(number,10)).toString(10);
}
total.text(number);
displayFix(number);
number = "";
newNumber = "";
});
$(document).keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode === 49) {
$("#num1").click();
} else if (keycode === 50) {
$("#num2").click();
} else if (keycode === 51) {
$("#num3").click();
}
});
});
I suppose I can replace the following lines:
var total = $(".display") with var total = document.querySelector(".display")
total.text("0") with total.innerHTML="0"
$(".dot").click(function() { with document.querySelector(".dot").onclick = function() {
Also, the browser I'm using is a updated Chrome and I don't need it to support other browsers.
youmightnotneedjquery is your friend.
You'll see that you can define your own replacement for jQuery.ready():
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
Then you'll need to get used to do without jQuery wrapper, which means dealing with array indexes and possibly empty results. So for instance document.querySelector(".dot").onclick = function() { is not going to be enough, you want to do
var dots = document.querySelector(".dot");
for(var i=0; i<dots.length; i++ ){
dots[i].onclick = function() { ... }
}
Finally, you need to discard elements manually since you have no jQuery .not():
var operators = document.querySelector(".operators span");
for(var i=0; i<operators.length; i++ ){
var operator = operators[i];
if(operator.className.indexOf("igual") < 0){
//do stuff
}else{
//don't
}
}
Note: you may want to use document.getElementById() and document.getElementsByClassName when your selector is just an id or a class.
Hope this short guidance is enough for you to start.
The Javascript equivalent will almost look like this for your jquery code,
(function() {
var displayFix = function(num) {
if (num.length > 9) {
total.innerHTML = num.substr(0, 9);
}
};
var number = "";
var newNumber = "";
var operator = "";
var total = document.getElementsByClassName("display");
total.innerHTML = "0";
var sel1 = document.querySelector(".numbers span");
for (var i = sel1.length; i--;) {
if (sel1[i].className != 'clear' && sel1[i].className != 'dot') {
var arg = sel1[i].innerHTML;
sel1[i].onclick = function(arg) {
return function() {
number += arg;
total.innerHTML = number;
displayFix(number);
};
};
}
}
var sel2 = document.querySelector(".dot");
sel2.onclick = function() {
if (number.length == 0) {
number = "0.";
} else {
number += sel2.innerHTML;
total.innerHTML = number;
displayFix(number);
};
};
var sel3 = document.querySelector(".operators span");
for (var i = sel3.length; i--;) {
if (sel3[i].className != 'igual') {
var arg = sel3[i].innerHTML;
sel3[i].onclick = function(arg) {
return function() {
operator = arg;
newNumber = number;
number = "";
total.innerHTML = "0";
};
};
}
}
document.querySelector(".clear").onclick = function() {
number = "";
total.innerHTML = "0";
newNumber = "";
};
document.querySelector(".igual").onclick = function() {
if (operator === "+") {
number = (parseFloat(newNumber, 10) + parseFloat(number, 10)).toString(10);
} else if (operator === "-") {
number = (parseFloat(newNumber, 10) - parseFloat(number, 10)).toString(10);
} else if (operator === "/") {
number = (parseFloat(newNumber, 10) / parseFloat(number, 10)).toString(10);
} else if (operator === "*") {
number = (parseFloat(newNumber, 10) * parseFloat(number, 10)).toString(10);
}
total.innerHTML = number;
displayFix(number);
number = "";
newNumber = "";
};
document.querySelector(".igual").onkeypress = function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
var elm = "";
if (keycode === 49) {
elm = document.getElementById("num1");
elm.onclick.apply(elm);
} else if (keycode === 50) {
elm = document.getElementById("num2");
elm.onclick.apply(elm);
} else if (keycode === 51) {
elm = document.getElementById("num3");
elm.onclick.apply(elm);
}
};
})();
Disclaimer: The code is just converted to the JavaScript equivalent, not tested with any values.

How to use AJAX or JSON in this code?

I am creating a website application that allows users to select a seat, if it is not already reserved, and reserve it.
I have created a very round about way of getting the seats that are previously reserved using iFrames, however that was temporarily, now I need to make it secure and "proper javascript code" using proper practices. I have no clue what AJAX (or JSON) is, nor how to add it to this code, but it needs to get the file "seatsReserved"+this.id(that is the date)+"Que.html" and compare the string of previously reserved seats to see which class to make the element. If this is horrible, or if any of the other things could work better, I am open to criticism to everything. Thank you all!
Here is the javascript code:
A little side note, all of the if statements are due to different amount of seats in each row
<script>
var i = " 0 ";
var counter = 0;
var leng=0;
document.getElementById("Show1").addEventListener("click", changeDay);
document.getElementById("Show2").addEventListener("click", changeDay);
document.getElementById("Show3").addEventListener("click", changeDay);
function changeDay() {
var iFrame = document.getElementById("seatList");
iFrame.src = "seatsReserved" + this.id + "Que.html";
document.getElementById('date').innerHTML = this.id;
var seatsTaken = iFrame.contentWindow.document.body.innerHTML;
var k = 0;
let = 'a';
var lc = 0;
for (lc = 1; lc <= 14; lc++) {
if (lc == 1) {
leng = 28;
}
else if (lc == 2) {
leng = 29;
}
else if (lc == 3) {
leng = 32;
}
else if (lc == 4 || lc == 6 || lc == 12 || lc == 14) {
leng = 33;
}
else if (lc == 5 || lc == 13) {
leng = 34;
}
else if (lc == 8 || lc == 10) {
leng = 35;
}
else {
leng = 36;
}
for (k = 1; k <= leng; k++) {
if (seatsTaken.indexOf((" " +
let +k + " ")) <= -1) {
seat = document.getElementById(let +k);
seat.removeEventListener("click", selectedSeat);
}
else {
document.getElementById(let +k).className = "openseat";
document.getElementById(let +k).removeEventListener("click", doNothing);
}
}
let = String.fromCharCode(let.charCodeAt(0) + 1);
}
}
function loadChanges() {
var iFrame = document.getElementById("seatList");
var seatsTaken = iFrame.contentWindow.document.body.innerHTML;
var k = 0;
let = 'a';
var lc = 0;
var leng = 0;
for (lc = 1; lc <= 14; lc++) {
if (lc == 1) {
leng = 28;
}
else if (lc == 2) {
leng = 29;
}
else if (lc == 3) {
leng = 32;
}
else if (lc == 4 || lc == 6 || lc == 12 || lc == 14) {
leng = 33;
}
else if (lc == 5 || lc == 13) {
leng = 34;
}
else if (lc == 8 || lc == 10) {
leng = 35;
}
else {
leng = 36;
}
for (k = 1; k <= leng; k++) {
if (seatsTaken.indexOf((" " +
let +k + " ")) <= -1) {
seat = document.getElementById(let +k);
seat.addEventListener("click", selectedSeat);
seat.className = "openseat";
}
else {
document.getElementById(let +k).className = "notAvailible";
document.getElementById(let +k).addEventListener("click", doNothing);
}
}
let = String.fromCharCode(let.charCodeAt(0) + 1);
}
i = " 0 ";
counter = 0;
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
document.getElementById("seatnums").innerHTML = counter;
}
i = document.getElementById("seatString").innerHTML;
counter = document.getElementById("seatnums").innerHTML;
function selectedSeat() {
var w = this.id;
var l = (" " + w);
var b = (" " + w + " ");
if (counter < 5) {
if (i.indexOf(b) <= 0) {
this.className = "closedseat";
i = i + b;
i = i.replace(" 0 ", " ");
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
counter = counter + 1;
document.getElementById("seatnums").innerHTML = counter;
}
else if (i.indexOf(b) > 0) {
this.className = "openseat";
i = i.replace(b, "");
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
counter = counter - 1;
document.getElementById("seatnums").innerHTML = counter;
}
}
else if (i.indexOf(b) > 0) {
this.className = "openseat";
i = i.replace(b, "");
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
counter = counter - 1;
document.getElementById("seatnums").innerHTML = counter;
}
}
function doNothing() {
}
var rannum = Math.random() * 1000;
document.getElementById('getConfirmation').value = rannum;
</script>

Javascript: Mathfloor still generating a 0

In my script to generate a playing card, it's generating a 0, even though my random generator is adding a 1, so it should never be 0. What am I doing wrong?! If you refresh, you'll eventually get a "0 of Hearts/Clubs/Diamonds/Spades":
var theSuit;
var theFace;
var theValue;
var theCard;
// deal a card
function generateCard() {
var randomCard = Math.floor(Math.random()*52+1)+1;
return randomCard;
};
function calculateSuit(card) {
if (card <= 13) {
theSuit = "Hearts";
} else if ((card > 13) && (card <= 26)) {
theSuit = "Clubs";
} else if ((card > 26) && (card <= 39)) {
theSuit = "Diamonds";
} else {
theSuit = "Spades";
};
return theSuit;
};
function calculateFaceAndValue(card) {
if (card%13 === 1) {
theFace = "Ace";
theValue = 11;
} else if (card%13 === 13) {
theFace = "King";
theValue = 10;
} else if (card%13 === 12) {
theFace = "Queen";
theValue = 10;
} else if (card%13 === 11) {
theFace = "Jack";
theValue = 10;
} else {
theFace = card%13;
theValue = card%13;
};
return theFace;
return theValue
};
function getCard() {
var randomCard = generateCard();
var theCard = calculateFaceAndValue(randomCard);
var theSuit = calculateSuit(randomCard);
return theCard + " of " + theSuit + " (this card's value is " + theValue + ")";
};
// begin play
var myCard = getCard();
document.write(myCard);`
This line is problematic:
} else if (card%13 === 13) {
Think about it: how a remainder of division to 13 might be equal to 13? ) It may be equal to zero (and that's what happens when you get '0 of... '), but will never be greater than 12 - by the very defition of remainder operation. )
Btw, +1 in generateCard() is not necessary: the 0..51 still give you the same range of cards as 1..52, I suppose.
card%13 === 13
This will evaluate to 0 if card is 13. a % n will never be n. I think you meant:
card % 13 === 0
return theFace;
return theValue
return exits the function; you'll never get to the second statement.

Categories

Resources