I am programming a very simple game in WPF Canvas - objects are moved in async Task by rendering the ellipse away by 1 pixel every 17 miliseconds - that is how I managed a ellipse to move. I even handled a collision with other objects - it just changes the direction. But the real problem is, that i can't handle Game Over, because the Task cannot be canceled, according to my research on stackoverflow. I can show a MessageBox if the ellipse went out of screen, but after clicking OK it just continues to do this async loop. Is there any way to make it stop?
async Task MoveStart()
{
double rozdiel = car.ActualWidth - snowball.ActualWidth;
Back:
while(crashed == false)
{
while(rightEl > 20)
{
topEl += 1;
rightEl -= 0.5;
leftEl += 0.5;
botEl -= 1;
Canvas.SetTop(snowball, topEl);
Canvas.SetLeft(snowball, leftEl);
if (botEl == botpixel + car.Height && leftpixel <= leftEl + snowball.ActualWidth && rightpixel <= rightEl + snowball.ActualHeight)
{
body++;
textBlock1.Text = "Points: " + body + "\nHealth: " + zdravie;
crashed = true;
goto Crashed;
}
if(botEl == 0)
{
zdravie--;
textBlock1.Text = "Points: " + body + "\nHealth: " + zdravie;
MessageBox.Show("Game over");
}
await Task.Delay(17);
}
}
Crashed:
while(crashed)
{
while (topEl > 50)
{
topEl -= 1;
rightEl -= 0.5;
leftEl += 0.5;
botEl += 1;
Canvas.SetTop(snowball, topEl);
Canvas.SetLeft(snowball, leftEl);
if (topEl == 50)
{
crashed = false;
goto Back;
}
await Task.Delay(17);
}
}
}
those doubles rightEl, leftEl... are margins of canvas I call the Task from simple async void
public async void Ready()
{
await MoveStart();
}
And this Ready() void i call from MainWindow, because MainWindow cannot be async