I've been working on a rock paper scissors game & I want the image to show as a result when the user makes a selection. For example, if i choose paper and the computer chooses rock, i want the rock image to display along with the 'lose' statement
I tried putting the images outside the folder to see if that worked but it didn't.
HTML
<div class="main-container">
<div class="score">
<p>You:0</p>
<p>Computer:0</p>
</div>
<div class="user-choices">
<img id='rock'class='choice' src="rock.png">
<img id='paper'class='choice' src="paper.png">
<img id='scissors'class='choice' src="scissors.png">
</div>
<div class='result'>
<div class="cpu-result"></div>
</div>
</div>
CSS
<style>
.result img {
height: 10rem;
}
.result{
text-align: center;
display: none;
}
</style>
Javascript
<script>
function cpuChoice() {
const rand = Math.random()
if (rand > .34) {
return 'paper'
} else if (rand <= .67) {
return 'rock'
} else {
return 'scissors'
}
}
function showWinner(winner,computerPick) {
if (winner === 'player') {
scoreboard.player++;
cpuResult.innerHTML = `<h2>Win!</h2>
<img class='cpu-result' src='${computerPick}.png>' `
} else if (winner === 'computer') {
scoreboard.computer++;
cpuResult.innerHTML = `<h2>Lose!</h2>
<img class='cpu-result' src='${computerPick}.png>'`
} else {
cpuResult.innerHTML = `<h2>Draw!</h2>
<img class'cpu-result' src='${computerPick}.png>' `
}
score.innerHTML = `
<p>Player:${scoreboard.player}</p>
<p>Computer: ${scoreboard.computer}</p>
`
result.style.display ='block'/
}
choices.forEach(choices => choices.addEventListener('click', play))
</script>
I want the image to display along with the win lose or draw message.
Related
EDIT: I was able to make it kind of work using the onclick function directly in the html, but I would like to know how to make it work with an event listener, so pls still help with this. Thanks guys
So, I'm new at this, and am trying to make an app that lets you play a rock paper scissors game first to 5 against a robot. It's part of The Odin Project.
I haven't yet implemented the best to five bit of it, as I'm just trying to make my buttons work :(
My event listener seems to be working fine, but I still get a "NULL" player choice no matter which button is pressed, when obviously I should be getting "ROCK", "PAPER", or "SCISSORS".
Would someone mind pointing out where I'm going wrong?
Here's my Javascript:
let playerChoice = "NULL"
let computerChoice = "NULL"
let playerScore = 0
let computerScore = 0
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min);
}
function getComputerChoice() {
let numChoice = getRandomInt(1,3);
let computerChoice = "NULL"
if (numChoice == 1) {
computerChoice = "ROCK";
} else if (numChoice == 2) {
computerChoice = "PAPER";
} else if (numChoice == 3){
computerChoice = "SCISSORS";
} else {
computerChoice = "NULL";
}
return computerChoice
}
function playerChoiceRock() {
playerChoice = "ROCK"
}
function playerChoiceScissors() {
playerChoice = "SCISSORS"
}
function playerChoicePaper() {
playerChoice = "PAPER"
}
function getPlayerChoice() {
document.getElementById("rockButton").addEventListener("click", playerChoiceRock)
document.getElementById("scissorsButton").addEventListener("click", playerChoiceScissors)
document.getElementById("paperButton").addEventListener("click", playerChoicePaper)
return playerChoice
}
function playRound() {
scoreComputer = document.getElementById("computerScore").innerHTML
scorePlayer = document.getElementById("playerScore").innerHTML
computerChoice = getComputerChoice()
playerChoice = getPlayerChoice()
if (computerChoice == "ROCK" && playerChoice == "PAPER") {
scorePlayer = scorePlayer + 1
} else if (computerChoice == "ROCK" && playerChoice == "SCISSORS") {
scoreComputer = scoreComputer + 1
} else if (computerChoice == "PAPER" && playerChoice == "SCISSORS") {
scorePlayer = scorePlayer + 1
} else if (computerChoice == "PAPER" && playerChoice == "ROCK") {
scoreComputer = scoreComputer + 1
} else if (computerChoice == "SCISSORS" && playerChoice == "PAPER") {
scoreComputer = scoreComputer + 1
} else if (computerChoice == "SCISSORS" && playerChoice == "ROCK") {
scorePlayer = scorePlayer + 1
} else {
scorePlayer = scorePlayer
scoreComputer = scoreComputer
}
alert(playerChoice)
document.getElementById("playerScore").innerHTML = scorePlayer
document.getElementById("computerScore").innerHTML = scoreComputer
}
And here's my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rock, Paper, Scissors</title>
</head>
<script src = "./script.js"></script>
<body>
<div>
<h1 style="display:flex; justify-content:center">Welcome To Rock, Paper Scissors.<h1></h1>
<h3 style="display:flex; justify-content: center;">The directions are simple. You will play against a computer in Rock, Paper, Scissors best out of 5. Choose a weapon from the menu, and hope that luck is on your side!</h3>
<h2 style="display: flex; justify-content: center;font-weight: bold;"><br><br>Rock beats Scissors, Scissors beats Paper, Paper beats Rock</h2>
</div>
<br>
<br>
<br>
<br>
<div style = "display: flex; justify-content: space-around;">
<button id = "rockButton" style = "display: flex; flex-direction: column; justify-content: center;" id = "Rock" onclick="playRound()">
<img src = ./stone.png alt = "image of a rock" height = "100px" width = "auto">
<p style="margin-left: auto; margin-right: auto">Rock</p>
</button>
<button id = "paperButton" style = "display: flex; flex-direction: column; justify-content: center;" id = "Paper" onclick="playRound()">
<img src = ./paper.png alt = "image of a Paper" height = "100px" width = "auto">
<p style="margin-left: auto; margin-right: auto">Paper</p>
</button>
<button id = "scissorsButton" style = "display: flex; flex-direction: column; justify-content: center;" id = "Scissors" onclick="playRound()">
<img src = ./scissors.png alt = "image of Scisors" height = "100px" width = "auto">
<p style="margin-left: auto; margin-right: auto">Scissors</p>
</button>
</div>
<div style = "display: flex; justify-content: center;">
<div style = "display: flex; justify-content: space-around; white-space: nowrap; width: 70%;">
<div style = "display: flex; white-space: nowrap;">
<h1><br><br><br>Your Score: <h1 id = "playerScore" style = "margin-left: 5%; margin-right: 5%;"><br><br><br>0</h1></h1>
</div>
<div style = "display: flex; white-space: nowrap; justify-content: center;">
<h1><br><br><br>Computer's Score: <h1 id = "computerScore" style = "margin-left: 5%; margin-right: 5%;"><br><br><br>0</h1></h1>
</div>
</div>
</div>
<div style = "display: flex; justify-content: center;">
<h1 style = "font: 40px; display: flex;"><br>Game Result</h1>
<h1 id = "gameResult"></h1>
</div>
<div>
</body>
</html>
Thanks all. I've tried to shuffle around the order in which the functions are executed, but it hasn't worked. Sorry if I'm asking a simple question, I'm pretty new and stumped :D
Event listeners are fired after the listened events were invoked. In your case, you need to add the event listener before fetching player choice, which should be in the very beginning of your code.
let playerChoice = "NULL"
let computerChoice = "NULL"
let playerScore = 0
let computerScore = 0
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min);
}
function getComputerChoice() {
let numChoice = getRandomInt(1, 3);
let computerChoice = "NULL"
if (numChoice == 1) {
computerChoice = "ROCK";
} else if (numChoice == 2) {
computerChoice = "PAPER";
} else if (numChoice == 3) {
computerChoice = "SCISSORS";
} else {
computerChoice = "NULL";
}
return computerChoice
}
function playerChoiceRock() {
playerChoice = "ROCK"
}
function playerChoiceScissors() {
playerChoice = "SCISSORS"
}
function playerChoicePaper() {
playerChoice = "PAPER"
}
function getPlayerChoice() {
return playerChoice
}
// add event listeners
document.getElementById("rockButton").addEventListener("click", playerChoiceRock)
document.getElementById("scissorsButton").addEventListener("click", playerChoiceScissors)
document.getElementById("paperButton").addEventListener("click", playerChoicePaper)
function playRound() {
scoreComputer = document.getElementById("computerScore").innerHTML
scorePlayer = document.getElementById("playerScore").innerHTML
computerChoice = getComputerChoice()
playerChoice = getPlayerChoice()
if (computerChoice == "ROCK" && playerChoice == "PAPER") {
scorePlayer = scorePlayer + 1
} else if (computerChoice == "ROCK" && playerChoice == "SCISSORS") {
scoreComputer = scoreComputer + 1
} else if (computerChoice == "PAPER" && playerChoice == "SCISSORS") {
scorePlayer = scorePlayer + 1
} else if (computerChoice == "PAPER" && playerChoice == "ROCK") {
scoreComputer = scoreComputer + 1
} else if (computerChoice == "SCISSORS" && playerChoice == "PAPER") {
scoreComputer = scoreComputer + 1
} else if (computerChoice == "SCISSORS" && playerChoice == "ROCK") {
scorePlayer = scorePlayer + 1
} else {
scorePlayer = scorePlayer
scoreComputer = scoreComputer
}
alert(playerChoice)
document.getElementById("playerScore").innerHTML = scorePlayer
document.getElementById("computerScore").innerHTML = scoreComputer
}
// add event listeners after the choice event
document.getElementById("rockButton").addEventListener("click", playRound)
document.getElementById("scissorsButton").addEventListener("click", playRound)
document.getElementById("paperButton").addEventListener("click", playRound)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rock, Paper, Scissors</title>
</head>
<script src="./script.js"></script>
<body>
<div>
<h1 style="display:flex; justify-content:center">Welcome To Rock, Paper Scissors.
<h1></h1>
<h3 style="display:flex; justify-content: center;">The directions are simple. You will play against a computer in Rock, Paper, Scissors best out of 5. Choose a weapon from the menu, and hope that luck is on your side!</h3>
<h2 style="display: flex; justify-content: center;font-weight: bold;"><br><br>Rock beats Scissors, Scissors beats Paper, Paper beats Rock</h2>
</div>
<br>
<br>
<br>
<br>
<div style="display: flex; justify-content: space-around;">
<button id="rockButton" style="display: flex; flex-direction: column; justify-content: center;" id="Rock">
<img src = ./stone.png alt = "image of a rock" height = "100px" width = "auto">
<p style="margin-left: auto; margin-right: auto">Rock</p>
</button>
<button id="paperButton" style="display: flex; flex-direction: column; justify-content: center;" id="Paper">
<img src = ./paper.png alt = "image of a Paper" height = "100px" width = "auto">
<p style="margin-left: auto; margin-right: auto">Paper</p>
</button>
<button id="scissorsButton" style="display: flex; flex-direction: column; justify-content: center;" id="Scissors">
<img src = ./scissors.png alt = "image of Scisors" height = "100px" width = "auto">
<p style="margin-left: auto; margin-right: auto">Scissors</p>
</button>
</div>
<div style="display: flex; justify-content: center;">
<div style="display: flex; justify-content: space-around; white-space: nowrap; width: 70%;">
<div style="display: flex; white-space: nowrap;">
<h1><br><br><br>Your Score:
<h1 id="playerScore" style="margin-left: 5%; margin-right: 5%;"><br><br><br>0</h1>
</h1>
</div>
<div style="display: flex; white-space: nowrap; justify-content: center;">
<h1><br><br><br>Computer's Score:
<h1 id="computerScore" style="margin-left: 5%; margin-right: 5%;"><br><br><br>0</h1>
</h1>
</div>
</div>
</div>
<div style="display: flex; justify-content: center;">
<h1 style="font: 40px; display: flex;"><br>Game Result</h1>
<h1 id="gameResult"></h1>
</div>
<div>
</body>
</html>
Also note that you need to invoke the playRound function after playerChoice**** listeners. To do that, simply remove the inline listener and add the playRound listeners after adding playerChoice listeners.
First, please check all your elements' id attribute.
You should set only one id in an element.
It's because your event doesn't pass to your function.
Base on this solution
You can use this function to bind your button
function showEvent(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}
e.g.
<button id="scissorsButton" onclick="showEvent(event)">
Then, you could see the event object in your browser console.
Ive attempted to make Tic Tac Toe as a javascript learning project and Im currently testing the first row winning state for Player 1, but for some reason every time the 3rd box is clicked regardless if the 1st and 2nd box has been clicked, it displays the winning message. Obviously thats not how tic tac toe works, as you need 3 in a row not 1 or 2.
Im using 2 arrays to test the winning state. 1 array for the boxes that have been already been clicked by the player, and 1 array that contains the winning combination for the first row. My goal was to test using an if statement to see if the boxes already clicked by the player matches the ones in the array with the winning combo.
I have tried using the .every method
for(let i=0;i<fRowBoxes.length;i++){
let fRowWin= () => X_Checked.includes((fRowBoxes[0],fRowBoxes[1],fRowBoxes[2])) ;
if(fRowBoxes.every(fRowWin) === true){
msg.innerHTML =`<h1> ${player1} Wins! </h1>`;
}
.textContent
if((fRowBoxes[0] && fRowBoxes[1] && fRowBoxes[2]).textContent == " x "){
msg.innerHTML =`<h1> ${player1} Wins! </h1>`;
}
and the .includes method
function checkScore(){
if (X_Checked.includes(fRowBoxes[0] && fRowBoxes[1] && fRowBoxes[2])){/*Only checks for fRowBoxes[2]?*/
msg.innerHTML =`<h1> ${player1} Wins! </h1>`;
}
}
Still nothing seems to work or it leads to the same result, any advice or suggestions would be highly appreciated.
let player1 = `<div class="symbol x"> x </div>`;
let player2 = `<div class="symbol o"> o </div>`;
let turn = player1;
let gridBoxes = document.querySelector('.grid').children;
let boxes = [];/*Stores all boxes in 3x3 grid*/
for(let i = 0; i < gridBoxes.length; i++){
boxes.push(gridBoxes[i]);
}
const msg = document.querySelector('div.msg ');
let fRowBoxes = [boxes[0],boxes[1],boxes[2]];/*Array with first row boxes*/
let sRowBoxes = [boxes[3],boxes[4],boxes[5]];
let tRowBoxes = [boxes[6],boxes[7],boxes[8]];
let fColBoxes = [boxes[0],boxes[3],boxes[6]];
let sColBoxes = [boxes[1],boxes[4],boxes[7]];
let tColBoxes = [boxes[2],boxes[5],boxes[8]];
let dBoxes1 =[boxes[0],boxes[4],boxes[8]];
let dBoxes2 = [boxes[2],boxes[4],boxes[6]];
let X_Checked = [];/*Stores boxes clicked by player 1*/
let O_Checked = [];
msg.display ='block';
function checkScore(){
if (X_Checked.includes(fRowBoxes[0] && fRowBoxes[1] && fRowBoxes[2])){/*Only checks for fRowBoxes[2]?*/
msg.innerHTML =`<h1> ${player1} Wins! </h1>`;
}
}
const tictactoe = (function(){/*START*/
msg.innerHTML = `<h1>Player 1 (X)</h1>`;
for(let i = 0; i<boxes.length; i++){
boxes[i].addEventListener('click',() =>{
if(boxes[i].value){
boxes[i].click(false);
}
else if(boxes[i].textContent === ""){
boxes[i].innerHTML = turn;
checkPlayer();
/**------------------------------------------- */
if (turn === player1){
O_Checked.push(boxes[i]);
console.log(O_Checked);
checkScore();/*Checks for a winner*/
}
else if (turn === player2){
X_Checked.push(boxes[i]);
console.log( X_Checked);
checkScore();
}
}
});}
}());/*END*/
let checkPlayer = (function(){
if(turn === player1){
turn = player2;
msg.innerHTML = `<h1>Player 2 (O)</h1>`;
}
else if(turn === player2){
turn = player1;
msg.innerHTML = `<h1>Player 1 (X)</h1>`;
}
});
let player1 = `<div class="symbol x"> x </div>`;
let player2 = `<div class="symbol o"> o </div>`;
let turn = player1;
let gridBoxes = document.querySelector('.grid').children;
let boxes = [];
for(let i = 0; i < gridBoxes.length; i++){
boxes.push(gridBoxes[i]);
}
const msg = document.querySelector('div.msg ');
let fRowBoxes = [boxes[0],boxes[1],boxes[2]];
let sRowBoxes = [boxes[3],boxes[4],boxes[5]];
let tRowBoxes = [boxes[6],boxes[7],boxes[8]];
let fColBoxes = [boxes[0],boxes[3],boxes[6]];
let sColBoxes = [boxes[1],boxes[4],boxes[7]];
let tColBoxes = [boxes[2],boxes[5],boxes[8]];
let dBoxes1 =[boxes[0],boxes[4],boxes[8]];
let dBoxes2 = [boxes[2],boxes[4],boxes[6]];
let X_Checked = [];
let O_Checked = [];
msg.display ='block';
function checkScore(){
if (X_Checked.includes(fRowBoxes[0] && fRowBoxes[1] && fRowBoxes[2])){
msg.innerHTML =`<h1> ${player1} Wins! </h1>`;
}
}
const tictactoe = (function(){/*START*/
msg.innerHTML = `<h1>Player 1 (X)</h1>`;
for(let i = 0; i<boxes.length; i++){
boxes[i].addEventListener('click',() =>{
if(boxes[i].value){
boxes[i].click(false);
}
else if(boxes[i].textContent === ""){
boxes[i].innerHTML = turn;
checkPlayer();
/**------------------------------------------- */
if (turn === player1){
O_Checked.push(boxes[i]);
console.log(O_Checked);
checkScore();
}
else if (turn === player2){
X_Checked.push(boxes[i]);
console.log( X_Checked);
checkScore();
}
}
});}
}());/*END*/
let checkPlayer = (function(){
if(turn === player1){
turn = player2;
msg.innerHTML = `<h1>Player 2 (O)</h1>`;
}
else if(turn === player2){
turn = player1;
msg.innerHTML = `<h1>Player 1 (X)</h1>`;
}
});
*{box-sizing:border-box;}
body{
margin:0;
padding:0;
font-family:arial;
}
.container{
display:flex;
height:100vh;
width:100%;
position:relative;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: tomato;
/* background-image:linear-gradient(to right, tomato, black, rgb(225, 225, 225)); */
}
.box:hover{
background-color:rgb(230,230,230);
transition: .4s ease-in-out;
}
.box,.grid{
cursor:pointer;
}
.box{
display:flex;
flex-direction:column;
justify-content: center;
align-items:center;
background-color:black;
}
.symbol{
font-size:4em;
font-style:bold;
font-family:arial;
text-transform:uppercase;
text-shadow:0px 0px 5px rgb(100,100,100);
}
.x{
color:tomato;
}
.o{
color:white;
}
.grid{
display: grid;
width: 350px;
grid-gap:10px;
border-radius:10px;
border:solid 10px white;
background-color:white;
grid-template-rows: repeat(3,100px);
grid-template-columns: repeat(3,1fr);
box-shadow: 0px 1px 8px rgb(50, 50, 50);
}
/* .grid:nth-child(even) */
.msg{
color:white;
position:absolute;
text-shadow: 0px 1px 3px rgb(50, 50, 50);
top:15px;
font-size:2em;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv ="author" content="Carl Dawkins">
<meta name ="description" content="A Tic Tac Toe Game">
<link type="text/css" href="../css/style.css" rel="stylesheet">
<title>TicTacToe</title>
</head>
<body>
<div class="container">
<div class="msg"> </div>
<div class="grid">
<div id="box-1" class="box" ></div>
<div id="box-2" class="box" ></div>
<div id="box-3" class="box" ></div>
<div id="box-4" class="box" ></div>
<div id="box-5" class="box" ></div>
<div id="box-6" class="box" ></div>
<div id="box-7" class="box" ></div>
<div id="box-8" class="box" ></div>
<div id="box-9" class="box" ></div>
</div>
</div>
<script src="../js/script.js"></script>
</body>
</html>
You are storing elements to array and try to compare elements.
I think comparing value (o or x) or id (box-1 ...) is better
X_Checked.every(e => e.innerText.trim() == 'x')
I am getting an error message of TypeError: Node.removeChild: Argument 1 is not an object when trying to select my 'resetBtn' in my removeReset() function. You will have to click the game until you or the player wins five times. The reset button shows up, it gets clicked and even though it goes away I still get this error.
What is the proper way to target this element?
The error message is coming from this
document.body.removeChild(document.querySelector('#buttonReset'));
In the removeReset(). Below is the javascript and html code. Thank you
const resetBtn = document.createElement("button");
resetBtn.id = 'buttonReset';
const rock = document.getElementById('submitRock');
const paper = document.getElementById('submitPaper');
const scissors = document.getElementById('submitScissors');
rock.addEventListener("click", function() {
choices = ['rock', 'paper', 'scissors'];
playRound(choices[0]);
});
paper.addEventListener('click', function() {
choices = ['rock', 'paper', 'scissors'];
playRound(choices[1]);
});
scissors.addEventListener('click', function() {
choices = ['rock', 'paper', 'scissors'];
playRound(choices[2]);
});
function updateScore() {
if (document.getElementById("ps").innerText === '5') {
document.getElementById("finalScore").innerText = `Player Wins!`;
alert('Player Wins')
remove();
} else if (document.getElementById("cs").innerText === '5') {
document.getElementById("finalScore").innerText = `Computer Wins!`;
alert('Computer Wins')
remove();
}
}
function playRound(playerChoice) {
computerChoice = choices[Math.floor(Math.random() * 3)]
if (computerChoice === choices[0] && playerChoice === choices[2]) {
document.getElementById("cs").innerText = Number(document.getElementById("cs").innerText) + 1;
updateScore();
} else if (computerChoice === choices[1] && playerChoice === choices[0]) {
document.getElementById("cs").innerText = Number(document.getElementById("cs").innerText) + 1;
updateScore();
} else if (computerChoice === choices[2] && playerChoice === choices[1]) {
document.getElementById("cs").innerText = Number(document.getElementById("cs").innerText) + 1;
updateScore();
} else if (computerChoice === playerChoice) {
document.getElementById('scoreboard').textContent = `Draw! Computer picked ${computerChoice} and you picked ${playerChoice}!`;
updateScore();
} else document.getElementById('scoreboard').textContent = `You win! You picked ${playerChoice} and the computer picked ${computerChoice}.`;
document.getElementById("ps").innerText = Number(document.getElementById("cs").innerText) + 1;
updateScore();
}
function remove() {
document.getElementById("ps").innerText = 0;
document.getElementById("cs").innerText = 0;
resetBtn.innerText = 'Reset';
resetBtn.setAttribute("style",
`display: block; margin: 0 auto 7.5rem auto; background-color: blue; color: white; padding: 2rem; font-size: 5rem; `);
document.getElementById('rock').removeChild(rock);
document.getElementById('paper').removeChild(paper);
document.getElementById('scissors').removeChild(scissors);
document.getElementById('body').appendChild(resetBtn);
}
function removeReset() {
document.body.removeChild(document.querySelector('#buttonReset'));
document.getElementById('rock').appendChild(rock);
document.getElementById('paper').appendChild(paper);
document.getElementById('scissors').appendChild(scissors);
}
resetBtn.addEventListener('click', function() {
removeReset();
});
resetBtn.addEventListener('click', function() {
removeReset();
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Rock Paper Scissors</title>
<link rel="stylesheet" href="index.css" />
</head>
<body id="body">
<h1 class="title">Welcome to Rock, Paper, Scissors!</h1>
<h2 class="title-sub">Against the computer....</h2>
<h1 id="scoreboard"></h1>
<h1 id="finalScore"></h1>
<div id="scoreContainer">
<div id="playerScore">
<h3 class="playersTitle playerColor">Player</h3>
<p id="ps"></p>
</div>
<div id="computerScore">
<h3 class="playersTitle computerColor">Computer</h3>
<p id="cs"></p>
</div>
</div>
<div id="options">
<div id="rock">
<button id="submitRock">ROCK</button>
</div>
<div id="paper">
<button id="submitPaper">PAPER</button>
</div>
<div id="scissors">
<button id="submitScissors">SCISSORS</button>
</div>
</div>
<div id='resetContainer'></div>
<p id="winner"></p>
<script type="text/javascript" src="console.js"></script>
</body>
</html>
You are setting 2 listeners on the click of the resetBtn:
resetBtn.addEventListener('click', function() {
removeReset();
});
resetBtn.addEventListener('click', function() {
removeReset();
});
So when you click on reset, both the listeners are triggered ; the first listener works well, but the second can't remove the element because it doesn't exist anymore.
Just remove one of the listener and it will work well.
Don't append and remove the button. Put it in the HTML, and change its display style.
You also have redundant click listeners, as mentioned in the other answer. If you use this solution, you won't get an error because of it, but you should still remove the extra one.
const resetBtn = document.querySelector("#buttonReset");
const rock = document.getElementById('submitRock');
const paper = document.getElementById('submitPaper');
const scissors = document.getElementById('submitScissors');
rock.addEventListener("click", function() {
choices = ['rock', 'paper', 'scissors'];
playRound(choices[0]);
});
paper.addEventListener('click', function() {
choices = ['rock', 'paper', 'scissors'];
playRound(choices[1]);
});
scissors.addEventListener('click', function() {
choices = ['rock', 'paper', 'scissors'];
playRound(choices[2]);
});
function updateScore() {
if (document.getElementById("ps").innerText === '5') {
document.getElementById("finalScore").innerText = `Player Wins!`;
alert('Player Wins')
remove();
} else if (document.getElementById("cs").innerText === '5') {
document.getElementById("finalScore").innerText = `Computer Wins!`;
alert('Computer Wins')
remove();
}
}
function playRound(playerChoice) {
computerChoice = choices[Math.floor(Math.random() * 3)]
if (computerChoice === choices[0] && playerChoice === choices[2]) {
document.getElementById("cs").innerText = Number(document.getElementById("cs").innerText) + 1;
updateScore();
} else if (computerChoice === choices[1] && playerChoice === choices[0]) {
document.getElementById("cs").innerText = Number(document.getElementById("cs").innerText) + 1;
updateScore();
} else if (computerChoice === choices[2] && playerChoice === choices[1]) {
document.getElementById("cs").innerText = Number(document.getElementById("cs").innerText) + 1;
updateScore();
} else if (computerChoice === playerChoice) {
document.getElementById('scoreboard').textContent = `Draw! Computer picked ${computerChoice} and you picked ${playerChoice}!`;
updateScore();
} else document.getElementById('scoreboard').textContent = `You win! You picked ${playerChoice} and the computer picked ${computerChoice}.`;
document.getElementById("ps").innerText = Number(document.getElementById("cs").innerText) + 1;
updateScore();
}
function remove() {
document.getElementById("ps").innerText = 0;
document.getElementById("cs").innerText = 0;
document.getElementById('rock').removeChild(rock);
document.getElementById('paper').removeChild(paper);
document.getElementById('scissors').removeChild(scissors);
resetBtn.style.display = "block";
}
function removeReset() {
resetBtn.style.display = "none";
document.getElementById('rock').appendChild(rock);
document.getElementById('paper').appendChild(paper);
document.getElementById('scissors').appendChild(scissors);
}
resetBtn.addEventListener('click', function() {
removeReset();
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Rock Paper Scissors</title>
<link rel="stylesheet" href="index.css" />
</head>
<body id="body">
<h1 class="title">Welcome to Rock, Paper, Scissors!</h1>
<h2 class="title-sub">Against the computer....</h2>
<h1 id="scoreboard"></h1>
<h1 id="finalScore"></h1>
<div id="scoreContainer">
<div id="playerScore">
<h3 class="playersTitle playerColor">Player</h3>
<p id="ps"></p>
</div>
<div id="computerScore">
<h3 class="playersTitle computerColor">Computer</h3>
<p id="cs"></p>
</div>
</div>
<div id="options">
<div id="rock">
<button id="submitRock">ROCK</button>
</div>
<div id="paper">
<button id="submitPaper">PAPER</button>
</div>
<div id="scissors">
<button id="submitScissors">SCISSORS</button>
</div>
</div>
<div id='resetContainer'></div>
<p id="winner"></p>
<button id="buttonReset" style="display: none; margin: 0 auto 7.5rem auto; background-color: blue; color: white; padding: 2rem; font-size: 5rem;">Reset</button>
<script type="text/javascript" src="console.js"></script>
</body>
</html>
In my class we were creating a program to provide images of dice and have them roll random numbers when the refresh button was clicked. We were practicing using querySelector and setAttribute. I thought it would be good for my learning to expand the lesson to do paper rock scissors so I could get more familiar with the coding. However, I cannot get my code to run through the functions that will display the picture of the paper, rock or scissors that is associated with randomNumber1 or randomNumber2. I tried using bootstrap4 and then just javascript and don't know what I'm doing wrong since I believe in my class we used almost the same code format for the random rolling of two dice, but only used js, css and html5 without using bootstrap.
First I tried writing the code using Bootstrap4, and everything appeared to be working correctly until I added in the function for randomizing the rolling of the dice by clicking refresh. Then I thought, maybe since I can't get bootstrap to work, I should try it in regular javascript and get it running. The code will not run there either. I am puzzled and have spent over a day trying to find answers to my problem. Below I have included the first set of code I created using bootstrap4 and the second set using just javascript. In both programs, the rock image that I just want to have take up space when the program is started, shows up so I know there is contact between the images folder and the program, but I don[t know why I cant't get the pictures to change once I click refresh.
First code using Bootstrap 4
<!-- css stylesheet -->
<link rel="stylesheet" href="stylesPractice2.css">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Kalam:400,700" rel="stylesheet">
</head>
<body>
<div class="container">
<h1 class="header">Rock, Paper, Scissors</h1>
<div class = "decision">
<h2 class = "subtopic">Need to make a decision???</h2>
</div>
<div class = "players">
<h2 class = "subtopic">Player 1</h2>
<img class = "responsive img1" src = "images/rockPaperScissors3.png">
</div>
<div class="players">
<h2 class = "subtopic">Player 2</h2>
<img class = "responsive img2" src = "images/rockPaperScissors3.png">
</div>
<div class = "whoWins">
<h2 class = "subtopic">And the winner is . . .</h2>
</div>
</div>
<script src = "rockPaperScissors.js" charset = "utf-8"></script>
</body>
JavaScript
// FIRST PLAYER CREATE RANDOM NUMBER
var randomNumber1 = (Math.floor(Math.random() * 3)) + 1;
// SECOND PLAYER CREATE RANDOM NUMBER
var randomNumber2 = Math.floor(Math.random() * 3) + 1;
function images1() {
if(randomNumber1 === 1) {
document.querySelector(".img1").setAttribute("src", "images/rockPaperScissors1.png");
}
else if(randomNumber1 === 2) {
document.querySelector(".img1").setAttribute("src", "images/rockPaperScissors2.png");
}
else if(randomNumber1 === 3) {
document.querySelector(".img1").setAttribute("src", "images/rockPaperScissors3.png");
}
}
and I stopped there because img1 was not randomizing and I could not find the answer in research.
2nd Programming No Bootstrap used.
<link rel="stylesheet" href="stylesPractice2.css">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Kalam:400,700" rel="stylesheet">
</head>
<body>
<div class="container">
<h1 class="header">Rock, Paper, Scissors</h1>
<div class = "decision">
<h2 class = "subtopic">Need to make a decision???</h2>
</div>
<div class = "players">
<h2 class = "subtopic">Player 1</h2>
<img class = "responsive img1" src = "images/rockPaperScissors3.png">
</div>
<div class="players">
<h2 class = "subtopic">Player 2</h2>
<img class = "responsive img2" src = "images/rockPaperScissors3.png">
</div>
<div class = "whoWins">
<h2 class = "subtopic">And the winner is . . .</h2>
</div>
</div>
<script src = "rockPaperScissors.js" charset = "utf-8"></script>
</body>
Both programs included the </html> tag
CSS
body {
font-family: 'Kalam', cursive;
background-color: #76fc23;
color: #2357fc;
}
.container {
width: 80%;
margin: auto;
text-align: center;
}
.title {
margin-top: 4.0rem;
}
.header {
font-weight: 700;
font-size: 5rem;
line-height: 1.5;
}
h2 {
font-size: 3rem;
}
.players {
display: inline-block;
margin: 0 2rem 3rem 2rem;
}
.player1 {
text-align: center;
margin-bottom: 3rem;
/* text-align: right;
padding-right: 5%; */
}
.player2 {
text-align: center;
margin-bottom: 3rem;
/* text-align: left;
padding-left: 5%; */
}
.img {
width: 100%;
height: auto;
}
JavaScript
// FIRST PLAYER CREATE RANDOM NUMBER
var randomNumber1 = Math.random();
randomNumber1 = Math.random() * 6;
randomNumber1 = (Math.floor(Math.random() * 6)) + 1;
// SECOND PLAYER CREATE RANDOM NUMBER
var randomNumber2 = Math.random();
randomNumber2 = Math.random() * 6;
randomNumber2 = Math.floor(Math.random() * 3) + 1;
function images1() {
if(randomNumber1 === 1) {
document.querySelector(".img1").setAttribute("src", "images/rockPaperScissors1.png");
}
else if(randomNumber1 === 2) {
document.querySelector(".img1").setAttribute("src", "images/rockPaperScissors2.png");
}
else{
document.querySelector(".img1").setAttribute("src", "images/rockPaperScissors3.png");
}
}
function images2() {
if(randomNumber2 === 1) {
document.querySelector(".img2").setAttribute("src", "images/rockPaperScissors1.png");
}
else if(randomNumber2 === 2) {
document.querySelector(".img2").setAttribute("src", "images/rockPaperScissors2.png");
}
else{
document.querySelector(".img2").setAttribute("src", "images/rockPaperScissors3.png");
}
}
images1();
images2();
In the javascript, I want my functions to change the images to the ones listed if randomNumber1 or randomNumber2 equal 1, 2 or 3. Instead, they just stay on the original image from html. I also need to use querySelector and setAttribute in my code.
You can't dynamically change an image's src attribute because img is a replaced element. This means that an img isn't part of the document, but an external resource that's inserted into the document. If the image doesn't exist in a real sense, then it can't be inserted.
You need to construct a new image via new Image() in your JS to be able to replace the existing image.
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 4 years ago.
Improve this question
I dont know how to check for the winning conditions.Could someone explain it to me step by step.I'll post my code. Im also new to coding.
prntscr.com/m06ew1
<!DOCTYPE html>
<html>
<head>
<title>Tic-Tac-Toe</title>
<link rel="stylesheet" href="TicTacToe.css">
</head>
<body>
<h1> Tic-Tac-Toe game!</h1>
<div class="grid">
<div class="grid-item" id="grid1" ></div>
<div class="grid-item" id="grid2" ></div>
<div class="grid-item" id="grid3" ></div>
<div class="grid-item" id="grid4" ></div>
<div class="grid-item" id="grid5" ></div>
<div class="grid-item" id="grid6" ></div>
<div class="grid-item" id="grid7" ></div>
<div class="grid-item" id="grid8" ></div>
<div class="grid-item" id="grid9" ></div>
</div>
</body>
<script type="text/javascript" src="jquery-3.3.1.js" ></script>
<script type="text/javascript" src="TicTacToe.js" ></script>
<aside>
<h2>History</h2>
</aside>
<section>Player <span id="player"> <b>1</b> </span> it's your
turn!</section>
<footer>
Copyright Irfan - 2018
</footer>
</html>
JSFILE
$("document").ready (function(){
const player1 = 'X'
const player2 = 'O'
CurrentPlayer = 1
$(".grid-item").click (function(){
if(CurrentPlayer == 1) {
$(this).html(player1);
$("#player").html("<b>2<b>")
CurrentPlayer = 2
}
else if ( CurrentPlayer == 2) {
$(this).html(player2);
$("#player").html("<b>1<b>")
CurrentPlayer =1
}
});
});
here is my code and i link a print screen above.Its for a tic tac tow game sdfafsdfdfsafdfasdafsdafafdfasddasfasdfafsdfda
var currentPlayer = "one";
var lastGridItem = "";
// Attach click event to grid-item
$(".grid-item").click(function() {
// Exit if disabled
if ($(this).hasClass("disabled")) {
return
}
// Determine if player has selected that grid-item
player = $(this).attr("player");
// Exit if already chosen by player
if ( player == "one" || player == "two" ) {
return
}
// Assign current player's choice of this grid-item
$(this).attr("player", currentPlayer);
// Save grid-item index so it can be undone
lastGridItem = $(this).attr("grid-value");
// Move to next player
switchPlayer();
// Check for a winner
checkWinner($(this));
});
function checkWinner(grid_item) {
$(".grid-item").each(function() {
// Get play who has selected grid-item
player = $(this).attr("player");
i = $(this).attr("grid-value");
// Exit if player has not been set for this grid-item
if (player == null || player == "") {
return
}
// Check if row assigned to player
// We only need to check do this once per row, using the far right grid-items
if (i % 3 === 0) {
// By using the far right grid-items, we know we need to check the ones with an index 1 lower and 2 lower
if (player == getPlayer(i - 1) && player == getPlayer(i - 2)) {
wonMessage(player);
}
}
// Check for columns
// We only need to do this for the bottom three grid-items
if (i > 6) {
// Check if the grid-items that are in that column have been assigned to the same player
if (player == getPlayer(i - 6) && player == getPlayer(i - 3)) {
wonMessage(player);
}
}
//Check for diagonals, only do this if checking center square
if (i == 5) {
// Check top left and bottom right against centerPlayer
if (player == getPlayer(1) && player == getPlayer(9)) {
wonMessage(player);
}
// Check centerPlayer against top right and bottom left
else if (player == getPlayer(3) && player == getPlayer(7)) {
wonMessage(player);
}
}
});
}
// Gets player assigned to grid-item
function getPlayer(i) {
return $("[grid-value=" + parseInt(i) + "]").attr("player")
}
// Prints winning message and disables game
function wonMessage(player) {
$("#winner").text("Player " + player + " has won");
$(".grid-item").addClass("disabled");
}
// Reset game
$("#reset").click( function() {
$(".grid-item").attr("player", "").removeClass("disabled");
$("#winner").text("");
currentPlayer = "one";
});
// Switch player
function switchPlayer() {
if (currentPlayer == "one") {
currentPlayer = "two";
} else {
currentPlayer = "one";
}
}
// Undo last move
$("#undo").click( function() {
// Clear player on grid-item
$(".grid-item[grid-value=" + lastGridItem + "]").attr("player", "");
// Re-enable if disabled
$(".grid-item.disabled").removeClass("disabled");
$("#winner").text("");
switchPlayer();
});
.grid {
width: 165px;
}
.grid-item {
width: 50px;
height: 50px;
border: 1px solid black;
display: inline-block;
}
.grid-item.disabled {
opacity: 0.7;
}
.grid-item[player=one] {
background: red;
}
.grid-item[player=two] {
background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1> Tic-Tac-Toe game!</h1>
<hr>
<strong>Instructions: </strong> click on grid to change player selection. <button id="undo">Undo</button> <button id="reset">Reset</button>
<hr>
<p id="winner"></p>
<div class="grid">
<div class="grid-item" grid-value="1"></div>
<div class="grid-item" grid-value="2"></div>
<div class="grid-item" grid-value="3"></div>
<div class="grid-item" grid-value="4"></div>
<div class="grid-item" grid-value="5"></div>
<div class="grid-item" grid-value="6"></div>
<div class="grid-item" grid-value="7"></div>
<div class="grid-item" grid-value="8"></div>
<div class="grid-item" grid-value="9"></div>
</div>