0

I'm new to JS, trying to build a game based around switching a set of tiles back and forth between two players.

One is function intended to switch turns between two players. Another changes the tiles' color, using the turn variable to determine which color to switch to.

I don't think either is working.

Fiddle: http://jsfiddle.net/f5mEY/3

var currentPlayer;
var playerOne;
var playerTwo;
var turnCounter = 0;

//this function is intended to iterate between the two players when a player completes their turn by hitting submit
$(document).ready(function() {
    $('#submit').click(function() {
        turnCounter += 1;
        if (turnCounter%2 === 0) {
            currentPlayer = playerOne;
        }
        else {
            currentPlayer = playerTwo;
        }
    });
});

//and this should turn the unplayed tiles to the correct player's color when they are clicked
$(document).ready(function() {
    $('.unplayedTile').click(function() {
        if (currentPlayer === playerOne) {
            $(this).toggleClass('unplayedTile playerOneTile');
        }
        else {
            $(this).toggleClass('unplayedTile playerTwoTile');
        }
    });
});

Many thanks in advance for any help!

3 Answers 3

1

You need to initiate playerOne and playerTwo with something that can be compared. Currently, playerOne and playerTwo are undefined which makes currentPlayer === playerOne always true

Sign up to request clarification or add additional context in comments.

Comments

0

In your jsFiddle, the variables playerOne and playerTwo never get anything assigned to them so therefore they are both undefined. If they have the same value, then you can't tell the difference between them in your if statements.

I don't know exactly how you intended to use those variables, but if you just assign them some initial value that is different between them, then your comparisons for who is the current player should start working.

var playerOne = 1;
var playerTwo = 2;
var currentPlayer = playerOne;

P.S. If you're trying to actually use the jsFiddle, you have to select the jQuery lib in the left hand panel so jQuery is available.

1 Comment

Thank you. I couldn't get it working this way. I think that setting a value for the p1/p2 variables made it call that value in the comparisons. But I removed those vars & it worked.
0

The problem is you are not assigning any values to the player constants.

var currentPlayer = 1;
var playerOne = 1;
var playerTwo = 2;
var turnCounter = 0;

Demo: Fiddle

Here the initial values are set so that currentPlayer will be the playerOne

Note: Also in the fiddle jQuery was not included

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.