Hey guys! So I’m building a turn based game with javascript and I’m currently struggling with limiting player movement.
So this is what I have:
let playerOneMoves = 0;
let playerTwoMoves = 0;
function movePlayerOne(){
$(tile).click(function(){
playerOneMoves += 1;
if(playerOneMoves < 4){
$(".active").append(playerOne);
}else if(playerOneMoves == 4){
alert("No more moves, players two turn!");
playerTwoMoves = 0;
movePlayerTwo();
}
})
}
function movePlayerTwo(){
$(tile).click(function(){
playerTwoMoves += 1;
if(playerTwoMoves < 4){
$(".active").append(playerTwo);
}else if(playerTwoMoves == 4){
playerOneMoves = 0;
alert("No more moves, players one turn!")
movePlayerOne();
}
})
}
So as player 2 finishes his move, and the next function (moveplayerone) is loaded, I only have 1 move with player 1. After a few more clicks, it starts appending both players to the same field.
So my question is, why can’t I reset the value of “let playerOneMoves = 0;” inside of a function?
If you want to see the code more in-depth, you can check it on CodePen: https://codepen.io/ronydkid/pen/oyqxJY
There’s nothing wrong with this code as far as your question is concerned. Your problem is elsewhere. Please give us more information about what errors you’re seeing in the console, variable values, or other information we can use to help you.
Side Note: always remember to never use == unless you know why you’d want to use it (it’s rare and better if you case the variables), always use a strict comparison of === or !==.
That’s exactly what’s going on my nerves! I don’t have any errors in the console. Oh sorry about that, I’ve changed it. Thanks!
You can inspect my code at the link I’ve provided, but it’s really not something complicated and I can’t see where I went wrong.
Odd. That shouldnt work, but it does… jQuery should be expecting a string there instead of an element array. Oh well.
One of the problems you’re running into is that you’re declaring click() over and over again, which doesnt remove the OLD click event, it just sets up a new one. See the off syntax. (Another is that your initial invocation on line 93 should just call movePlayerOne(), rather than bind it to a click.)
Btw, I’ve bound that just on the codepen, since I couldn’t bind it to the body. In the main javascript that’s on my pc the moveplayer function is bound to body onload = “moveplayerone”