Tracking time and display it at next game - javascript

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.

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

js / css flip card game bug in shuffle function

I have created a js memory game. It has a 24-card grid, and it is supposed to shuffle randomly out of a deck of 15 cards in order to create a little variety. The game should be different every time. However, at random the game shuffles the initial deck and builds the board with 11 pairs and one non-pair of cards. Here's the whole js file:
`var score;
var cardsmatched;
var ui = $("#gameUI");
var uiIntro =$("#gameIntro");
var uiStats = $("# gameStats");
var uiComplete = $("#gameComplete");
var uiCards = $("#cards");
var uiScore = $(".gameScore");
var uiReset = $(".gameReset");
var uiPlay = $("#gamePlay");
var uiTimer = $("#timer");
var matchingGame = {};
matchingGame.deck = ['grilledfish', 'grilledfish','barbacoa', 'barbacoa','tripa', 'tripa','bajafish', 'bajafish','carneasada', 'carneasada','carnitas', 'carnitas', 'chorizoasado','chorizoasado','shrimptaco','shrimptaco','decabeza','decabeza','alpastor', 'alpastor','dorados','dorados', 'lengua','lengua','chicharron','chicharron','sudados','sudados', 'polloasado','polloasado',];
$(function(){
init();
});
function init() {
uiComplete.hide();
uiCards.hide();
playGame = false;
uiPlay.click(function(e){
e.preventDefault();
uiIntro.hide();
startGame();
});
uiReset.click(function(e){
e.preventDefault();
uiComplete.hide();
reStartGame();
});
}
function startGame(){
uiTimer.show();
uiScore.html("0 seconds");
uiStats.show();
uiCards.show();
score = 0;
cardsmatched= 0;
if (playGame == false) {
playGame = true;
matchingGame.deck.sort(shuffle);
for (var i=0; i<25; i++){
$(".card:first-child").clone().appendTo("#cards");
}
uiCards.children().each(function(index) {
$(this).css({
"left" : ($(this).width() + 20) * (index % 6),
"top" : ($(this).height() + 20) * Math.floor(index / 6)
});
var pattern = matchingGame.deck.pop();
$(this).find(".back").addClass(pattern);
$(this).attr("data-pattern",pattern);
$(this).click(selectCard);
});
timer();
};
}
function timer(){
if (playGame){
scoreTimeout = setTimeout(function(){
uiScore.html(++score = "seconds");
timer();
}, 1000);
};
};
function shuffle() {
return 0.5 - Math.random();
}
function selectCard(){
if($(".card-flipped").size()> 1){
return;
}
$(this).addClass("card-flipped");
if($(".card-flipped").size() == 2) {
setTimeout(checkPattern, 1000);
};
};
function checkPattern(){
if (isMatchPattern()) {
$(".card-flipped").removeClass("card-flipped").addClass("card-removed");
if(document.webkitTransitionEnd){
$(".card-removed").bind("webkitTransitionEnd", removeTookCards);
}else{
removeTookCards();
} else {
$(".card-flipped").removeClass("card-flipped");
}
}
function isMatchPattern(){
var cards = $(".card-flipped");
var pattern = $(cards[0]).data("pattern");
var anotherPattern = $(cards[1]).data("pattern");
return (pattern == anotherPattern);
}
function removeTookCards() {
if (cardsmatched < 12) {
cardsmatched++;
$(".card-removed").remove();
}else{
$(".card-removed").remove();
uiCards.hide();
uiComplete.show();
clearTimeout(scoreTimeout);
}
}
function reStartGame(){
playGame = false;
uiCards.html("<div class='card'><div class='face front'></div><div class='face back'></div></div>");
clearTimeout(scoreTimeout);
matchingGame.deck = ['grilledfish', 'grilledfish','barbacoa', 'barbacoa','tripa', 'tripa','bajafish', 'bajafish','carneasada', 'carneasada','carnitas', 'carnitas', 'chorizoasado','chorizoasado','shrimptaco','shrimptaco','decabeza','decabeza','alpastor', 'alpastor','dorados','dorados', 'lengua','lengua','chicharron','chicharron','sudados','sudados', 'polloasado','polloasado',];
startGame();
}
`

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

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

Setinterval not firing at individual times - and uncaught typeerror

On the function on this code, whatareyousingingpatrick(),, when the function is called a new element and setinterval should be called, however it doesn't seem like a new one is created with a new original variable, it just seems like the same one gets fired over and over. Thanks for your help
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<!DOCTYPE html>
<body onclick="whatareyousingingpatrick();" onkeypress="pretend();">
<span id="money">25</span>$ - <span id="lives">100</span>/100 lives - Level: <span id="level">1</span>
<br><br>
<span style="background-color:#c3c3c3;width:1000px;height:175px;overflow:hidden;position:relative;display:block;" id="track"></span>
<br>
<span id="divthing" style="position:relative;display:block;"></span>
<script>
money = 25;
lives = 100;
mycars = {};
function doofus() {
if($("div:first").offset().left > 1000){
$("div:first").remove();
lives = lives-1;
document.getElementById("lives").innerHTML = lives;
}
}
function dodat() {
var btn = document.createElement("div");
btn.style.width = "25px";
btn.style.height = "25px";
btn.style.backgroundColor = "red";
btn.style.boxShadow = "inset 0px 0px 0px 2px black";
btn.style.position = "absolute";
btn.style.left = "0px";
btn.style.webkitTransition = "opacity 1s";
var numba = Math.round(Math.random() * 50);
btn.class = "haha";
btn.id = numba;
mycars[numba] = -50;
var move = function () {
mycars[numba] = mycars[numba] + 1.5;
document.getElementById(numba).style.left = mycars[numba] + "px";
if(mycars[numba] > 100 && mycars[numba] < 150){
document.getElementById(numba).style.top = mycars[numba]/0.5-200 + "px";
}
};
setInterval(move, 10);
document.getElementById("track").appendChild(btn);
}
setInterval(dodat, 2000);
setInterval(doofus, 200);
function dis1() {
$("shooter").css("background-color", "red");
setTimeout('$("shooter").css("background-color", "blue");', '1000');
compareEl = $("#shoot1");
// Let's find the closest block!
var otherEls = $('div'),
compareTop = compareEl.offset().top,
compareLeft = compareEl.offset().left,
winningScore = Infinity,
score, winner, curEl;
otherEls.each(function () {
// Calculate the score of this element
curEl = $(this);
score = Math.abs(curEl.offset().left - compareLeft);
if (score < winningScore) {
winningScore = score;
winner = this;
}
});
document.getElementById(winner.id).style.opacity="0";
money = money+1;
document.getElementById("money").innerHTML=""+money+"";
}
function dis2() {
compareEl2 = $("#shoot2");
// Let's find the closest block!
var otherEls2 = $('div'),
compareTop2 = compareEl2.offset().top,
compareLeft2 = compareEl2.offset().left,
winningScore2 = Infinity,
score2, winner2, curEl2;
otherEls2.each(function () {
// Calculate the score of this element
curEl2 = $(this);
score2 = Math.abs(curEl2.offset().left - compareLeft2);
if (score2 < winningScore2) {
winningScore2 = score;
winner2 = this;
}
});
document.getElementById(winner2.id).style.opacity="0";
}
function dis3() {
compareEl3 = $("#shoot3");
// Let's find the closest block!
var otherEls3 = $('div'),
compareTop3 = compareEl3.offset().top,
compareLeft3 = compareEl3.offset().left,
winningScore3 = Infinity,
score3, winner3, curEl3;
otherEls3.each(function () {
// Calculate the score of this element
curEl3 = $(this);
score3 = Math.abs(curEl3.offset().left - compareLeft3);
if (score3 < winningScore3) {
winningScore3 = score;
winner3 = this;
}
});
document.getElementById(winner3.id).style.opacity="0";
}
function dis4(){
compareEl4 = $("#shoot4");
// Let's find the closest block!
var otherEls4 = $('div'),
compareTop4 = compareEl4.offset().top,
compareLeft4 = compareEl4.offset().left,
winningScore4 = Infinity,
score4, winner4, curEl4;
otherEls4.each(function () {
// Calculate the score of this element
curEl4 = $(this);
score4 = Math.abs(curEl4.offset().left - compareLeft4);
if (score4 < winningScore4) {
winningScore4 = score;
winner4 = this;
}
});
document.getElementById(winner4.id).style.opacity="0";
}
original = 0;
function whatareyousingingpatrick(){
if(money >= 1){
money = money+10000000;
original = original+1;
setInterval("dis"+original+"();alert("+original+");", 1800);
var btn = document.createElement("shooter");
btn.style.display = "block";
btn.id = "shoot"+original+"";
btn.style.height = "25px";
btn.style.width = "25px";
btn.style.backgroundColor = "blue";
btn.innerHTML = "<img src='http://www.bubblews.com/assets/images/news/1317280976_1370202845.png' style='height:100%;width:100%;border-radius:100%;opacity:0.7;'>";
btn.style.borderRadius= "100%";
btn.style.boxShadow= "0px 0px 200px 75px rgba(0, 0, 0, 0.2)";
btn.style.position = "absolute";
btn.style.left = event.pageX-20;
btn.style.top = event.pageY-250;
document.getElementById("divthing").appendChild(btn);
}
else{
alert("Sorry, this dude costs over 25 bucks.");
}
}
function pretend(){
if(money >= 60){
money = money-60;
if (event.keyCode == 49) {
alert("You have bought the FASTER SHOOTING upgrade for your first missile. Note that you can purchase this upgrade an unlimited number of times.");
setInterval("dis1();", "1000");
}
if (event.keyCode == 50) {
alert("You have bought the FASTER SHOOTING upgrade for your second missile. Note that you can purchase this upgrade an unlimited number of times.");
setInterval("dis2();", "1000");
}
if (event.keyCode == 51) {
alert("You have bought the FASTER SHOOTING upgrade for your third missile. Note that you can purchase this upgrade an unlimited number of times.");
setInterval("dis3();", "1000");
}
if (event.keyCode == 52) {
alert("You have bought the FASTER SHOOTING upgrade for your fourth missile. Note that you can purchase this upgrade an unlimited number of times.");
setInterval("dis4();", "1000");
}
}
else
{
alert("Sorry, the cost of the FASTER SHOOTING upgrade for this missile is 60$");
}
}
</script>
<script>
setTimeout('document.getElementById("level").innerHTML="2";setInterval(dodat, 8000);', '40000');
</script>
<br><br>
Here it is isolated.
original = 0;
function whatareyousingingpatrick(){
if(money >= 1){
money = money+10000000;
original = original+1;
setInterval("dis"+original+"();alert("+original+");", 1800);
var btn = document.createElement("shooter");
btn.style.display = "block";
btn.id = "shoot"+original+"";
btn.style.height = "25px";
btn.style.width = "25px";
btn.style.backgroundColor = "blue";
btn.innerHTML = "<img src='http://www.bubblews.com/assets/images/news/1317280976_1370202845.png' style='height:100%;width:100%;border-radius:100%;opacity:0.7;'>";
btn.style.borderRadius= "100%";
btn.style.boxShadow= "0px 0px 200px 75px rgba(0, 0, 0, 0.2)";
btn.style.position = "absolute";
btn.style.left = event.pageX-20;
btn.style.top = event.pageY-250;
document.getElementById("divthing").appendChild(btn);
}
else{
alert("Sorry, this dude costs over 25 bucks.");
}
}
When I try:
setInterval(function(){
var func = 'dis' + original;
func();
alert(original); //for some reason
}, 1800);
I keep getting Uncaught TypeError: string is not a function. Any clue why?
You are trying to call a function on a string variable.
var func = 'dis' + original;
so func is now a string not a callable function.
If the resultant string func is actualltly a function name you could do this:
window[func]();
To call func with a string variable.

Categories