求助:C#实现计时器归零时弹出Game Over提示框的方法
问题描述
我正在Visual Studio中使用C#开发一款游戏,想要在计时器归零时弹出显示“Game Over”的提示框。目前倒计时会变为负数且游戏仍继续运行,以下是我的尝试代码:
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(); }
解决方案
要解决倒计时变负数、游戏不停止的问题,只需在计时器逻辑中添加结束判断,停止计时器并触发提示,具体修改如下:
修改
TimerFunctions,添加结束判断
在每次递减倒计时前先检查是否已归零,避免继续减少:private void TimerFunctions() { if (_countDown <= 0) { endGame(); return; } _countDown--; LblCountdown.Text = _countDown.ToString(); }实现
endGame方法,停止计时器并弹出提示
先添加一个变量控制计时器运行状态,再在endGame中停止计时器并显示提示:private bool _isTimerRunning = true; private void SetUpMyTimers() { Device.StartTimer(TimeSpan.FromMilliseconds(1000), () => { Device.BeginInvokeOnMainThread(() => { TimerFunctions(); }); // 通过返回值控制计时器是否继续执行 return _isTimerRunning; }); } private void endGame() { // 停止计时器 _isTimerRunning = false; // 将倒计时显示固定为0 LblCountdown.Text = "0"; // 弹出Game Over提示框 DisplayAlert("游戏结束", "Game Over", "确定"); }修正
MainPage构造函数
移除初始化时错误调用的endGame(),这个方法应该在倒计时结束时自动触发:public MainPage() { InitializeComponent(); _random = new Random(); _countDown = 30; SetUpMyTimers(); // 移除此处的endGame()调用 }
修改完成后,倒计时归零时会自动停止,不再出现负数,同时弹出“Game Over”提示框。
内容的提问来源于stack exchange,提问作者Timmy Forde
相关产品推荐
相关产品推荐

