How do I add my GameOver-Page in Main class when my timcounter shows 0 (Flash Builder)? - flash-builder

public function SeedsAndPots()
{
startpage = new StartPage();
addChild(startpage);
buttonPage = new ButtonPage();
addChild(buttonPage);
buttonPage.addEventListener(MouseEvent.CLICK, GoToGame);
}
public function GoToGame(e:MouseEvent):void
{
removeChild(startpage);
buttonPage.removeEventListener(MouseEvent.CLICK, GoToGame);
removeChild(buttonPage);
gamePage = new GamePage();
addChild(gamePage);
}
// I wanna do a function that says that if time is 0 i should go to my GameOver-Page.
}
}

Create a countdown variable to reflect time in seconds.
Instantiate a timer when you load your game page to countdown every second.
When time has reached 0, apply the logic to end the current level and display your game over page.
// store time remaining in a countdown timer
protected var countdown:uint = 60;
// create a timer, counting down every second
protected var timer:Timer;
// in your go to game, or when you want to start the timer
public function GoToGame(e:MouseEvent):void
{
// ... your go to game function
// start your countdown timer.
timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, timerHandler);
timer.start();
}
protected function timerHandler(event:TimerEvent):void
{
// countdown a second
--countdown;
// update any counter time text field display here...
// if you've reached 0 seconds left
if(countdown == 0)
{
// stop the timer
timer.removeEventListener(TimerEvent.TIMER, timerHandler);
timer.reset();
// remove current gamePage
// addChild to your game over page.
}
}

Related

onSensorChanged function is called in an other app but not in mine (Kotlin)

i want to implement a step counter in my app, so i search how to make that and i found lot of differents implementations.
I notably found an app on GitHub which works. I have tried to implement this code in my app and in an other "test" app but any of them works and i don't no why.
The problem is caused by the onSensorChanged function of my STEP_COUNTER which is not called.
I have search in all the files of the app and i don't found the problem.
If somebody have a solution...
(I'm french so sorry if it's badly written)
the code i use:
private var sensorManager: SensorManager? = null
// Creating a variable which will give the running status
// and initially given the boolean value as false
private var running = false
// Creating a variable which will counts total steps
// and it has been given the value of 0 float
private var totalSteps = 0f
// Creating a variable which counts previous total
// steps and it has also been given the value of 0 float
private var previousTotalSteps = 0f
//in the onCreate
loadData()
resetSteps()
// Adding a context of SENSOR_SERVICE as Sensor Manager
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
override fun onResume() {
super.onResume()
mainHandler.post(pingRunnable)
binding.map.onResume()
running = true
// Returns the number of steps taken by the user since the last reboot while activated
// This sensor requires permission android.permission.ACTIVITY_RECOGNITION.
// So don't forget to add the following permission in AndroidManifest.xml present in manifest folder of the app.
val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
if (stepSensor == null) {
// This will give a toast message to the user if there is no sensor in the device
Toast.makeText(this, "No sensor detected on this device", Toast.LENGTH_SHORT).show()
} else {
// Rate suitable for the user interface
sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI)
}
}
override fun onSensorChanged(event: SensorEvent?) {
// Calling the TextView that we made in activity_main.xml
// by the id given to that TextView
var tvStepsTaken = findViewById<TextView>(R.id.step)
if (running) {
totalSteps = event!!.values[0]
// Current steps are calculated by taking the difference of total steps
// and previous steps
val currentSteps = totalSteps.toInt() - previousTotalSteps.toInt()
// It will show the current steps to the user
tvStepsTaken.text = ("$currentSteps")
}
}
private fun resetSteps() {
var resetButton = findViewById<Button>(R.id.reset)
resetButton.setOnClickListener {
// This will give a toast message if the user want to reset the steps
previousTotalSteps = totalSteps
// When the user will click long tap on the screen,
// the steps will be reset to 0
testFragment?.binding?.step?.text = 0.toString()
// This will save the data
saveData()
true
}
}
private fun saveData() {
// Shared Preferences will allow us to save
// and retrieve data in the form of key,value pair.
// In this function we will save data
val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putFloat("key1", previousTotalSteps)
editor.apply()
}
private fun loadData() {
// In this function we will retrieve data
val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val savedNumber = sharedPreferences.getFloat("key1", 0f)
// Log.d is used for debugging purposes
Log.d("MainActivity", "$savedNumber")
previousTotalSteps = savedNumber
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
// We do not have to write anything in this function for this app
}

FastObjectListView UpdateObject() randomly reorders rows within primary sort

Data is a generic List of domain objects.
I click the "Deploy Status" column header to sort on that column.
I have a button that does nothing more than folv.UpdateObject(someObject) .
Every time I press that button, the Deploy Status column maintains its sort, but all rows within the sorted blocks are randomly reordered, as per screenshot.
I have commented out everything in the form's code beyond loading the data, the test button, and the FastObjectListView's column.Add() and .SetObjects(). There are no event handlers wired up for the FastObjectListView. I am not setting PrimarySort or SecondarySort in code; only by clicking with the mouse.
You should be able to fix this problem by either calling Sort after your button's call to UpdateObject or changing your usage of UpdateObject to RefreshObject
Reproducing the problem (C# Repro for the issue in the API)
This seems to reproduce the problem you are having. Run the code, sort the Other column ascending. Click the update button.
public class MainForm : Form
{
public MainForm()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
//
// MainForm
//
this.ClientSize = new System.Drawing.Size(300, 300);
this.Name = "MainForm";
this.ResumeLayout(false);
this.PerformLayout();
var OLVa = new FastObjectListView();
OLVa.Width = 250;
OLVa.Height = 250;
OLVa.Columns.Add(new OLVColumn("ID", "ID"));
OLVa.Columns.Add(new OLVColumn("Other", "Other"));
var l1 = new lolz(1, 3);
OLVa.AddObject(l1);
OLVa.AddObject(new lolz(2,3));
this.Controls.Add(OLVa);
var btn = new Button()
{
Text = "Update",
Top = OLVa.Bottom
};
btn.Click += (s,e)=>OLVa.UpdateObject(l1);
this.Controls.Add(btn);
}
private class lolz
{
public int ID;
public int Other;
public lolz(int id, int other)
{
ID = id;
Other = other;
}
}
}
Fixing the problem
The following would fix it for the above example:
btn.Click += (s,e)=>
{
OLVa.BeginUpdate();
try
{
OLVa.UpdateObject(l1);
OLVa.Sort();
}
finally
{
OLVa.EndUpdate();
}
};

Delay a task in Blazor without blocking the UI

I created a .razor Notification Component in Blazor, and I'm trying to autoclose the notification div after xx seconds.
So far it works with this Method
private async Task CloseToast(Guid Id, bool autoclose = false)
{
if (autoclose)
{
await Task.Delay(TimeSpan.FromSeconds(5));
}
//Code to remove the notification from list
StateHasChanged();
}
The problem is that for 5 seconds the UI data binding is stuck, any one way or two way binding update to variables (text fields etc..) is on hold until the Notification is closed and the Task resumes.
How can I launch a method or code block after xx seconds without blocking the main UI task in Blazor?
A component with a timer that counts back
<h3>#Time</h3>
#code {
[Parameter] public int Time { get; set; } = 5;
public async void StartTimerAsync()
{
while (Time > 0)
{
Time--;
StateHasChanged();
await Task.Delay(1000);
}
}
protected override void OnInitialized()
=> StartTimerAsync();
}
Usage:
<Component />
<Component Time="7"/>
Tested on client side Blazor. Should behave the same way in server-side Blazor.
Hope this helps
You can use .NET Timer from System.Timers as well and set the Delay in milisec. When it elapsed event will triggered and you can put your logic into the event handler. If you don't want to bother with all the config and Disposing of Timer you can use this Nuget package. It is a very convenient wrapper for the Timer with many extra features see docs.
<AdvancedTimer Occurring="Times.Once()" IntervalInMilisec="#_closeInMs" AutoStart="true" OnIntervalElapsed="#(e => { IsVisible = false; })" />
#code {
private int _closeInMs = 5000;
...
}
The official Blazor Server EFCore sample project includes this as an example, in TextFilter.razor. The essence of the code is:
Timer? timer;
// ... code in a function to start the timer
timer?.Dispose();
timer = new(DebounceMs);
timer.Elapsed += NotifyTimerElapsed;
timer.Enabled = true;
private async void NotifyTimerElapsed(object? sender, ElapsedEventArgs e)
{
timer?.Dispose();
timer = null;
// SomeMethodAsync will need to call StateHasChanged()
InvokeAsync(() => SomeMethodAsync());
}
and a Dispose() function for the page to dispose any timer in progress when user navigates away.

Dynamic time display crash on orientation

I have a layout that will display a TextView which is used to display a ticking time.I followed the codes from this link
How to Display current time that changes dynamically for every second in android
but I get an error of
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
I had the same problem here but I fixed it
Intent extras null on configuration change
Here are the Java codes
void clockTicking(){
final CountDownTimer newtimer = new CountDownTimer(1000000000, 1000) {
public void onTick(long millisUntilFinished) {
timeDisplay = (TextView)findViewById(R.id.txtTime);
Calendar c = Calendar.getInstance();
timeDisplay.setText(c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND)+" PM");
}
public void onFinish() {
}
};
newtimer.start();
In your code timeDisplay object is null.
Make sure your textview id is correct. Double check this line timeDisplay = (TextView)findViewById(R.id.txtTime);
I think your id txtTime is incorrect.
Hope it will helpful.
Okay so I finally fixed it,the only reason why it crashed was because during orientation the layout I used has no TextView which Mitesh Vanaliya stated was correct.So I fixed it by turning it off upon orientation using this code thanks to Ayyappan from
How to Display current time that changes dynamically for every second in android
Turning off the clock
void clockUnTicking(){
CountDownTimer newtimer = new CountDownTimer(1000000000, 1000) {
public void onTick(long millisUntilFinished) {
timeDisplay = (TextView)findViewById(R.id.txtTime);
Calendar c = Calendar.getInstance();
timeDisplay.setText(c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND));
}
public void onFinish() {
}
};
newtimer.cancel();
}
to turn it on just replace newtimer.cancel(); with newtimer.start()

Kendo UI Scheduler individual business hours

I'm trying to define individual business hours for the kendo scheduler. The kendo scheduler only uses a single start/end time for each work day. I want to define start/end times for each day specifically (ie. monday has different times than tuesday).
Someone recently asked this question on
http://www.telerik.com/forums/set-business-hours-for-individual-days
I'm wondering if someone has extended a view to add similar functionality.
I don't have access to the non-minified version of the views (kendo.ui.DayView, kendo.ui.WeekView). Based on the kendo.scheduler.dayview.min.js file, I'd assume I'd have to extend the DayView, and override the _content function, however I just can't copy the minified version of the function into the extending view.
I'm currently using jQuery to loop through the timeslots to add a css class for this on the data-bound event, however, the performance can be pretty bad if you're on the weekly view and have the major tick set to 5.
The code to loop through the timeslots is similar to
http://www.telerik.com/forums/color-code-resource-unavailable-days-hours
dataBound: function (e) {
var scheduler = this;
var view = scheduler.view();
view.table.find("td[role=gridcell]").each(function () {
var element = $(this);
var slot = scheduler.slotByElement(element);
//your custom logic based on the slot object
if (true) {
element.addClass("customClass");
}
})
}
To define start/end times for each day specifically, use the "schedulerInstance.options" property in "Navigation" method of scheduler.e.g.
navigate: function (e) {
var schedulerInstance = $("#schedulerInterface").data('kendoScheduler');
var options = schedulerInstance.options;
switch (new Date().getDay())
{
case 0:
options.startTime = // Your start time;
options.endTime = //Your end time;
break;
case 1:
options.startTime = // Your start time;
options.endTime = //Your end time;
break;
case 2:
options.startTime = // Your start time;
options.endTime = //Your end time;
break;
case 3:
options.startTime = // Your start time;
options.endTime = //Your end time;
break;
case 4:
options.startTime = // Your start time;
options.endTime = //Your end time;
break;
case 5:
options.startTime = // Your start time;
options.endTime = //Your end time;
break;
case 6:
options.startTime = // Your start time;
options.endTime = //Your end time;
break;
}
}
Hope it helps.