Could anyone tell how the code made to work properly? [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
This is a code supposed to generate sine wave ? But while running the code I am getting the output in decimal form ,But I need the output as a sine wave .Here is my code
<!DOCTYPE html>
<html>
<head>
<title>Try Create Sine Wave</title>
</head>
<body>
<div id="wave"></div>
<button id="play" onClick="SweepFreq(100,100,500);initSweep(document.getElementById('wave'));"> Start</button>
<script type="text/javascript">
function SweepFreq(cyc,lo, hi) {
this.cyclesPerMinute = cyc;
this.cycle_length = 60.0/this.cyclesPerMinute;
this.lowFreq = lo;
this.highFreq = hi;
this.time = 0.0;
this.buffer = null;
alert("hai");
window.initSweep = function (element) {
var sampleRate = 10000.0;
var seconds = 1;
var length = sampleRate*seconds;
this.buffer = new Float32Array(length);
alert("hallo");
this.generateSineWave(this.buffer, sampleRate, seconds);
}
this.generateSineWave = function(buffer, sampleRate, seconds) {
var deltaTime = 1.0/(sampleRate);
var oldCyclePosition=0;
alert("happy");
for (var i = 0; i < sampleRate*seconds; i++) {
var frequencyFactor = this.getFrequencyFactor(deltaTime);
var frequency = ((this.highFreq-this.lowFreq)*frequencyFactor)+this.lowFreq;
var distanceMovedInThisSample = frequency / sampleRate;
var currentCyclePosition = distanceMovedInThisSample + oldCyclePosition;
var val = Math.sin(currentCyclePosition * 2.0 * Math.PI);
this.buffer[i] = val;
oldCyclePosition = currentCyclePosition;
document.write(val);
}
};
this.getFrequencyFactor = function(deltaTime) {
this.time += deltaTime;
if (this.time > this.cycle_length)
this.time -= this.cycle_length;
var progress = this.time/this.cycle_length;
if (progress < 0.5) {
return progress*2.0;
}
else {
return 1.0-((progress-0.5)*2.0);
}
};
}
</script>
</body>
</html>
And further more I was trying to generate a sound form from the sine wave , using the audio tag in html5.
Thanks in advance

The function initSweep is never called. Try this instead (the only difference is initSweep(document.getElementById('wave')); was added to the onclick of the button):
<!DOCTYPE html>
<html>
<head>
<title>Try Create Sine Wave</title>
</head>
<body>
<div id="wave"></div>
<button id="play" onClick="SweepFreq(100,100,500);initSweep(document.getElementById('wave'));"> Start</button>
<script type="text/javascript">
function SweepFreq(cyc,lo, hi) {
this.cyclesPerMinute = cyc;
this.cycle_length = 60.0/this.cyclesPerMinute;
this.lowFreq = lo;
this.highFreq = hi;
this.time = 0.0;
this.buffer = null;
window.initSweep = function (element) {
var sampleRate = 10000.0;
var seconds = 1;
var length = sampleRate*seconds;
this.buffer = new Float32Array(length);
this.generateSineWave(this.buffer, sampleRate, seconds);
}
this.generateSineWave = function(buffer, sampleRate, seconds) {
var deltaTime = 1.0/(sampleRate);
var oldCyclePosition=0;
for (var i = 0; i < sampleRate*seconds; i++) {
var frequencyFactor = this.getFrequencyFactor(deltaTime);
var frequency = ((this.highFreq-this.lowFreq)*frequencyFactor)+this.lowFreq;
var distanceMovedInThisSample = frequency / sampleRate;
var currentCyclePosition = distanceMovedInThisSample + oldCyclePosition;
var val = Math.sin(currentCyclePosition * 2.0 * Math.PI);
this.buffer[i] = val;
oldCyclePosition = currentCyclePosition;
console.log(val);
}
};
this.getFrequencyFactor = function(deltaTime) {
this.time += deltaTime;
if (this.time > this.cycle_length)
this.time -= this.cycle_length;
var progress = this.time/this.cycle_length;
if (progress < 0.5) {
return progress*2.0;
}
else {
return 1.0-((progress-0.5)*2.0);
}
};
}
</script>
</body>
</html>

window.initSweep is not called in your code
The following lines executed in your code,
this.cyclesPerMinute = cyc;
this.cycle_length = 60.0/this.cyclesPerMinute;
this.lowFreq = lo;
this.highFreq = hi;
this.time = 0.0;
this.buffer = null;
then you have functions declarations that never executed

Related

Triying to create a JS random dungeon generator

I'm triying to create a game that generates a random dungeon in a map; I'm having trouble generating the rooms and having them connect between themselves.
I'm triying to create an algorithm that generates a room once a player has passed through a door; I have created a variable size map using and I have created the first room; but i've got no idea on how to start generating new rooms using the first room as a reference and how to solve the various problems random dungeon generators have (having rooms collide with the map limit or another room, checking if there is enough space for a room (and not creating a door if there isn't enough), having rooms reuse the doors that another room has placed, etc.). The idea I had in mind for creating the rooms is that once the player steps on a door; the algorythm runs a function to calculate the distance between the player and the closest wall (from a room or the map limit); once the generator knows the maximum size a room can have in that space; it rolls a random number to determine the width and heigth the room will have (under some parameters); when the room generates, it will have 4 doors; one in each direction, by doing that i can eliminate the possibiliy of having an unaccesible room. I'll leave the code I have developed below; any help or ideas you can give me on how to do this will be great. Thanks for your attention :) .
<html lang="es">
<head>
<title>Mi primera página</title>
<meta charset="utf-8"/>
<script type="text/javascript">
let mapa = [];
let ancho;
let alto;
let zoom;
function crearMapa(){
var color='';
var cuadro=zoom;
zoom.oninput=cuadro;
document.getElementById('pantalla').innerHTML = '';
mapa = [];
let div = document.createElement('div');
div.id = 'mesa';
div.style.width = ancho*cuadro + 'px';
div.style.height = alto*cuadro + 'px';
for (var j=0;j<alto;j++){
let fila = [];
for(var i=0;i<ancho;i++){
if((i+j)%2==0) color='#ffffff'; else color='#cccccc';
let casilla = document.createElement('div');
casilla.id = 'cuadro-x-y';
casilla.style.width = cuadro + 'px';
casilla.style.height = cuadro + 'px';
casilla.style.float = 'left';
casilla.style.backgroundColor = color;
fila.push(casilla);
div.appendChild(casilla);
}
mapa.push(fila);
}
document.getElementById('pantalla').appendChild(div);
}
function pintaMapa(){
ancho=parseInt(document.getElementById('ancho').value);
alto=parseInt(document.getElementById('alto').value);
zoom=document.getElementById('slider').value;
crearMapa();
generaSalaInicial();
}
const MAX_ALTURA = 10;
const MAX_ANCHURA = 10;
const MIN_ALTURA = 5;
const MIN_ANCHURA = 5;
const MURO = 'red';
const MURO2 = 'green';
const MURO3 = 'blue';
function generaAltura() {
return Math.floor(Math.random() * MAX_ALTURA + MIN_ALTURA);
}
function generaAnchura() {
return Math.floor(Math.random() * MAX_ANCHURA + MIN_ANCHURA);
}
let altura;
let anchura;
function generaSalaInicial() {
altura = generaAltura();
anchura = generaAnchura();
let anchura0 = 0;
let altura0 = 0;
let mitadAltura = Math.trunc(altura / 2);
let mitadAnchura = Math.trunc(anchura / 2);
for (let i = 0; i <= anchura; i++) {
mapa[anchura0][i].style.backgroundColor = MURO;
if (i != mitadAnchura) {
mapa[altura][i].style.backgroundColor = MURO;
}
}
for (let i = 0; i <= altura; i++) {
mapa[i][altura0].style.backgroundColor = MURO;
if (i != mitadAltura) {
mapa[i][anchura].style.backgroundColor = MURO;
}
}
}
var disDer;
var disIzq;
var disArr;
var disAbj;
function distDer(){
disDer = ancho - anchura - 1 ;
}
function distIzq(){//broken
disIzq = anchura + 1;
}
function distArr(){//broken
disArr = altura + 1;
}
function distAbj(){
disAbj = alto - altura - 1;
}
function genHabDer(){//broken
distDer()
alert(disDer)
let anchura0 = anchura +1;
let altura0 = altura +1;
altura = generaAltura();
anchura = generaAnchura();
let mitadAltura = Math.trunc(altura / 2);
let mitadAnchura = Math.trunc(anchura / 2);
for (let i = 0; i <= anchura; i++) {
mapa[anchura0][i].style.backgroundColor = MURO2;
if (i != mitadAnchura) {
mapa[altura][i].style.backgroundColor = MURO2;
}
}
for (let i = 0; i <= altura; i++) {
mapa[i][altura0].style.backgroundColor = MURO2;
if (i != mitadAltura) {
mapa[i][anchura].style.backgroundColor = MURO2;
}
}
}
</script>
</head>
<body onkeypress="mover(event)">
AnchoMapa (en cuadritos): <input type="text" id="ancho" value="40"><br>
AltoMapa (en cuadritos): <input type="text" id="alto" value="40"><br>
Tamaño de la cuadricula (zoom) (se mide en pixels):<input type="range" id="slider" min="1" max="50" value="10" onchange="pintaMapa()">
<br>
<input type="button" value="Crear Mapa" onclick="pintaMapa()"><br>
<div id="pantalla"></div>
</body>
</html>```

Repeat an audioContext oscillator every 5 seconds

I am trying to write a morse code trainer that produces a random two letter pattern every 5 seconds with the audiocontext recreated each loop, but I cannot figure out how to add code which will call for a repeated loop. I've tried setTimeout() setInterval(), but they both eliminate the audio.
Also, after pressing the button five times on the following code.
I get the error
" TypeError: null is not an object (evaluating 'ctx.currentTime')"
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button onclick = "startIt()">Play</button>
<button onclick = "stopIt()">Stop</button>
<h2>Morse Code</h2>
<h1 id="demo"></h1>
<h1 id="demo2"></h1>
<script>
var codeStream = '';
var dot = 1.2 / 15;
var text = "";
var display = "";
var k = 0;
var alphabet = [["A",".-"],["B","-..."],["C","-.-."],["D","-.."],["E","."],["F","..-."],["G","--."],["H","...."],["I",".."],["J",".---"],
["K","-.-"],["L",".-.."],["M","--"],["N","-."],["O","---"],["P",".--."],["Q","--.-"],["R",".-."],["S","..."],["T","-"],["U","..-"],
["V","...-"],["W",".--"],["X","-..-"],["Y","-.--"],["Z","--.."],["1",".----"],["2","..---"],["3","...--"],["4","....-"],["5","....."],
["6","-...."],["7","--..."],["8","---.."],["9","----."],["0","-----"],[".",".-.-.-"],[",","--..--"],["?","..--.."],["'",".----."],["!","-.-.--"],
["/","-..-."],[":","---..."],[";","-.-.-."],["=","-...-"],["-","-....-"],["_","..--.-"],["\"",".-..-."],["#",".--.-."],["(","-.--.-"],[" ",""]];
stopIt = function(){
ctx.close();
location.reload();
}
function nextGroup() {
for (i = 0; i < 2; i++){
var randomLetter = Math.floor(Math.random() * 26);
var code = alphabet[randomLetter][1] + " ";
var character = alphabet[randomLetter][0];
display += code;
text += character;
}
codeStream = display;
}
function startIt(){
var AudioContext = window.AudioContext || window.webkitAudioContext;
var ctx = new AudioContext();
var t = ctx.currentTime;
var oscillator = ctx.createOscillator();
oscillator.type = "sine";
oscillator.frequency.value = 600;
oscillator.start();
var gainNode = ctx.createGain();
nextGroup();
console.log(codeStream);
document.getElementById("demo").innerHTML = text;
document.getElementById("demo2").innerHTML = codeStream;
display = "";
text = "";
gainNode.gain.setValueAtTime(0, t);
for (var i = 0; i < codeStream.length; i++) {
switch(codeStream.charAt(i)) {
case ".":
gainNode.gain.setValueAtTime(1, t);
t += dot;
gainNode.gain.setValueAtTime(0, t);
t += dot;
break;
case "-":
gainNode.gain.setValueAtTime(1, t);
t += 3 * dot;
gainNode.gain.setValueAtTime(0, t);
t += dot;
break;
case " ":
t += 7 * dot;
break;
}
}
gainNode.gain.setValueAtTime(0, t);
t += 50 * dot;
oscillator.connect(gainNode);
gainNode.connect(ctx.destination);
codeStream = '';
oscillator.stop(t);
}
</script>
</body>
</html>
It looks like some of the issues are to do with scoping and state management of the oscillator. I wasn't able to reproduce the error you were seeing but the stopIt function certainly doesn't have access to ctx created in startIt.
An alternative might be to, rather than recreate the context, oscillator and gain node on each run, create them once and reuse them instead. Demo here: http://jsfiddle.net/kts74g0x/
The code:
const ALPHABET = [
["A", ".-"],
...
[" ",""]
];
const DOT = 1;
const DASH = 3;
const NEXT = DOT;
const SPACE = 7;
const SPEED = 1.2 / 15;
const AudioContext = window.AudioContext || window.webkitAudioContext;
/**
* Create a single audio context, oscillator and gain node and repeatedly
* use them instead of creating a new one each time. The gain is just
* silent most of the time.
*/
const ctx = new AudioContext();
const oscillator = ctx.createOscillator();
const gainNode = ctx.createGain();
oscillator.type = "sine";
oscillator.frequency.value = 600;
oscillator.connect(gainNode);
oscillator.start();
gainNode.connect(ctx.destination);
gainNode.gain.value = 0;
function playCodeStream(stream) {
let t = ctx.currentTime;
gainNode.gain.setValueAtTime(0, t);
for (var i = 0; i < stream.length; i++) {
switch(stream.charAt(i)) {
case ".":
gainNode.gain.setValueAtTime(1, t);
t += DOT * SPEED;
gainNode.gain.setValueAtTime(0, t);
t += NEXT * SPEED;
break;
case "-":
gainNode.gain.setValueAtTime(1, t);
t += DASH * SPEED;
gainNode.gain.setValueAtTime(0, t);
t += NEXT * SPEED;
break;
case " ":
t += SPACE * SPEED;
break;
}
}
}
/**
* Set interval will wait initially for the period of
* time before first triggering the function.
*/
setInterval(() => { playCodeStream([
ALPHABET.filter(v => v[0] === "H"),
ALPHABET.filter(v => v[0] === "E"),
ALPHABET.filter(v => v[0] === "L"),
ALPHABET.filter(v => v[0] === "L"),
ALPHABET.filter(v => v[0] === "O")
].join(" ")); }, 10000);
Set interval returns an ID that can be passed to clearInterval to prevent future runs, the play button might start the interval and the stop button could clear it, for example.
For iOS there are restrictions so that an AudioContext cannot play sound unless it is in response to a user interaction (https://hackernoon.com/unlocking-web-audio-the-smarter-way-8858218c0e09). We can get around the problem by adding a button.
<button id="go">Go</button>
And checking the state of the audio context / starting the interval in response to clicking this button (demo: http://jsfiddle.net/7gfnrubc/). The updated code:
function next() {
playCodeStream([
ALPHABET.filter(v => v[0] === "H"),
ALPHABET.filter(v => v[0] === "E"),
ALPHABET.filter(v => v[0] === "L"),
ALPHABET.filter(v => v[0] === "L"),
ALPHABET.filter(v => v[0] === "O")
].join(" "));
}
function go() {
if (ctx.state === 'suspended') {
ctx.resume();
}
/**
* Set interval will wait initially for the period of
* time before first triggering the function. Can call
* the function initially to start off.
*/
next();
setInterval(next, 10000);
}
const button = document.getElementById("go");
button.addEventListener("click", go);

Tracking time and display it at next game

I have an assignment and I am a bit stuck. The assignment states:
Modify the game so that the time is tracked and a best time (or time to beat) is stored and displayed at the end of the game and at the beginning of the next game that is played. This functionality assumes the browser is not closed and that each successive game is begun through the "Play Again?" link. The display of the time to beat is shown below.
I have all files necessary, but I am stuck in this part. Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Recipe: Drawing a square</title>
<script src="easel.js"></script>
<script type="text/javascript">
var canvas;
var stage;
var placementArray = [];
var tileClicked;
var timeAllowable;
var totalMatchesPossible;
var matchesFound;
var txt;
var matchesFoundText;
var tileHeight = 30;
var tileWidth = 45;
var border = 1;
var globalPadding = 10;
var margin = 10;
var padding = 5;
var textTiles;
var flashcards = [
["a", "\u3042"],
["i", "\u3044"],
["u", "\u3046"],
["e", "\u3048"],
["o", "\u304A"],
["ka", "\u304B"],
["ki", "\u304D"],
["ku", "\u304F"],
["ke", "\u3051"],
["ko", "\u3053"],
["sa", "\u3055"],
["shi", "\u3057"],
["su", "\u3059"],
["se", "\u305B"],
["so", "\u305D"],
["ta", "\u305F"],
["chi", "\u3061"],
["tsu", "\u3064"],
["te", "\u3066"],
["to", "\u3068"],
["na", "\u306A"],
["ni", "\u306B"],
["nu", "\u306C"],
["ne", "\u306D"],
["no", "\u306E"],
["ha", "\u306F"],
["hi", "\u3072"],
["fu", "\u3075"],
["he", "\u3078"],
["ho", "\u307B"],
["ma", "\u307E"],
["mi", "\u307F"],
["mu", "\u3080"],
["me", "\u3081"],
["mo", "\u3082"],
["ya", "\u3084"],
["yu", "\u3086"],
["yo", "\u3088"],
["ra", "\u3089"],
["ri", "\u308A"],
["ru", "\u308B"],
["re", "\u308C"],
["ro", "\u308D"],
["wa", "\u308F"],
["wo", "\u3092"],
["n", "\u3093"]
];
function init() {
canvas = document.getElementById('myCanvas');
stage = new Stage(canvas);
totalMatchesPossible = flashcards.length;
var numberOfTiles = totalMatchesPossible * 2;
matchesFound = 0;
var columns = 12;
timeAllowable = 500;
txt = new Text(timeAllowable, "30px Monospace", "#000");
txt.textBaseline = "top";
txt.x = 700;
txt.y = 0;
stage.addChild(txt);
textTiles = [];
matchesFoundText = new Text(matchesFound + "/" + totalMatchesPossible, "30px Monospace", "#000");
matchesFoundText.textBaseline = "top";
matchesFoundText.x = 700;
matchesFoundText.y = 40;
stage.addChild(matchesFoundText);
Ticker.init();
Ticker.addListener(window);
Ticker.setPaused(false);
setPlacementArray(numberOfTiles);
for (var i = 0; i < numberOfTiles; i++) {
var placement = getRandomPlacement(placementArray);
var pairIndex = Math.floor(i / 2);
text = flashcards[pairIndex][i % 2];
var textTile = drawTextTile(text, pairIndex);
textTile.x = (tileWidth + margin) * (placement % columns) + globalPadding;
textTile.y = (tileHeight + margin) * Math.floor(placement / columns) + globalPadding;
stage.addChild(textTile);
background = new Shape();
background.x = textTile.x - padding;
background.y = textTile.y - padding;
background.graphics.setStrokeStyle(border).beginStroke("#000").beginFill('#eee').drawRect(0, 0, tileWidth, tileHeight);
textTiles.push(background);
stage.addChildAt(background);
background.text = textTile;
background.onPress = handleOnPress;
stage.update();
};
}
function drawTextTile(text, pairIndex) {
textTile = new Text(text, "20px Monospace", "#000");
textTile.pairIndex = pairIndex;
textTile.textBaseline = "top";
return textTile;
}
function randomColor() {
var color = Math.floor(Math.random() * 255);
var color2 = Math.floor(Math.random() * 255);
var color3 = Math.floor(Math.random() * 255);
return Graphics.getRGB(color, color2, color3)
}
function setPlacementArray(numberOfTiles) {
for (var i = 0; i < numberOfTiles; i++) {
placementArray.push(i);
}
}
function getRandomPlacement(placementArray) {
randomNumber = Math.floor(Math.random() * placementArray.length);
return placementArray.splice(randomNumber, 1)[0];
}
function handleOnPress(event) {
var tile = event.target;
if (!!tileClicked === false || tileClicked === tile) {
tileClicked = tile;
} else {
tileClicked.graphics.beginFill('#eee').drawRect(0, 0, tileWidth, tileHeight);
tile.graphics.beginFill('#aae').drawRect(0, 0, tileWidth, tileHeight);
if (tileClicked.text.pairIndex === tile.text.pairIndex && tileClicked.id != tile.id) {
tileClicked.visible = false;
tile.visible = false;
matchesFound++;
matchesFoundText.text = matchesFound + "/" + totalMatchesPossible;
if (matchesFound === totalMatchesPossible) {
gameOver(true);
}
}
tileClicked = tile;
}
stage.update();
}
function tick() {
secondsLeft = Math.floor((timeAllowable - Ticker.getTime() / 1000));
txt.text = secondsLeft;
if (secondsLeft <= 0) {
gameOver(false);
}
stage.update();
}
function gameOver(win) {
Ticker.setPaused(true);
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play Again?</a>";
for (var i = 0; i < textTiles.length; i++) {
textTiles[i].onPress = null;
}
if (win === true) {
matchesFoundText.text = "You win!"
} else {
txt.text = secondsLeft + "... Game Over";
}
}
function replay() {
init();
}
</script>
</head>
<body onload="init()">
<header id="header">
<p id="replay"></p>
</header>
<canvas id="myCanvas" width="960" height="400"></canvas>
</body>
</html>
I give you 1 option for this, though you can do it also in other ways,
we declare global variables which are
var prev_time;
var best_time;
add that to your global variable declarations, then give it a value when you compute the time i guess we had that here:
function tick() {
secondsLeft = Math.floor((timeAllowable - Ticker.getTime() / 1000));
txt.text = secondsLeft;
if (secondsLeft <= 0) {
gameOver(false);
}
//compute here the total time player had and give it to prev_time
//var totalTimePlayerplayed = some computation here which should be allowed time per player - secondsLeft
prev_time = totalTimePlayerplayed;
stage.update();
}
function gameOver(win) {
Ticker.setPaused(true);
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play A
gain?</a>";
for (var i = 0; i < textTiles.length; i++) {
textTiles[i].onPress = null;
}
if (win === true) {
matchesFoundText.text = "You win!"
if(best_time !== NULL){
best_time = prev_time;
//WE assume that the last player is the best scorer
}
} else {
//if there is already existing top scorer
if(best_time < prev_time){
best_time = prev_time
}
txt.text = secondsLeft + "... Game Over";
}
}
then give that time of the first player to the prev_time. Upon Game over or Game ended we validate here if the best_time has a value if not, then we give it a value of the value of prev_time, else we validate if the score is higher that the previous best_time and here's a tip, now when the player would trigger the "Play again" which I can't seem find right now, you get the variable best_time's value and display it as the score to beat. Hope you get the concept and somehow it helped you accomplished what you're intended to do, but like i said before you also have some other options to do this.

Error code JS with my function Game Over

I am making a game and I encounter a problem.
When I click on the hammer, the game must show a "Game Over".
However, when a hammer appear, that I don't click on the case where it was and later I click again on this same case, "Game Over" is still displayed.
var temps = 50;
var compte = temps;
var pointCounter=0;
//ONLY SELECTOR FOR DOM
var $contener = document.querySelector(".contener");
var $bestscore = document.querySelector("#bestscore");
var $compt = document.querySelector("#compt");
var $score = document.querySelector("#score");
var $button = document.querySelector('.resetBouton');
for( var i = 0; i <= 8; i++){
$contener.innerHTML += "<div class='case case" + i + "'></div>";
}
if(localStorage.getItem('score')){
$bestscore.textContent = 'Score : ' + localStorage.getItem('score');
}
else{
localStorage.setItem('score', 0);
$bestscore.textContent = 'Score : 0';
}
function decompte(){
if(compte <= 1) {
pluriel = "";
} else {
pluriel = "s";
}
$compt.innerHTML = compte + " seconde" + pluriel;
if(!compte || compte < 0) {
reset();
if(pointCounter > localStorage.getItem('score')){
localStorage.setItem('score', pointCounter);
$bestscore.textContent = 'Score : ' + pointCounter;
}
}
//decrease 1 point
compte--;
}
let timer = setInterval(decompte,1000);
let taupe = setInterval(randomPosition,1000);
//RANDOM POSITION
function randomPosition() {
var $cases = document.querySelectorAll('.case');
// cannot click 2 times
for (var i =0; i< $cases.length; i++){
$cases[i].removeEventListener('click', losePoints);
$cases[i].removeEventListener('click', earnPoints);
$cases[i].innerHTML = '';
}
var x = Math.floor(Math.random() * 9);
var min = 1;
var max = 7;
var nbrRandom = min + Math.floor(Math.random() * max);
if (nbrRandom === 2) {
$cases[x].innerHTML = '<div id="darktaupe"><img src="images/darkTaupiqueur.png" alt="darktopiqueur"/></div>';
$cases[x].addEventListener('click', losePoints);
} else if(nbrRandom ===6) {
$cases[x].innerHTML = '<div id="darktaupe"><img src="images/Marteau_TFH.png" alt="marteau"/></div>';
$cases[x].addEventListener('click', gameOver);
}
else
{
$cases[x].innerHTML = '<div id="taupe"><img src="images/Taupiqueur.png" alt="t opiqueur"/></div>';
$cases[x].addEventListener('click', earnPoints);
}
}
function losePoints(event){
/* JouerSon(); */
pointCounter -=10;
if(pointCounter <0){
pointCounter =0
}
$score.textContent = pointCounter;
event.currentTarget.removeEventListener('click', losePoints);
}
function earnPoints(event){
/* JouerSon(); */
pointCounter ++;
$score.textContent = pointCounter;
event.currentTarget.removeEventListener('click', earnPoints);
}
/*function JouerSon() {
var sound = document.getElementById("beep");
sound.play();
} */
// RESET BUTTON
function reset(){
$button.classList.remove("reset");
$button.addEventListener('click', resetGame);
clearInterval(timer);
clearInterval(taupe);
}
function resetGame(){
pointCounter = 0;
compte = temps;
$score.textContent = pointCounter;
timer = setInterval(decompte,1000);
taupe = setInterval(randomPosition,1000);
$button.removeEventListener('click', resetGame);
$button.classList.add('reset');
}
function gameOver(event){
event.currentTarget.removeEventListener('click', gameOver);
alert("GAME OVER");
reset();
}
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles/style.css">
<meta charset="utf-8"/>
</head>
<body>
<span id="compt"></span>
<span id="score">Score : </span> <span id="bestscore"></span>
<div class="contener"></div>
<button class="resetBouton reset"> reset </button>
<button class="resetBouton jouer"> Jouer </button>
<audio id="beep" src="test1.wav">
<script type='text/javascript' src="script/main.js"></script>
</body>
</html>
From a quick examination of your game, it looks like you are calling randomPosition every second, selecting a random element and then attaching one of three event handlers to it.
It looks like you are removing your losePoints and earnPoints handlers on each call to randomPosition, but never removing gameOver.

Adding a Pause Button [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I have the following code to create the stopwatch functionality. The only thing I would like to have is to create the startandstop button be startandpause. But I have been wracking my brain ang the internet trying to find out how to do this. Any help would be greatly appreciated. Thanks!
<script type="text/javascript">
<!-- Stopwatch
var stopwatch;
var runningstate = 0; // 1 means the timecounter is running 0 means counter stopped
var stoptime = 0;
var lapcounter = 0;
var currenttime;
var lapdate = '';
function timecounter(starttime)
{
currentdate = new Date();
stopwatch = document.getElementById('stopwatch');
var timediff = currentdate.getTime() - starttime;
if(runningstate == 0)
{
timediff = timediff + stoptime
}
if(runningstate == 1)
{
stopwatch.value = formattedtime(timediff);
refresh = setTimeout('timecounter(' + starttime + ');',10);
}
else
{
window.clearTimeout(refresh);
stoptime = timediff;
}
}
function marklapH()
{
if(runningstate == 1)
{
if(lapdate != '')
{
var lapold = lapdate.split(':');
var lapnow = stopwatch.value.split(':');
var lapcount = new Array();
var x = 0
for(x; x < lapold.length; x++)
{
lapcount[x] = new Array();
lapcount[x][0] = lapold[x]*1;
lapcount[x][1] = lapnow[x]*1;
}
if(lapcount[1][1] < lapcount[1][0])
{
lapcount[1][1] += 60;
lapcount[0][1] -= 1;
}
if(lapcount[2][1] < lapcount[2][0])
{
lapcount[2][1] += 10;
lapcount[1][1] -= 1;
}
}
lapdate = stopwatch.value;
Hlapdetails.value += (++lapcounter) + '. ' + stopwatch.value + '\n';
}
}
function startandstop()
{
var startandstop = document.getElementById('startandstopbutton');
var startdate = new Date();
var starttime = startdate.getTime();
if(runningstate==0)
{
startandstop.value = 'Stop';
runningstate = 1;
timecounter(starttime);
}
else
{
startandstop.value = 'Start';
runningstate = 0;
lapdate = '';
}
}
function resetstopwatch()
{
lapcounter = 0;
stoptime = 0;
lapdate = '';
window.clearTimeout(refresh);
if(runningstate == 1)
{
var resetdate = new Date();
var resettime = resetdate.getTime();
timecounter(resettime);
}
else
{
stopwatch.value = "0:0:0";
}
}
function formattedtime(unformattedtime)
{
var decisec = Math.floor(unformattedtime/100) + '';
var second = Math.floor(unformattedtime/1000);
var minute = Math.floor(unformattedtime/60000);
decisec = decisec.charAt(decisec.length - 1);
second = second - 60 * minute + '';
return minute + ':' + second + ':' + decisec;
}
</script>
Try this code,
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="show"></div>
<input type="button" id="start" value="start" onclick="countup()" />
<input type="button" id="pause" value="pause" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
<script type="text/javascript">
var h = 0;
var m = 0;
var s = 0;
var ml = 0;
document.getElementById("show").innerHTML = "0:0:0:0";
function countup() {
ml++;
if (ml > 99 ) {
s++;
ml = 0;
}
if (s >59) {
s = 0;
m++;
}
if (m >59) {
m = 0;
h++;
}
var t = h + ":" + m + ":" + s + ":" + ml;
document.getElementById("show").innerHTML = t;
}
var timer;
$("#pause").click(function () {
clearInterval(timer);
});
$("#start").click(function () {
timer = setInterval(countup, 10)
});
</script>
</body>
</html>

Categories