It's my timer that counts time. Is it possible when the game gets to the new scene automatically insert the previous scene's best time? what code should i insert in the new scene to expose the best time?
/**
* TIMER (JAVASCRIPT)
* Copyright (c) gameDev7
*
* This is an HH:MM:SS count down/up timer
* Includes functions for pausing timer
*
* TIP: Search where to place your functions
* 1. Press Cntrl/Cmd + F
* 2a. Type UP for count up timer (CAPS)
* 2b. Type DOWN for count down timer (CAPS)
* 3. Check Match whole word only
* 4. Check Match case
* 5. Click Find Next
*/
/// INPUT VARIABLES
var timerStyle:GUIStyle;
var countdown:boolean = false; //switches between countdown and countup
var hours:float = 0f;
var minutes:float = 1f;
var seconds:float = 30f;
var printDebug:boolean = false; //for debugging purposes
/// CALCULATION VARIABLES
private var pauseTimer:boolean = false;
private var timer:float = 0f;
private var hrs:float = 0f;
private var min:float = 0f;
private var sec:float = 0f;
/// DISPLAY VARIABLES
private var strHours:String = "00";
private var strMinutes:String = "00";
private var strSeconds:String = "00";
private var strHrs:String = "00";
private var strMin:String = "00";
private var strSec:String = "00";
private var message:String = "Timing...";
// Use this for initialization
//end start
// Update is called once per frame
function Update () {
if(Input.GetKeyUp("j")) {
if(pauseTimer) {
pauseTimer = false;
} else {
pauseTimer = true;
}//end if
if(printDebug) print("TimerJS - Paused: " + pauseTimer);
}//end if
if(pauseTimer) {
message = "Timer paused";
Time.timeScale = 0;
} else {
//message = "Timer resumed";
Time.timeScale = 1;
}//end if
if(seconds > 59) {
message = "Seconds must be less than 59!";
return;
} else if (minutes > 59) {
message = "Minutes must be less than 59!";
} else {
FindTimer();
}//end if
}//end update
/* TIMER FUNCTIONS */
//Checks which Timer has been initiated
function FindTimer() {
if(!countdown) {
CountUp();
} else
{
CountDown();
}//end if
}//end FindTimer
//Timer starts at 00:00:00 and counts up until reaches Time limit
function CountUp() {
timer += Time.deltaTime;
if(timer >= 1f) {
sec++;
timer = 0f;
}//end if
if(sec >= 60) {
min++;
sec = 0f;
}//end if
if(min >= 60) {
hrs++;
min = 0f;
}//end if
if(sec >= seconds && min >= minutes && hrs >= hours) {
sec = seconds;
min = minutes;
hrs = hours;
message = "Time limit reached!";
if(printDebug) print("TimerJS - Out of time!");
///----- TODO: UP -----\\\
}//end if
}//end countUp
//Timer starts at specified time and counts down until it reaches 00:00:00
function CountDown() {
timer -= Time.deltaTime;
if(timer <= -1f) {
sec--;
timer = 0f;
}//end if
if(hrs <= 0f) {
hrs = 0f;
}//end if
if(min <= 0f) {
hrs--;
min = 59f;
}//end if
if(sec <= 0f) {
min--;
sec = 59f;
}//end if
if(sec <= 0 && min <= 0 && hrs <= 0) {
sec = 0;
min = 0;
hrs = 0;
message = "Time's Up!";
if(printDebug) print("TimerJS - Out of time!");
///----- TODO: DOWN -----\\\
}//end if
}//end countDown
function FormatTimer () {
if(sec < 10) {
strSec = "0" + sec.ToString();
} else {
strSec = sec.ToString();
}//end if
if(min < 10) {
strMin = "0" + min.ToString();
} else {
strMin = min.ToString();
}//end if
if(hrs < 10) {
strHrs = "0" + hrs.ToString();
} else {
strHrs = hrs.ToString();
}//end if
if(seconds < 10) {
strSeconds = "0" + seconds.ToString();
} else {
strSeconds = seconds.ToString();
}//end if
if(minutes < 10) {
strMinutes = "0" + minutes.ToString();
} else {
strMinutes = minutes.ToString();
}//end if
if(hours < 10) {
strHours = "0" + hours.ToString();
} else {
strHours = hours.ToString();
}//end if
}//end formatTimer
/* DISPLAY TIMER */
function OnGUI () {
FormatTimer();
if(!countdown) {
GUI.Label(new Rect(Screen.width/4-155,Screen.height/3-10,200,90), strHrs + ":" + strMin + ":" + strSec + "", timerStyle);
} //end if
}//end onGui
/* GETTERS & SETTERS */
public function GetPaused() { return pauseTimer; }
public function SetPaused(val:boolean) { pauseTimer = val; }
public function GetSec() { return sec; }
public function GetMin() { return min; }
public function GetHrs() { return hrs; }
public function GetMessage() { return message; }
public function SetMessage(val:String) { message = val; }
Save your best time as a static variable in your Timer script (or whatever you have named it): static var bestTime = 01:32:12.
You can then access it globally from any other script (such as one used on a different scene) as: Timer.bestTime.
You could save the time as a static variable which will make it available across scenes. Alternatively you could use DontDestroyOnLoad(gameObject) to preserve the game object that contains that script which means the game object and all the values of the components attached to it will retain their values. Be careful of using the second approach because if you go back to the scene that originally had the object, you will have duplicates. I believe the best solution in this case would be to just use a static variable and use it across all scenes.
Related
I have a problem: I have tested the single pong game, and then I found an error when the game live reached 0 and moved to a Game Over screen for a single pong game.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at BlowfishPong_fla::MainTimeline/loop()
Can you check this code?
Here is my code for the single pong game:
import flash.events.MouseEvent;
import flash.utils.Dictionary;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundMixer;
import flash.display.MovieClip;
import flash.text.TextField;
import flash.net.SharedObject;
import flash.events.Event;
stop();
var sound: Sound
var sound_channel: SoundChannel;
var gameMiss: Miss = new Miss();
var gameBounce: BounceWall = new BounceWall();
var gameHit: Hit = new Hit();
var ballSpeedX: int = -3;
var ballSpeedY: int = -2;
var gameScore = 0;
var gameLives = 3;
var plzStop: Boolean = false;
helpContent.visible = false;
reset_btn.addEventListener(MouseEvent.CLICK, scoreReset);
function scoreReset(event: MouseEvent): void {
gameScore = 0;
gameLives = 3;
updateTextFields();
}
pause_btn.addEventListener(MouseEvent.CLICK, goPause);
function goPause(event: MouseEvent): void {
if (plzStop == true) {
plzStop = false;
} else {
plzStop = true;
}
}
home_btn.addEventListener(MouseEvent.CLICK, goHome);
function goHome(event: MouseEvent): void {
plzStop = true;
gotoAndStop("startScreen");
}
help_btn2.addEventListener(MouseEvent.CLICK, goHelp2);
function goHelp2(event: MouseEvent): void {
if (plzStop == true) {
helpContent.visible = false;
plzStop = false;
} else {
helpContent.visible = true;
plzStop = true;
}
}
function init(): void {
score_txt.text = gameScore;
lives_txt.text = gameLives;
stage.addEventListener(Event.ENTER_FRAME, loop);
}
function updateTextFields(): void {
score_txt.text = gameScore;
lives_txt.text = gameLives;
}
function calculateBallAngle(paddleY: Number, ballY: Number): Number {
var ySpeed: Number = 5 * ((ballY - paddleY) / 25);
return ySpeed;
}
function loop(e: Event): void {
if (plzStop == false) {
characterPaddle.y = mouseY;
blowfishPong.x += ballSpeedX;
blowfishPong.y += ballSpeedY;
if (blowfishPong.x <= blowfishPong.width / 2) {
blowfishPong.x = blowfishPong.width / 2;
ballSpeedX *= -1;
gameBounce.play();
}
else if (blowfishPong.x >= stage.stageWidth - blowfishPong.width / 2) {
blowfishPong.x = stage.stageWidth - blowfishPong.width / 2;
ballSpeedX *= -1;
gameMiss.play();
gameLives--;
lives_txt.text = gameLives;
if(gameLives == 0){
stage.removeEventListener(Event.ENTER_FRAME,loop);
gotoAndStop("gameover_Single");
SoundMixer.stopAll();
}
}
if (blowfishPong.y <= blowfishPong.height / 2) {
blowfishPong.y = blowfishPong.height / 2;
ballSpeedY *= -1;
gameBounce.play();
}
else if (blowfishPong.y >= stage.stageHeight - blowfishPong.height / 2) {
blowfishPong.y = stage.stageHeight - blowfishPong.height / 2;
ballSpeedY *= -1;
gameBounce.play();
}
if (characterPaddle.y - characterPaddle.height / 3 < 0) {
characterPaddle.y = characterPaddle.height / 3;
}
else if (characterPaddle.y + characterPaddle.height / 3 > stage.stageHeight) {
characterPaddle.y = stage.stageHeight - characterPaddle.height / 3;
}
if (characterPaddle.hitTestObject(blowfishPong) == true) {
if (ballSpeedX > 0) {
ballSpeedX *= -1;
ballSpeedY = calculateBallAngle(characterPaddle.y, blowfishPong.y);
gameScore++;
updateTextFields();
gameHit.play();
}
}
}
}
init();
Then, for the PlayerSkin function, there are some errors to fix:
character.addEventListener(Event.ENTER_FRAME, playerSkin);
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at BlowfishPong_fla::MainTimeline/goHome3()[BlowfishPong_fla.MainTimeline::frame28:55]
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at BlowfishPong_fla::MainTimeline/playerSkin()[BlowfishPong_fla.MainTimeline::frame28:268]
Need help.
so i was making a game with my friend for college using visual studio 2017 and there's something weird about the program.
we're set it so that when the life is zero, a message box would show up and chose whether to retry the game or not, but when we tried the game, the message box show's up at least at 20 - 30 second after playing the game and the timer for the game is still going even though we add "timergame.enable = false;".
where's seems to be the problem?
private void timerGame_Tick(object sender, EventArgs e)
{
for (int i = 0; i < listOfSardine.Count; i++)
{
listOfSardine[i].Top += (int)listOfSardine[i].Tag;
if (listOfSardine[i].Bounds.IntersectsWith(pictureBoxGrass.Bounds))
{
userLives--;
labelLives.Text = "Lives: " + userLives;
listOfSardine[i].Dispose();
listOfSardine.RemoveAt(i);
if (userLives == 0)
{
highScore = userScore;
timerBonusSpeed.Enabled = false;
timerGame.Enabled = false;
timerHealth.Enabled = false;
timerMatatabi.Enabled = false;
timerSardine.Enabled = false;
DialogResult dialogResultLose = MessageBox.Show
("Sorry.... you have lost, continue?", "Continue??", MessageBoxButtons.YesNo);
if (dialogResultLose == DialogResult.Yes)
{
for (int j = 0; j < listOfHealth.Count; j++)
{
listOfHealth[j].Dispose();
}
listOfHealth.Clear();
for (int q = 0; q < listOfSardine.Count; q++)
{
listOfSardine[q].Dispose();
}
listOfSardine.Clear();
for (int k = 0; k < listOfMatatabi.Count; k++)
{
listOfMatatabi[k].Dispose();
}
listOfMatatabi.Clear();
userLives = USER_LIVES;
userScore = USER_SCORE;
timerBonusSpeed.Enabled = true;
timerGame.Enabled = true;
timerHealth.Enabled = true;
timerMatatabi.Enabled = true;
timerSardine.Enabled = true;
}
else
{
this.Visible = false;
FormMainMenu formMainMenu = new FormMainMenu();
formMainMenu.Owner = this;
formMainMenu.ShowDialog();
}
}
}
else if (listOfSardine[i].Bounds.IntersectsWith(pictureBoxMainCharacter.Bounds))
{
listOfSardine[i].Dispose();
listOfSardine.RemoveAt(i);
userScore += 1;
labelScore.Text = "Score: " + userScore;
if (userScore % 100 == 0)
{
listOfSardine[i].Top += (int)listOfSardine[i].Tag * 4;
}
if(userScore == 1000)
{
timerBonusSpeed.Enabled = false;
timerGame.Enabled = false;
timerHealth.Enabled = false;
timerMatatabi.Enabled = false;
timerSardine.Enabled = false;
highScore = userScore;
}
}
else
{
listOfSardine[i].Refresh();
}
}
for (int i = 0; i < listOfHealth.Count; i++)
{
listOfHealth[i].Top += (int)listOfHealth[i].Tag;
if (listOfHealth[i].Bounds.IntersectsWith(pictureBoxGrass.Bounds))
{
listOfHealth[i].Dispose();
listOfHealth.RemoveAt(i);
}
else if (listOfHealth[i].Bounds.IntersectsWith(pictureBoxMainCharacter.Bounds))
{
listOfHealth[i].Dispose();
listOfHealth.RemoveAt(i);
userLives++;
labelLives.Text = "Lives: " + userLives;
}
else
{
listOfHealth[i].Refresh();
}
Not enough clear what you did. However, I think you have a counter for life, and which are decreasing as per your game's event. On timer event just check life counter is equal or less than Zero or not. If so, just stop timer, give user confirmation for retry. If user want to retry, then reset life counter and start timer.
Ahh already found the answer
our problem is about the ownership of the form, we just incorrectly insert the ownership for each form
thanks for the people who have answered my question earlier
I have this AS3 script (it works fine), I just want to make the loop to pause for seconds each time then it can continue looping. Like if I like it to stop for Milliseconds.Thanks
var myText:String;
var counter:int = 0;
var format : TextFormat = new TextFormat();
format.size = 16;
format.font = "Verdana";
format.bold = true;
format.color = 0x000000;
var textField : TextField = new TextField();
textField.width = 200;
textField.height = 50;
textField.selectable = false;
textField.wordWrap = true;
textField.defaultTextFormat = format;
textField.x = textField.y =0;
addChild(textField);
var textLoader:URLLoader = new URLLoader(new URLRequest("text.txt"));
textLoader.addEventListener(Event.COMPLETE, function(e:Event){initText(e.target.data);});
function initText(string:String):void{
myText = string;
addEventListener(Event.ENTER_FRAME, writeText);
}
function writeText(e:Event):void{
if (counter <= myText.length){
textField.text = myText.substr(0,counter);
counter++;
/*What I can put here to make it pause for a while*/
}
else{
removeEventListener(Event.ENTER_FRAME,writeText);
}
}
Your code is fine, you need to tweak it a little bit.
function initText(string:String):void
{
myText = string;
addEventListener(Event.ENTER_FRAME, writeText);
}
// Variable to keep the next print time in milliseconds.
var nextPrint:int;
function writeText(e:Event):void
{
// Function getTimer() returns time in milliseconds since app start.
// Skip this frame if time is not right.
if (getTimer() < nextPrint) return;
// Variable nextPrint is initially 0 so the first char will print immediately.
if (counter <= myText.length)
{
textField.text = myText.substr(0, counter);
counter++;
/*What I can put here to make it pause for a while*/
// Print next character in ~100 ms.
nextPrint = getTimer() + 100;
}
else
{
removeEventListener(Event.ENTER_FRAME, writeText);
}
}
onSelfEvent (load)
{
var start : String = "02:00";
result.text = start;
_global.min = int(start.slice(0,2));
_global.sec = int(start.slice(3,5));
var timerInterval : Number;
var not_active : Boolean = true;
var keyListener : Object = new Object();
keyListener.onKeyDown = function() //on key down
{
if (not_active) //check if countdown not_active onkeypress , if true = start/resume
{
if (Key.isDown(32)) //keypress
{
//trace("active");
timerInterval = setInterval(counter, 1000);
not_active = false;
}
}
else //pause
{
//trace("pause");
clearInterval(timerInterval);
not_active = true;
}
}
Key.addListener(keyListener); //register the listener with the Key object so that it can receive notification from the key down and key up events.
}
function counter() : void
{
//trace("min = " add min);
//trace("sec = " add sec);
//trace("typeof min = " add typeof min add " typeof sec = " add typeof sec)
if(sec == 0)
{
if(min == 0) //if sec = 0 and min = 0
{
clearInterval(timerInterval); //clearintervam
}
else //if sec = 0 and min != 0
{
sec = 59;
min --; // min = min - 1
}
}
else
{
sec --; //sec = sec - 1
}
result.text = zero_check(min) add ":" add zero_check(sec); //less than 10 add a 0 to number
}
function zero_check(check : int)
{
if(check < 10)
{
check = "0" add check; //add a 0
}
return(check);
}
onSelfEvent (load){
clock=Math.floor(getTimer()/100)/10;
/* if (seconds==0) {
seconds=600;
minute--
}
if (x!=clock) {
seconds--
}*/
x=clock;
if (var ==00 && var ==59) {
result.textColor = 0xFF9900;
}}
I want to my countdown timer to turn orange when it reaches 59 sec and red when reaches 30sec but it doesnt work and I dont now why,Im working on Swish I dont know what language it uses for scripting .
I need the timer to be able to reset when the game ends. The Timer is set to 1:05 to count down from that value but the timer when it is supposed to reset when it runs out, it does not it just stays at 0:00. Here is the code below:
package {
import flash.display.MovieClip;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.events.ThrottleEvent;
public class MainTimer extends MovieClip {
private var currentMin:int;
private var currentSec:int;
private var oneSecondTimer:Timer = new Timer(1000,1);
public var timerHasStopped:Boolean = false;
public function MainTimer() {
// constructor code
trace("the main timer is here");
currentMin = 1;
currentSec = 5;
minBox.text = String(currentMin);
if(currentSec < 10) {
secBox.text = "0" + String(currentSec);
}else{
secBox.text = String(currentSec);
}
oneSecondTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
oneSecondTimer.start();
}
private function onTimerComplete(event:TimerEvent):void{
currentSec = currentSec - 1;
if (currentSec < 0){
currentSec = 59;
currentMin = currentMin - 1;
}
if(currentMin < 0) {
currentMin = 0;
currentSec = 0;
}else{
oneSecondTimer.start();
}
minBox.text = String(currentMin);
secBox.text = String(currentSec);
if(currentSec < 10){
secBox.text = "0" + String(currentSec);
}
}
public function resetTimer():void{
//update our display
currentMin = 1;
currentSec = 5;
minBox.text = String(currentMin);
secBox.text = String(currentSec);
//Adjust display for seconds less than 10
if (currentSec < 10){
secBox.text = "0" + String(currentSec);
}//end if
timerHasStopped = false;
oneSecondTimer.start();
}//end function
}
}
I have amended your code. Your code wasn't calling the resetTimer function. Also, I've listen for TIMER instead of TIMER_COMPLETE. When the timer reaches 0, its calls the resetTimer.
package {
import flash.display.MovieClip;
import flash.events.TimerEvent;
import flash.utils.Timer;
//import flash.events.ThrottleEvent;
public class MainTimer extends MovieClip {
private var currentMin:int;
private var currentSec:int;
private var oneSecondTimer:Timer = new Timer(1000);
public var timerHasStopped:Boolean = false;
public function MainTimer() {
// constructor code
trace("the main timer is here");
currentMin = 1;
currentSec = 5;
minBox.text = String(currentMin);
if(currentSec < 10) {
secBox.text = "0" + String(currentSec);
}else{
secBox.text = String(currentSec);
}
oneSecondTimer.addEventListener(TimerEvent.TIMER, onTimerComplete);
oneSecondTimer.start();
}
private function onTimerComplete(event:TimerEvent):void{
trace("TIMER HAS STARTED. COUNTING DOWN.......");
currentSec = currentSec - 1;
if (currentSec < 0){
currentSec = 59;
currentMin = currentMin - 1;
}
if(currentMin < 0) {
currentMin = 0;
currentSec = 0;
resetTimer();
}
minBox.text = String(currentMin);
secBox.text = String(currentSec);
if(currentSec < 10){
secBox.text = "0" + String(currentSec);
}
}
public function resetTimer():void{
oneSecondTimer.removeEventListener(TimerEvent.TIMER, onTimerComplete);
trace("TIMER HAS FINISHED. RESETTING.......");
//update our display
currentMin = 1;
currentSec = 5;
minBox.text = String(currentMin);
secBox.text = String(currentSec);
//Adjust display for seconds less than 10
if (currentSec < 10){
secBox.text = "0" + String(currentSec);
}//end if
timerHasStopped = false;
//if the timer needs to start again, add the following line of code.
oneSecondTimer.addEventListener(TimerEvent.TIMER, onTimerComplete);
}//end function
}
}
Hope this helps.