Skip to content

Commit 985bc08

Browse files
committed
Use single bot per tournament
1 parent 2569a88 commit 985bc08

3 files changed

Lines changed: 24 additions & 2 deletions

File tree

services/app/apps/codebattle/lib/codebattle/bot/context.ex

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,14 @@ defmodule Codebattle.Bot.Context do
4343
|> Enum.map(&Map.merge(&1, params))
4444
end
4545

46+
@spec get(pos_integer()) :: User.t() | nil
47+
def get(id) do
48+
case Repo.get(User, id) do
49+
%User{is_bot: true} = bot -> bot
50+
_ -> nil
51+
end
52+
end
53+
4654
defp bots_query(limit \\ 1) do
4755
from(
4856
user in User,

services/app/apps/codebattle/lib/codebattle/tournament/strategy/base.ex

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -888,6 +888,21 @@ defmodule Codebattle.Tournament.Base do
888888
game_params
889889
end
890890

891+
defp get_or_build_tournament_bot(tournament) do
892+
meta = tournament.meta || %{}
893+
bot_id = Map.get(meta, :bot_id)
894+
895+
case bot_id && Bot.Context.get(bot_id) do
896+
%{} = bot ->
897+
{tournament, Tournament.Player.new!(bot)}
898+
899+
_ ->
900+
bot = Bot.Context.build()
901+
meta = Map.put(meta, :bot_id, bot.id)
902+
{update_struct(tournament, %{meta: meta}), Tournament.Player.new!(bot)}
903+
end
904+
end
905+
891906
defp upsert_tournament_user_results(tournament) do
892907
Tournament.TournamentUserResult.upsert_results(tournament)
893908
end

services/app/apps/codebattle/lib/codebattle/tournament/strategy/swiss.ex

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ defmodule Codebattle.Tournament.Swiss do
22
@moduledoc false
33
use Codebattle.Tournament.Base
44

5-
alias Codebattle.Bot
65
alias Codebattle.Tournament
76

87
@impl Tournament.Base
@@ -41,7 +40,7 @@ defmodule Codebattle.Tournament.Swiss do
4140
def build_round_pairs(tournament) do
4241
{player_pairs, unmatched_players, played_pair_ids} = build_player_pairs(tournament)
4342

44-
opponent_bot = Tournament.Player.new!(Bot.Context.build())
43+
{tournament, opponent_bot} = get_or_build_tournament_bot(tournament)
4544

4645
unmatched_pairs = Enum.map(unmatched_players, fn player -> [player, opponent_bot] end)
4746

0 commit comments

Comments
 (0)