-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrounds.lua
609 lines (529 loc) · 19 KB
/
rounds.lua
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
require("config")
require("bot_script_env")
require("lib/timer")
require("lib/inspect")
require("lib/table")
require("lib/base64")
require("lib/json")
AVAILABLE_TEAMS = {
DOTA_TEAM_CUSTOM_1,
DOTA_TEAM_CUSTOM_2,
DOTA_TEAM_CUSTOM_3,
DOTA_TEAM_CUSTOM_4,
DOTA_TEAM_CUSTOM_5,
DOTA_TEAM_CUSTOM_6,
DOTA_TEAM_CUSTOM_7,
DOTA_TEAM_CUSTOM_8,
}
Candidates = {}
RestTeamId = ""
if Rounds == nil then
Rounds = class({})
end
function Rounds:UpdateRoundTimerPanel(cur_time)
local event = {
round_count = self.round_count,
cur_time = cur_time
}
CustomGameEventManager:Send_ServerToAllClients(
"updateRoundTimer",
event
)
end
function Rounds:UpdateScoresPanel()
local scores_to_display = {
round_count = self.round_count,
scores = {}
}
for candidate_num, score in pairs(self.scores_this_round) do
local name = Candidates[candidate_num]
scores_to_display.scores[name] = score
end
CustomGameEventManager:Send_ServerToAllClients(
"updateScores",
scores_to_display
)
end
function Rounds:UpdateRoundEndPanel()
local event = {
round_count = self.round_count
}
CustomGameEventManager:Send_ServerToAllClients(
"roundEnd",
event
)
end
--[[
Send scores to server and reset to 0
]]
function Rounds:FlushScoresAndRunNextRound()
print("[xctf Rounds:FlushRoundScores]" .. "Flushing round scores")
if self.round_count > 0 then
local last_scores = deepcopy(self.scores_this_round)
table.insert(self.history.scores, last_scores)
end
local req = CreateHTTPRequest("POST", Config.server_url.service)
if req == nil then
print("[xctf Rounds:FlushRoundScores]" .. "Failed to create http request")
return
end
local teams_data = {}
for candidate_id, score in pairs(self.scores_this_round) do
table.insert(teams_data, {
team_id = candidate_id,
score = score,
result = self.wins_this_round[candidate_id],
})
end
local json_data = json.encode({
task_id = self.task_id,
turn = self.round_count,
teams = teams_data
})
print("[xctf Rounds:FlushRoundScores]" .. "request body: " .. json_data)
req:SetHTTPRequestHeaderValue("X-CLIENT-SECRET", Config.server_token)
req:SetHTTPRequestRawPostBody("application/json", json_data)
req:Send(function(result)
local body = result["Body"]
print("[xctf Rounds:FlushRoundScores]" .. "got body: " .. body)
Rounds:PrepareBeginRound()
end)
end
function Rounds:AdjustScore(candidate, score_delta)
if self.scores_this_round[candidate] == nil then
self.scores_this_round[candidate] = 0
end
self.scores_this_round[candidate] = self.scores_this_round[candidate] + score_delta
Rounds:UpdateScoresPanel()
end
function Rounds:Init()
print("[xctf Rounds:Init()]" .. "rounds constructor called")
self.game_started = false
self.initialized = false
self.round_count = 0
self.task_id = ""
-- team id => scores
self.scores_this_round = {}
self.wins_this_round = {}
-- team id => hero object
self.heros = {}
self.available_players = {}
-- player id to candidate id
self.player_to_candidate = {}
self.candidate_to_player = {}
-- rest order => candidate id
self.candidate_rest_order = {}
-- to support `x fr` command
self.restarting = false
self.history = {
scores = {},
choices = {},
}
self.default_hero = "npc_dota_hero_bloodseeker"
self.default_action = "return {}"
end
function Rounds:InitGameMode()
print("[xctf Rounds:InitGameMode()]" .. "Rounds:InitGameMode...")
GameRules:SetUseUniversalShopMode(true)
-- for faster entering
GameRules:SetPreGameTime(3.0)
-- disable auto gold gain
GameRules:SetStartingGold(0)
GameRules:SetGoldPerTick(0)
local game_mode = GameRules:GetGameModeEntity()
game_mode:SetAlwaysShowPlayerNames(true)
game_mode:SetBuybackEnabled(false)
game_mode:SetAllowNeutralItemDrops(false)
end
function Rounds:InitFromServerAndBeginGame()
if self.initialized and not self.restarting then
return
end
-- remove the host hero
local host_hero = FindUnitsInRadius(
DOTA_TEAM_FIRST,
Vector(0, 0),
nil, -- cacheUnit
1000,
DOTA_UNIT_TARGET_TEAM_BOTH,
DOTA_UNIT_TARGET_HERO,
DOTA_UNIT_TARGET_FLAG_PLAYER_CONTROLLED,
FIND_ANY_ORDER,
false -- canGrowCache
)[1]
if host_hero ~= nil then -- host_hero == nil when the game is restarted by console command
host_hero:RemoveSelf()
end
print("[xctf Rounds:InitFromServerAndBeginGame()]" .. "fetching init data from server")
local req = CreateHTTPRequest("GET", Config.server_url.init)
if req ~= nil then
req:SetHTTPRequestHeaderValue("X-CLIENT-SECRET", Config.server_token)
req:Send(function(result)
local body = result["Body"]
print("[xctf Rounds:InitFromServerAndBeginGame()]" .. "got body: " .. body)
json_data = json.decode(body)
if json_data ~= nil and json_data.code == "AD-000000" then
local candidates_count = 0
for _, team in pairs(json_data.data.teams) do
Candidates[team.team_id] = team.team_name
candidates_count = candidates_count + 1
table.insert(self.candidate_rest_order, team.team_id)
end
-- set config vars
Config.candidate_count = candidates_count
if candidates_count <= 8 then
Config.team_count = candidates_count
elseif candidates_count % 2 == 0 then
Config.team_count = candidates_count / 2
else
Config.team_count = (candidates_count - 1) / 2
end
if candidates_count > 8 then
Config.candidates_per_team = 2
else
Config.candidates_per_team = 1
end
self.initialized = true
Rounds:BeginGame()
else
print("[xctf Rounds:InitFromServerAndBeginGame()]" .. "failed to fetch init data from server, aborting")
end
end)
else
print("[xctf Rounds:InitFromServerAndBeginGame()]" .. "request failed")
end
end
function Rounds:CleanupLivingHerosAndClearUnits()
local entities = Entities:FindAllInSphere(Vector(0, 0), 1e6)
for _, entity in ipairs(entities) do
if entity:GetName() ~= "" then
entity:RemoveSelf()
end
end
self.heros = {}
for _, team in pairs(AVAILABLE_TEAMS) do
local team_units = FindUnitsInRadius(
team,
Vector(0, 0),
nil, -- cacheUnit
1e6,
DOTA_UNIT_TARGET_TEAM_BOTH,
DOTA_UNIT_TARGET_ALL,
DOTA_UNIT_TARGET_FLAG_NONE,
FIND_ANY_ORDER,
false -- canGrowCache
)
for _, unit in pairs(team_units) do
unit:RemoveSelf()
end
end
end
--[[
As we need bot player to know who is the killer,
we setup the bot players with fake heros first.
]]
function Rounds:SetupBotPlayers()
print("[xctf Rounds:SetupBotPlayers()]" .. ".. debug ? " .. tostring(debug.sethook))
for team_id, team_name in pairs(Candidates) do
local ob_hero = GameRules:AddBotPlayerWithEntityScript(
"npc_dota_hero_abaddon",
team_name,
DOTA_TEAM_GOODGUYS,
"bot/ob_hero_act.lua",
false
)
assert(ob_hero, "add bot player failed")
ob_hero:SetRespawnsDisabled(true)
local player_id = ob_hero:GetPlayerID()
ob_hero:RemoveSelf()
print("[xctf Rounds:SetupBotPlayers()]" .. "adding player id " .. tostring(player_id) .. " to team " .. tostring(team_id))
self.player_to_candidate[player_id] = team_id
self.candidate_to_player[team_id] = player_id
end
end
function Rounds:SetupLastHitListener()
ListenToGameEvent("last_hit", function(event)
local _entity_killed = event["EntKilled"]
local player_id = event["PlayerID"]
local candidate = self.player_to_candidate[player_id]
Rounds:AdjustScore(candidate, 1)
end, nil)
end
function Rounds:BeginGame()
if self.restarting then
Rounds:PrepareBeginRound()
self.restarting = false
return
end
if not self.game_started then
-- TODO: use add bot player with entity script to add
-- player so that we can listen to last hit to add
-- the score.
-- Explain: last_hit can only get you the player id instead
-- of the entity id.
Rounds:SetupBotPlayers()
Rounds:SetupLastHitListener()
Rounds:PrepareBeginRound()
self.game_started = true
-- all next rounds should be called on timer set by next round
end
end
function Rounds:NextRound(scripts)
print("[xctf Rounds:NextRound()]" .. "Next Round")
Rounds:CleanupLivingHerosAndClearUnits()
Rounds:ChooseHeros(scripts["chooser_scripts"], scripts["attributes"], scripts["bot_scripts"])
Timers:CreateTimer(
Config.round_begin_delay,
function ()
Rounds:BeginRound(scripts["bot_scripts"])
end
)
end
function Rounds:InitCandidateHero(hero, attr)
hero:SetRespawnsDisabled(true)
attr = attr or {}
hero:SetGold(attr.gold or 0, false)
hero:AddExperience(attr.experience or 0, DOTA_ModifyXP_Unspecified, false, false)
hero:ModifyStrength(attr.strength or 0)
hero:ModifyIntellect(attr.intelligence or 0)
hero:ModifyAgility(attr.agility or 0)
end
function Rounds:ChooseHeros(chooser_scripts, attributes, bot_scripts)
-- TODO: add hero chooser fetch flag so that game only starts
-- when hero is added
print("[xctf Rounds:ChooseHeros()]" .. "choosing heros")
local choices = {}
-- split teams
local team_config = {}
for candidate_id, _ in pairs(Candidates) do
if candidate_id ~= RestTeamId then
table.insert(team_config, candidate_id)
end
end
team_config = table.shuffle(team_config)
print("[xctf Rounds:ChooseHeros()]" .. "team config " .. GameRules.inspect(team_config))
local hero_locations = {}
for i = 1, Config.candidate_count do
hero_locations[i] = Vector(
math.cos(2 * math.pi * i / Config.candidate_count) * Config.hero_locations_radius,
math.sin(2 * math.pi * i / Config.candidate_count) * Config.hero_locations_radius
)
end
local cur_id = 1
for i = 1, Config.team_count do
local cur_candidates = {}
for _ = 1, Config.candidates_per_team do
table.insert(cur_candidates, table.remove(team_config, 1))
end
local cur_team_id = AVAILABLE_TEAMS[i]
for _, candidate_id in ipairs(cur_candidates) do
local chooser = Sandbox:LoadChooseHeroScript(chooser_scripts[candidate_id], Candidates[candidate_id])
local hero_name = Sandbox:RunChooseHero(chooser, Candidates[candidate_id])
local player_id = self.candidate_to_player[candidate_id]
local player_owner = PlayerResource:GetPlayer(player_id)
-- ban non-hero unit
if string.sub(hero_name, 1, 14) ~= "npc_dota_hero_" then
print("[xctf Rounds:ChooseHeros()]" .. "found non-hero unit, using default hero instead")
hero_name = self.default_hero
bot_scripts[candidate_id] = self.default_action
end
print("[xctf Rounds:ChooseHeros()]" .. "player owner: " .. tostring(player_owner) .. "team id " .. tostring(cur_team_id))
local candidate_hero = CreateUnitByName(
hero_name,
hero_locations[cur_id],
true, -- findClearSpace
nil, -- npcowner
player_owner, -- entity owner
cur_team_id
)
print("[xctf Rounds:ChooseHeros()]" .. "check player and team .. " .. tostring(candidate_hero:GetPlayerID()) .. " " .. tostring(candidate_hero:GetTeam()))
candidate_hero.candidate_id = candidate_id
Rounds:InitCandidateHero(candidate_hero, attributes[candidate_id])
self.heros[candidate_id] = candidate_hero
choices[candidate_id] = hero_name
cur_id = cur_id + 1
end
end
table.insert(self.history.choices, choices)
end
function Rounds:PrepareBeginRound()
local req = CreateHTTPRequest("GET", Config.server_url.service)
print("[xctf Rounds:PrepareBeginRound()]" .. "fetching data for next round")
req:SetHTTPRequestHeaderValue("X-CLIENT-SECRET", Config.server_token)
if req == nil then
print("[xctf Rounds:PrepareBeginRound()]" .. "cannot create http request, aborting")
return
end
req:Send(function(result)
local body = result["Body"]
print("[xctf Rounds:PrepareBeginRound()]" .. "got body: " .. body)
json_data = json.decode(body)
if json_data == nil or json_data.code ~= "AD-000000" then
print("[xctf Rounds:PrepareBeginRound()]" .. "failed to parse data from server as json, aborting")
return
end
local data = json_data.data
local chooser_scripts = {}
local bot_scripts = {}
local attributes = {}
self.round_count = data.turn
self.task_id = data.task_id
self.scores_this_round = {}
-- for attributes calculation
local round_index = self.round_count / Config.total_rounds_count
round_index = math.min(round_index, 1) -- make sure it is not greater than 1
for _, team in pairs(data.teams) do
self.scores_this_round[team.team_id] = 0
chooser_scripts[team.team_id] = from_base64(team.select)
bot_scripts[team.team_id] = from_base64(team.act)
local rank_index = (Config.candidate_count - team.rank) / (Config.candidate_count - 1)
attributes[team.team_id] = {
gold = (1 - round_index) * ((1 - rank_index) * 600 + rank_index * 1200) + round_index * ((1 - rank_index) * 5000 + rank_index * 10000),
experience = round_index * 64400,
}
end
local scripts = {
chooser_scripts = chooser_scripts,
bot_scripts = bot_scripts,
attributes = attributes,
}
-- if total_rounds_count is odd, candidates will rest in turns
if Config.candidate_count > 8 and Config.candidate_count % 2 ~= 0 then
RestTeamId = self.candidate_rest_order[(self.round_count - 1) % Config.candidate_count + 1]
end
Rounds:NextRound(scripts)
end)
end
--[[
Returns living teams in an array.
]]
function Rounds:GetLivingTeams()
-- count team alive heros
local team_alive_counts = {}
for _, team_id in pairs(AVAILABLE_TEAMS) do
team_alive_counts[team_id] = 0
end
for candidate_id, _ in pairs(Candidates) do
local hero = self.heros[candidate_id]
if hero == nil then
-- this happens when a candidate is resting
goto continue
end
if hero:IsAlive() then
local team = hero:GetTeam()
team_alive_counts[team] = team_alive_counts[team] + 1
end
::continue::
end
-- when less than one team got alive heros, round should be over
local alive_teams = {}
for team_num, alives in pairs(team_alive_counts) do
if alives > 0 then
table.insert(alive_teams, team_num)
end
end
return alive_teams
end
--[[
Scoring when the round ends
]]
function Rounds:RoundEndedScoring()
local living_teams = Rounds:GetLivingTeams()
for candidate_id, _ in pairs(Candidates) do
self.wins_this_round[candidate_id] = false
end
if #living_teams == 1 then
-- we got a winning team!
local winning_team = living_teams[1]
for candidate_id, _ in pairs(Candidates) do
local hero = self.heros[candidate_id]
if hero == nil then
-- this happens when a candidate is resting
goto continue
end
local team = hero:GetTeam()
if team == winning_team then
self.wins_this_round[candidate_id] = true
Rounds:AdjustScore(candidate_id, 1)
end
::continue::
end
else
-- Multiple teams won..
-- we add scores to the living heros.
for candidate_id, _ in pairs(Candidates) do
local hero = self.heros[candidate_id]
if hero == nil then
-- this happens when a candidate is resting
goto continue
end
local team = hero:GetTeam()
if hero:IsAlive() then
self.wins_this_round[candidate_id] = true
Rounds:AdjustScore(candidate_id, 1)
end
::continue::
end
end
end
function Rounds:BeginRound(bot_scripts)
Rounds:UpdateScoresPanel()
Rounds:UpdateRoundTimerPanel(GameRules:GetDOTATime(false, false))
Timers:CreateTimer(
"round_limit_timer",
{
endTime = Config.round_time,
callback = function ()
Timers:RemoveTimer("round_periodic_timer")
Rounds:RoundEndedScoring()
Rounds:UpdateRoundEndPanel()
Rounds:FlushScoresAndRunNextRound()
Sandbox:CleanUpItems()
end
}
)
Timers:CreateTimer(
"round_periodic_timer",
{
endTime = 1,
callback = function()
local living_teams = Rounds:GetLivingTeams()
if #living_teams <= 1 then
Timers:RemoveTimer("round_limit_timer")
Rounds:RoundEndedScoring()
Rounds:UpdateRoundEndPanel()
Rounds:FlushScoresAndRunNextRound()
Sandbox:CleanUpItems()
return
else
return 1
end
end
}
)
for candidate_num, candidate_name in pairs(Candidates) do
local hero = self.heros[candidate_num]
if hero then
local script = bot_scripts[candidate_num]
BotScriptEnv:AttachScriptOnUnit(hero, script, candidate_name)
end
end
end
if not Rounds.heros then Rounds:Init() end
Sandbox:SetupGameInfo{
GetRoundCount = function()
return Rounds.round_count
end,
GetHistoryScores = function(round)
local scores = Rounds.history.scores[round]
return deepcopy(scores)
end,
GetHistoryChoices = function(round)
local choices = Rounds.history.choices[round]
return deepcopy(choices)
end,
GetCandidates = function()
return deepcopy(Candidates)
end
}
GameRules.Rounds = Rounds