Getting a NaN even though im using parseInt for additive equation - javascript

Im doing a project for class, it's a paper rock scissor type game. I have the game working fine, I'm now simply trying to make it so that you play for a best of three scenario.
I coded it (at least I tried to) so that when you win, playerwin gets a point, and when you lose, compwin gets a point. When one of you has two points, you get an alert saying you won or lost.
I ran through stack trying to find out how to do this on my own, since this is new to me. Tried my best, came up short. Im not getting any actual errors, its just not doing what I want. I thought that parseInt-'ing the variable would make it a number, but it's coming up as NaN, so its clearly not. What am I doing wrong?
Jsfiddle - http://jsfiddle.net/Lwj2zny5/
Html -
<body>
<div id="wrapper">
<h1>Lizard, paper, scissors, spock, rock</h1>
<div id="images">
<img class="game-image" src="Images/lizard.jpg" width="150" height="150" alt="" data-value="1"/>
<img class="game-image" src="Images/paper.jpg" width="150" height="150" alt="" data-value="2"/>
<img class="game-image" src="Images/scissors.jpg" width="150" height="150" alt="" data-value="3"/>
<img class="game-image" src="Images/spock.jpg" width="150" height="150" alt="" data-value="4"/>
<img class="game-image" src="Images/rock.jpg" width="150" height="150" alt="" data-value="5"/>
</div>
<div id="win">
</div>
<div id="score">
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="unit2.js"></script>
</body>
JS -
$(function() {
$(document).on('click', '.game-image', function(event) {
var value = $(event.target).data('value');
var win;
var playerwin = parseInt($.trim($(this).html()));
var compwin = parseInt($.trim($(this).html()));
var comproll = 1 + Math.floor(Math.random() * 5);
//$('#comproll').html('Result: '+comproll)
if (comproll === 1) {
comp = "Lizard";
} else if (comproll === 2) {
comp = "paper";
} else if (comproll === 3) {
comp = "scissors";
} else if (comproll === 4) {
comp = "Spock";
} else if (comproll === 5) {
comp = "Rock";
}
if (value === comproll) {
win = "This ends in a tie, computer chose " + comp + " also.";
} else if (value === 1) {
if (comproll === 2 || comproll === 4) {
win = "You win, comp choose " + comp + ".";
$(this).html(++playerwin);
} else if (comproll === 3 || comproll === 5) {
win = "You lose, comp choose " + comp + ".";
$(this).html(++compwin);
}
} else if (value === 2) {
if (comproll === 4|| comproll === 5) {
win = "You win, comp choose " + comp + ".";
$(this).html(++playerwin);
} else if (comproll === 1 ||comproll === 3) {
win = "You lose, comp choose " + comp + ".";
$(this).html(++compwin);
}
} else if (value === 3) {
if (comproll === 1 || comproll === 2) {
win = "You win, comp choose " + comp + ".";
$(this).html(++playerwin);
} else if (comproll === 4 || comproll === 5) {
win = "You lose, comp choose " + comp + ".";
$(this).html(++compwin);
}
} else if (value === 4) {
if (comproll === 3 || comproll === 5) {
win = "You win, comp choose " + comp + ".";
$(this).html(++playerwin);
} else if (comproll === 1 || comproll === 2) {
win = "You lose, comp choose " + comp + ".";
$(this).html(++compwin);
}
} else if (value === 5) {
if (comproll === 1 || comproll === 3) {
win = "You win, comp choose " + comp + ".";
$(this).html(++playerwin);
} else if (comproll === 2 || comproll === 4) {
win = "You lose, comp choose " + comp + ".";
$(this).html(++compwin);
}
}
$('#score').text(playerwin, compwin);
if (playerwin == 2) {
alert("You Won");
} else if (compwin == 2) {
alert("You lose");
}
$('#win').text(win);
}); //closes play function
}); // closes function
Yes i know this is bulky code, but what we're learning atm is if/else statements so thats what im using.
Thanks ahead of time!

$(document).on('click', '.game-image', function(event) {
...
var playerwin = parseInt($.trim($(this).html()));
...
$(this) refers to the clicked image. Images do not contain .html()

$(function() {
var compwin = 0;
var playerwin = 0;
$(document).on('click', '.game-image', function(event) {
var value = $(event.target).data('value');
var win;
var comproll = 1 + Math.floor(Math.random() * 5);
then
$("#win").text(win);
$('#score').text("Player = " + playerwin + ", Computer = " + compwin);
if (playerwin == 2) {
alert("You Won");
compwin = 0;
playerwin = 0;
$('#score').text("");
$("#win").text("");
} else if (compwin == 2) {
alert("You lose");
compwin = 0;
playerwin = 0;
$('#score').text("");
$("#win").text("");
}

As others have pointed out, you are getting the scores from image html instead of having variables tracking it. I created a jsfiddle trying to understand your code. But I cleaned it up too much and looks little bit different.
http://jsfiddle.net/sheth/uzagumu7/22/
I created short functions trying to make the code cleaner.
var playerScore = 0;
var computerScore = 0;
var choices = ["Lizard", "Paper", "Scissors", "Spock", "Rock"];
var computerRoll = function () {
return 1 + Math.floor(Math.random() * 5);
}
var resultOfGame = function (playerChoice, computerChoice) {
if (playerChoice === computerChoice) {
return 0; // tie
} else if (
((playerChoice === 1) && ((computerChoice === 2) || (computerChoice === 4))) ||
((playerChoice === 2) && ((computerChoice === 4) || (computerChoice === 5))) ||
((playerChoice === 3) && ((computerChoice === 1) || (computerChoice === 2))) ||
((playerChoice === 4) && ((computerChoice === 3) || (computerChoice === 5))) ||
((playerChoice === 5) && ((computerChoice === 1) || (computerChoice === 3))))
{
// player wins
return 1;
} else {
return -1;
}
}
Newer version of jsfiddle has image with usemap. Also removed the alert.
http://jsfiddle.net/sheth/uzagumu7/78/

Related

Score adds 2 points sometimes instead of 1 point

I have written a rock, paper, scissor game using javascript. I have got it to play 5 rounds and to keep track of the score every round. However, for some reason every now and then it will add 2 points to the score instead of 1. I am a beginner to javascript and have no idea where I am going wrong. I keep logically going through my loop and don't understand why it does this. How can I stop this from happening?
Help would be greatly appreciated!
let playerScore = 0;
let compScore = 0;
let draw;
/* Players Choice */
function round() {
let userInput = prompt('Rock, Paper, or Scissor?: ');
console.log(userInput);
if (userInput == 'rock'){
console.log(userInput = 1);
} else if (userInput == 'paper'){
console.log(userInput = 2);
} else if (userInput == 'scissor'){
console.log(userInput = 3);
}
/* Computers Choice */
let compMove = Math.floor(Math.random()*3) + 1;
console.log(compMove);
if (compMove == 1) {
alert('Rock!');
} else if (compMove == 2){
alert('Paper!');
} else if (compMove == 3){
alert('Scissor!');
}
return {
compMove,
userInput
};
};
/* Compare */
function result(compMove, userInput) {
if (compMove == 2 && userInput == 1) {
alert('You lose!');
compScore += 1;
} else if (compMove == 3 && userInput == 1){
alert('You Win!');
playerScore += 1;
} else if (compMove == 1 && userInput == 2){
alert('You Win!');
playerScore += 1;
} else if (compMove == 1 && userInput == 3){
alert('You Lose!')
compScore += 1;
} else if (compMove == userInput){
compScore;
playerScore;
}
return {
compScore,
playerScore
};
}
function game() {
for (let i=1; i <= 5; i++) {
let roundNumber = round();
result(roundNumber.compMove, roundNumber.userInput);
console.log(result(compScore, playerScore));
};
return {
compScore,
playerScore
};
};
console.log(game());
if (playerScore > compScore) {
alert('You Won the Best of 5!');
} else if (playerScore < compScore) {
alert('You Lost.')
} else {
alert('It is a Draw!');
}
You have made calls to result() twice in game(). Store the result() in a
const and put that in console.log.
Also, in the result function, you haven't really covered all the possibilities of outcomes by computer and the user. You should cover the cases where userInput is 2 and compMove is 3, also where userInput is 3 and compMove is 2.

Node.js: telnet "Rock, Paper, Scissors" Program not working

So I am trying to create this Rock, Paper, Scissors program to run on a telnet server. Except It's not allowing me to enter the words "Rock","Paper", or "Scissors".
First CPUhand is showing up as undefined and is not setting to one of the options in my if statements.
Second whenever I enter a single character in the command prompt, It gives me my "Invalid, try again!" else statement and skips to the next line.
Is anyone able to figure out why my if statements for CPUhand are not working or why I can't enter more than a single character in command prompt?
Screenshot1 Screenshot2
"use strict";
const
net = require('net'),
server = net.createServer(function(connection) { //create server
let randomNum = randomNumber(1, 3);
let CPUhand
if(randomNum == 1){
CPUhand == "Rock";
} else if(randomNum == 2){
CPUhand == "Paper";
} else if(randomNum == 3){
CPUhand == "Scissors";
}
connection.write("Enter: Rock, Paper, or Scissors!\r\n");
connection.on('data', function(chunk) { //collect data from user
let USERhand = chunk.toString();
if(CPUhand === "Rock" && USERhand === "Scissors" || USERhand === "Rock" && CPUhand === "Scissors"){
connection.write("Rock beats Scissors!\r\n");
}
else if(CPUhand === "Paper" && USERhand === "Rock" || USERhand === "Paper" && CPUhand === "Rock"){
connection.write("Paper beats Rock!\r\n");
}
else if(CPUhand === "Scissors" && USERhand === "Paper" || USERhand === "Scissors" && CPUhand === "Paper"){
connection.write("Scissors beats Paper!\r\n");
}
else if(CPUhand === USERhand){
connection.write("Draw!\r\n");
}
else{
connection.write("Invalid! Try Again! \r\n");
}
});
}); server.listen(5432); //bind port
function randomNumber(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
1) Typo in block:
if(randomNum == 1){
CPUhand == "Rock";
} else ...
Should be:
if(randomNum == 1){
CPUhand = "Rock";
} else ...
2) In user input you have also line break symbol:
let USERhand = chunk.toString();
Replace with:
let USERhand = chunk.toString().trim();

How to make my rock, paper, scissors game refresh on button click?

This is not a duplicate because window.load() refreshes after 3 seconds without letting the user see the result fully
What I want to do is have the game reset automatically when the user clicks another button to make a new choice without having to refresh the page to click a "reset" button.
Would this involve clearing the innerHTMLs and resetting the variables onclick before running the script again?
My code is here: http://jsbin.com/yuvalucupo/edit?html,css,js
//var rock = document.getElementById("rock");
//var paper = document.getElementById("paper");
//var scissors = document.getElementById("scissors");
var screen = document.getElementById("screen");
var compAnswer = Math.random();
//Set computer value
if (compAnswer >= 0 && compAnswer <= 0.33) {
compAnswer = "rock";
} else if (compAnswer >= 0.34 && compAnswer <= 0.66) {
compAnswer = "paper";
} else {
compAnswer = "scissors";
}
function result(choice1, choice2) {
if (choice1 === choice2) {
screen.innerHTML = "<p>It's a tie!</p>";
}
//Rock Start
else if (choice1 === "rock" && choice2 === "scissors") {
screen.innerHTML = "<p>Rock Wins!</p>";
} else if (choice1 === "rock" && choice2 === "paper") {
screen.innerHTML = "<p>Paper Wins!</p>";
}
//End Rock
//Paper Start
else if (choice1 === "paper" && choice2 === "scissors") {
screen.innerHTML = "<p>Scissors Wins!</p>";
} else if (choice1 === "paper" && choice2 === "rock") {
screen.innerHTML = "<p>Paper Wins</p>!";
}
//Paper End
//Scissors Start
else if (choice1 === "scissors" && choice2 === "paper") {
screen.innerHTML = "<p>Scissors Wins</p>";
} else if (choice1 === "scissors" && choice2 === "rock") {
screen.innerHTML = "<p>Rock Wins</p>";
}
//Scissors End
}
//Display Computer's Answer
function displayCompAnswer() {
var computer = document.getElementById("computerAnswer");
computer.innerHTML = compAnswer;
}
#screen, #computerAnswer {
height: 100px;
width: 250px;
background-color: lightgrey;
border: 1px solid black;
}
<div id="screen"></div>
<button id="rock" onclick="userAnswer = 'rock'; result(userAnswer, compAnswer); displayCompAnswer();">Rock</button>
<button id="paper" onclick="userAnswer = 'paper'; result(userAnswer, compAnswer); displayCompAnswer();">Paper</button>
<button id="scissors" onclick="userAnswer = 'scissors'; result(userAnswer, compAnswer); displayCompAnswer();">Scissors</button>
<div id="computerAnswer"></div>
You might do something like this to "reset" your game:
function clearMessage(event) {
event.preventDefault(); // Stops the page from refreshing
var screen = document.getElementById("screen");
screen.innerHTML = '';
}
Then you could have a reset button like this
<button onclick="clearMessage(event)">Reset</button>
Here are some other thoughts as I look over your code. See how each function does only one thing?
// input: 0 = rock, 1 = paper and 2 = scissors
function makeUserSelection(choice) {
var computerChoice = getCompAnswer();
var result = getResult(choice, computerChoice);
displayResult(result);
}
// output: 0 = rock, 1 = paper and 2 = scissors
function getCompAnswer() {
var rand = Math.random();
if (compAnswer <= 0.33) {
return 0;
}
return (compAnswer <= 0.66) ? 1 : 2;
}
// input: 0 = rock, 1 = paper and 2 = scissors
// output: 0 = draw, 1 = user wins and -1 = user loses.
function getResult(userValue, computerValue) {
if(userValue === computerValue) {
return 0; // draw
}
return ((userValue + 1) % 3 === computerValue) ? return -1 : 1;
}
displayMessage(message) {
var screen = document.getElementById('screen');
screen.innerHTML = '<p>' + message + '</p>';
}
function displayResult(result) {
messages = ["It's a draw", "You lose", "You win"];
displayMessage(messages[result]);
}
Here is how I would update the buttons:
<div id="screen"></div>
<button id="rock" onclick="makeUserSelection(0);">Rock</button>
<button id="paper" onclick="makeUserSelection(1);">Paper</button>
<button id="scissors" onclick="makeUserSelection(2);">Scissors</button>
<button id="reset" onclick="clearMessage(event);">Reset</button>
<div id="computerAnswer"></div>

Rock, paper, scissors jQuery game not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Doing a Rock, paper, scissors, spock, lizard game, and it's not working. Im sure i wasnt writing it correctly, but wanted to do as much as i could before i asked for help. So yeah, it doesnt work :/
Jsfiddle - http://jsfiddle.net/yo5Lnmqn/
html -
<body>
<div id="wrapper">
<h1>Lizard, paper, scissors, spock, rock</h1>
<div id="images">
<img class="game-image" src="Images/lizard.jpg" width="150" height="150" alt="" data-value="1"/>
<img class="game-image" src="Images/paper.jpg" width="150" height="150" alt="" data-value="2"/>
<img class="game-image" src="Images/scissors.jpg" width="150" height="150" alt="" data-value="3"/>
<img class="game-image" src="Images/spock.jpg" width="150" height="150" alt="" data-value="4"/>
<img class="game-image" src="Images/rock.jpg" width="150" height="150" alt="" data-value="5"/>
</div>
<div id="win">
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="unit2.js"></script>
</body>
JS-
$(function(){
$(document).on('click', '.game-image', function(event) {
var value = event.target.data('value');
var comproll = 1 + Math.floor(Math.random() * 5);
//$('#comproll').html('Result: '+comproll)
if (#comproll === 1) {
comp = "Lizard";
}
else if (#comproll === 2) {
comp = "paper";
}
else if (#comproll === 3) {
comp = "scissors";
}
else if (#comproll === 4) {
comp = "Spock";
}
else if (#comproll === 5) {
comp = "Rock";
}
if (#game-image === comproll) {
#win = "This ends in a tie"
}
else if (game-image === 1) {
if (comproll === 2, 4) {
#win = "You win, comp choose" + comp + ".";
} else if (comproll === 3, 5){
#win = "You lose, comp choose " + comp + ".";
}
else if (game-image === 2) {
if (comproll === 4, 5) {
#win = "You win, comp choose" + comp + ".";
} else if (comproll === 1, 3){
#win = "You lose, comp choose " + comp + ".";
}
else if (game-image === 3) {
if (comproll === 1, 2) {
#win = "You win, comp choose" + comp + ".";
} else if (comproll === 4, 5){
#win = "You lose, comp choose " + comp + ".";
}
else if (game-image === 4) {
if (comproll === 3, 5) {
#win = "You win, comp choose" + comp + ".";
} else if (comproll === 1, 2){
#win = "You lose, comp choose " + comp + ".";
}
else if (game-image === 5) {
if (comproll === 1, 3) {
#win = "You win, comp choose" + comp + ".";
} else if (comproll === 2, 4){
#win = "You lose, comp choose " + comp + ".";
}
});//closes play function
});// closes function
as usual, thanks, u guys are awesome.
As Robby Cornelissen said, your variable names are not valid. See this previously asked question about this topic : What characters are valid for JavaScript variable names?
That being said, you do have quite a few errors popping so before coming to us, try investigating them. That's how you'll make some progress, instead of having someone do the job for you.
Once those errors are solved, you get something that works (see snippet below). However your method is awfully painful and bulky. I don't have the whole what-beats-what in rock-paper-scissors-lizard-spock, but to write elegant code, you should try to find a way to decide who is the winner without describing each particular case with an if statement.
Maybe there's something worth looking into with having your values inside an array, comparing the indexes of your values (your user's and the computer's) and i'm thinking about permutation cycles on the array to have the values in the correct order.
$(function() {
$(document).on('click', '.game-image', function(event) {
var value = $(event.target).data('value');
var win;
var comproll = 1 + Math.floor(Math.random() * 5);
//$('#comproll').html('Result: '+comproll)
if (comproll === 1) {
comp = "Lizard";
} else if (comproll === 2) {
comp = "paper";
} else if (comproll === 3) {
comp = "scissors";
} else if (comproll === 4) {
comp = "Spock";
} else if (comproll === 5) {
comp = "Rock";
}
if (value === comproll) {
win = "This ends in a tie"
} else if (value === 1) {
if (comproll === 2, 4) {
win = "You win, comp choose" + comp + ".";
} else if (comproll === 3, 5) {
win = "You lose, comp choose " + comp + ".";
}
} else if (value === 2) {
if (comproll === 4, 5) {
win = "You win, comp choose" + comp + ".";
} else if (comproll === 1, 3) {
win = "You lose, comp choose " + comp + ".";
}
} else if (value === 3) {
if (comproll === 1, 2) {
win = "You win, comp choose" + comp + ".";
} else if (comproll === 4, 5) {
win = "You lose, comp choose " + comp + ".";
}
} else if (value === 4) {
if (comproll === 3, 5) {
win = "You win, comp choose" + comp + ".";
} else if (comproll === 1, 2) {
win = "You lose, comp choose " + comp + ".";
}
} else if (value === 5) {
if (comproll === 1, 3) {
win = "You win, comp choose" + comp + ".";
} else if (comproll === 2, 4) {
win = "You lose, comp choose " + comp + ".";
}
}
$('#win').text(win);
}); //closes play function
}); // closes function
<body>
<div id="wrapper">
<h1>Lizard, paper, scissors, spock, rock</h1>
<div id="images">
<img class="game-image" src="Images/lizard.jpg" width="150" height="150" alt="" data-value="1" />
<img class="game-image" src="Images/paper.jpg" width="150" height="150" alt="" data-value="2" />
<img class="game-image" src="Images/scissors.jpg" width="150" height="150" alt="" data-value="3" />
<img class="game-image" src="Images/spock.jpg" width="150" height="150" alt="" data-value="4" />
<img class="game-image" src="Images/rock.jpg" width="150" height="150" alt="" data-value="5" />
</div>
<div id="win"></div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="unit2.js"></script>
</body>
Unclear what you're trying to do here, but
#comproll
#game-image
game-image
are not valid variable names. And even if they were, the variables are not being declared anywhere.
There you go
HTML
<div class="item" id="rock" data-val="0">
<img src="" alt="rock"></img>
</div>
<div class="item" id="paper" data-val="1">
<img src="" alt="paper"></img>
</div>
<div class="item" id="scissors" data-val="2">
<img src="" alt="scissors"></img>
</div>
<div class="item" id="lizrd" data-val="3">
<img src="" alt="lizrd"></img>
</div>
<div class="item" id="spock" data-val="4">
<img src="" alt="spock"></img>
</div>
JS
$.fn.versus = function() {
var you = $(this).data('val');
var oponent = getRandomInt(0, 4);
// Instead of using a lot if/else stuff
// we can use some kind of versus result matrix
// where rows are your selection (first index)
// and columns are your oponent's selection (second index)
// 0 : you win
// 1 : you lose
// 2 : tie
var versusMatrix = [
// 0 1 2 3 4
// r p s l sp
[ 2, 1, 0, 0, 1 ], //0. rock
[ 0, 2, 1, 1, 0 ], //1. paper
[ 1, 0, 2, 0, 1 ], //2. scissors
[ 1, 0, 1, 2, 0 ], //3. lizard
[ 0, 1, 0, 1, 2 ] //4. spock
];
var result = versusMatrix[you][oponent];
return getResultMessage(you, oponent, result);
}
function getRandomInt(bottom, top) {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
function getResultMessage(you, oponent, result) {
var items = ["rock", "paper", "scissors", "lizard", "spock"];
var results = ["You won!", "You lost!", "It's a tie!"]
return 'You: ' + items[you] + '\nOponent: ' + items[oponent] + '\n\n' + results[result];
}
$(document).ready(function(){
initGame();
});
function initGame() {
var items = $('.item');
items.click(function(){
alert($(this).versus());
});
}

Javascript - Uncaught TypeError:string is not a function

Im having some trouble with a javascript code for a tic tac toe webpage. Whenever I make a move this error occurs in the console:
Uncaught TypeError: string is not a function
Here is my webpage's link :
http://www.cgscomputing.com/36558/test.html
And here is the code:
<h1>Tic Tac Toe</h1>
<table>
<tr>
<td id = "spot1"></td>
<td id = "spot2"></td>
<td id = "spot3"></td>
</tr>
<tr>
<td id = "spot4"></td>
<td id = "spot5"></td>
<td id = "spot6"></td>
</tr>
<tr>
<td id = "spot7"></td>
<td id = "spot8"></td>
<td id = "spot9"></td>
</tr>
</table>
<!---Contains the message telling which players' turn it currently is-->
<p id = "footer"></p>
<script type = "text/javascript">
//select a random number to decide which player goes first
var randNum = Math.floor((Math.random() * 2));
//list which contains what is printed to the document concerning the turn
var beginTurn = ["Computer's ", "Your "];
var turn = beginTurn[randNum];
//print who's turn it is underneath the board
var footer = document.getElementById("footer");
footer.innerHTML = turn + " turn";
//array containing all the possible combinations through which a player can win the game
var possibleCombinations = [[2, 5, 8], [3, 5, 7], [6, 5, 4], [9, 5, 1], [1, 2, 3], [7, 8, 9], [1, 4, 7], [3, 6, 9]];
//through the game, keeps track if there is a winner or not
var won = false;
//when true, the player will not be able to place another marker on the board, and will have to wait for the computer to put in a marker first
var computerTurn = false;
//function for the computer to find a spot to place its marker in the board
function findLocation() {
for (var n = 0; n < 8; n++) {
//The computer first checks if it can win by placing one more insertMarker on the board
if ((document.getElementById("spot" + possibleCombinations[n][0]).innerHTML == "O") && (document.getElementById("spot" + possibleCombinations[n][1]).innerHTML == "O") && (document.getElementById("spot" + possibleCombinations[n][2]).innerHTML == "")) {
return possibleCombinations[n][2];
break;
}
else if ((document.getElementById("spot" + possibleCombinations[n][0]).innerHTML == "O") && (document.getElementById("spot" + possibleCombinations[n][1]).innerHTML == "") && (document.getElementById("spot" + possibleCombinations[n][2]).innerHTML == "O")) {
return possibleCombinations[n][1];
break;
}
else if ((document.getElementById("spot" + possibleCombinations[n][0]).innerHTML == "") && (document.getElementById("spot" + possibleCombinations[n][1]).innerHTML == "O") && (document.getElementById("spot" + possibleCombinations[n][2]).innerHTML == "O")) {
return possibleCombinations[n][0];
break;
}
//If the computer cannot win, it checks if it can block the human player
else if ((document.getElementById("spot" + possibleCombinations[n][0]).innerHTML == "X") && (document.getElementById("spot" + possibleCombinations[n][1]).innerHTML == "X") && (document.getElementById("spot" + possibleCombinations[n][2]).innerHTML == "")) {
return possibleCombinations[n][2];
break;
}
else if ((document.getElementById("spot" + possibleCombinations[n][0]).innerHTML == "X") && (document.getElementById("spot" + possibleCombinations[n][1]).innerHTML == "") && (document.getElementById("spot" + possibleCombinations[n][2]).innerHTML == "X")) {
return possibleCombinations[n][1];
break;
}
else if ((document.getElementById("spot" + possibleCombinations[n][0]).innerHTML == "") && (document.getElementById("spot" + possibleCombinations[n][1]).innerHTML == "X") && (document.getElementById("spot" + possibleCombinations[n][2]).innerHTML == "X")) {
return possibleCombinations[n][0];
break;
}
}
//=======
//If it cannot Win or Block, the compter chooses a random spot on the board to place a insertMarker on.
//An empty array to contain all the avaliable spots on the board
avaliableSpots = [];
//The for loop adds all the avaliable spots from the board into the array
for (var i = 1; i <= 9; i++) {
var spot = "spot" + i;
if (document.getElementById(spot).innerHTML == "") {
avaliableSpots.push(i);
}
}
//A random number is generated and it is used to find a spot on the board from the avaliable spots contained in the array
var randomSpot = Math.floor((Math.random() * (avaliableSpots.length)));
return avaliableSpots[randomSpot];
}
//this function places the marker of the player and the computer on the board
function insertMarker(insertMarker, spot) {
if (won == false) {
if (document.getElementById("spot" + spot).innerHTML == "") {
if (insertMarker == "X" && computerTurn == false) {
document.getElementById("spot" + spot).innerHTML = insertMarker;
footer.innerHTML = "Computer's turn";
turn = "Computer's ";
computerTurn = true;
//Sets a delay of 1 second before the computer places its marker
setTimeout(function(){
insertMarker("O", findLocation());
}, 1000);
} else if (insertMarker == "O") {
document.getElementById("spot" + spot).innerHTML = insertMarker;
computerTurn = false;
footer.innerHTML = "Your turn";
humanturn();
}
winner();
}
}
}
//Function for the human player's turn. When the player selects a spot on the board, the insertMarker function is called, with the parameters X and the number of the spot.
function humanturn() {
//when the human player clicks on an empty spot, the insertMarker function is called with the parameters "x" and the number of the box
document.getElementById("spot1").onclick = function() {insertMarker("X", 1)};
document.getElementById("spot2").onclick = function() {insertMarker("X", 2)};
document.getElementById("spot3").onclick = function() {insertMarker("X", 3)};
document.getElementById("spot4").onclick = function() {insertMarker("X", 4)};
document.getElementById("spot5").onclick = function() {insertMarker("X", 5)};
document.getElementById("spot6").onclick = function() {insertMarker("X", 6)};
document.getElementById("spot7").onclick = function() {insertMarker("X", 7)};
document.getElementById("spot8").onclick = function() {insertMarker("X", 8)};
document.getElementById("spot9").onclick = function() {insertMarker("X", 9)};
}
//This functions checks if there is a winner
function winner() {
for (var i = 0; i < 8; i++) {
if ((document.getElementById("spot" + possibleCombinations[i][0]).innerHTML == "O") && (document.getElementById("spot" + possibleCombinations[i][1]).innerHTML == "O") && (document.getElementById("spot" + possibleCombinations[i][2]).innerHTML == "O")) {
footer.innerHTML = "COMPUTER WINS";
footer.style.color = "red";
document.getElementById("spot" + possibleCombinations[i][0]).style.backgroundColor = "yellow";
document.getElementById("spot" + possibleCombinations[i][1]).style.backgroundColor = "yellow";
document.getElementById("spot" + possibleCombinations[i][2]).style.backgroundColor = "yellow";
won = true;
break;
}
else if ((document.getElementById("spot" + possibleCombinations[i][0]).innerHTML == "X") && (document.getElementById("spot" + possibleCombinations[i][1]).innerHTML == "X") && (document.getElementById("spot" + possibleCombinations[i][2]).innerHTML == "X")) {
footer.innerHTML = "PLAYER WINS";
footer.style.color = "red";
document.getElementById("spot" + possibleCombinations[i][0]).style.backgroundColor = "yellow";
document.getElementById("spot" + possibleCombinations[i][1]).style.backgroundColor = "yellow";
document.getElementById("spot" + possibleCombinations[i][2]).style.backgroundColor = "yellow";
won = true;
break;
}
}
}
//If it is the computer's turn, the computer places a insertMarker using the insertMarker function
if (turn == "Computer's ") {
document.getElementById("footer").innerHTML = "Computer's turn";
insertMarker("O", findLocation());
turn = "Your ";
}
//If it is the human player's turn, the player places a insertMarker using the insertMarker function
else if (turn == "Your ") {
document.getElementById("footer").innerHTML = "Your turn";
humanturn();
turn = "Computer's ";
}
</script>
</body>
Any help will be much appreciated.
You've called the method the same name as a parameter, so when you make the recursive call you're calling the parameter which is either "O" or "X" - not the function. Rename one of them and it should resolve this problem
EDIT: should have said which method. it's 'insertMarker'

Categories