I'm actually practicing with event listener. I'm trying to do a very simple game where an arrow shows up and the user matches it on the keyboard . If it's correct score increases and if it's not score is reset.
It's working ok but when the arrow is not matched the if statement who resets the score is not triggered and the score is increased instead.
Here is my code (i apologize it's not clean)
const fleche = document.querySelector('.fas');
const showScore = document.querySelector('#score');
window.addEventListener('keydown',compare);
let score = 0;
let jet = 0;
showScore.innerHTML=`Score : ${score}`;
function jetdes(){
jet = Math.floor(Math.random()*4+1);
randomArrow();
}
function randomArrow(){
switch (jet) {
case 1:
fleche.classList.remove('fa-arrow-up','fa-arrow-down','fa-arrow-left','fa-arrow-right');
fleche.classList.add('fa-arrow-up');
break;
case 2:
fleche.classList.remove('fa-arrow-up','fa-arrow-down','fa-arrow-left','fa-arrow-right');
fleche.classList.add('fa-arrow-down');
break;
case 3:
fleche.classList.remove('fa-arrow-up','fa-arrow-down','fa-arrow-left','fa-arrow-right');
fleche.classList.add('fa-arrow-left');
break;
case 4:
fleche.classList.remove('fa-arrow-up','fa-arrow-down','fa-arrow-left','fa-arrow-right');
fleche.classList.add('fa-arrow-right');
break;
}}
function compare(e){
if(e.code='ArrowUp' && jet === 1){
score++;
showScore.innerHTML=`Score : ${score}`;
console.log(1);
jetdes();
}
else if(e.code='ArrowDown' && jet === 2){
score++;
showScore.innerHTML=`Score : ${score}`;
console.log(2);
jetdes();
}
else if(e.code='ArrowLeft' && jet === 3){
score++;
showScore.innerHTML=`Score : ${score}`;
console.log(3);
jetdes();
}
else if(e.code='ArrowRight' && jet === 4){
score++;
showScore.innerHTML=`Score : ${score}`;
console.log(4);
jetdes();
}
else {
score = 0;
showScore.innerHTML=`Score : ${score}`;
console.log(5);
jetdes();
}
}
jetdes();
I know it's probably an obvious mistake but i've been scratching my head over that for a while.
Thanks !
Related
I am doing a calculator that stores a history of previous calculations and list it in a table. The list needs to be stored in local storage of the web browser.
Since data is stored on local storage it should not lose context even on page refresh.
I am attaching my Javascript code below:
let currentTotal = 0;
let buffer = "0"; //what's on display
let previousOperator = null;
const calcScreen = document.querySelector(".calc-numbers");
document.querySelector('.calculator-buttons').addEventListener("click",function(event){
//call function buttonClick
buttonClick(event.target.innerHTML);
});
//separates de value of the button clicks into NotANumber and Numbers
function buttonClick(value){
if(isNaN(parseInt(value))){
handleSymbol(value);
}else{
handleNumber(value);
}
rerenderScreen();
}
function handleSymbol(value){
switch (value){
case "C":
buffer = "0";
currentTotal = 0;
previousOperator = null;
break;
case "=":
if(previousOperator === null){ //this would mean that there is nothing to be calculated yet
return;
}
flushOperation(parseInt(buffer));
buffer = "" + currentTotal;
previousOperator = null;
currentTotal = 0;
break;
case "←":
if(buffer.length === 1){ //if the screen is any single number, always turn it to 0 when deleting
buffer = "0";
}
else{
buffer = buffer.substring(0,buffer.length-1); //delete the numbers one by one
}
break;
default:
handleMath(value);
break;
}
}
function handleNumber(value){
if(buffer === "0"){
buffer = value;
}else{
buffer += value;
}
}
function handleMath(value){
const internalBuffer = parseInt(buffer);
if (currentTotal === 0){
currentTotal = internalBuffer;
}else{
flushOperation(internalBuffer);
}
previousOperator = value;
buffer = "0";
}
function flushOperation(internalBuffer){
if(previousOperator === "+"){
currentTotal += internalBuffer;
}else if(previousOperator === "-"){
currentTotal -= internalBuffer;
}else if(previousOperator === "x"){
currentTotal *= internalBuffer;
}else{
currentTotal /= internalBuffer;
}
}
function rerenderScreen(){
calcScreen.value = buffer;
}
I referred this link how to add a localstorage for my Calculator?
I added this code under my previous Javascript code:
let itemsArray = []
localStorage.setItem('items', JSON.stringify(itemsArray))
const data = JSON.parse(localStorage.getItem('items'))
itemsArray.push(input.value)
localStorage.setItem('items', JSON.stringify(itemsArray))
I refreshed my page. But the data is not stored locally. I tried typing localstorage in console but it was empty.
Adding screenshot of the result obtained in console tab
Iam getting this error too at the same time
Uncaught ReferenceError: input is not defined
For some reason my function is not returning a 1 or 2 even though it's specifically setup to do so. What am I doing wrong? I'm looking at the chrome dev tools and it's telling me that var processed is undefined.
I'm quite stumped on this. I've been reading if it's because a variable could be used as a parameter but I'm not sure if this is the case
var processChoices = function (player, computer){
switch (player) {
case player == 'rock':
if (computer == 'paper'){
var winner = 2;
} else if (computer == 'scissors'){
var winner = 1;
}
break;
case player == 'paper':
if (computer == 'scissors'){
var winner = 2;
} else if (computer == 'rock'){
var winner = 1;
}
break;
case player == 'scissors':
if (computer == 'rock'){
var winner = 2;
} else if (computer == 'paper'){
var winner = 1;
}
break;
default:
if (computer == player){
var winner = console.log('We have a tie, go again!');
}
break;
}
return winner
}
var determineWinner = function (){
var computer = computerPlay();
var player = playerChoice();
var processed = processChoices(player, computer);
if (processed == 1){
playerCount += 1;
} else {
computerCount += 1;
}
var message = (processed == 2) ? `The computer wins! ${computer} beats ${player}!` : `The player wins! ${player} beats ${computer}!`;
console.log(message);
}
I'm expecting the output of var processed to be 1 or 2. It's coming back as undefined.
It looks like you're not using the switch statement correctly. Your case statements need to just be the value that you want to match. See below.
It's would also be good to declare the variable winner once.
var processChoices = function(player, computer) {
var winner = 0;
switch (player) {
case 'rock':
if (computer == 'paper') {
winner = 2;
} else if (computer == 'scissors') {
winner = 1;
}
break;
case 'paper':
if (computer == 'scissors') {
winner = 2;
} else if (computer == 'rock') {
winner = 1;
}
break;
case 'scissors':
if (computer == 'rock') {
winner = 2;
} else if (computer == 'paper') {
winner = 1;
}
break;
default:
if (computer == player) {
console.log('We have a tie, go again!');
}
break;
}
return winner
}
var computer = "rock";
var player = "paper";
console.log("Player chose:", player, "Computer chose:", computer);
console.log("The winner is...", processChoices(player, computer));
First off the switch format is wrong.
switch (player) {
case player == 'rock': // wrong
case 'rock': // correct
Second you need to check all states of computer or else check at the end
var processChoices = function (player, computer){
let winner = 0;
switch (player) {
case 'rock':
if (computer === 'paper'){
winner = 2;
} else if (computer === 'scissors'){
winner = 1;
}
break;
case 'paper':
if (computer === 'scissors'){
winner = 2;
} else if (computer === 'rock'){
winner = 1;
}
break;
case 'scissors':
if (computer === 'rock'){
winner = 2;
} else if (computer === 'paper'){
winner = 1;
}
break;
}
if (winner === 0) {
console.log('We have a tie, go again!');
}
return winner
}
ps:
use const and let. Don't use `var'
use === not ==
Also the entire thing can be a lot smaller
const winnerTable = {
rock: {
rock: 0,
paper: 2,
scissors: 1,
},
paper: {
rock: 1,
paper: 0,
scissors: 2,
},
scissors: {
rock: 2,
paper: 1,
scissors: 0,
},
};
var processChoices = function (player, computer){
return winnerTable[player][computer];
};
well I guess it's in var determineWinner u called
var processed = processChoices(player, computer);
and processChoices is a var not a function with parameters
=>delete (player, computer);
I wrote this code to get ended my homework as a practice.
This code controls browser with nightmare.js.It just iterates clicking button and waiting for a sec.
But this code issued an error of heap out of memory. I just tried out "--max-old-space-size=4096". but it didn't work...
ANYONE HELP ME??
I checked other than iterations can work. Then putting iterations..., it cannot work due to heap out of memory.
To be honest, I am not good at coding and English. If there are any miswriting, ask me please!
const Nightmare = require('nightmare');
const nightmare = Nightmare({show: true});
const LinguaURL = "";
const NumberOfMine = "";
const PwdOfMine = "";
var i,j = -1;
var selection, progress;
var radioSelect = -1;
function main() {
nightmare
.goto(LinguaURL)
.wait(1000)
.type("input[type='text']", NumberOfMine)
.type("input[type='password']", PwdOfMine)
.click("input[type='submit']")
.wait(5000)
.click('a[href="javascript:document.Study.submit()"]')
.wait(3000)
.click("input[type='button']")
.wait(3000);
for(i = 3;i<43;i++){
nightmare
.click('a[onclick="unit_view_page(\''+i.toString()+'\');"]');
while(true){
j++;
if(j % 4 == 0){
nightmare
.click('input[onclick="select_unit(\'drill\', \''+(1833+j).toString()+'\', \'\');"]')
.wait(1000);
while(true){
radioSelect++;
nightmare
.click('input[id="answer_0_' + radioSelect.toString() +'"]')
.wait(1000)
.click('input[id="ans_submit"]')
.wait(1000)
.evaluate(function (){
return selection = document.querySelector('.btn btn-answer-view form-font-size');
})
.evaluate(function (){
return progress = document.querySelector('btn btn-next-problem form-font-size');
});
if(selection == null && progress == null)break;
if(selection != null){
continue;
}else{
nightmare
.click('input[class="btn btn-next-problem form-font-size"]');
continue;
}
}
if((j + 1) % 10 == 0)break;
}
}
}
nightmare
.wait(100)
.end()
.then(console.log);
}
main();
If I'm not mistaken, I think this is the reason.
function main() {
for(i = 3;i<43;i++){
while(true){
j++;
if(j % 4 == 0){
while(true){
/**** break for the second while. ****/
if(selection == null && progress == null) break;
if(selection != null){
continue;
}else{
continue;
}
}
/**** break for the first while. ****/
// But this code will be run if 'j % 4 == 0',
// and I can't see any assigned the value to 'j' variable inside of 'if'.
// There's no way the result will be true.
if((j + 1) % 10 == 0) { break; }
}
}
}
}
var j = -1;
var limit = 2000 * 4;
while(true){
j++;
if(j != 0 && j % 1000 == 0) console.log("loop: " + j);
// here we go.
if(j % 4 == 0){
while(true){
break;
}
// But this code will be run if 'j % 4 == 0',
// and I can't see any assigned the value to 'j' variable inside of 'if'.
// There's no way the result will be true.
if((j + 1) % 10 == 0) { console.log("your if statement"); break; }
// limit
if (j == limit) { console.log("break using limit"); break; }
}
// Maybe (do you just want to run ten times?)
// if((j + 1) % 10 == 0) { console.log("[maybe] your if statement"); break; }
}
console.log("process end");
I am creating a rock paper scissors game, I’m using buttons that the user can choose from to either select rock paper or scissors, but I don’t know how to compare the results of the user’s answer and the computer’s answer to find out who won.
number = Math.floor(Math.random()*6)+1;
function results(){
switch(number){
case 6: case 5: var a = document.getElementById("computer").innerHTML="Rock";
break;
case 4: case 3: var b = document.getElementById("computer").innerHTML="Paper";
break;
case 2: case 1: var c = document.getElementById("computer").innerHTML="Scissors";
break;
}
}
function paper(){
switch(true){
case (number <= 6): var paper = document.getElementById("user").innerHTML="Paper";
break;
}
}
function rock(){
switch(true){
case (number <= 6): var rock = document.getElementById("user").innerHTML="Rock";
break;
}
}
function scissors(){
switch(true){
case (number <= 6): var rock = document.getElementById("user").innerHTML="Scissors";
break;
}
}
You need only one function which will trigger when user click on any of options, then in same function you produce a choice for computer and then based on them figure out the winner. check the example below :
HTML :
<div id="c"></div>
<div id="u"></div>
<div id="r"></div>
// send parameter to function, 1 for Rock, 2 for Paper and 3 for Scissors
<button onclick="startg(1)">
Rock
</button>
<button onclick="startg(2)">
Paper
</button>
<button onclick="startg(3)">
Scissors
</button>
Java script :
function startg(userChoice){
document.getElementById("u").innerHTML="";
document.getElementById("c").innerHTML="";
document.getElementById("r").innerHTML="";
var comNumber = Math.floor(Math.random()*3)+1;
switch (userChoice){
case 1 : {
document.getElementById("u").innerHTML="You Choosed : Rock";
break;
}
case 2 : {
document.getElementById("u").innerHTML="You Choosed : Paper";
break;
}
case 3 : {
document.getElementById("u").innerHTML="You Choosed : Scissors";
break;
}
}
switch (comNumber){
case 1 : {
document.getElementById("c").innerHTML="Compouter Choosed :Rock";
break;
}
case 2 : {
document.getElementById("c").innerHTML="Compouter Choosed :Paper";
break;
}
case 3 : {
document.getElementById("c").innerHTML="Compouter Choosed :Scissors";
break;
}
}
//Results :
if (userChoice == 1 && comNumber==2)
document.getElementById("r").innerHTML="Result : Computer Win!";
else if (userChoice == 2 && comNumber==1)
document.getElementById("r").innerHTML="Result : You Win!";
else if (userChoice == 1 && comNumber==3)
document.getElementById("r").innerHTML="Result : You Win!";
else if (userChoice == 3 && comNumber==1)
document.getElementById("r").innerHTML="Result : Computer Win!";
else if (userChoice == 2 && comNumber==3)
document.getElementById("r").innerHTML="Result : Computer Win!";
else if (userChoice == 3 && comNumber==2)
document.getElementById("r").innerHTML="Result : You Win!";
else if (userChoice == comNumber)
document.getElementById("r").innerHTML="Result : Draw";
}
You can see a working example here : https://jsfiddle.net/emilvr/wpkj6rw6/4/
My code is working fine from case 2 upto case 4. But from case 5 up to case 9,it just produces the output of inside switch statements and do not check for if else conditions below for case 5 upto case 9. I think there is some minor error, I am not able to identify. Please help me see where is the problem.
Here is the code:
$(document).ready(function() {
var a = [],
array,input,output,userclicked,comp,ranOne=0,ranTwo=0,ranThree=0,ranFour=0,ranFive=0,ranSix=0,ranSeven=0,ranEight=0,ranNine=0;
array = [".1,.2,.3,.4,.5,.6,.7,.8,.9"];
bootbox.dialog({
message:"Choose X or O",
title:"Tic Tac Toe game",
buttons:{
success:{
label:"X",
className: "btn-success",
callback:function(){
input="X";
output="O";
/*var randomInitialOutput = (function(ranarrayElement) {
var ranarray=[".1",".5",".7",".3",".9"];
ranarrayElement = ranarray[Math.floor(Math.random() * 5)]; //random element
return ranarrayElement;
})();*/
var randomInitialOutput=".1";
$(randomInitialOutput).html(output); //random initial output
a.push(output);
$(array.join("")).click(function() {
$(this).html(input);
var hello=this;//Crazy code starts
hello= hello.className.split(/\s+/)
var blaharray=["1","2","3","4","5","6","7","8","9"]
for(var i=0;i<hello.length;i++){
if(blaharray.indexOf(hello[i])>0){
userclicked="."+hello[i];
}
}//Crazy code ends to tell us what the user clicked
if(randomInitialOutput==".1"){
$(".1").off("click");
if((ranTwo==0)&&(ranThree==0)&&(ranFour==0)&&(ranFive==0)&&(ranSix==0)&&(ranSeven==0)&&(ranEight==0)&&(ranNine==0)){
switch (userclicked) {
case ".2":
ranTwo++;
$(".7").html(output);
break;
case ".3":
ranThree++;
$(".7").html(output);
break;
case ".4":
ranFour++;
$(".5").html(output);
break;
case ".5":
ranFive++;
$(".9").html(output);
break;
case ".6":
ranSix++;
$(".3").html(output);
break;
case ".7":
ranSeven++;
$(".3").html(output);
break;
case ".8":
ranEight++;
$(".3").html(output);
break;
case ".9":
ranNine++;
$(".3").html(output);
break;
}
}//if
if((ranTwo==1)&&(userclicked==".4")){
$(".5").html(output);
ranTwo=2;
}else if ((ranTwo==2)&&(userclicked==".3")) {
$(".9").html(output); //comp won
}else if ((ranTwo==2)&&(userclicked==".9")) {
$(".3").html(output); //comp won
}
if ((ranThree==1)&&(userclicked==".4")) {
$(".9").html(output);
ranThree=2;
}else if ((ranThree==2)&&(userclicked==".5")) {
$(".8").html(output); //comp won
}else if ((ranThree==2)&&(userclicked==".8")) {
$(".5").html(output); //comp won
}
if ((ranFour==1)&&(userclicked==".9")) {
$(".3").html(output);
ranfour=2;
}else if ((ranfour==2)&&(userclicked==".2")) {
$(".7").html(output);//comp won
}else if ((ranfour==2)&&(userclicked==".7")) {
$(".2").html(output);//comp won
}
if((ranFive==1)&&(userclicked==".7")){//error starts from number 5 upto 9
$(".3").html(output);
ranfive=2;
}else if ((ranfive==2)&&(userclicked==".2")) {
$(".6").html(output);//comp won
}else if ((ranfive==2)&&(userclicked==".6")) {
$(".2").html(output);//comp won
}
if((ranSix==1)&&(userclicked==".2")){
$(".7").html(output);
ranSix=2;
}else if ((ranSix==2)&&(userclicked==".4")) {
$(".5").html(output);//comp won
}else if ((ranSix==2)&&(userclicked==".5")) {
$(".4").html(output);//comp won
}
if ((ranSeven==1)&&(userclicked==".2")) {
$(".5").html(output);
ranSeven=2;
}else if ((ranSeven==2)&&(userclicked==".9")) {
$(".8").html(output);
ranSeven=3;
}else if ((ranSeven==3)&&(userclicked==".6")) {
$(".4").html(output);//tie
}else if ((ranSeven==3)&&(userclicked==".4")) {
$(".6").html(output); //tie
}
if((ranEight==1)&&(userclicked==".2")){
$(".5").html(output);
ranEight=2;
}else if ((ranEight==2)&&(userclicked==".9")) {
$(".7").html(output);//comp won
}else if ((ranEight==2)&&(userclicked==".7")) {
$(".9").html(output);//comp won
}
if ((ranNine==1)&&(userclicked==".2")) {
$(".7").html(output);
ranNine=2;
}else if ((ranNine==2)&&(userclicked==".4")) {
$(".5").html(output);//comp won
}else if ((ranNine==2)&&(userclicked==".5")) {
$(".4").html(output);//comp won
}
}// randomInitialOutput==".1"
else if (randomInitialOutput==".5") {
}else if (randomInitialOutput==".7") {
}else if (randomInitialOutput==".3") {
}else if (randomInitialOutput==".9") {
}
a.push($(this).html());
if (a.length == 9) {
$(".yo").html("Game Over!");
} //Game Over
});
}//callback
},
main:{
label:"O",
className: "btn-primary",
callback:function(){
input="O";
$(array).click(function() {
$(this).html(input);
a.push($(this).html());
if (a.length == 9) {
$(".yo").html("Game Over!");
} //Game Over
});
}//callback
}//main
}//buttons
});//BootBoxDialogue
});//document ready function
Here the link to my code http://codepen.io/meow414/pen/rLJaPJ
Cases ".1",".2" etc are used to denote class of a box div
There is spelling mistake, ranFour is written ranfour in loop and ranFive is written ranfive. Now working correctly.