[SOLVED] Trying to display a timer clock

Started by Funkpanzer, Tue 08/12/2015 23:30:16

Previous topic - Next topic

Funkpanzer

I've looked around the manual and forum posts and couldn't find anything on this.

I'm trying to have a clock that shows minutes and seconds (0:00) but am stumped as to how to get the seconds to only display up to 59 at a time.

Currently the clock looks like this:



Here is my code:
Code: ags

function repeatedly_execute() {
  if (countdown == 1) { //this is where the end of round code will go
    }
  else if (countdown >1) {
    countdown--;
    if (countdown > 400) { //countdown is more than 10sec
    lblCTD.Text=String.Format
    ("%d:%d", FloatToInt(IntToFloat(countdown/2400)), FloatToInt(IntToFloat(countdown/40)));
    }
    else if (countdown < 400) { //countdown falls below 10sec, adds a '0' before the last digit
      lblCTD.Text=String.Format
      ("%d:0%d", FloatToInt(IntToFloat(countdown/2400)), FloatToInt(IntToFloat(countdown/40)));
    }
  }
}

Snarky

A couple of things:

First, to do zero-padding of the numbers so that they always display with (at least) two digits, you can use "%02d". That way you don't need the separate cases.

Second, the way to make a number "loop around" is to take the remainder of division by the max number plus one, an operation known as modulo or mod. In this case we want the total number of seconds mod 60. AGS (like many other programming languages), uses the % sign for the modulo operation.

Oh, and third, the FloatToInt(), IntToFloat() calls are entirely unnecessary here. In fact, you're just doing an integer division, converting the RESULT (which is an int) to a float, and then immediately converting it back to an int. If you wanted to do the division as a floating-point operation (so that you actually calculate the fractional value), you'd have to convert countdown to a float, and then divide by another float. However, you don't actually want this, you specifically want the result of integer division, rounded down (so, e.g. when you wonder how many minutes are in 112 seconds, you just want 1, not 1.866).

So your code can be simplified to:

Code: ags
function repeatedly_execute() {
  if (countdown == 1) {
    // this is where the end-of-round code will go
  }
  else if (countdown >1) {
    countdown--;
    int secs = countdown / 40; // or GetGameSpeed() if you want to be on the safe side
    lblCTD.Text = String.Format("%02d:%02d", secs/60, secs%60);
  }
}

Funkpanzer

#2
Thank you so much for your help and the explanation, that works perfectly! :-D

SMF spam blocked by CleanTalk