Triying to create a JS random dungeon generator - javascript

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>```

Related

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.

How to work mraid script into airpush

I have a query can you help me?I want to publish campaigns with mraid script into airpush and I have tested into mraid simulator (http://webtester.mraid.org/) its run perfectly on that.My script is:
<div id="adContainer" style="margin:0px;padding:0px;background-color:white;">
<div id="normal" style="display:none;margin:auto;position:relative;top:0px;left:0px;background-color:white;border-style:solid;border-width:1px;border-color:rgb(238,50,36);" onclick="javascript:resize();"><img id="smallbanner" style="position:relative!important;top:0px;left:0px;" src="http://winnowwin.com/ap/directory2422/21_banner.jpg" />
<a href="">
<div style="position:absolute;top:5px;right:5px;background-color:rgb(238,50,36);">
<div style="width:20px;height:20px;display:table-cell;text-align:center;vertical-align:middle;font-family: Arial, Helvetica, sans-serif;">X</div>
</div>
</a>
</div>
<div id="resized" style="display:none;margin:auto;position:relative;top:0px;left:0px;background-color:white;border-style:solid;border-width:1px;border-color:rgb(238,50,36);">
<img id="bigbanner" src="http://winnowwin.com/ap/directory2422/19_bg.png" />
<div style="position:absolute;top:5px;right:5px;background-color:rgb(238,50,36);">
<div style="width:20px;height:20px;display:table-cell;text-align:center;vertical-align:middle;font-family: Arial, Helvetica, sans-serif;">X</div>
</div>
</div>
</div>
<script>
function collapse() {
mraid.close();
}
function showMyAd() {
var el = document.getElementById("normal");
el.style.display = "";
mraid.addEventListener("stateChange", updateAd);
}
function resize() {
mraid.setResizeProperties({
"width": bw,
"height": bh,
"offsetX": 0,
"offsetY": 0,
"allowOffscreen": false
});
mraid.resize();
}
function updateAd(state) {
if (state == "resized") {
toggleLayer("normal", "resized");
} else if (state == "default") {
toggleLayer("resized", "normal");
}
}
function toggleLayer(fromLayer, toLayer) {
var fromElem = document.getElementById(fromLayer);
fromElem.style.display = "none";
var toElem = document.getElementById(toLayer);
toElem.style.display = "";
}
function doReadyCheck() {
var currentPosition = mraid.getCurrentPosition();
sw = currentPosition.width;
sh = currentPosition.height;
var adcon = document.getElementById("adContainer");
adcon.style.width = sw + "px";
var sb = document.getElementById("smallbanner");
sb.height = sh;
sb.width = sw;
var nor = document.getElementById("normal");
nor.style.width = parseInt(sw) - 2 + "px";
nor.style.height = parseInt(sh) - 2 + "px";
var maxSize = mraid.getMaxSize();
bw = maxSize.width;
bh = maxSize.height;
var bb = document.getElementById("bigbanner");
bb.height = bh;
bb.width = bw;
var e2 = document.getElementById("resized");
e2.style.width = bw + "px";
e2.style.height = bh + "px";
showMyAd();
}
var bw = "";
var bh = "";
var sw = "";
var sh = "";
doReadyCheck();
</script>
I'm facing issue, script is not rendering on airpush during published.can you tell me why it is happening?
You problem is you are directly using Mraid related functionality without waiting for mraid container to be in ready state. You need to wait until SDK/Container finishes initializing MRAID library into the webview, without doing will result your ad in bad/corrupt state because most of the mraid related methods will return wrong data or throw exceptions.
So you need to first wait until Mraid is in ready state and then add mraid related listeners or functionality
E.g.
function doReadyCheck()
{
if (mraid.getState() == 'loading')
{
mraid.addEventListener("ready", mraidIsReady);
}
else
{
mraidIsReady();
}
}
function mraidIsReady()
{
mraid.removeEventListener("ready", mraidIsReady);
//NOTE: Here you shall do rest of the stuff which you are currently doing in doReadyCheck method
var currentPosition = mraid.getCurrentPosition();
sw = currentPosition.width;
sh = currentPosition.height;
var adcon = document.getElementById("adContainer");
adcon.style.width = sw + "px";
var sb = document.getElementById("smallbanner");
sb.height = sh;
sb.width = sw;
var nor = document.getElementById("normal");
nor.style.width = parseInt(sw) - 2 + "px";
nor.style.height = parseInt(sh) - 2 + "px";
var maxSize = mraid.getMaxSize();
bw = maxSize.width;
bh = maxSize.height;
var bb = document.getElementById("bigbanner");
bb.height = bh;
bb.width = bw;
var e2 = document.getElementById("resized");
e2.style.width = bw + "px";
e2.style.height = bh + "px";
showMyAd();
}
doReadyCheck();

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

DHTML - Show picture for limited time

im try to use DHTML in order to make animation for 3-5 sec( the anumation supose to start from the left to the right...).
any idea how to do tthat???
//this one will set the the pictue on the right side of the screen
function setUpPicture() {
subRunnerOBJ = new Object();
subRunnerOBJ.topPos = 100;
subRunnerOBJ.leftPos = 0;
subRunnerOBJ.velX = 400;
subRunnerOBJ.velY = 0;
subRunnerOBJ.score = 0;
hide1.style.visibility = "visible";
hide1.style.left = subRunnerOBJ.leftPos + "px";
hide1.style.top = subRunnerOBJ.topPos + "px";
hide1.style.position = "absolute";
//once we place the location of the sub , we will Call to new function that will move it
startMovePicture();
}
function startMovePicture() {
dt = 50; // in miliseconds
h = setInterval("moveObj(subRunnerOBJ)", dt);
}
function moveObj(someObj) {
counter = 0;
while (counter < 30000) {
subRunnerOBJ.leftPos = subRunnerOBJ.leftPos + subRunnerOBJ.velX * dt / 1000;
subRunnerOBJ.topPos = subRunnerOBJ.topPos + subRunnerOBJ.velY * dt / 1000;
hide1.style.left = subRunnerOBJ.leftPos + "px";
hide1.style.top = subRunnerOBJ.topPos + "px";
counter = counter + 50;
if (counter == 3000) {
stopRunning();
}
}
}
function stopRunning() {
clearInterval(h);
hide1.style.visibility = "hidden";
}
with this function i can see the picture for less than a sec...
how can i set the time here??
Replace the milliseconds value with a number equal to the desired number of seconds, which would be 5000 for five seconds. Remove the while loop inside of moveObj and replace it by adding clearInterval(h) and hide1.style.visibility = "hidden"; as the last statement inside that block.

Categories