I am creating a game in visual studio using c sharp and want to add a pop up message saying 'game Over' once the timer reaches 0. Currently the countdown timer goes to negative seconds and the game keeps going. Currently attempt is below and any help is apricated.
public MainPage()
{
InitializeComponent();
_random = new Random(); // r is my random number generator
_countDown = 30;
SetUpMyTimers();// method for my timer
endGame();
}
private void endGame()
{
throw new NotImplementedException();
}
private void SetUpMyTimers() // calling my method
{
// start a timer to run a method every 1000ms
// that method is "TimerFunctions" that runs on the UI thread
Device.StartTimer(TimeSpan.FromMilliseconds(1000), () =>
{
Device.BeginInvokeOnMainThread(() =>
{ TimerFunctions(); });
return true;
});
}
private void TimerFunctions()
{
// change the countdown.
_countDown--;
LblCountdown.Text = _countDown.ToString();
}
CodePudding user response:
The countdown is over to call the function.Use winform timer control to implement countdown function
public partial class Form1 : Form
{
TimeSpan Span = new TimeSpan(0, 0, 10);
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
Span = Span.Subtract(new TimeSpan(0, 0, 1));
label1.Text = Span.Hours.ToString() ":" Span.Minutes.ToString() ":" Span.Seconds.ToString();//时间格式0:0:10
if (Span.TotalSeconds < 0.0)//when the countdown is over
{
timer1.Enabled = false;
MessageBox.Show("game over");
}
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Interval = 1000;//Set every interval to 1 second
timer1.Enabled = true;
MessageBox.Show("End the game after 10s");
}
}
Test timer:
CodePudding user response:
You could try the following code.
<Grid>
<TextBlock Name="tbTime" />
</Grid>
Codebehind:
DispatcherTimer _timer;
TimeSpan _time;
public MainWindow()
{
InitializeComponent();
_time = TimeSpan.FromSeconds(10);
_timer = new DispatcherTimer(new TimeSpan(0, 0, 1), DispatcherPriority.Normal, delegate
{
tbTime.Text = _time.ToString("c");
if (_time == TimeSpan.Zero)
{
_timer.Stop();
MessageBox.Show("GameOver");
}
_time = _time.Add(TimeSpan.FromSeconds(-1));
}, Application.Current.Dispatcher);
_timer.Start();
}
The result: