feat,wip: 토너먼트 베팅 진행

This commit is contained in:
2022-04-25 00:30:31 +09:00
parent 18f2e9ffea
commit 42fc0f6aed
7 changed files with 164 additions and 178 deletions
-1
View File
@@ -84,7 +84,6 @@ return [
'hwe/j_adjust_icon.php', 'hwe/j_adjust_icon.php',
'hwe/j_autoreset.php', 'hwe/j_autoreset.php',
'hwe/j_basic_info.php', 'hwe/j_basic_info.php',
'hwe/j_betting.php',
'hwe/j_board_article_add.php', 'hwe/j_board_article_add.php',
'hwe/j_board_comment_add.php', 'hwe/j_board_comment_add.php',
'hwe/j_board_get_articles.php', 'hwe/j_board_get_articles.php',
+51 -42
View File
@@ -17,40 +17,10 @@ TurnExecutionHelper::executeAllCommand();
$generalID = $session->generalID; $generalID = $session->generalID;
$bettingID = $gameStor->lastTournamentBettingID ?? 0;
if ($bettingID == 0) {
//TODO: 좋은 방법 없나?
die('아직 베팅이 열리지 않았습니다.');
}
$betting = new Betting($bettingID);
$info = $betting->getInfo();
$myBet = [];
$globalBet = [];
foreach ($db->queryAllLists(
'SELECT general_id, user_id, amount, betting_type FROM ng_betting WHERE betting_id = %i',
$this->bettingID
) as [$betGeneralID, $userID, $amount, $bettingTypeKey]) {
$bettingKey = Json::decode($bettingTypeKey)[0];
if ($betGeneralID == $generalID) {
$myBet[$bettingKey] = $amount;
}
if (key_exists($bettingKey, $globalBet)) {
$globalBet[$bettingKey] += $amount;
} else {
$globalBet[$bettingKey] = $amount;
}
}
$me = $db->queryFirstRow('SELECT no,tournament,con,turntime from general where owner=%i', $userID); $me = $db->queryFirstRow('SELECT no,tournament,con,turntime from general where owner=%i', $userID);
$myBetTotal = array_sum($myBet);
$globalBetTotal = array_sum($globalBet);
$admin = $gameStor->getValues(['tournament', 'phase', 'tnmt_type', 'develcost']); $admin = $gameStor->getValues(['tournament', 'phase', 'tnmt_type', 'develcost']);
$con = checkLimit($me['con']); $con = checkLimit($me['con']);
@@ -60,34 +30,68 @@ if ($con >= 2) {
} }
switch ($admin['tnmt_type']) { switch ($admin['tnmt_type']) {
default:
throw new \RuntimeException('Invalid tnmt_type');
case convertTournamentType('전력전'): case convertTournamentType('전력전'):
$tnmt_type = "<font color=cyan>전력전</font>"; $tnmt_type = "전력전";
$color = "cyan";
$tp = "total"; $tp = "total";
$tp2 = "종합"; $tp2 = "종합";
$tp3 = "total"; $tp3 = "total";
break; break;
case convertTournamentType('통솔전'): case convertTournamentType('통솔전'):
$tnmt_type = "<font color=cyan>통솔전</font>"; $tnmt_type = "통솔전";
$color = "cyan";
$tp = "leadership"; $tp = "leadership";
$tp2 = "통솔"; $tp2 = "통솔";
$tp3 = "leadership"; $tp3 = "leadership";
break; break;
case convertTournamentType('일기토'): case convertTournamentType('일기토'):
$tnmt_type = "<font color=cyan>일기토</font>"; $tnmt_type = "일기토";
$color = "cyan";
$tp = "strength"; $tp = "strength";
$tp2 = "무력"; $tp2 = "무력";
$tp3 = "strength"; $tp3 = "strength";
break; break;
case convertTournamentType('설전'): case convertTournamentType('설전'):
$tnmt_type = "<font color=cyan>설전</font>"; $tnmt_type = "설전";
$color = "cyan";
$tp = "intel"; $tp = "intel";
$tp2 = "지력"; $tp2 = "지력";
$tp3 = "intel"; $tp3 = "intel";
break; break;
default:
throw new \RuntimeException('Invalid tnmt_type');
} }
$bettingID = $gameStor->lastTournamentBettingID ?? 0;
$myBet = [];
$globalBet = [];
if ($bettingID != 0) {
$betting = $bettingID != 0 ? new Betting($bettingID) : null;
$info = $betting->getInfo();
foreach ($db->queryAllLists(
'SELECT general_id, user_id, amount, betting_type FROM ng_betting WHERE betting_id = %i',
$bettingID
) as [$betGeneralID, $userID, $amount, $bettingTypeKey]) {
$bettingKey = Json::decode($bettingTypeKey)[0];
if ($betGeneralID == $generalID) {
$myBet[$bettingKey] = $amount;
}
if (key_exists($bettingKey, $globalBet)) {
$globalBet[$bettingKey] += $amount;
} else {
$globalBet[$bettingKey] = $amount;
}
}
} else {
$info = getDummyBettingInfo($tnmt_type);
}
$myBetTotal = array_sum($myBet);
$globalBetTotal = array_sum($globalBet);
$str1 = getTournament($admin['tournament']); $str1 = getTournament($admin['tournament']);
$str2 = getTournamentTime(); $str2 = getTournamentTime();
if ($str2) { if ($str2) {
@@ -114,6 +118,11 @@ if ($str3) {
<?= WebUtil::printCSS('../d_shared/common.css') ?> <?= WebUtil::printCSS('../d_shared/common.css') ?>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard/dist/web/static/pretendard.css" /> <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard/dist/web/static/pretendard.css" />
<?= WebUtil::printDist('ts', ['common', 'betting']) ?> <?= WebUtil::printDist('ts', ['common', 'betting']) ?>
<?= WebUtil::printStaticValues([
'staticValues'=>[
'bettingID'=> $bettingID
]
])?>
</head> </head>
<body> <body>
@@ -128,7 +137,7 @@ if ($str3) {
</tr> </tr>
<tr> <tr>
<td colspan=16 align=center> <td colspan=16 align=center>
<font color=white size=6><?= $tnmt_type ?> (<?= $str1 . $str2 . $str3 ?>)</font> <font color=white size=6><span style="color:<?= $color ?>"><?= $tnmt_type ?></span> (<?= $str1 . $str2 . $str3 ?>)</font>
</td> </td>
</tr> </tr>
<tr> <tr>
@@ -368,7 +377,7 @@ if ($str3) {
<tr align=center>"; <tr align=center>";
foreach (range(0, 15) as $i) { foreach (range(0, 15) as $i) {
$amount = $bet[$keyMap[$i]] ?? 0; $amount = $bet[$keyMap[$i] ?? -1] ?? 0;
echo "<td width=70><font color=skyblue>{$amount}</font></td>"; echo "<td width=70><font color=skyblue>{$amount}</font></td>";
} }
?> ?>
@@ -394,7 +403,7 @@ if ($str3) {
<tr align=center> <tr align=center>
<?php <?php
foreach (range(0, 15) as $i) { foreach (range(0, 15) as $i) {
$amount = $myBet[$keyMap[$i]] ?? 0; $amount = $myBet[$keyMap[$i] ?? -1] ?? 0;
echo "<td><font color=orange>{$amount}</font></td>"; echo "<td><font color=orange>{$amount}</font></td>";
} }
?> ?>
@@ -420,7 +429,7 @@ if ($str3) {
<tr align=center> <tr align=center>
<?php <?php
foreach (range(0, 15) as $i) { foreach (range(0, 15) as $i) {
$amount = $gold[$keyMap[$i]] ?? 0; $amount = $gold[$keyMap[$i] ?? -1] ?? 0;
echo "<td><font color=cyan>{$amount}</font></td>"; echo "<td><font color=cyan>{$amount}</font></td>";
} }
@@ -433,7 +442,7 @@ if ($str3) {
<tr align=center>"; <tr align=center>";
foreach (range(0, 15) as $i) { foreach (range(0, 15) as $i) {
$key = $keyMap[$i]; $key = $keyMap[$i] ?? -1;
echo " echo "
<td> <td>
<select size=1 id='target_{$key}' style=color:white;background-color:black;> <select size=1 id='target_{$key}' style=color:white;background-color:black;>
@@ -453,7 +462,7 @@ if ($str3) {
<tr align=center>"; <tr align=center>";
foreach (range(0, 15) as $i) { foreach (range(0, 15) as $i) {
$key = $keyMap[$i]; $key = $keyMap[$i] ?? -1;
echo " echo "
<td><input type=button class='submitBtn' data-target='{$key}' value=베팅! style=width:100%;color:white;background-color:black;></td>"; <td><input type=button class='submitBtn' data-target='{$key}' value=베팅! style=width:100%;color:white;background-color:black;></td>";
} }
+71 -21
View File
@@ -15,6 +15,7 @@ increaseRefresh("토너먼트", 1);
TurnExecutionHelper::executeAllCommand(); TurnExecutionHelper::executeAllCommand();
$me = $db->queryFirstRow('select no,tournament,con,turntime from general where owner=%i', $userID); $me = $db->queryFirstRow('select no,tournament,con,turntime from general where owner=%i', $userID);
$generalID = $session->generalID;
$admin = $gameStor->getValues(['tournament', 'phase', 'tnmt_msg', 'tnmt_type', 'develcost', 'tnmt_trig']); $admin = $gameStor->getValues(['tournament', 'phase', 'tnmt_msg', 'tnmt_type', 'develcost', 'tnmt_trig']);
@@ -25,34 +26,76 @@ if ($con >= 2) {
} }
switch ($admin['tnmt_type']) { switch ($admin['tnmt_type']) {
default: case convertTournamentType('전력전'):
throw new \RuntimeException('invalid tnmt_type'); $tnmt_type = "전력전";
case 0: $color = 'cyan';
$tnmt_type = "<font color=cyan>전력전</font>";
$tp = "total"; $tp = "total";
$tp2 = "종합"; $tp2 = "종합";
$tp3 = "total"; $tp3 = "total";
break; break;
case 1: case convertTournamentType('통솔전'):
$tnmt_type = "<font color=cyan>통솔전</font>"; $tnmt_type = "통솔전";
$color = 'cyan';
$tp = "leadership"; $tp = "leadership";
$tp2 = "통솔"; $tp2 = "통솔";
$tp3 = "leadership"; $tp3 = "leadership";
break; break;
case 2: case convertTournamentType('일기토'):
$tnmt_type = "<font color=cyan>일기토</font>"; $tnmt_type = "일기토";
$color = 'cyan';
$tp = "strength"; $tp = "strength";
$tp2 = "무력"; $tp2 = "무력";
$tp3 = "strength"; $tp3 = "strength";
break; break;
case 3: case convertTournamentType('설전'):
$tnmt_type = "<font color=cyan>설전</font>"; $tnmt_type = "설전";
$color = 'cyan';
$tp = "intel"; $tp = "intel";
$tp2 = "지력"; $tp2 = "지력";
$tp3 = "intel"; $tp3 = "intel";
break; break;
default:
throw new \RuntimeException('invalid tnmt_type');
} }
$bettingID = $gameStor->lastTournamentBettingID ?? 0;
if ($bettingID != 0) {
$betting = $bettingID != 0 ? new Betting($bettingID) : null;
$info = $betting->getInfo();
} else {
$info = getDummyBettingInfo($tnmt_type);
}
$myBet = [];
$globalBet = [];
if ($bettingID != 0) {
$betting = $bettingID != 0 ? new Betting($bettingID) : null;
$info = $betting->getInfo();
foreach ($db->queryAllLists(
'SELECT general_id, user_id, amount, betting_type FROM ng_betting WHERE betting_id = %i',
$bettingID
) as [$betGeneralID, $userID, $amount, $bettingTypeKey]) {
$bettingKey = Json::decode($bettingTypeKey)[0];
if ($betGeneralID == $generalID) {
$myBet[$bettingKey] = $amount;
}
if (key_exists($bettingKey, $globalBet)) {
$globalBet[$bettingKey] += $amount;
} else {
$globalBet[$bettingKey] = $amount;
}
}
} else {
$info = getDummyBettingInfo($tnmt_type);
}
$myBetTotal = array_sum($myBet);
$globalBetTotal = array_sum($globalBet);
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
@@ -209,7 +252,7 @@ switch ($admin['tnmt_type']) {
</tr> </tr>
<tr> <tr>
<td colspan=8 align=center> <td colspan=8 align=center>
<font color=white size=6><?= $tnmt_type ?> (<?= $str1 . $str2 . $str3 ?>)</font> <font color=white size=6><span style="color:<?= $color ?>"><?= $tnmt_type ?></span> (<?= $str1 . $str2 . $str3 ?>)</font>
</td> </td>
</tr> </tr>
<tr> <tr>
@@ -418,24 +461,31 @@ switch ($admin['tnmt_type']) {
echo " echo "
</tr>"; </tr>";
$globalBet = $db->queryFirstList('SELECT * FROM betting WHERE general_id = 0') ?? [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,];
$globalBet = array_splice($globalBet, -16);
$globalBetTotal = array_sum($globalBet);
$admin = $gameStor->getValues(['tournament', 'phase']); $admin = $gameStor->getValues(['tournament', 'phase']);
$bet = []; $bet = [];
for ($i = 0; $i < 16; $i++) { $gold = [];
if ($globalBet[$i] == 0) { $keyMap = [];
$bet[$i] = '∞'; foreach ($info->candidates as $key => $candidate) {
continue; $keyMap[$candidate->aux['idx']] = $key;
}
foreach ($globalBet as $key => $amount) {
if ($amount == 0) {
$bet[$key] = "∞";
$gold[$key] = 0;
} else {
$rewardRatio = round($globalBetTotal / $amount, 2);
$bet[$key] = $rewardRatio;
$gold[$key] = $rewardRatio * ($myBet[$key] ?? 0);
} }
$bet[$i] = round($globalBetTotal / $globalBet[$i], 2);
} }
echo " echo "
<tr align=center>"; <tr align=center>";
for ($i = 0; $i < 16; $i++) { foreach (range(0, 15) as $i) {
echo "<td><font color=skyblue>{$bet[$i]}</font></td>"; $amount = $bet[$keyMap[$i] ?? -1] ?? 0;
echo "<td><font color=skyblue>{$amount}</font></td>";
} }
echo " echo "
+2
View File
@@ -225,6 +225,8 @@ if($btn == "자동개최설정") {
finallyAll($admin['tnmt_type'], $admin['tournament'], $admin['phase']); finallyAll($admin['tnmt_type'], $admin['tournament'], $admin['phase']);
} elseif($btn == "배정") { } elseif($btn == "배정") {
final16set(); final16set();
$phase = 0;
startBetting($admin['tnmt_type'], 720);
} elseif($btn == "베팅마감") { } elseif($btn == "베팅마감") {
$dt = date("Y-m-d H:i:s", time() + 60); $dt = date("Y-m-d H:i:s", time() + 60);
$gameStor->tournament=7; $gameStor->tournament=7;
+25 -34
View File
@@ -380,29 +380,12 @@ function startTournament($auto, $type)
$gameStor->tnmt_time = (new \DateTimeImmutable())->add(new \DateInterval("PT{$unit}M"))->format('Y-m-d H:i:s'); $gameStor->tnmt_time = (new \DateTimeImmutable())->add(new \DateInterval("PT{$unit}M"))->format('Y-m-d H:i:s');
$gameStor->tournament = 1; $gameStor->tournament = 1;
$gameStor->tnmt_type = $type; $gameStor->tnmt_type = $type;
$gameStor->lastTournamentBettingID = 0;
$gameStor->phase = 0; $gameStor->phase = 0;
$db->update('general', [ $db->update('general', [
'tournament' => 0, 'tournament' => 0,
], true); ], true);
$db->update('betting', [
'bet0' => 0,
'bet1' => 0,
'bet2' => 0,
'bet3' => 0,
'bet4' => 0,
'bet5' => 0,
'bet6' => 0,
'bet7' => 0,
'bet8' => 0,
'bet9' => 0,
'bet10' => 0,
'bet11' => 0,
'bet12' => 0,
'bet13' => 0,
'bet14' => 0,
'bet15' => 0
], true);
$db->query('TRUNCATE TABLE tournament'); $db->query('TRUNCATE TABLE tournament');
$opener = $db->queryFirstField('SELECT `general`.`name` FROM `general` JOIN `nation` ON `general`.`nation` = `nation`.`nation` WHERE `general`.`officer_level` = 12 AND `nation`.`level` = 7 ORDER BY rand() LIMIT 1'); $opener = $db->queryFirstField('SELECT `general`.`name` FROM `general` JOIN `nation` ON `general`.`nation` = `nation`.`nation` WHERE `general`.`officer_level` = 12 AND `nation`.`level` = 7 ORDER BY rand() LIMIT 1');
@@ -429,6 +412,21 @@ function startTournament($auto, $type)
pushGlobalHistoryLog($history, $admin['year'], $admin['month']); pushGlobalHistoryLog($history, $admin['year'], $admin['month']);
} }
function getDummyBettingInfo(string $tnmt_type): BettingInfo
{
return new BettingInfo(
id: 0,
type: 'tournament',
name: $tnmt_type,
finished: true,
selectCnt: 1,
reqInheritancePoint: false,
openYearMonth: 0,
closeYearMonth: 0,
candidates: []
);
}
function startBetting($type, $unit) function startBetting($type, $unit)
{ {
$db = DB::db(); $db = DB::db();
@@ -449,24 +447,22 @@ function startBetting($type, $unit)
//어차피 강제로 닫을 것이므로 크게 신경쓰지 않는다. //어차피 강제로 닫을 것이므로 크게 신경쓰지 않는다.
$monthGap = floor(Util::valueFit($unit * 60, 3600) / ($turnterm * 60)) + 1;
$openYearMonth = Util::joinYearMonth($year, $month); $openYearMonth = Util::joinYearMonth($year, $month);
$closeYearMonth = $openYearMonth + $monthGap; $closeYearMonth = $openYearMonth + 120;
/** @var \sammo\DTO\SelectItem[] */ /** @var \sammo\DTO\SelectItem[] */
$candidates = []; $candidates = [];
$generalList = $db->query('SELECT no,npc,name,win,leadership,strength,intel,leadership+strength+intel as total from tournament where grp>=20 order by grp, grp_no LIMIT 16'); $generalList = $db->query('SELECT no,npc,name,win,leadership,strength,intel,leadership+strength+intel as total from tournament where grp>=20 order by grp, grp_no LIMIT 16');
foreach($generalList as $idx=>$general) { foreach ($generalList as $idx => $general) {
if($general['no'] <= 0){ if ($general['no'] <= 0) {
continue; continue;
} }
$general['idx'] = $idx; $general['idx'] = $idx;
$candidates[$general['no']] = new \sammo\DTO\SelectItem( $candidates[$general['no']] = new \sammo\DTO\SelectItem(
$general['name'], title: $general['name'],
"{$statName}: {$general[$statKey]}", info: "{$statName}: {$general[$statKey]}",
$general aux: $general
); );
} }
$candidateCnt = count($candidates); $candidateCnt = count($candidates);
@@ -491,14 +487,10 @@ function startBetting($type, $unit)
$npcList = $db->queryFirstColumn('SELECT no FROM general WHERE npc >= 2 AND gold >= (500 + %i)', $betGold); $npcList = $db->queryFirstColumn('SELECT no FROM general WHERE npc >= 2 AND gold >= (500 + %i)', $betGold);
$npcBet = []; $npcBet = [];
$betSum = [
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
];
$targetList = array_keys($candidates);
foreach ($npcList as $npcID) { foreach ($npcList as $npcID) {
$target = Util::randRangeInt(0, $candidateCnt - 1); $target = Util::choiceRandom($targetList);
$betSum[$target] += $betGold;
$npcBet[] = [$npcID, $target]; $npcBet[] = [$npcID, $target];
} }
@@ -1216,10 +1208,9 @@ function setRefund()
$bettingID = $gameStor->lastTournamentBettingID ?? 0; $bettingID = $gameStor->lastTournamentBettingID ?? 0;
if (!$bettingID == 0) { if (!$bettingID == 0) {
$betting = new Betting($bettingID); $betting = new Betting($bettingID);
if(!$betting->getInfo()->finished){ if (!$betting->getInfo()->finished) {
$betting->giveReward([-1]); $betting->giveReward([-1]);
} }
} }
-55
View File
@@ -1,55 +0,0 @@
<?php
namespace sammo;
include "lib.php";
include "func.php";
WebUtil::requireAJAX();
$betTarget = Util::getPost('target', 'int', -1);
$betGold = Util::getPost('amount', 'int', 0);
if ($betGold < 10 || $betGold > 1000) {
Json::die([
'result' => false,
'reason' => '올바르지 않은 입력입니다'
]);
}
//로그인 검사
$session = Session::requireGameLogin()->setReadOnly();
$userID = Session::getUserID();
$generalID = $session->generalID;
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
increaseRefresh("베팅", 1);
$tournament = $gameStor->tournament;
if ($tournament != 6) {
Json::die([
'result' => false,
'reason' => '베팅 기간이 아닙니다.'
]);
}
$bettingID = $gameStor->lastTournamentBettingID;
$betting = new Betting($bettingID);
try {
$betting->bet($generalID, $userID, [$betTarget], $betGold);
} catch (\Exception $e) {
Json::die([
'result' => false,
'reason' => $e->getMessage()
]);
}
Json::die([
'result' => true,
'reason' => 'SUCCESS'
]);
+13 -23
View File
@@ -4,39 +4,29 @@ import { setAxiosXMLHttpRequest } from '@util/setAxiosXMLHttpRequest';
import type { InvalidResponse } from '@/defs'; import type { InvalidResponse } from '@/defs';
import { convertFormData } from '@util/convertFormData'; import { convertFormData } from '@util/convertFormData';
import { unwrap_any } from '@util/unwrap_any'; import { unwrap_any } from '@util/unwrap_any';
import { SammoAPI } from './SammoAPI';
$(function($){ declare const staticValues: {
setAxiosXMLHttpRequest(); bettingID: number;
}
$('.submitBtn').on('click', async function(e){ $(function ($) {
$('.submitBtn').on('click', async function (e) {
e.preventDefault(); e.preventDefault();
const $this = $(this); const $this = $(this);
const target = parseInt($this.data('target')); const target = parseInt($this.data('target'));
const amount = parseInt(unwrap_any<string>($(`#target_${target}`).val())); const amount = parseInt(unwrap_any<string>($(`#target_${target}`).val()));
let result: InvalidResponse; try {
await SammoAPI.Betting.Bet({
try{ bettingID: staticValues.bettingID,
const response = await axios({ bettingType: [target],
url: 'j_betting.php', amount: amount,
responseType: 'json',
method: 'post',
data: convertFormData({
target: target,
amount: amount
})
}); });
result = response.data; } catch (e) {
}catch(e){
console.error(e); console.error(e);
alert(`에러: ${e}`); alert(`베팅을 실패했습니다: ${e}`);
location.reload();
return;
}
if(!result.result){
alert(`베팅을 실패했습니다: ${result.reason}`);
location.reload(); location.reload();
return; return;
} }