Trouble with showing time in Javascript - javascript

I created an easy game with Javascript, the purpose is to pick a square who has a RGB color(random generated) from a list of squares and show the length of time until the square with the correct color is found. Everything works fine, except after the time is shown corectly and I click on a button, the time continues to change and show again a new time and i don't want that. I try to give display: none or textcontent ="" after showing the time, but is not working.
The problem is in these lines:
end = new Date().getTime();
timeTaken = (end - start) / 1000;
timp.style.display ="inline";
timp.innerHTML = "Timpul tau: " + timeTaken + " s.";
Thanks!
The game link: https://ionutbedeoan.github.io/joc/
My javascript code :
var numSquares = 6;
var colors = generateRandomColors(numSquares);
var squares = document.querySelectorAll(".square");
var pickedColor = pickColor();
var colorDisplay = document.getElementById("colorDisplay");
var messageDisplay = document.querySelector("#message");
var h1 = document.querySelector("h1");
var resetButton = document.querySelector("#reset");
var easyBtn = document.querySelector("#easyBtn");
var hardBtn = document.querySelector("#hardBtn");
var numSquares = 6;
var timp = document.getElementById("timeTaken");
var start = new Date().getTime();
var end;
var timeTaken;
easyBtn.addEventListener("click", function () {
start = new Date().getTime();
numSquares = 3;
this.classList.add("selected");
hardBtn.classList.remove("selected");
colors = generateRandomColors(numSquares);
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
for (var i = 0; i < 3; i++) {
squares[i].style.backgroundColor = colors[i];
}
for (var i = 3; i < squares.length; i++) {
squares[i].style.display = "none";
}
timp.textContent= "";
messageDisplay.textContent = "";
h1.style.background = "steelblue";
});
hardBtn.addEventListener("click", function () {
start = new Date().getTime();
this.classList.add("selected");
numSquares = 6;
easyBtn.classList.remove("selected");
colors = generateRandomColors(numSquares);
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
for (var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = colors[i];
squares[i].style.display = "block";
}
messageDisplay.textContent = "";
timp.textContent= "";
h1.style.background = "steelblue";
});
resetButton.addEventListener("click", function () {
start = new Date().getTime();
//generare noi culori
colors = generateRandomColors(numSquares);
//alegem o noua culoare random din vector
pickedColor = pickColor();
//schimbam colorDisplay sa fie la fel cu culoarea aleasa
colorDisplay.textContent = pickedColor;
//schimbare culori ale patratelor
for (var i = 0; i < squares.length; i++) {
// adaug culorile la fiecare patrat
squares[i].style.background = colors[i];
}
h1.style.background = "steelblue";
messageDisplay.textContent = "";
this.textContent = "Culori noi";
timp.textContent= "";
});
colorDisplay.textContent = pickedColor;
for (var i = 0; i < squares.length; i++) {
// adaug culorile la fiecare patrat
squares[i].style.background = colors[i];
//cand dau click pe un patrat
squares[i].addEventListener("click", function () {
// pun intr-o variabila culoarea patratatului ca sa o verific cu culoarea pe care trebuie sa o ghicesc, pentru a vedea daca am nimerit culoarea
var clickedColor = this.style.backgroundColor;
if (clickedColor === pickedColor) {
messageDisplay.textContent = "Corect!"
resetButton.textContent = "Joc nou"
changeColors(clickedColor);
h1.style.backgroundColor = clickedColor;
end = new Date().getTime();
timeTaken = (end - start) / 1000;
timp.style.display ="inline";
timp.innerHTML = "Timpul tau: " + timeTaken + " s.";
} else {
this.style.backgroundColor = "#232323";
messageDisplay.textContent = "Gresit!";
}
});
};
function changeColors(color) {
//schimbam culoarea la fiecare patrat
for (var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = color;
}
}
function pickColor() {
var random = Math.floor(Math.random() * colors.length);
return colors[random];
}
function generateRandomColors(num) {
// fac un vector
var arr = [];
//adaugam numarul de culori random
for (var i = 0; i < num; i++) {
//alegem o culoare random si o bagam in vector
arr[i] = randomColor();
}
//returnam vectorul
return arr;
}
function randomColor() {
// alegem un rosu intre 0 si 255
var r = Math.floor(Math.random() * 256);
//alegem un verde intre 0 si 255
var g = Math.floor(Math.random() * 256);
//alegem un albastru intre 0 si 255
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + ", " + g + ", " + b + ")";
}
Thanks !

Check if the correct answer was already selected in your square's event listener and return if so. This will prevent it from running the rest of the event listener's code where it updates the time.
if (clickedColor === pickedColor) {
if (messageDisplay.textContent === "Corect!") return;
...
} else {
...
}

Related

function to find the division of 2 numbers contained in an array

I am creating a function to calculate the division of 2 numbers that are inside an array. The problem I have is that the division is done the other way around. ej: if I put 10/2 as parameters, the result that returns is 2/10. So how could I solve this error?
Here I leave the complete code, just check the code of the function "fDividir".
Code javascript:
sysc es un sistema que podrás usar para implementar para la creación de tu calculadora.
// inicio de las funciones
//función sumar
const fSumar = function (valores = "0"){
let arregloNum = valores.split("+");
let oSuma = 0;
for (let i = 0; i < arregloNum.length; i++){
oSuma = parseInt(arregloNum[i]) + oSuma;
}
return oSuma;
}
//función restar
const fRestar = function (valores = "0"){
let arregloNum = valores.split("-");
let oResta = 0;
for (let i = 0; i < arregloNum.length; i++){
oResta = parseInt(arregloNum[i]) - oResta;
}
return oResta;
}
// función multiplicar
const fMultiplicar = function (valores = "0"){
let arregloNum = valores.split("×");
let oMultiplicacion = 1;
for (let i = 0; i < arregloNum.length; i++){
oMultiplicacion = parseInt(arregloNum[i]) * oMultiplicacion;
}
return oMultiplicacion;
}
// función dividir
const fDividir = function (valores = "0"){
let arregloNum = valores.split("/");
let oDivision = 1;
for (let i = 0; i < arregloNum.length; i++){
oDivision = parseInt(arregloNum[i]) / oDivision;
}
return oDivision;
}
// fin de las funciones
console.log(fDividir("10/2")); // 0.2
Change your division function:
// función dividir
const fDividir = function (valores = "0"){
let arregloNum = valores.split("/");
let oDivision = 1;
for (let i = arregloNum.length - 1; i > 0; i--){
oDivision = parseInt(arregloNum[i]) * oDivision;
}
return arregloNum[0] / oDivision;
}
Note that you were inverting the divisors order...
Another, possible solution:
// función dividir
const fDividir = function (valores = "0"){
let arregloNum = valores.split("/");
let oDivision = arregloNum[0];
for (let i = 1; i < arregloNum.length; i++){
oDivision /= parseInt(arregloNum[i]);
}
return oDivision;
}

Processes for optimizing canvas animations

I've got a small web app in development to simulate the Ising model of magnetism. I've found that the animation slows down considerably after a few seconds of running, and it also doesn't loop after 5 seconds like I want it to with the command:
setInteval(main, 500)
I've added start and stop buttons. When I stop the animation, and then restart it, it begins fresh at the usual speed, but again slows down.
My question is: what steps can I take to troubleshoot and optimize the performance of my canvas animation? I hope to reduce or mitigate this slowing effect.
JS code:
window.onload = function() {
var canvas = document.getElementById("theCanvas");
var context = canvas.getContext("2d");
var clength = 100;
var temperature = 2.1;
var playAnim = true;
canvas.width = clength;
canvas.height = clength;
var imageData = context.createImageData(clength, clength);
document.getElementById("stop").addEventListener("click",function(){playAnim=false;});
document.getElementById("start").addEventListener("click",function(){playAnim=true;});
function init2DArray(xlen, ylen, factoryFn) {
//generates a 2D array of xlen X ylen, filling each element with values defined by factoryFn, if called.
var ret = []
for (var x = 0; x < xlen; x++) {
ret[x] = []
for (var y = 0; y < ylen; y++) {
ret[x][y] = factoryFn(x, y)
}
}
return ret;
}
function createImage(array, ilen, jlen) {
for (var i = 0; i < ilen; i++) {
for (var j = 0; j < jlen; j++) {
var pixelIndex = (j * ilen + i) * 4;
if (array[i][j] == 1) {
imageData.data[pixelIndex] = 0; //r
imageData.data[pixelIndex+1] = 0; //g
imageData.data[pixelIndex+2] = 0; //b
imageData.data[pixelIndex+3] = 255; //alpha (255 is fully visible)
//black
} else if (array[i][j] == -1) {
imageData.data[pixelIndex] = 255; //r
imageData.data[pixelIndex+1] = 255; //g
imageData.data[pixelIndex+2] = 255; //b
imageData.data[pixelIndex+3] = 255; //alpha (255 is fully visible)
//white
}
}
}
}
function dU(i, j, array, length) {
var m = length-1;
//periodic boundary conditions
if (i == 0) { //top row
var top = array[m][j];
} else {
var top = array[i-1][j];
}
if (i == m) { //bottom row
var bottom = array[0][j];
} else {
var bottom = array[i+1][j];
}
if (j == 0) { //first in row (left)
var left = array[i][m];
} else {
var left = array[i][j-1];
}
if (j == m) { //last in row (right)
var right = array[i][0];
} else {
var right = array[i][j+1]
}
return 2.0*array[i][j]*(top+bottom+left+right); //local magnetization
}
function randInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
var myArray = init2DArray(clength, clength, function() {var c=[-1,1]; return c[Math.floor(Math.random()*2)]}); //creates a 2D square array populated with -1 and 1
function main(frame) {
if (!playAnim){return;} // stops
window.requestAnimationFrame(main);
createImage(myArray, clength, clength);
context.clearRect(0,0,clength,clength);
context.beginPath();
context.putImageData(imageData,0,0);
for (var z = 0; z < 10*Math.pow(clength,2); z++) {
i = randInt(clength-1);
j = randInt(clength-1);
var deltaU = dU(i, j, myArray, clength);
if (deltaU <= 0) {
myArray[i][j] = -myArray[i][j];
} else {
if (Math.random() < Math.exp(-deltaU/temperature)) {
myArray[i][j] = -myArray[i][j];
}
}
}
}
var timer = setInterval(main, 500);
}

How to display rainbow message in console.log

Hi have a script for rainbowtizing console.log output.
When i try, console.log output raw string, but if i copy this output in another console.log, he output the message with the correct color.
Do you know why ?
var input = document.getElementById('input');
input.addEventListener("blur", function() {
var inputValue = input.value;
var inputSplitted = inputValue.split("");
let i = 0,
inputLength = inputSplitted.length;
var newLog ='"';
var colors = "";
for(i=0; i<inputLength; i++){
// Chaque lettre est contenue dans inputSplitted[i]
newLog += "%c"+inputSplitted[i];
colors += ',"color: '+randomColor()+';"';
}
newLog +='"';
var log = newLog+colors;
console.log(log);
console.log("%ch%ce%cl%cl%co%c %cw%co%cr%cl%cd","color: #144143;","color: #40C71F;","color: #5B7487;","color: #E3E226;","color: #6A8693;","color: #EC8802;","color: #9D44DE;","color: #1F1C4D;","color: #92812D;","color: #7A412C;","color: #73936F;");
});
function randomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
<input type=text name=input id=input>
As is said in the comment the browser handles the string just as a string and not as parameters.
You have to declare an array and use console.log.apply.
Have a look:
var input = document.getElementById('input');
input.addEventListener("blur", function() {
var inputValue = input.value;
var inputSplitted = inputValue.split("");
let i = 0,
inputLength = inputSplitted.length;
var newLog ='';
var colors = "";
for(i=0; i<inputLength; i++){
// Chaque lettre est contenue dans inputSplitted[i]
newLog += "%c"+inputSplitted[i];
colors += '||color: '+randomColor()+';';
}
newLog +='';
var log = newLog+colors;
var arr = log.split('||');
console.log.apply(console, arr);
console.log("%ch%ce%cl%cl%co%c %cw%co%cr%cl%cd","color: #144143;","color: #40C71F;","color: #5B7487;","color: #E3E226;","color: #6A8693;","color: #EC8802;","color: #9D44DE;","color: #1F1C4D;","color: #92812D;","color: #7A412C;","color: #73936F;");
});
function randomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
<input type=text name=input id=input>
Hope this code will help you. :)

Keep the clicked objects in an array in javascript

I made a puzzle game in javascript. I have made objects to keep some attributes relevant to the each pazzle squares. I want to get the object id which is relevant to the onclick.(not the div id). How to get the specific object id relevant to the clicked div?
window.onload = function() {
createDivs();
objects();
random();
onclickeventHanlder(event);
};
var getId;
var x = 3;
var counting = 0;
var tileSize = 600 / x;
var array2 = [];
var object = [];
function createDivs() {
var count = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var id = i + "" + j;
var element = document.createElement('div');
element.setAttribute("class", "pieces");
element.setAttribute("id", id);
element.style.width = 600 / x + "px";
element.style.height = 600 / x + "px";
element.style.margin = "0px auto";
element.style.overflow = "hidden";
element.setAttribute("onclick", "onclickeventHanlder(this)");
if (count > 0) { // to break row-wise
if (i == count && j == 0) {
element.style.clear = "both";
}
}
element.style.float = "left";
document.getElementById('puzzle-body').appendChild(element);
}
count++;
}
}
function objects(){
var count = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var objName = new Object();
objName.position = -(j * tileSize) + "px" + " " + -(i * tileSize) + "px";
objName.divID = document.getElementById(i + "" + j);
objName.id = count;
if(count<x*x-1){
objName.state = true; // if image is there
}else{
objName.state = false; // if image isn't there
}
object[count] = objName;
count++;
}
}
}
function reset(){
var looping = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var obj = object[looping];
if(obj.id<8){
var urlString = 'url("../images/Golden.jpg")';
obj.divID.style.backgroundImage = urlString;
obj.divID.style.backgroundPosition = obj.position;
}
looping++;
}
}
}
function random(){
var array = [];
while (array.length < ((x * x) - 1)) {
var randomnumber = Math.floor(Math.random() * ((x * x) - 1));
var found = false;
for (var i = 0; i < array.length; i++) {
if (array[i] == randomnumber) {
found = true;
break;
}
}
if (!found) {
array[array.length] = randomnumber;
}
}
var looping = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
if (looping < x * x-1) {
var random = array[looping];
var obj = object[random];
var obj2 = object[looping];
if(obj.id<8){
var urlString = 'url("../images/Golden.jpg")';
obj.divID.style.backgroundImage = urlString;
obj.divID.style.backgroundPosition = obj2.position;
}
}
looping++;
}
}
}
function onclickeventHanlder(event) {
var pos = event;
}

making groups with random names in it in javascript

I am new to coding Javascript. I am trying to to shuffle list of names inputted on a textarea. The user selects the number of groups desired, and shuffle on click, then show the divided groups as output result. Below is my code but it is not working as it should be, pls help!
<script>
function ArrayToGroups(source, groups){
var groupList = [];
groupSize = Math.ceil(source.length/groups);
var queue = source;
for(var r = 0; r < groups; r++){
groupList.push(queue.splice(0,groupSize));
}
return groupList;
}
function textSpliter(splitText){
var textInput = document.getElementById("inputText").value;
var splitText = textInput.split(',');
var newList = [];
for(x = 0; x <= splitText.length; x++) {
var random = Math.floor(Math.random() * splitText.length);
var p = splitText[random];
newList.push(p);
splitText.splice(p,groupList);
}
for(var i = 0; i < newList.length; i++){
var s = newList[i];
document.getElementById('resInput').value += s + "\n" ;
}
return splitText;
}
</script>
Below is my input and output textareas
</head>
<body>
<form>
<textarea id="inputText" placeholder="text" rows="10" cols="40"></textarea>
<input type="number" name="number" max="6" value="1" id="groupNumber">
<textarea id="resInput" placeholder="text" rows="10" cols="40"></textarea>
<input type="button" name="Shuffle" value="shuffle" onclick="textSpliter()">
</form>
</body>
</html>
function shuffle() {
// Get list
// Example: element1, element 2, ele ment 3, ...
var list = document.getElementById("inputText").value.replace(/\s*,\s*/g, ",").split(",");
// Get number of groups
var n = parseInt(document.getElementById("groupNumber").value);
// Calculate number of elements per group
var m = Math.floor(list.length / n);
// Enought elements
if (n * m == list.length) {
// Create groups
var groups = new Array();
for (i = 0; i < n; i++) {
groups[i] = new Array();
for (j = 0; j < m; j++) {
// Random
rand = Math.floor(Math.random() * list.length);
// Add element to group
groups[i][j] = list[rand];
// Remove element to list
list.splice(rand, 1);
}
}
// Output
var text = "";
for (i = 0; i < n; i++) {
text += "Group " + (i + 1) + ": ";
for (j = 0; j < m; j++) {
if (j != 0) { text += ", "; }
text += groups[i][j];
}
text += "\n";
}
document.getElementById("resInput").value = text;
} else {
alert("Add more elements");
}
}
I rewrote your code. It's pretty self-explanatory.
FIDDLE
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [];
for (var i = 0; i < groupCount; i++) {
var group = [];
for (var j = 0; j < groupSize; j++) {
var random = Math.floor(Math.random() * names.length);
var name = names[random];
if (name != undefined) {
group.push(name);
names.splice(names.indexOf(name), 1);
}
}
group.sort();
groups.push(group);
}
printGroups(groups);
}
function printGroups(group) {
var output = document.getElementById("resInput");
output.value = "";
for (var i = 0; i < group.length; i++) {
var currentGroup = "";
for (var j = 0; j < group[i].length; j++) {
currentGroup = group[i].join(",");
}
output.value += currentGroup + "\r";
}
}
ES6 version ;-)
http://jsfiddle.net/dLgpny5z/1/
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.replace(/\s*,\s*|\n/g, ",").split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [...Array(groupCount)].map(() => Array());
var i = 0
while (names.length > 0) {
var m = Math.floor(Math.random() * names.length);
groups[i].push(names[m]);
names.splice(m, 1);
i = (i >= groupCount - 1) ? 0 : i + 1
}
printGroups(groups);
}
function printGroups(groups) {
var output = document.getElementById("resInput");
output.value = groups.map(group => group.join(',')).join('\r');
}

Categories