This repository has been archived by the owner on Jan 3, 2019. It is now read-only.
forked from Teetime/teeworlds
-
Notifications
You must be signed in to change notification settings - Fork 4
/
zcatch.cpp
779 lines (677 loc) · 23.8 KB
/
zcatch.cpp
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
/* zCatch by erd and Teetime */
/* Modified by Teelevision for zCatch/TeeVi, see readme.txt and license.txt. */
#include <engine/shared/config.h>
#include <game/server/gamecontext.h>
#include <game/server/gamecontroller.h>
#include <game/server/entities/character.h>
#include <game/server/player.h>
#include "zcatch.h"
#include <string.h>
CGameController_zCatch::CGameController_zCatch(class CGameContext *pGameServer) :
IGameController(pGameServer)
{
m_pGameType = "zCatch/TeeVi";
m_OldMode = g_Config.m_SvMode;
}
CGameController_zCatch::~CGameController_zCatch() {
/* save all players */
for (int i = 0; i < MAX_CLIENTS; i++)
if (GameServer()->m_apPlayers[i])
SaveRanking(GameServer()->m_apPlayers[i]);
}
/* ranking system: create zcatch score table */
void CGameController_zCatch::OnInitRanking(sqlite3 *rankingDb) {
char *zErrMsg = 0;
/* lock database access in this process */
GameServer()->LockRankingDb();
/* when another process uses the database, wait up to 10 seconds */
sqlite3_busy_timeout(GameServer()->GetRankingDb(), 10000);
int rc = sqlite3_exec(GameServer()->GetRankingDb(), "\
BEGIN; \
CREATE TABLE IF NOT EXISTS zCatch( \
username TEXT PRIMARY KEY, \
score UNSIGNED INTEGER DEFAULT 0, \
numWins UNSIGNED INTEGER DEFAULT 0, \
numKills UNSIGNED INTEGER DEFAULT 0, \
numKillsWallshot UNSIGNED INTEGER DEFAULT 0, \
numDeaths UNSIGNED INTEGER DEFAULT 0, \
numShots UNSIGNED INTEGER DEFAULT 0, \
highestSpree UNSIGNED INTEGER DEFAULT 0, \
timePlayed UNSIGNED INTEGER DEFAULT 0 \
); \
CREATE INDEX IF NOT EXISTS zCatch_score_index ON zCatch (score); \
CREATE INDEX IF NOT EXISTS zCatch_numWins_index ON zCatch (numWins); \
CREATE INDEX IF NOT EXISTS zCatch_numKills_index ON zCatch (numKills); \
CREATE INDEX IF NOT EXISTS zCatch_numKillsWallshot_index ON zCatch (numKillsWallshot); \
CREATE INDEX IF NOT EXISTS zCatch_numDeaths_index ON zCatch (numDeaths); \
CREATE INDEX IF NOT EXISTS zCatch_numShots_index ON zCatch (numShots); \
CREATE INDEX IF NOT EXISTS zCatch_highestSpree_index ON zCatch (highestSpree); \
CREATE INDEX IF NOT EXISTS zCatch_timePlayed_index ON zCatch (timePlayed); \
COMMIT; \
", NULL, 0, &zErrMsg);
/* unlock database access */
GameServer()->UnlockRankingDb();
/* check for error */
if (rc != SQLITE_OK) {
char aBuf[512];
str_format(aBuf, sizeof(aBuf), "SQL error (#%d): %s\n", rc, zErrMsg);
GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "ranking", aBuf);
sqlite3_free(zErrMsg);
exit(1);
}
}
void CGameController_zCatch::Tick()
{
IGameController::Tick();
if(m_OldMode != g_Config.m_SvMode && !GameServer()->m_World.m_Paused)
{
EndRound();
}
}
void CGameController_zCatch::DoWincheck()
{
if(m_GameOverTick == -1)
{
int Players = 0, Players_Spec = 0, Players_SpecExplicit = 0;
int winnerId = -1;
CPlayer *winner = NULL;
for(int i = 0; i < MAX_CLIENTS; i++)
{
if(GameServer()->m_apPlayers[i])
{
Players++;
if(GameServer()->m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS)
Players_Spec++;
else
{
winnerId = i;
winner = GameServer()->m_apPlayers[i];
}
if(GameServer()->m_apPlayers[i]->m_SpecExplicit)
Players_SpecExplicit++;
}
}
int Players_Ingame = Players - Players_SpecExplicit;
if(Players_Ingame <= 1)
{
//Do nothing
}
else if((Players - Players_Spec) == 1)
{
for(int i = 0; i < MAX_CLIENTS; i++)
{
if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS)
{
GameServer()->m_apPlayers[i]->m_Score += g_Config.m_SvBonus;
if(Players_Ingame < g_Config.m_SvLastStandingPlayers)
GameServer()->m_apPlayers[i]->ReleaseZCatchVictim(CPlayer::ZCATCH_RELEASE_ALL);
}
}
if(winner && winner->m_HardMode.m_Active && winner->m_HardMode.m_ModeTotalFails.m_Active && winner->m_HardMode.m_ModeTotalFails.m_Fails > winner->m_HardMode.m_ModeTotalFails.m_Max)
{
winner->ReleaseZCatchVictim(CPlayer::ZCATCH_RELEASE_ALL);
winner->m_HardMode.m_ModeTotalFails.m_Fails = 0;
GameServer()->SendChatTarget(-1, "The winner failed the hard mode.");
GameServer()->SendBroadcast("The winner failed the hard mode.", -1);
}
else if(Players_Ingame < g_Config.m_SvLastStandingPlayers)
{
winner->HardModeRestart();
GameServer()->SendChatTarget(-1, "Too few players to end round.");
GameServer()->SendBroadcast("Too few players to end round.", -1);
}
else
{
// give the winner points
if (winnerId > -1)
{
RewardWinner(winnerId);
}
// announce if winner is in hard mode
if(winner->m_HardMode.m_Active) {
char aBuf[256];
auto name = GameServer()->Server()->ClientName(winnerId);
str_format(aBuf, sizeof(aBuf), "Player '%s' won in hard mode (%s).", name, winner->m_HardMode.m_Description);
GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf);
}
EndRound();
}
}
IGameController::DoWincheck(); //do also usual wincheck
}
}
int CGameController_zCatch::OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int WeaponID)
{
if(!pKiller)
return 0;
CPlayer *victim = pVictim->GetPlayer();
if(pKiller != victim)
{
/* count players playing */
int numPlayers = 0;
for(int i = 0; i < MAX_CLIENTS; i++)
if(GameServer()->m_apPlayers[i] && !GameServer()->m_apPlayers[i]->m_SpecExplicit)
++numPlayers;
/* you can at max get that many points as there are players playing */
pKiller->m_Score += min(victim->m_zCatchNumKillsInARow + 1, numPlayers);
++pKiller->m_Kills;
++victim->m_Deaths;
/* Check if the killer has been already killed and is in spectator (victim may died through wallshot) */
if(pKiller->GetTeam() != TEAM_SPECTATORS && (!pVictim->m_KillerLastDieTickBeforceFiring || pVictim->m_KillerLastDieTickBeforceFiring == pKiller->m_DieTick))
{
++pKiller->m_zCatchNumKillsInARow;
pKiller->AddZCatchVictim(victim->GetCID(), CPlayer::ZCATCH_CAUGHT_REASON_KILLED);
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "You are caught until '%s' dies.", Server()->ClientName(pKiller->GetCID()));
GameServer()->SendChatTarget(victim->GetCID(), aBuf);
}
}
else
{
// selfkill/death
if(WeaponID == WEAPON_SELF || WeaponID == WEAPON_WORLD)
{
victim->m_Score -= g_Config.m_SvKillPenalty;
++victim->m_Deaths;
}
}
// release all the victim's victims
victim->ReleaseZCatchVictim(CPlayer::ZCATCH_RELEASE_ALL);
victim->m_zCatchNumKillsInARow = 0;
victim->m_zCatchNumKillsReleased = 0;
// Update colours
OnPlayerInfoChange(victim);
OnPlayerInfoChange(pKiller);
// ranking
++victim->m_RankCache.m_NumDeaths;
if(pKiller != victim && WeaponID != WEAPON_GAME)
{
++pKiller->m_RankCache.m_NumKills;
if (WeaponID == WEAPON_RIFLE && pVictim->m_TookBouncedWallshotDamage)
{
++pKiller->m_RankCache.m_NumKillsWallshot;
}
}
// zCatch/TeeVi: hard mode
if(pKiller->m_HardMode.m_Active && pKiller->m_HardMode.m_ModeKillTimelimit.m_Active)
{
pKiller->m_HardMode.m_ModeKillTimelimit.m_LastKillTick = Server()->Tick();
}
return 0;
}
void CGameController_zCatch::OnPlayerInfoChange(class CPlayer *pP)
{
if(g_Config.m_SvColorIndicator && pP->m_zCatchNumKillsInARow <= 20)
{
int Num = max(0, 160 - pP->m_zCatchNumKillsInARow * 10);
pP->m_TeeInfos.m_ColorBody = Num * 0x010000 + 0xff00;
if(pP->m_HardMode.m_Active)
pP->m_TeeInfos.m_ColorFeet = 0xffff00; // red
else
pP->m_TeeInfos.m_ColorFeet = pP->m_zCatchNumKillsInARow == 20 ? 0x40ff00 : pP->m_TeeInfos.m_ColorBody;
pP->m_TeeInfos.m_UseCustomColor = 1;
}
}
void CGameController_zCatch::StartRound()
{
// if sv_mode changed: restart map (with new mode then)
if(m_OldMode != g_Config.m_SvMode)
{
m_OldMode = g_Config.m_SvMode;
Server()->MapReload();
}
IGameController::StartRound();
for(int i = 0; i < MAX_CLIENTS; i++)
{
if(GameServer()->m_apPlayers[i])
{
GameServer()->m_apPlayers[i]->m_Kills = 0;
GameServer()->m_apPlayers[i]->m_Deaths = 0;
GameServer()->m_apPlayers[i]->m_TicksSpec = 0;
GameServer()->m_apPlayers[i]->m_TicksIngame = 0;
GameServer()->m_apPlayers[i]->RankCacheStartPlaying();
}
}
}
void CGameController_zCatch::OnCharacterSpawn(class CCharacter *pChr)
{
// default health and armor
pChr->IncreaseHealth(10);
if(g_Config.m_SvMode == 2)
pChr->IncreaseArmor(10);
// give default weapons
switch(g_Config.m_SvMode)
{
case 1: /* Instagib - Only Riffle */
pChr->GiveWeapon(WEAPON_RIFLE, -1);
break;
case 2: /* All Weapons */
pChr->GiveWeapon(WEAPON_HAMMER, -1);
pChr->GiveWeapon(WEAPON_GUN, g_Config.m_SvWeaponsAmmo);
pChr->GiveWeapon(WEAPON_GRENADE, g_Config.m_SvWeaponsAmmo);
pChr->GiveWeapon(WEAPON_SHOTGUN, g_Config.m_SvWeaponsAmmo);
pChr->GiveWeapon(WEAPON_RIFLE, g_Config.m_SvWeaponsAmmo);
break;
case 3: /* Hammer */
pChr->GiveWeapon(WEAPON_HAMMER, -1);
break;
case 4: /* Grenade */
pChr->GiveWeapon(WEAPON_GRENADE, g_Config.m_SvGrenadeEndlessAmmo ? -1 : g_Config.m_SvWeaponsAmmo);
break;
case 5: /* Ninja */
pChr->GiveNinja();
break;
}
//Update colour of spawning tees
OnPlayerInfoChange(pChr->GetPlayer());
}
void CGameController_zCatch::EndRound()
{
if(m_Warmup) // game can't end when we are running warmup
return;
for(int i = 0; i < MAX_CLIENTS; i++)
{
auto player = GameServer()->m_apPlayers[i];
if(player)
{
// save ranking stats
SaveRanking(player);
player->RankCacheStopPlaying();
if(!player->m_SpecExplicit)
{
player->SetTeamDirect(GameServer()->m_pController->ClampTeam(1));
if(player->m_TicksSpec != 0 || player->m_TicksIngame != 0)
{
char aBuf[128];
double TimeIngame = (player->m_TicksIngame * 100.0) / (player->m_TicksIngame + player->m_TicksSpec);
str_format(aBuf, sizeof(aBuf), "K/D: %d/%d, ingame: %.2f%%", player->m_Kills, player->m_Deaths, TimeIngame);
GameServer()->SendChatTarget(i, aBuf);
}
// release all players
player->ReleaseZCatchVictim(CPlayer::ZCATCH_RELEASE_ALL);
player->m_zCatchNumKillsInARow = 0;
}
// zCatch/TeeVi: hard mode
// reset hard mode
player->ResetHardMode();
}
}
GameServer()->m_World.m_Paused = true;
m_GameOverTick = Server()->Tick();
m_SuddenDeath = 0;
}
bool CGameController_zCatch::CanChangeTeam(CPlayer *pPlayer, int JoinTeam)
{
if(pPlayer->m_CaughtBy >= 0)
return false;
return true;
}
bool CGameController_zCatch::OnEntity(int Index, vec2 Pos)
{
if(Index == ENTITY_SPAWN)
m_aaSpawnPoints[0][m_aNumSpawnPoints[0]++] = Pos;
else if(Index == ENTITY_SPAWN_RED)
m_aaSpawnPoints[1][m_aNumSpawnPoints[1]++] = Pos;
else if(Index == ENTITY_SPAWN_BLUE)
m_aaSpawnPoints[2][m_aNumSpawnPoints[2]++] = Pos;
return false;
}
/* celebration and scoring */
void CGameController_zCatch::RewardWinner(int winnerId) {
CPlayer *winner = GameServer()->m_apPlayers[winnerId];
int numEnemies = min(15, winner->m_zCatchNumKillsInARow - winner->m_zCatchNumKillsReleased);
/* calculate points (multiplied with 100) */
int points = 100 * numEnemies * numEnemies * numEnemies / 225;
/* set winner's ranking stats */
++winner->m_RankCache.m_NumWins;
/* abort if no points */
if (points <= 0)
{
return;
}
winner->m_RankCache.m_Points += points;
/* saving is done in EndRound() */
/* the winner's name */
const char *name = GameServer()->Server()->ClientName(winnerId);
/* announce in chat */
char aBuf[96];
str_format(aBuf, sizeof(aBuf), "Winner '%s' gets %.2f points.", name, points/100.0);
GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf);
}
/* save a player's ranking stats */
void CGameController_zCatch::SaveRanking(CPlayer *player)
{
if (!GameServer()->RankingEnabled())
return;
/* prepare */
player->RankCacheStopPlaying(); // so that m_RankCache.m_TimePlayed is updated
/* check if saving is needed */
/* because compared to simply the & operator, the && operator does not conpinue to check all the conditions
of the if statement if one of them does not meet the criteria, so the order of the conditions decides how fast
those are checked
I wonder if the numKillsWallshot is actually needed due to every wallshot being a shot, meaning that the wallshot
doesn't need to be checked*/
if (player->m_RankCache.m_NumShots == 0 &&
player->m_RankCache.m_TimePlayed == 0 &&
player->m_RankCache.m_NumKills == 0 &&
player->m_RankCache.m_NumDeaths == 0 &&
player->m_zCatchNumKillsInARow == 0 &&
player->m_RankCache.m_NumWins == 0 &&
player->m_RankCache.m_Points == 0 &&
player->m_RankCache.m_NumKillsWallshot == 0)
return;
/* player's name */
char *name = (char*)malloc(MAX_NAME_LENGTH);
str_copy(name, GameServer()->Server()->ClientName(player->GetCID()), MAX_NAME_LENGTH);
/* give the points */
GameServer()->AddRankingThread(new std::thread(&CGameController_zCatch::SaveScore,
GameServer(), // username
name, // username
player->m_RankCache.m_Points, // score
player->m_RankCache.m_NumWins, // numWins
player->m_RankCache.m_NumKills, // numKills
player->m_RankCache.m_NumKillsWallshot, // numKillsWallshot
player->m_RankCache.m_NumDeaths, // numDeaths
player->m_RankCache.m_NumShots, // numShots
player->m_zCatchNumKillsInARow, // highestSpree
player->m_RankCache.m_TimePlayed / Server()->TickSpeed() // timePlayed
));
/* clean rank cache */
player->m_RankCache.m_Points = 0;
player->m_RankCache.m_NumWins = 0;
player->m_RankCache.m_NumKills = 0;
player->m_RankCache.m_NumKillsWallshot = 0;
player->m_RankCache.m_NumDeaths = 0;
player->m_RankCache.m_NumShots = 0;
player->m_RankCache.m_TimePlayed = 0;
player->RankCacheStartPlaying();
}
/* adds the score to the player */
void CGameController_zCatch::SaveScore(CGameContext* GameServer, char *name, int score, int numWins, int numKills, int numKillsWallshot, int numDeaths, int numShots, int highestSpree, int timePlayed) {
/* debug */
char aBuf[512];
str_format(aBuf, sizeof(aBuf), "Saving user stats of '%s'", name);
GameServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "ranking", aBuf);
/* prepare */
const char *zTail;
const char *zSql = "\
INSERT OR REPLACE INTO zCatch ( \
username, score, numWins, numKills, numKillsWallshot, numDeaths, numShots, highestSpree, timePlayed \
) \
SELECT \
new.username, \
COALESCE(old.score, 0) + ?2, \
COALESCE(old.numWins, 0) + ?3, \
COALESCE(old.numKills, 0) + ?4, \
COALESCE(old.numKillsWallshot, 0) + ?5, \
COALESCE(old.numDeaths, 0) + ?6, \
COALESCE(old.numShots, 0) + ?7, \
MAX(COALESCE(old.highestSpree, 0), ?8), \
COALESCE(old.timePlayed, 0) + ?9 \
FROM ( \
SELECT ?1 as username \
) new \
LEFT JOIN ( \
SELECT * \
FROM zCatch \
) old ON old.username = new.username; \
";
sqlite3_stmt *pStmt;
int rc = sqlite3_prepare_v2(GameServer->GetRankingDb(), zSql, strlen(zSql), &pStmt, &zTail);
if (rc == SQLITE_OK)
{
/* bind parameters in query */
sqlite3_bind_text(pStmt, 1, name, strlen(name), 0);
sqlite3_bind_int(pStmt, 2, score);
sqlite3_bind_int(pStmt, 3, numWins);
sqlite3_bind_int(pStmt, 4, numKills);
sqlite3_bind_int(pStmt, 5, numKillsWallshot);
sqlite3_bind_int(pStmt, 6, numDeaths);
sqlite3_bind_int(pStmt, 7, numShots);
sqlite3_bind_int(pStmt, 8, highestSpree);
sqlite3_bind_int(pStmt, 9, timePlayed);
/* lock database access in this process */
GameServer->LockRankingDb();
/* when another process uses the database, wait up to 1 minute */
sqlite3_busy_timeout(GameServer->GetRankingDb(), 60000);
/* save to database */
switch (sqlite3_step(pStmt))
{
case SQLITE_DONE:
/* nothing */
break;
case SQLITE_BUSY:
GameServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "ranking", "Error: could not save records (timeout).");
break;
default:
char aBuf[512];
str_format(aBuf, sizeof(aBuf), "SQL error (#%d): %s", rc, sqlite3_errmsg(GameServer->GetRankingDb()));
GameServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "ranking", aBuf);
}
/* unlock database access */
GameServer->UnlockRankingDb();
}
else
{
/* print error */
char aBuf[512];
str_format(aBuf, sizeof(aBuf), "SQL error (#%d): %s", rc, sqlite3_errmsg(GameServer->GetRankingDb()));
GameServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "ranking", aBuf);
}
sqlite3_finalize(pStmt);
free(name);
}
/* when a player typed /top into the chat */
void CGameController_zCatch::OnChatCommandTop(CPlayer *pPlayer, const char *category)
{
const char *column;
if (!str_comp_nocase("score", category) || !str_comp_nocase("", category))
{
column = "score";
}
else if (!str_comp_nocase("wins", category))
{
column = "numWins";
}
else if (!str_comp_nocase("kills", category))
{
column = "numKills";
}
else if (!str_comp_nocase("wallshotkills", category))
{
column = "numKillsWallshot";
}
else if (!str_comp_nocase("deaths", category))
{
column = "numDeaths";
}
else if (!str_comp_nocase("shots", category))
{
column = "numShots";
}
else if (!str_comp_nocase("spree", category))
{
column = "highestSpree";
}
else if (!str_comp_nocase("time", category))
{
column = "timePlayed";
}
else
{
GameServer()->SendChatTarget(pPlayer->GetCID(), "Usage: /top [score|wins|kills|wallshotkills|deaths|shots|spree|time]");
return;
}
GameServer()->AddRankingThread(new std::thread(&CGameController_zCatch::ChatCommandTopFetchDataAndPrint, GameServer(), pPlayer->GetCID(), column));
}
/* get the top players */
void CGameController_zCatch::ChatCommandTopFetchDataAndPrint(CGameContext* GameServer, int clientId, const char *column)
{
/* prepare */
const char *zTail;
char sqlBuf[128];
str_format(sqlBuf, sizeof(sqlBuf), "SELECT username, %s FROM zCatch ORDER BY %s DESC LIMIT 5;", column, column);
const char *zSql = sqlBuf;
sqlite3_stmt *pStmt;
int rc = sqlite3_prepare_v2(GameServer->GetRankingDb(), zSql, strlen(zSql), &pStmt, &zTail);
if (rc == SQLITE_OK)
{
/* lock database access in this process, but wait maximum 1 second */
if (GameServer->LockRankingDb(1000))
{
/* when another process uses the database, wait up to 1 second */
sqlite3_busy_timeout(GameServer->GetRankingDb(), 1000);
/* fetch from database */
int numRows = 0;
int rc;
while ((rc = sqlite3_step(pStmt)) == SQLITE_ROW)
{
const unsigned char* name = sqlite3_column_text(pStmt, 0);
int value = sqlite3_column_int(pStmt, 1);
char aBuf[64], bBuf[32];
FormatRankingColumn(column, bBuf, value);
str_format(aBuf, sizeof(aBuf), "[%s] %s", bBuf, name);
/* if the player left and the client id is unused, nothing will happen */
/* if another player joined, there is no big harm that he receives it */
/* maybe later i have a good idea how to prevent this */
GameServer->SendChatTarget(clientId, aBuf);
++numRows;
}
/* unlock database access */
GameServer->UnlockRankingDb();
if (numRows == 0)
{
if (rc == SQLITE_BUSY)
GameServer->SendChatTarget(clientId, "Could not load top ranks. Try again later.");
else
GameServer->SendChatTarget(clientId, "There are no ranks");
}
}
else
{
GameServer->SendChatTarget(clientId, "Could not load top ranks. Try again later.");
}
}
else
{
/* print error */
char aBuf[512];
str_format(aBuf, sizeof(aBuf), "SQL error (#%d): %s", rc, sqlite3_errmsg(GameServer->GetRankingDb()));
GameServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "ranking", aBuf);
}
sqlite3_finalize(pStmt);
}
/* when a player typed /top into the chat */
void CGameController_zCatch::OnChatCommandOwnRank(CPlayer *pPlayer)
{
OnChatCommandRank(pPlayer, GameServer()->Server()->ClientName(pPlayer->GetCID()));
}
/* when a player typed /top into the chat */
void CGameController_zCatch::OnChatCommandRank(CPlayer *pPlayer, const char *name)
{
char *queryName = (char*)malloc(MAX_NAME_LENGTH);
str_copy(queryName, name, MAX_NAME_LENGTH);
GameServer()->AddRankingThread(new std::thread(&CGameController_zCatch::ChatCommandRankFetchDataAndPrint, GameServer(), pPlayer->GetCID(), queryName));
}
/* get the top players */
void CGameController_zCatch::ChatCommandRankFetchDataAndPrint(CGameContext* GameServer, int clientId, char *name)
{
/* prepare */
const char *zTail;
const char *zSql = "\
SELECT \
a.score, \
a.numWins, \
a.numKills, \
a.numKillsWallshot, \
a.numDeaths, \
a.numShots, \
a.highestSpree, \
a.timePlayed, \
(SELECT COUNT(*) FROM zCatch b WHERE b.score > a.score) + 1, \
MAX(0, (SELECT MIN(b.score) FROM zCatch b WHERE b.score > a.score) - a.score) \
FROM zCatch a \
WHERE username = ?1\
;";
sqlite3_stmt *pStmt;
int rc = sqlite3_prepare_v2(GameServer->GetRankingDb(), zSql, strlen(zSql), &pStmt, &zTail);
if (rc == SQLITE_OK)
{
/* bind parameters in query */
sqlite3_bind_text(pStmt, 1, name, strlen(name), 0);
/* lock database access in this process, but wait maximum 1 second */
if (GameServer->LockRankingDb(1000))
{
/* when another process uses the database, wait up to 1 second */
sqlite3_busy_timeout(GameServer->GetRankingDb(), 1000);
/* fetch from database */
int row = sqlite3_step(pStmt);
/* unlock database access */
GameServer->UnlockRankingDb();
/* result row was fetched */
if (row == SQLITE_ROW)
{
int score = sqlite3_column_int(pStmt, 0);
int numWins = sqlite3_column_int(pStmt, 1);
int numKills = sqlite3_column_int(pStmt, 2);
int numKillsWallshot = sqlite3_column_int(pStmt, 3);
int numDeaths = sqlite3_column_int(pStmt, 4);
int numShots = sqlite3_column_int(pStmt, 5);
int highestSpree = sqlite3_column_int(pStmt, 6);
int timePlayed = sqlite3_column_int(pStmt, 7);
int rank = sqlite3_column_int(pStmt, 8);
int scoreToNextRank = sqlite3_column_int(pStmt, 9);
char aBuf[512];
if (g_Config.m_SvMode == 1) // laser
{
str_format(aBuf, sizeof(aBuf), "'%s' is rank %d with a score of %.*f points (%d wins, %d kills (%d wallshot), %d deaths, %d shots, spree of %d, %d:%02dh played, %.*f points for next rank)", name, rank, score % 100 ? 2 : 0, score/100.0, numWins, numKills, numKillsWallshot, numDeaths, numShots, highestSpree, timePlayed / 3600, timePlayed / 60 % 60, scoreToNextRank % 100 ? 2 : 0, scoreToNextRank/100.0);
}
else
{
str_format(aBuf, sizeof(aBuf), "'%s' is rank %d with a score of %.*f points (%d wins, %d kills, %d deaths, %d shots, spree of %d, %d:%02dh played, %.*f points for next rank)", name, rank, score % 100 ? 2 : 0, score/100.0, numWins, numKills, numDeaths, numShots, highestSpree, timePlayed / 3600, timePlayed / 60 % 60, scoreToNextRank % 100 ? 2 : 0, scoreToNextRank/100.0);
}
GameServer->SendChatTarget(clientId, aBuf);
}
/* database is locked */
else if (row == SQLITE_BUSY)
{
char aBuf[64];
str_format(aBuf, sizeof(aBuf), "Could not get rank of '%s'. Try again later.", name);
GameServer->SendChatTarget(clientId, aBuf);
}
/* no result found */
else if (row == SQLITE_DONE)
{
char aBuf[64];
str_format(aBuf, sizeof(aBuf), "'%s' has no rank", name);
GameServer->SendChatTarget(clientId, aBuf);
}
}
else
{
char aBuf[64];
str_format(aBuf, sizeof(aBuf), "Could not get rank of '%s'. Try again later.", name);
GameServer->SendChatTarget(clientId, aBuf);
}
}
else
{
/* print error */
char aBuf[512];
str_format(aBuf, sizeof(aBuf), "SQL error (#%d): %s", rc, sqlite3_errmsg(GameServer->GetRankingDb()));
GameServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "ranking", aBuf);
}
sqlite3_finalize(pStmt);
free(name);
}
void CGameController_zCatch::FormatRankingColumn(const char* column, char buf[32], int value)
{
if (!str_comp_nocase("score", column))
str_format(buf, sizeof(buf), "%.*f", value % 100 ? 2 : 0, value/100.0);
else if (!str_comp_nocase("timePlayed", column))
str_format(buf, sizeof(buf), "%d:%02dh", value/3600, value/60 % 60);
else
str_format(buf, sizeof(buf), "%d", value);
}