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

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());
});
}

Related

How do I make a function that checks if the images are the same and returns a result

I'm working on a rock paper scissor game. I'm fairly new to javascript so I don't know a lot. I created a function already that displays the choice of the computer when the user makes a selection. What I'm trying to do next is make a function that compares the choice the user made and the choice the cpu made and then return a result, whether it's win, lose or draw.
I've tried to run an if statement to check if they're equal but i cant figure out how to check if the two images are equal to each other when the choices are made.
let userRock = document.querySelector('.rock')
let userPaper = document.querySelector('.paper')
let userScissors = document.querySelector('.scissors')
const cpuScissors = document.querySelector('.cpu-scissors')
const cpuPaper = document.querySelector('.cpu-paper')
const cpuRock = document.querySelector('.cpu-rock')
let result = document.querySelector('.result')
let currentItem;
userPaper.addEventListener('click', start)
userScissors.addEventListener('click', cpuChoice)
userRock.addEventListener('click', cpuChoice)
function start() {
cpuChoice()
getWinner()
}
// Computer Choice
function cpuChoice() {
const rand = Math.random()
if (currentItem) {
currentItem.style.display = 'none'
}
if (rand < .34) {
cpuPaper.style.display = 'inline-block'
currentItem = cpuPaper;
} else if (rand >= .67) {
cpuRock.style.display = 'inline-block'
currentItem = cpuRock;
} else {
cpuScissors.style.display = 'inline-block'
currentItem = cpuScissors;
}
}
// Get Winner
function getWinner() {
}
<div class="main-container">
<div class="score">
<p>You:0</p>
<p>Computer:0</p>
</div>
<div class="user-choice">
<img class="rock" src="icons/rock.png">
<img class="paper" src="icons/paper.png">
<img class="scissors" src="icons/scissors.png">
</div>
<div class="cpu-result">
<img class="cpu-rock" src="icons/rock.png">
<img class="cpu-paper" src="icons/paper.png">
<img class="cpu-scissors" src="icons/scissors.png">
</div>
<div class="result"></div>
Your approach is wrong in the way that :
- you make the player choose;
- you make the computer choose;
- you update the view (hiding/showing images);
- you then try to compare the images that are on display to determine who won.
The correct logic would be :
- make the player choose;
- make the computer choose;
- Compare both results to determine who won;
- Update the view (hide/show images).
What's on display is just a reflection of what's happening behind the scenes in the script.
I've put together in 10 minutes a little rock-paper-scissors game. There are probably more clever ways to find the winner, but you'll get the idea.
const items = ["rock", "paper", "scissors"],
issues = ["Draw", "You win", "Computer wins"];
let playerChoice = "",
compChoice = "";
$("button").click(function() {
const $this = $(this);
$("button").css("outline", "none");
$this.css("outline", "blue solid 2px");
playerChoice = $this.data("val");
computerChooses();
})
const computerChooses = () => {
const rand = Math.floor(Math.random() * 3); // 0,1 or 2
compChoice = items[rand]; // "rock", "paper" or "scissors"
$(".compChoice img").hide();
$(".compChoice").show();
$("#img" + rand).show();
findWinner()
}
const findWinner = () => {
let issue;
if (playerChoice === compChoice) {
issue = 0;
} else if (playerChoice === "rock") {
issue = compChoice === "scissors" ? 1 : 2;
} else if (playerChoice === "paper") {
issue = compChoice === "scissors" ? 2 : 1;
} else { // player chose scissors
issue = compChoice === "rock" ? 2 : 1;
}
$(".result").text(issues[issue]) // "Draw", "You win" or "Computer wins"
}
button {
cursor: pointer;
}
img {
width: 32px;
height: 32px;
}
.compChoice {
display: none;
}
.compChoice img {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Choose :</div>
<button data-val="rock">
<img src="https://image.flaticon.com/icons/svg/838/838023.svg"/>
</button>
<button data-val="paper">
<img src="https://img.icons8.com/metro/1600/sheet-of-paper.png"/>
</button>
<button data-val="scissors">
<img src="https://png.icons8.com/scissors/win8/1600"/></button>
<br/>
<br/>
<div class="compChoice">
<div>Computer picks :</div><img id="img0" src="https://image.flaticon.com/icons/svg/838/838023.svg" /><img id="img1" src="https://img.icons8.com/metro/1600/sheet-of-paper.png" /><img id="img2" src="https://png.icons8.com/scissors/win8/1600" />
</div>
<br/>
<div class="result"></div>

Not sure whether I have syntax errors or errors with the code

I am currently creating a dice game where you roll two dice and the javascript decides whether you won lost or tied with the computer. It is simple code, but I am unsure as to if I have made a syntax error or the code itself.
I have already tried looking over the code, but I am fairly new to this and some professional eyes would be useful.
<!DOCTYPE html>
<html>
<head>
<title> Game of dice </title>
<script>
var player;
var computer;
function randDice() {
var number = randNum(1,6);
return number;
}
function rollDice(){
player = randDice();
computer = randDice();
if (player == 1) {
document.getElementById("dieOne").src= "die1.png"
} else if (player == 2) {
document.getElementById("dieOne").src= "die2.png"
} else if (player == 3) {
document.getElementById("dieOne").src= "die3.png"
} else if (player == 4) {
document.getElementById("dieOne").src= "die4.png"
} else if (player == 5) {
document.getElementById("dieOne").src= "die5.png"
} else (player == 6) {
document.getElementById("dieOne").src= "die6.png"
if (computer == 1) {
document.getElementById("dieTwo").src= "die1.png"
} else if (computer == 2) {
document.getElementById("dieTwo").src= "die2.png"
} else if (computer == 3) {
document.getElementById("dieTwo").src= "die3.png"
} else if (computer == 4) {
document.getElementById("dieTwo").src= "die4.png"
} else if (computer == 5) {
document.getElementById("dieTwo").src= "die5.png"
} else (computer == 6) {
document.getElementById("dieTwo").src= "die6.png"
checkWin();
}
function checkWin(){
if (player == computer){
document.getElementById("winner").innerHTML = "You tied";
} else if (player > computer){
document.getElementById("winner").innerHTML = "You-won!";
} else (player < computer){
document.getElementById("winner").innerHTML = "You-lost";
}
}
</script>
</head>
<body>
<h1> Die roll </h1>
<img src="die1.png" id="dieOne"><image>
<img src="die2.png" id="dieTwo"><image>
<br>
<br>
<button onClick="rollDice();">Roll</button>
<br>
<p id="winner"></p>
</body>
</html>
There are some error in your source code:
Missing } in function rollDice
You wrong else if condition else (player == 6)
Put script tag in head, need move to close body tag.
Also check refer for randNum() method
You can F12 and see console tab for detail error message at what line of code.
<!DOCTYPE html>
<html>
<head>
<title> Game of dice </title>
</head>
<body>
<h1> Die roll </h1>
<img src="die1.png" id="dieOne"><image>
<img src="die2.png" id="dieTwo"><image>
<br>
<br>
<button onClick="rollDice();">Roll</button>
<br>
<p id="winner"></p>
<script>
var player;
var computer;
function randDice() {
var number = randNum(1,6);
return number;
}
function rollDice(){
player = randDice();
computer = randDice();
if (player == 1) {
document.getElementById("dieOne").src= "die1.png"
} else if (player == 2) {
document.getElementById("dieOne").src= "die2.png"
} else if (player == 3) {
document.getElementById("dieOne").src= "die3.png"
} else if (player == 4) {
document.getElementById("dieOne").src= "die4.png"
} else if (player == 5) {
document.getElementById("dieOne").src= "die5.png"
} else if(player == 6) {
document.getElementById("dieOne").src= "die6.png"
}
if (computer == 1) {
document.getElementById("dieTwo").src= "die1.png"
} else if (computer == 2) {
document.getElementById("dieTwo").src= "die2.png"
} else if (computer == 3) {
document.getElementById("dieTwo").src= "die3.png"
} else if (computer == 4) {
document.getElementById("dieTwo").src= "die4.png"
} else if (computer == 5) {
document.getElementById("dieTwo").src= "die5.png"
} else if(computer == 6) {
document.getElementById("dieTwo").src= "die6.png"
checkWin();
}
}
function checkWin(){
if (player == computer){
document.getElementById("winner").innerHTML = "You tied";
} else if (player > computer){
document.getElementById("winner").innerHTML = "You-won!";
} else if(player < computer){
document.getElementById("winner").innerHTML = "You-lost";
}
}
</script>
</body>
</html>
i've done this game before this was my code
<html>
<head>
<script>
var roll1;
var roll2;
function rollTheDice()
{
roll1 = Math.floor(Math.random() * 6) + 1;
document.getElementById('imgDice').src = roll1 + ".jpg";
return roll1;
}
function rollTheDice2()
{
roll2 = Math.floor(Math.random() * 6) + 1;
document.getElementById('imgDice2').src = roll2 + "a.jpg";
return roll2;
}
function compareDice()
{
if (roll1 < roll2 ) {alert("You Loose")
;
} else if (roll1 > roll2 ) {
alert ("You Win")
;
} else {alert ("You Tie")
;
}
}
</script>
</head>
<body>
<input type="button"
onclick="rollTheDice();"
value="Get Your Die"/>
<img src="" id="imgDice"/>
<br>
<input type="button"
onclick="rollTheDice2();"
value="Choose Opponent's Die"/>
<img src="" id="imgDice2"/>
<br>
<input type="button"
onclick="compareDice();"
value="Who wins?"/>
<img src="" id="imgDice"/>
</body>
</html>

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>

Getting a NaN even though im using parseInt for additive equation

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/

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