Adding autoplay to games

The main feature I added this week to Sac Sac Mate is the ability to autoplay a game, so that the user doesn't have to click (or tap) the "make next move" potentially a hundred times to see a game all the way to the end.

The loop

Instead of using a setTimeout to recursively call the method to make the next move, I opted for an ember-concurrency task (that uses a generator function). I thought the resulting code was going to be readable and indeed, that's all I needed to write:

// (...)
import { task } from 'ember-concurrency-decorators';
import { timeout } from 'ember-concurrency';

export default class GamePlayService extends Service {
  // (...)
  @task
  * autoplay() {
    if (this.atLastMove) {
      this.isAutoplaying = false;
      return;
    }
    this.isAutoplaying = true;
    this.makeNextMove();
    yield timeout(500);
    this.autoplay.perform();
  }
  // (...)
}

To be able to use the @task decorator, I installed ember-concurrency-decorators.

I then just call {{on "click" (perform this.gamePlay.autoplay)}} from the template.

As I often do, I recorded the development process:

You can check the feature out on the deployed site. I recommend this thrilling game that has a queen sacrifice.