I am learning java script for my OU course and have hit brickwall.
Can any kind fold help me please?
I am trying to write a function for this statement:
*switches current player
*
*function takes no argument
* if current player is 1, sets current player to 2
* otherwise sets current player to 1
*function returns no value
So far I have:
code:
function switchCurrentPlayer()
{
if (currentPlayer = 1)
{
currentPlayer = 2;
}
else
{
currentPlayer = 1;
}
}
is always returning true, and is setting current player to 1
(and then because it tests true (i.e. the script is able to set current player to 1) it is then being set to 2, by the enclosed code.
code:
function switchCurrentPlayer()
{
if (currentPlayer == 1)
{
currentPlayer = 2;
}
else
{
currentPlayer = 1;
}
}
Whilst what Xen says will work, it's possibly worth pointing out there is also a "===" operator.
The difference being that "==" will do type conversion to encourage a match, whilst "===" is stricter and requires same type too.
For example:
code:
var a = 0;
var b = '0';
document.write(a==b);
document.write('\n');
document.write(a===b);
Some people argue you should always do === (unless you explicitly need == instead), though I'm not sure how much it matters (possibly a bit slower for non-matches, but most likely not worth worrying about).
And one more post, in a last ditch attempt to not have to go write a really boring report thing - this is all based on there only ever being two players.
It's good practise to write more modular code that can be used for other purposes - for this example, multi-player turn-based switching can be done with very little extra work:
code:
function switchCurrentPlayer()
{
currentPlayer++
if ( currentPlayer > PlayerCount )
{
currentPlayer=1
}
}
Set PlayerCount to any number, and this will cycle through them in order, whether there is 2 or 20 players.
(The "++" just means "add one")
Anyway, I better get on with wasting time doing what I'm supposed to be doing right now. :(
Possibly badly worded - by "cycle through" I just meant each time called you'd get the appropriate next player - you'd call the function at the end of each player's turn (which in most games is a manually triggered event).