summaryrefslogtreecommitdiff
path: root/Impostor-dev/src/Impostor.Server/Net/Manager/GameManager.cs
blob: a37829e585460dbceb9d05c420b74a9bc374fdce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Impostor.Api;
using Impostor.Api.Events.Managers;
using Impostor.Api.Games;
using Impostor.Api.Games.Managers;
using Impostor.Api.Innersloth;
using Impostor.Server.Config;
using Impostor.Server.Events;
using Impostor.Server.Net.Redirector;
using Impostor.Server.Net.State;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Impostor.Server.Net.Manager
{
    internal class GameManager : IGameManager
    {
        private readonly ILogger<GameManager> _logger;
        private readonly INodeLocator _nodeLocator;
        private readonly IPEndPoint _publicIp;
        private readonly ConcurrentDictionary<int, Game> _games;
        private readonly IServiceProvider _serviceProvider;
        private readonly IEventManager _eventManager;
        private readonly IGameCodeFactory _gameCodeFactory;

        public GameManager(ILogger<GameManager> logger, IOptions<ServerConfig> config, INodeLocator nodeLocator, IServiceProvider serviceProvider, IEventManager eventManager, IGameCodeFactory gameCodeFactory)
        {
            _logger = logger;
            _nodeLocator = nodeLocator;
            _serviceProvider = serviceProvider;
            _eventManager = eventManager;
            _gameCodeFactory = gameCodeFactory;
            _publicIp = new IPEndPoint(IPAddress.Parse(config.Value.ResolvePublicIp()), config.Value.PublicPort);
            _games = new ConcurrentDictionary<int, Game>();
        }

        IEnumerable<IGame> IGameManager.Games => _games.Select(kv => kv.Value);

        IGame IGameManager.Find(GameCode code) => Find(code);

        public async ValueTask<IGame> CreateAsync(GameOptionsData options)
        {
            // TODO: Prevent duplicates when using server redirector using INodeProvider.
            var (success, game) = await TryCreateAsync(options);

            for (int i = 0; i < 10 && !success; i++)
            {
                (success, game) = await TryCreateAsync(options);
            }

            if (!success)
            {
                throw new ImpostorException("Could not create new game"); // TODO: Fix generic exception.
            }

            return game;
        }

        private async ValueTask<(bool success, Game game)> TryCreateAsync(GameOptionsData options)
        {
            var gameCode = _gameCodeFactory.Create();
            var gameCodeStr = gameCode.Code;
            var game = ActivatorUtilities.CreateInstance<Game>(_serviceProvider, _publicIp, gameCode, options);

            if (await _nodeLocator.ExistsAsync(gameCodeStr) || !_games.TryAdd(gameCode, game))
            {
                return (false, null);
            }

            await _nodeLocator.SaveAsync(gameCodeStr, _publicIp);
            _logger.LogDebug("Created game with code {0}.", game.Code);

            await _eventManager.CallAsync(new GameCreatedEvent(game));

            return (true, game);
        }

        public Game Find(GameCode code)
        {
            _games.TryGetValue(code, out var game);
            return game;
        }

        public IEnumerable<Game> FindListings(MapFlags map, int impostorCount, GameKeywords language, int count = 10)
        {
            var results = 0;

            // Find games that have not started yet.
            foreach (var (_, game) in _games.Where(x =>
                x.Value.IsPublic &&
                x.Value.GameState == GameStates.NotStarted &&
                x.Value.PlayerCount < x.Value.Options.MaxPlayers))
            {
                // Check for options.
                if (!map.HasFlag((MapFlags)(1 << game.Options.MapId)))
                {
                    continue;
                }

                if (!language.HasFlag(game.Options.Keywords))
                {
                    continue;
                }

                if (impostorCount != 0 && game.Options.NumImpostors != impostorCount)
                {
                    continue;
                }

                // Add to result.
                yield return game;

                // Break out if we have enough.
                if (++results == count)
                {
                    yield break;
                }
            }
        }

        public async ValueTask RemoveAsync(GameCode gameCode)
        {
            if (_games.TryGetValue(gameCode, out var game) && game.PlayerCount > 0)
            {
                foreach (var player in game.Players)
                {
                    await player.KickAsync();
                }

                return;
            }

            if (!_games.TryRemove(gameCode, out game))
            {
                return;
            }

            _logger.LogDebug("Remove game with code {0} ({1}).", GameCodeParser.IntToGameName(gameCode), gameCode);
            await _nodeLocator.RemoveAsync(GameCodeParser.IntToGameName(gameCode));

            await _eventManager.CallAsync(new GameDestroyedEvent(game));
        }
    }
}