TickController.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using gameapi.Library;
  6. using Microsoft.Extensions.Hosting;
  7. public class TickController : IHostedService
  8. {
  9. private Timer timer;
  10. private GameState game;
  11. private DateTime lastTime;
  12. public TickController()
  13. {
  14. this.game = GameState.GetInstance();
  15. lastTime = DateTime.UtcNow;
  16. }
  17. public Task StartAsync(CancellationToken cancellationToken)
  18. {
  19. this.timer = new Timer(o => TickUpdate(), null, TimeSpan.Zero, TimeSpan.FromMilliseconds(100));
  20. return Task.CompletedTask;
  21. }
  22. public async void TickUpdate()
  23. {
  24. List<Task> tasksToComplete = new List<Task>();
  25. var population = this.game.GetAllPlayers();
  26. var currentTime = DateTime.UtcNow;
  27. var delta = 1 + currentTime.Subtract(lastTime).TotalMilliseconds / 1000;
  28. // foreach (var player in population)
  29. // {
  30. // player.Update(delta);
  31. // tasksToComplete.Add(this.game.MessageAllOtherPlayersInSector(player, "move " + player.GetShipData()));
  32. // }
  33. await Task.WhenAll(tasksToComplete);
  34. lastTime = currentTime;
  35. }
  36. public Task StopAsync(CancellationToken cancellationToken)
  37. {
  38. timer.Change(Timeout.Infinite, 0);
  39. return Task.CompletedTask;
  40. }
  41. }