Phaser stopwatch - phaser-framework

I have started a game and I want a stopwatch (countup timer) in it I have found a code to activate it. But how to stop it?
Source: https://docs.idew.org/video-game/project-references/phaser-coding/timers#create-count-up-timer
Code related to the stopwatch:
//global vars
var timeText; var min, sec;
function create timeText = game.add.text(600, 20, "", { fontSize: '20px', fill: '#FFF' }); timeText.fixedToCamera = true;
function displayTimeElapsed(){
if (knight.x >= 96){
var time = Math.floor(game.time.totalElapsedSeconds() );
min = Math.floor(time / 60);
sec = time % 60;
if (min < 10) {
min = "0" + min;
}
if (sec < 10) {
sec = "0" + sec;
}
timeText.text = "Time: " + min + ":" + sec;
}
}
//update displayTimeElapsed();

you could add a boolean pause that if true it will set the time to what the remaining time is and when false keep doing what is doing.
it would be easier to explain it if you show your code. I will update my answer accordingly.

Lets create it from scratch,
first of all in your create() function, lets add a text to display the timer on the screen:
// CREATE()
this.timerText = this.add.text(x, y, "").setColor("#000000");
Second lets create a function, bellow the update(), to count down :
showTimer(){
// Assuming you want 60 seconds, if not just chenge the 60's for whatever time you want
let maxTime = 60;
let time = Math.floor(this.time.totalElapsedSeconds() );
let sec = time % 60;
timeText.setText(sec); // Adding the timer to our text
}
Third, create a variable in the create() to track when the timer ends:
// CREATE()
this.timerOver = false;
// And lets start the timer
this.timer = this.time.delayedCall(60000);
Now lets modify our showTimer() function:
showTimer(){
let maxTime = 60;
let time = Math.floor(this.time.totalElapsedSeconds() );
let timeLeft = maxTime - time; // Check how much time is left
// When the countdown is over
if(timeLeft <= 0){
timeLeft = 0;
this.timerOver = true; // Setting our variable to true
}
let sec = time % 60;
timeText.setText(sec);
}
and last, in our update() function lets check if our variable this.timerOver is true
if (this.timerOver === false){
this.showTimer(); // Calling our function every frame
}
else {
// Whatever you want it to do when timer comes to 0
}

Related

Moment js get seconds remained

I have a timestamp and I need to run my code 30 seconds before timestamp is reached.
Logic
Get current time
Get database timestamp
Run code 30 seconds before database timestamp
sample code
const now = moment(); // current time
const then = moment.unix(chainIds[i].timestamp); // returns: 2023-02-15T18:11:00+07:00
// run something (console log perhaps)
so based on my database timestamp my code has to be run at 18:10:30
actual code
Note: problem with this code is that its running even days after timestamp is passed.
const now = moment();
const then = moment.unix(chainIds[i].timestamp);
const delta = now.diff(then, 'seconds'); // get the seconds difference
var itstime = false;
if(moment.unix(delta).format("ss") <= 30){
itstime = false;
} else {
itstime = true;
}
I know I'm close to the solution but there is a bug that I can't figure it, any idea?
You can add a minimum value condition to make sure it won't run too far after the target. Here I'm giving it a 60 second buffer so that it will still run if the code isn't triggered exactly at 30 seconds, but you can adjust that to your needs.
var itstime = false;
var seconds = moment.unix(delta).format("ss");
if(seconds <= 30 && seconds >= -30){
itstime = false;
} else {
itstime = true;
}
You can make it a lot more simple
const now = moment();
const then = moment.unix(chainIds[i].timestamp);
const delta = now.diff(then, 'seconds');
var itstime = false;
if(delta < 30){
itstime = true;
}
I am not super sure but from what I understood, your difference is getting a second time, now.diff gets the result, see
https://www.geeksforgeeks.org/moment-js-moment-diff-function/
so I donĀ“t think you need
moment.unix(delta).format("ss") <= 30
have you tried something like
const now = moment();
const then = moment().add('minutes', 1);
const delta = now.diff(then, 'seconds'); // get the seconds difference
var itstime = false;
if (delta <= 30) {
itstime = false;
} else {
itstime = true;
}

Variable is undefined outside of the function

Can someone please help me out with this? I'm getting an error 'count is not defined' when executing the below code. I'm trying to create a countdown clock in node.js. If I log the timer variable inside the function it works but outside of the function, it is undefined.
const getOrder = async(request, response) => {
const data = await knex("orderbook_table").select()
const time_data = await knex("orderbook_table").select("timestamp")
console.log(time_data)
var timer;
setInterval(function count() {
for (var i = 0; i < time_data.length; i++) {
//console.log(tableRows[i]);
var entryDate = time_data[i].timestamp;
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
countDown = new Date(entryDate).getTime();
let now = new Date().getTime();
distance = countDown - now;
days = Math.floor(distance / (day));
hours = Math.floor((distance % (day)) / (hour));
minutes = Math.floor((distance % (hour)) / (minute));
seconds = Math.floor((distance % (minute)) / second);
timer = days + "d:" + hours + "h:" + minutes + "m:" + seconds + "s";
//console.log(timer);
}
}, 1000);
var orderStr = data;
count();
console.log(timer);
response.send({ orderStr });
//refresh()
The count function is defined and scoped under the setTimer, you should create the function as callback outside of setInterval then call within that setInterval the created function
You can give a look to this previously answered thread or to the documentation

Web Audio Api Record audio node

Can I somehow record and output to WAV with trackPosition, offset. it works fine when played in browser works fine I just wanna output is to WAV file.
for (var i = 0; i <= loop; ++i) {
node = that.context.createBufferSource();
that.nodes.push(node);
node.buffer = clip.get('buffer');
node.connect(gainNode);
// clip offset and duration times
if (loop > 0) {
if (i === 0) { // first subclip
offset = startTime;
duration = duration - offset;
} else if (i === loop) { // last subclip
offset = 0;
duration = endTime;
} else {
offset = 0;
duration = clip.get('buffer').duration;
}
} else { // loop === 0
offset = startTime;
if (inClipStart)
duration = endTime - startTime;
else
duration = clip.clipLength();
}
// sets the clip's playback start time
node.start(
currentTime + trackPosition - cursor,
offset,
duration
);
trackPosition += duration;
}
Check out https://github.com/mattdiamond/Recorderjs - it let's you record/save the output of your Web Audio app as a .wav, which sound like what you're looking for!

How do I get a web audio api oscillator to sound more than 6 times

Here's the basic code:
In the html I have a button that calls playInterval.
In the script I have the playInterval script that creates and connects four oscillators, then plays two oscillators together for 1s, waits 0.5 seconds and plays the 2nd two oscillators together for 1s.
The problem is, I can't get the interval pairs to play more than 6 times. I've searched and tried everything I can think of.
I know I shouldn't have the AudioContext in the function - that's why it is being called six+ times, but it doesn't work if I take the AudioContext declaration out of the function.
I know there must be a simple solution for this. Any help would be greatly appreciated.
The code below works for the first two levels.
Also, I have had to fake a button choice with the confirm window because I couldn't figure out how to do it with regular buttons.
Note: this is being tested in Chrome.
HTML:
<table border="1" cellspacing ="10" align = "left">
<tr align = "right">
<td>Testing Beat Speed Difference Sensitivity (BSDS) of:</td>
<td align = "left" id ="beatSpeedDifference"></td>
</tr>
<tr align = "right">
<td>Current level (out of 13 levels):</td>
<td align = "left" id ="currentLevel"></td>
</tr>
<tr align = "right">
<td>Consecutive correct answers at this BSDS:</td>
<td align = "left" id ="curConCorrect"></td>
</tr>
</table>
SCRIPT:
// define and assign variables
var faster = [447.5, 447, 446.5, 446, 445.75, 445.63, 445.5, 445.4, 445.3, 445.25, 445.2, 445.15, 445.1];
var slower = [436.67, 436.43, 436.15, 435.83, 435.65, 435.56, 435.45, 435.37, 435.28, 435.24, 435.19, 435.15, 435.1];
var bsd = [0.5, 0.4, 0.3, 0.2, 0.15, 0.13, 0.1, 0.08, 0.06, 0.05, 0.04, 0.03, 0.02];
var passed = [0,0,0,0,0,0,0,0,0,0,0,0,0];
var conCorrect = 0; //concurrent correct answers
var level = 0;
var setup = 0;
var quit = 0;
var playing = 0;
var pitch;
var choice = "empty";
moveableA440 = 440;
document.getElementById("beatSpeedDifference").innerHTML = bsd[level]*100 + "%";
document.getElementById("currentLevel").innerHTML = level + 1;
document.getElementById("curConCorrect").innerHTML = conCorrect;
alert("BEAT SPEED DIFFERENCE SENSIVITY TEST. \n\
You will hear two beat speeds. \n\
The first one will be beating at 5bps. \n\
The second one will be beating faster or slower. \n\
Click OK to accept if the 2nd beat speed is faster.\n\
Click CANCEL if the 2nd beat speed is not faster than the first.");
while (quit === 0) {
//setup chooses a new beat speed if first or previous has been answered
if (setup === 0) {
pitch = getPitch();
if (pitch < 445) { // to elliminate slower BSD sounding flatter
pitch = pitch + 5;
moveableA440 = moveableA440 + 5;
}
setup = 1;
}
//playing plays the two beat speeds once
if (playing === 0) {
playInterval();
playing = 1;
}
//Enter user choice if no choice has been made
if (choice === "empty") {
var r = confirm("OK = Sped Up\n\Cancel = Slowed Down");
if (r === true) {
choice = "faster";
} else {
choice = "slower";
}
}
//Once choice has been made
if (choice !== "empty") { //reset everything for next beat speed
setup = 0; //reset for a new beat speed
playing = 0; //reset to play new beat speed
//Do if correct choice
if (choice === "faster" && pitch > 445 || choice === "slower" && pitch < 445) {
// Stop beats if user selects ok before beats finish
constRef.stop();
moveablePitch.stop();
conCorrect = conCorrect + 1; //Advance and display concurrent correct choices
document.getElementById("curConCorrect").innerHTML = conCorrect;
//Do if three correct answers
if (conCorrect > 2) {
if (passed[level] === 1) { // Do if three correct and has passed this level already
alert("Your Beat Speed Sensitivity is " + bsd[level]*100 + "%");
quit = 1; //stop script
}
// Do if three correct but not passed level yet
conCorrect = 0; //Reset concurrent correct choices
passed[level] = 1;//record level passed
level = level + 1; //advance and display level
document.getElementById("currentLevel").innerHTML = level + 1;
document.getElementById("beatSpeedDifference").innerHTML = bsd[level]*100 + "%";
conCorrect = 0; //reset and display conCorrect
document.getElementById("curConCorrect").innerHTML = conCorrect;
if (level > 12) {// No more levels
alert("Your Beat Speed Sensitivity is " + bsd[12]*100 + "%");
quit = 1;
}
};
} else { //Do if choice is wrong
// Stop beats if user selects ok before beats finish
constRef.stop();
moveablePitch.stop();
level = level - 1;
if (level < 0) {
alert("Your Beat Speed Sensitivity is " + bsd[0]*100 + "%");
quit = 1;
}
document.getElementById("currentLevel").innerHTML = level + 1;
document.getElementById("beatSpeedDifference").innerHTML = bsd[level]*100 + "%";
conCorrect = 0; //reset and display conCorrect
document.getElementById("curConCorrect").innerHTML = conCorrect;
}
choice = "empty" //reset choice
}
}
var r = confirm("Play Again?");
if (r === true) {
window.location.reload()
} else {
alert("Thanks for playing.\n\Please subscribe to howtotunepianos.com");
}
//Functions
function getPitch() {
var coin = Math.random();
if (coin > 0.5) {
return faster[level];
} else {
return slower[level];
}
}
function playInterval() {
context = new webkitAudioContext();
// Create oscillators
constRef = context.createOscillator();
moveablePitch = context.createOscillator();
a440 = context.createOscillator();
a445 = context.createOscillator();
// Connect to output
constRef.connect(context.destination);
moveablePitch.connect(context.destination);
a440.connect(context.destination);
a445.connect(context.destination);
// Define values for oscillators
constRef.type = "sine";
constRef.frequency.value = moveableA440;
moveablePitch.type = "sine";
moveablePitch.frequency.value = pitch;
a440.type = "sine";
a440.frequency.value = 440;
a445.type = "sine";
a445.frequency.value = 445;
// Play
a440.start(0);
a445.start(0);
a440.stop(1);
a445.stop(1);
constRef.start(1);
moveablePitch.start(1);
constRef.stop(2);
moveablePitch.stop(2);
moveableA440 = 440;// reset
}
Ok. I figured it out.
I had to define the oscillator and gain as variables outside the function as well as call the audioContext.
var osc, oscGain
Then the function.
function playIntervals()
I also figured out how to use buttons instead of the clunky confirm window; each button calls it's own function.
I was using a while (quit=o) loop, but that created too many problems. Now the whole thing is done using functions.
Thanks for your help.

Count down timer which don't reset on page refresh

How can I create a count down timer in JSF? I don't want the timer reset when refresh the page.
You can simply use Java Script for it.
Or
You can use RichFaces a4j:poll and poll count data from server where your timer will be running
You can use simply this script
var seconds = readCookie('countdown') || 60;
alert(seconds);
function secondPassed()
{
seconds--;
var minutes = parseInt(seconds / 60);
var remainingSeconds = parseInt(seconds % 60);
if (remainingSeconds < 10) {
remainingSeconds = "0" + parseInt(remainingSeconds);
}
document.getElementById('countdown').innerHTML = minutes + " mins : " + remainingSeconds + " secs";
if (parseInt(seconds) === 0)
{
alert("Time is over");
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Time is Over";
document.forms["myForm"].submit();
document.location.href = "examresult.jsp";
}
}
var countdownTimer = setInterval(function() {
secondPassed();
if (seconds === 0) {
eraseCookie(seconds);
} else {
createCookie(seconds, seconds, 7);
}
}, 1000);

Resources