JS for await...of equivalent in C#

102 Views Asked by At

My goal is to recreate a small slot machine, written in JavaScript, in C#. I am doing this to learn C#. I found the project on Github (user: asiryk, repository: slot-game).

Except for the file ReelsContainer.ts, I have already managed to translate the project. This file is currently proving to be my main problem. Specifically, it's about these two functions, for which I don't know how to get the same result in C#:

async spin() {
    // Overall time of spinning = shiftingDelay * this.reels.length
    //
    const shiftingDelay = 500;
    const start = Date.now();
    const reelsToSpin = [...this.reels];
    
    for await (let value of this.infiniteSpinning(reelsToSpin)) {
        const shiftingWaitTime = (this.reels.length - reelsToSpin.length + 1) * shiftingDelay;
        
        if (Date.now() >= start + shiftingWaitTime) {
            reelsToSpin.shift();
        }

        if (!reelsToSpin.length) break;
    }

    // reel.sprites[2] - Middle visible symbol of the reel
    //
    return this.checkForWin(this.reels.map(reel => reel.sprites[2]));
}

private async* infiniteSpinning(reelsToSpin: Array<Reel>) {
    while (true) {
        const spinningPromises = reelsToSpin.map(reel => reel.spinOneTime());
        await Promise.all(spinningPromises);
        this.blessRNG();
        yield;
    }
}

What I have tried so far is the following structure:

public async Task<bool> Spin()
{
    const int shiftingDelay = 500;
    DateTime start = DateTime.Now;
    List<Reel> reelsToSpin = new List<Reel>(reels);

    /* INCOMPLETE infiniteSpinning */

    return this.CheckForWin(this.reels.Select(reel => reel.sprites[2]));
}

private async Task infiniteSpinning(List<Reel> reelsToSpin)
{
    var spinningPromises = reelsToSpin.Select(reel => reel.SpinOneTime());
    await Task.WhenAll(spinningPromises);
    this.BlessRNG();
}

But now I'm stuck and can't get any further because I don't know how to implement the for await...of and the private async* method in C#.

How do I implement the methods Spin() and InfiniteSpinning() in C#?

[Edit] The following information about my development environment: Visual Studio 2013 (C# 5.0), .NET Framework 4.8, WPF

1

There are 1 best solutions below

0
On

I think your after await foreach.

From Iterating with Async Enumerables in C# 8:

await foreach (int item in RangeAsync(10, 3))
  Console.Write(item + " "); // Prints 10 11 12

with

static async IAsyncEnumerable<int> RangeAsync(int start, int count)
{
 for (int i = 0; i < count; i++)
 {
   await Task.Delay(i);
   yield return start + i;
 }
}