Peter Chong
Peter Chong

Reputation: 1

Delay a single method for snake game c#

I am using SwinGame to develop a snake game. The method MoveForward handles the movement of the snake. The problem that I have now is that i am unable to delay that particular method so that the snake will be moving at a constant slow speed.

Here are the codes in the Main:

using System;
using SwinGameSDK;
using System.Threading.Tasks;


namespace MyGame
{
    public class GameMain
    {

    public static void Main ()
    {

        //Open the game window
        SwinGame.OpenGraphicsWindow ("GameMain", 800, 600);
        SwinGame.ShowSwinGameSplashScreen ();

        Snake snake = new Snake ();


        //Run the game loop
        while (false == SwinGame.WindowCloseRequested ()) {
            //Fetch the next batch of UI interaction
            SwinGame.ProcessEvents ();

            //Clear the screen and draw the framerate
            SwinGame.ClearScreen (Color.White);

            SwinGame.DrawFramerate (0, 0);

            // Has to go after ClearScreen and NOT before refreshscreen

            snake.Draw ();

            Task.Delay (1000).ContinueWith (t => snake.MoveForward ());


            snake.HandleSnakeInput ();

            //Draw onto the screen
            SwinGame.RefreshScreen (60);


        }
    }
}
}

As you can see from the codes, the game runs on a while loop. I was able to delay the method using "Task.Delay (1000).ContinueWith (t => snake.MoveForward ());" but only on the first loop. When i debug, the snake delays successfully on the first loop but zoom pasts the rest of the loops.

How can i implement the code so that at every loop the method is delayed so that the snake can move at a constant speed?

Thanks in advance.

Upvotes: 0

Views: 379

Answers (1)

EpicSam
EpicSam

Reputation: 185

You're creating a delayed task on every iteration of the loop. You're not actually delaying the loop you're just delaying the execution of the MoveForward method, so the loop still runs at maximum speed. This causes that after the initial delay tasks are executed at the same speed as the loop was run. To wait for a task to complete use await.

If you want the snake to move at a certain interval why not use a timer?

Timer timer = new Timer(1000);
timer.AutoReset = true;
timer.Elapsed += ( sender, e ) => snake.MoveForward();
timer.Start();

Upvotes: 2

Related Questions