<?
include "lib.php";
include "func.php";
//로그인 검사
CheckLogin();
$connect = dbConn();
increaseRefresh($connect, "시뮬", 2);

$query = "select no,tournament,userlevel,con,turntime from general where user_id='$_SESSION[p_id]'";
$result = MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect),"");
$me = MYDB_fetch_array($result);

$query = "select * from game where no='1'";
$result = MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect),"");
$game = MYDB_fetch_array($result);

$con = checkLimit($me[userlevel], $me[con], $game[conlimit]);
if($con >= 2) { printLimitMsg($me[turntime]); exit(); }

if($me[userlevel] < 3) {
    echo "특별회원이 아닙니다.";
    exit();
}

$nationLevel = array(

);

$genPriv = array(
    array(1, '일반'),
    array(2, '시중'),
    array(3, '군사'),
    array(4, '태수'),
    array(5, '제3모사'),
    array(6, '제3장군'),
    array(7, '제2모사'),
    array(8, '제2장군'),
    array(9, '제1모사'),
    array(10, '제1장군'),
    array(11, '참모'),
    array(12, '군주'),
);

$dexInfos = array(
    array(0, 0, 'F-'),
    array(1, 2500, 'F'),
    array(2, 7500, 'F+'),
    array(3, 15000, 'E-'),
    array(4, 25000, 'E'),
    array(5, 37500, 'E+'),
    array(6, 52500, 'D-'),
    array(7, 70000, 'D'),
    array(8, 90000, 'D+'),
    array(9, 112500, 'C-'),
    array(10, 137500, 'C'),
    array(11, 165000, 'C+'),
    array(12, 195000, 'B-'),
    array(13, 227500, 'B'),
    array(14, 262500, 'B+'),
    array(15, 300000, 'A-'),
    array(16, 340000, 'A'),
    array(17, 382500, 'A+'),
    array(18, 427500, 'S-'),
    array(19, 475000, 'S'),
    array(20, 525000, 'S+'),
    array(21, 577500, 'SS-'),
    array(22, 632500, 'SS'),
    array(23, 690000, 'SS+'),
    array(24, 750000, 'SSS-'),
    array(25, 812500, 'SSS'),
    array(26, 877500, 'SSS+'),
    array(27, 945000, 'Z-'),
    array(28, 1015000, 'Z'),
    array(29, 1087500, 'Z+'),
    array(30, 1162500, '?')
);    

$armTypeInfo = array(
    array(0, '보병'),
    array(1, '청주병'),
    array(2, '수병'),
    array(3, '자객병'),
    array(4, '근위병'),
    array(5, '등갑병'),
    array(10, '궁병'),
    array(11, '궁기병'),
    array(12, '연노병'),
    array(13, '강궁병'),
    array(14, '석궁병'),
    array(20, '기병'),
    array(21, '백마병'),
    array(22, '중장기병'),
    array(23, '돌격기병'),
    array(24, '철기병'),
    array(25, '수렵기병'),
    array(26, '맹수병'),
    array(27, '호표기병'),
    array(30, '귀병'),
    array(31, '신귀병'),
    array(32, '백귀병'),
    array(33, '흑귀병'),
    array(34, '악귀병'),
    array(35, '남귀병'),
    array(36, '황귀병'),
    array(37, '천귀병'),
    array(38, '마귀병'),
    array(40, '정란'),
    array(41, '충차'),
    array(42, '벽력거'),
    array(43, '목우'),
);

function findInvList($niddle, $target, $keyIdx=0, $isExactKey=false){
    //바이너리 서치 안해
    foreach($target as $idx => $values){
        
        if($isExactKey && $values[$keyIdx] == $item){
            return values;
        }


        if(!$isExactKey && $item < $values[$keyIdx]){
            return $target[$idx - 1];
        }
    }

    //이건 일부러.
    return $target[0];
}

$mydeathnumSum = 0;
$mykillnumSum = 0;
$expSum = 0;
$ricingSum = 0;
$expSum2 = 0;
$ricingSum2 = 0;

if($isgen == "장수평균" || $isgen == "성벽평균") {
    $simulCount = 1000;
} else {
    $simulCount = 1;
}

if($isgen == "장수공격" || $isgen == "성벽공격" || $isgen == "장수평균" || $isgen == "성벽평균") {
    $msg2 = "";
    for($i=0; $i < $simulCount; $i++) {
        $general[leader] = $leader1;
        $general[power] = $power1;
        $general[intel] = $intel1;
        $general[crewtype] = $type1;
        $general[crew] = $crew1;
        $general[train] = $train1;
        $general[atmos] = $atmos1;
        $general[level] = $level1;
        $general[explevel] = $explevel1;
        $general[dex0] = $dex10;
        $general[dex10] = $dex110;
        $general[dex20] = $dex120;
        $general[dex30] = $dex130;
        $general[dex40] = $dex140;

        $oppose[leader] = $leader2;
        $oppose[power] = $power2;
        $oppose[intel] = $intel2;
        $oppose[crewtype] = $type2;
        $oppose[crew] = $crew2;
        $oppose[train] = $train2;
        $oppose[atmos] = $atmos2;
        $oppose[level] = $level2;
        $oppose[explevel] = $explevel2;
        $oppose[dex0] = $dex20;
        $oppose[dex10] = $dex210;
        $oppose[dex20] = $dex220;
        $oppose[dex30] = $dex230;
        $oppose[dex40] = $dex240;

        $city[def] = $def;
        $city[wall] = $wall;

        if($isgen == "장수공격" || $isgen == "장수평균") {
            $opposecount = 1;
        } else {
            $opposecount = 0;
        }

        $warphase = getRate($game, $general[crewtype], "spd");   //병종간 페이즈 수 얻기

        // 우선 스케일링
        $city[def] *= 10;
        $city[wall] *= 10;

        $msg = "";
        $msg .= "<C>●</>1월:공격장수가 <R>공격</>합니다.<br>";

        $exp = 0;   //병사 소진 시킨 만큼
        $opexp = 0;
        $exp2 = 1;  //능력경험치
        $phase = 0;
        while($phase < $warphase) {
            // 장수가 없어서 도시 공격
            if($opposecount == 0) {
                $msg .= "<C>●</>".getTypename($general[crewtype])."(으)로 성을 <M>공격</>합니다.<br>";

                $mykillnum = 0; $mydeathnum = 0;
                while($phase < $warphase) {
                    $phase++;
                    $myAtt = getAtt($game, $general, $tech1,0);
                    $myDef = getDef($game, $general, $tech1);
                    $cityAtt = getCityAtt($city);
                    $cityDef = getCityDef($city);

                    // 감소할 병사 수
                    $cityCrew = $_armperphase + $myAtt - $cityDef;
                    $myCrew = $_armperphase + $cityAtt - $myDef;
                    $cityweight = $myAtt - $cityDef;
                    $myweight = $cityAtt - $myDef;

                    //훈련 사기따라
                    $myCrew = getCrew($myCrew, $atmos3, $general[train]);
                    $cityCrew = getCrew($cityCrew, $general[atmos], $train3);
                    //숙련도 따라
                    $genDexAtt = getGenDex($general, $general[crewtype]);
                    $genDexDef = getGenDex($general, 40);
                    $cityCrew *= getDexLog($genDexAtt, ($train3-60)*7200);
                    $myCrew *= getDexLog(($atmos3-60)*7200, $genDexDef);

                    $avoid = 1;
                    // 병종간 특성
                    if(floor($general[crewtype]/10) == 3) {   // 귀병
                        $int = $general[intel] + getBookEff($general[book]);
                        if($general[crewtype] == 30) {
                            $ratio2 = $int * 5;   // 0~500 즉 50%
                        } elseif($general[crewtype] == 31) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        } elseif($general[crewtype] == 32) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        } elseif($general[crewtype] == 33) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        } elseif($general[crewtype] == 34) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        } elseif($general[crewtype] == 35) {
                            $ratio2 = $int * 8;   // 0~800 즉 80%
                        } elseif($general[crewtype] == 36) {
                            $ratio2 = $int * 8;   // 0~800 즉 80%
                        } elseif($general[crewtype] == 37) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        } elseif($general[crewtype] == 38) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        }
                        $ratio = rand() % 1000; // 0~999
                        if($ratio <= $ratio2) {
                            $ratio = rand() % 100; // 0~99
                            if($ratio >= 30) {
                                $type = rand() % 3;
                                switch($type) {
                                case 0:
                                    $msg .= "<C>●</><D>급습</>을 <C>성공</>했다!<br>";
                                    $cityCrew *= 1.2;
                                    break;
                                case 1:
                                    $msg .= "<C>●</><D>위보</>를 <C>성공</>했다!<br>";
                                    $cityCrew *= 1.4;
                                    break;
                                case 2:
                                    $msg .= "<C>●</><D>혼란</>을 <C>성공</>했다!<br>";
                                    $cityCrew *= 1.6;
                                    break;
                                }
                            } else {
                                $type = rand() % 3;
                                switch($type) {
                                case 0:
                                    $msg .= "<C>●</><D>급습</>을 <R>실패</>했다!<br>";
                                    $cityCrew /= 1.2;
                                    $myCrew *= 1.2;
                                    break;
                                case 1:
                                    $msg .= "<C>●</><D>위보</>를 <R>실패</>했다!<br>";
                                    $cityCrew /= 1.4;
                                    $myCrew *= 1.4;
                                    break;
                                case 2:
                                $msg .= "<C>●</><D>혼란</>을 <R>실패</>했다!<br>";
                                $cityCrew /= 1.6;
                                $myCrew *= 1.6;
                                    break;
                                }
                            }
                        }
                    } elseif($general[crewtype] == 40) { // 정란
                        $cityCrew = $cityCrew * 1.5;
                    } elseif($general[crewtype] == 41) { // 충차
                        $cityCrew = $cityCrew * 2.0;
                    } elseif($general[crewtype] == 42) { // 벽력거
                        $cityCrew = $cityCrew * 1.5;
                    }
                    //군주, 참모, 장군 공격 보정 5%
                    if($general[level] == 12 || $general[level] == 11 || $general[level] == 10 || $general[level] == 8 || $general[level] == 6) {
                        $cityCrew = $cityCrew * 1.05;
                    }
                    //레벨 보정
                    $cityCrew = $cityCrew * (100 + $general[explevel]/6)/100;

                    //크리
                    $rd = rand() % 100; // 0 ~ 99
                    $ratio = CriticalRatio3($general[leader], $general[power], $general[intel], $general['crewtype']);
                    if($ratio >= $rd && $avoid == 1) {
                        $msg .= "<C>●</><C>필살</>공격!</><br>";
                        $cityCrew = CriticalScore2($cityCrew);
                        $avoid = 0;
                    }
                    //회피
                    $ratio = rand() % 100; // 0 ~ 99
                    $ratio2 = getRate($game, $general[crewtype], "avd");   //회피율
                    $ratio2 = round($ratio2 * $general['train'] / 100); //훈련 반영
                    if($ratio < $ratio2 && $avoid == 1) {
                        $msg .= "<C>●</><C>회피</>했다!</><br>";
                        $myCrew /= 10; // 10%만 소모
                        $avoid = 0;
                    }

                    //랜타추가
                    $cityCrew *= (rand() % 21 + 90)/100; // 90~110%
                    $myCrew *= (rand() % 21 + 90)/100; // 90~110%

                    $general[crew] -= round($myCrew);
                    $city[def] -= round($cityCrew);
                    $city[wall] -= round($cityCrew);

                    $tempMyCrew = $myCrew; $tempCityCrew = $cityCrew;
                    $tempGeneralCrew = $general[crew]; $tempCityDef = $city[def];

                    if($city[wall] <= 0) { $city[wall] = 0; }

                    if($city[def] < 0) {
                        $offset = round($tempCityDef*$tempMyCrew/$tempCityCrew);
                        $myCrew += $offset;
                        $general[crew] -= $offset;
                        $cityCrew += $tempCityDef;
                        $city[def] = 0;
                    }
                    if($general[crew] < 0) {
                        $offset = round($tempGeneralCrew*$tempCityCrew/$tempMyCrew);
                        $cityCrew += $offset;
                        $city[def] -= $offset;
                        $myCrew += $tempGeneralCrew;
                        $general[crew] = 0;
                    }

                    $exp += $cityCrew;
                    $opexp += $myCrew;
                    $general[crew] = round($general[crew]);
                    $cityCrew = round($cityCrew);
                    $myCrew = round($myCrew);
                    $myAtt = round($myAtt, 2);
                    $myDef = round($myDef, 2);
                    $cityAtt = round($cityAtt, 2);
                    $cityDef = round($cityDef, 2);
                    $msg .= "<C>●</> $phase : <Y1>【공격장수】</> <C>$general[crew] (-$myCrew)</> VS <C>$city[def] (-$cityCrew)</> <Y1>【성벽】</><br>";

                    $mykillnum += $cityCrew; $mydeathnum += $myCrew;

                    if($city[def] <= 0) { break; }
                    if($general[crew] <= 0) { break; }
                }

                // 도시쌀 소모 계산
                $opexp = round($opexp / 50);
                $rice = round($opexp * 4 * getCrewtypeRice($game, 0, 0) * ($train3/100 - 0.2));

                //원래대로 스케일링
                $city[def] = round($city[def] / 10);
                $city[wall] = round($city[wall] / 10);
                //내정 감소
                $dec = round($cityCrew / 10);
                $city[agri] -= $dec;
                $city[comm] -= $dec;
                $city[secu] -= $dec;
                if($city[agri] < 0) { $city[agri] = 0; }
                if($city[comm] < 0) { $city[comm] = 0; }
                if($city[secu] < 0) { $city[secu] = 0; }
                $msg .= "<S>★</>병사수 변화 : <C>-$mydeathnum</> vs <C>-$mykillnum</><br>";
                $msg .= "<R>★</>【성벽】내정 감소량 : $dec 【성벽】쌀 소모 : $rice<br>";

//                $msg2 .= "<S>★</>병사수 변화 : <C>-$mydeathnum</> vs <C>-$mykillnum</>　　　";
//                $msg2 .= "<R>★</>【성벽】내정 감소량 : $dec 【성벽】쌀 소모 : $rice<br>";

                if($city[def] == 0 || $general[crew] == 0) {
                    break;
                }
            // 장수 대결
            } else {
                $msg .= "<C>●</>".getTypename($general[crewtype])."(으)로 <Y>수비장수</>의 ".getTypename($oppose[crewtype])."(을)를 공격합니다.<br>";

                $mykillnum = 0; $mydeathnum = 0;
                while($phase < $warphase) {
                    $phase++;

                    $myAtt = getAtt($game, $general, $tech1,0);
                    $myDef = getDef($game, $general, $tech1);
                    $opAtt = getAtt($game, $oppose, $tech2,0);
                    $opDef = getDef($game, $oppose, $tech2);
                    // 감소할 병사 수
                    $myCrew = $_armperphase + $opAtt - $myDef;
                    $opCrew = $_armperphase + $myAtt - $opDef;
                    //훈련 사기따라
                    $myCrew = getCrew($myCrew, $oppose[atmos], $general[train]);
                    $opCrew = getCrew($opCrew, $general[atmos], $oppose[train]);
                    //숙련도 따라
                    $genDexAtt = getGenDex($general, $general[crewtype]);
                    $genDexDef = getGenDex($general, $oppose[crewtype]);
                    $oppDexAtt = getGenDex($oppose, $oppose[crewtype]);
                    $oppDexDef = getGenDex($oppose, $general[crewtype]);
                    $opCrew *= getDexLog($genDexAtt, $oppDexDef);
                    $myCrew *= getDexLog($oppDexAtt, $genDexDef);

                    $myAvoid = 1;
                    $opAvoid = 1;
                    // 병종간 특성
                    if(floor($general[crewtype]/10) == 3) {   // 귀병
                        $int = $general[intel] + getBookEff($general[book]);
                        if($general[crewtype] == 30) {
                            $ratio2 = $int * 5;   // 0~500 즉 50%
                        } elseif($general[crewtype] == 31) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        } elseif($general[crewtype] == 32) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        } elseif($general[crewtype] == 33) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        } elseif($general[crewtype] == 34) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        } elseif($general[crewtype] == 35) {
                            $ratio2 = $int * 8;   // 0~800 즉 80%
                        } elseif($general[crewtype] == 36) {
                            $ratio2 = $int * 8;   // 0~800 즉 80%
                        } elseif($general[crewtype] == 37) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        } elseif($general[crewtype] == 38) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        }
                        $ratio = rand() % 1000; // 0~999
                        if($ratio <= $ratio2) {
                            $ratio = rand() % 100;
                            if($ratio >= 30) {
                                $type = rand() % 5; // 0~4
                                switch($type) {
                                case 0:
                                    $msg .= "<C>●</><D>위보</>를 <C>성공</>했다!<br>";
                                    $opCrew *= 1.2;
                                    break;
                                case 1:
                                    $msg .= "<C>●</><D>매복</>을 <C>성공</>했다!<br>";
                                    $opCrew *= 1.4;
                                    break;
                                case 2:
                                    $msg .= "<C>●</><D>반목</>을 <C>성공</>했다!<br>";
                                    $opCrew *= 1.6;
                                    break;
                                case 3:
                                    $msg .= "<C>●</><D>화계</>를 <C>성공</>했다!<br>";
                                    $opCrew *= 1.8;
                                    break;
                                case 4:
                                    $msg .= "<C>●</><D>혼란</>을 <C>성공</>했다!<br>";
                                    $opCrew *= 2.0;
                                    break;
                                }
                            } else {
                                $type = rand() % 5; // 0~4
                                switch($type) {
                                case 0:
                                    $msg .= "<C>●</><D>위보</>를 <R>실패</>했다!<br>";
                                    $opCrew /= 1.1;
                                    $myCrew *= 1.1;
                                    break;
                                case 1:
                                    $msg .= "<C>●</><D>매복</>을 <R>실패</>했다!<br>";
                                    $opCrew /= 1.2;
                                    $myCrew *= 1.2;
                                    break;
                                case 2:
                                    $msg .= "<C>●</><D>반목</>을 <R>실패</>했다!<br>";
                                    $opCrew /= 1.3;
                                    $myCrew *= 1.3;
                                    break;
                                case 3:
                                    $msg .= "<C>●</><D>화계</>를 <R>실패</>했다!<br>";
                                    $opCrew /= 1.4;
                                    $myCrew *= 1.4;
                                    break;
                                case 4:
                                    $msg .= "<C>●</><D>혼란</>을 <R>실패</>했다!<br>";
                                    $opCrew /= 1.5;
                                    $myCrew *= 1.5;
                                    break;
                                }
                            }
                        }
                    }

                    // 상대 장수 병종간 특성
                    if(floor($oppose[crewtype]/10) == 3) {   // 귀병
                        $int = $oppose[intel] + getBookEff($oppose[book]);
                        if($oppose[crewtype] == 30) {
                            $ratio2 = $int * 5;   // 0~500 즉 50%
                        } elseif($oppose[crewtype] == 31) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        } elseif($oppose[crewtype] == 32) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        } elseif($oppose[crewtype] == 33) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        } elseif($oppose[crewtype] == 34) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        } elseif($oppose[crewtype] == 35) {
                            $ratio2 = $int * 8;   // 0~800 즉 80%
                        } elseif($oppose[crewtype] == 36) {
                            $ratio2 = $int * 8;   // 0~800 즉 80%
                        } elseif($oppose[crewtype] == 37) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        } elseif($oppose[crewtype] == 38) {
                            $ratio2 = $int * 6;   // 0~600 즉 60%
                        }
                        $ratio = rand() % 1000; // 0~999
                        if($ratio <= $ratio2) {
                            $ratio = rand() % 100;
                            if($ratio >= 30) {
                                $type = rand() % 5; // 0~4
                                switch($type) {
                                case 0:
                                    $msg .= "<C>●</><D>위보</>에 당했다!<br>";
                                    $myCrew *= 1.2;
                                    break;
                                case 1:
                                    $msg .= "<C>●</><D>매복</>에 당했다!<br>";
                                    $myCrew *= 1.4;
                                    break;
                                case 2:
                                    $msg .= "<C>●</><D>반목</>에 당했다!<br>";
                                    $myCrew *= 1.6;
                                    break;
                                case 3:
                                    $msg .= "<C>●</><D>화계</>에 당했다!<br>";
                                    $myCrew *= 1.8;
                                    break;
                                case 4:
                                    $msg .= "<C>●</><D>혼란</>에 당했다!<br>";
                                    $myCrew *= 2.0;
                                    break;
                                }
                            } else {
                                $type = rand() % 5; // 0~4
                                switch($type) {
                                case 0:
                                    $msg .= "<C>●</><D>위보</>를 간파했다!<br>";
                                    $myCrew /= 1.1;
                                    $opCrew *= 1.1;
                                    break;
                                case 1:
                                    $msg .= "<C>●</><D>매복</>을 간파했다!<br>";
                                    $myCrew /= 1.2;
                                    $opCrew *= 1.2;
                                    break;
                                case 2:
                                    $msg .= "<C>●</><D>반목</>을 간파했다!<br>";
                                    $myCrew /= 1.3;
                                    $opCrew *= 1.3;
                                    break;
                                case 3:
                                    $msg .= "<C>●</><D>화계</>를 간파했다!<br>";
                                    $myCrew /= 1.4;
                                    $opCrew *= 1.4;
                                    break;
                                case 4:
                                    $msg .= "<C>●</><D>혼란</>을 간파했다!<br>";
                                    $myCrew /= 1.5;
                                    $opCrew *= 1.5;
                                    break;
                                }
                            }
                        }
                    }

                    if($oppose[crewtype] == 43) { // 목우
                        $r = 0;
                        $r += $oppose[atmos];
                        $r += $oppose[train];
                        $ratio = rand() % 400;  // 최대 50% 저지
                        if($ratio < $r && $opAvoid == 1) {
                            $msg .= "<C>●</><R>저지</>당했다!</><br>";
                            $opAvoid = 0;
                            continue;
                        }
                    }

                    // my 입장 상성
                    // 보병계열 > 궁병계열
                    if(floor($general[crewtype]/10) == 0 && floor($oppose[crewtype]/10) == 1) {
                        $myCrew *= 0.8;
                        $opCrew *= 1.2;
                    }
                    // 궁병계열 > 기병계열
                    if(floor($general[crewtype]/10) == 1 && floor($oppose[crewtype]/10) == 2) {
                        $myCrew *= 0.8;
                        $opCrew *= 1.2;
                    }
                    // 기병계열 > 보병계열
                    if(floor($general[crewtype]/10) == 2 && floor($oppose[crewtype]/10) == 0) {
                        $myCrew *= 0.8;
                        $opCrew *= 1.2;
                    }
                    // 차병계열
                    if(floor($general[crewtype]/10) == 4) {
                        $myCrew *= 1.2;
                        $opCrew *= 0.8;
                    }

                    // op 입장 상성
                    // 보병계열 > 궁병계열
                    if(floor($oppose[crewtype]/10) == 0 && floor($general[crewtype]/10) == 1) {
                        $opCrew *= 0.8;
                        $myCrew *= 1.2;
                    }
                    // 궁병계열 > 기병계열
                    if(floor($oppose[crewtype]/10) == 1 && floor($general[crewtype]/10) == 2) {
                        $opCrew *= 0.8;
                        $myCrew *= 1.2;
                    }
                    // 기병계열 > 보병계열
                    if(floor($oppose[crewtype]/10) == 2 && floor($general[crewtype]/10) == 0) {
                        $opCrew *= 0.8;
                        $myCrew *= 1.2;
                    }
                    // 차병계열
                    if(floor($oppose[crewtype]/10) == 4) {
                        $opCrew *= 1.2;
                        $myCrew *= 0.8;
                    }

                    //군주, 참모, 장군 공격 보정 5%
                    if($general[level] == 12 || $general[level] == 11 || $general[level] == 10 || $general[level] == 8 || $general[level] == 6) {
                        $opCrew = $opCrew * 1.05;
                    }
                    //상대장수 관직 보정
                    //군주, 참모, 모사 방어 보정 5%
                    if($oppose[level] == 12 || $oppose[level] == 11 || $oppose[level] == 9 || $oppose[level] == 7 || $oppose[level] == 5) {
                        $opCrew = $opCrew * 0.95;
                    } elseif($oppose[level] == 4 && $oppose[no] == $city[gen1]) { // 태수 보정
                        $opCrew = $opCrew * 0.95;
                    } elseif($oppose[level] == 3 && $oppose[no] == $city[gen2]) { // 군사 보정
                        $opCrew = $opCrew * 0.95;
                    } elseif($oppose[level] == 2 && $oppose[no] == $city[gen3]) { // 시중 보정
                        $opCrew = $opCrew * 0.95;
                    }

                    //레벨 보정
                    $myCrew = $myCrew * ((100 - $general[explevel]/3)/100);
                    $opCrew = $opCrew / ((100 - $general[explevel]/3)/100);
                    $myCrew = $myCrew / ((100 -  $oppose[explevel]/3)/100);
                    $opCrew = $opCrew * ((100 -  $oppose[explevel]/3)/100);

                    //크리
                    $rd = rand() % 100; // 0 ~ 99
                    $ratio = CriticalRatio3($general[leader], $general[power], $general[intel], $general['crewtype']);
                    if($ratio >= $rd && $myAvoid == 1) {
                        $msg .= "<C>●</><C>필살</>공격!</><br>";
                        $opCrew = CriticalScore2($opCrew);
                        $myAvoid = 0;
                    }
                    //크리
                    $rd = rand() % 100; // 0 ~ 99
                    $ratio = CriticalRatio3($oppose[leader], $oppose[power], $oppose[intel], $oppose['crewtype']);
                    if($ratio >= $rd && $opAvoid == 1) {
                        $msg .= "<C>●</>상대의 <R>필살</>공격!</><br>";
                        $myCrew = CriticalScore2($myCrew);
                        $opAvoid = 0;
                    }
                    //회피
                    $ratio = rand() % 100; // 0 ~ 99
                    $ratio2 = getRate($game, $general[crewtype], "avd");   //회피율
                    $ratio2 = round($ratio2 * $general['train'] / 100); //훈련 반영
                    if($ratio < $ratio2 && $myAvoid == 1) {
                        $msg .= "<C>●</><C>회피</>했다!</><br>";
                        $myCrew /= 10; // 10%만 소모
                        $myAvoid = 0;
                    }
                    //회피
                    $ratio = rand() % 100; // 0 ~ 99
                    $ratio2 = getRate($game, $oppose[crewtype], "avd");   //회피율
                    $ratio2 = round($ratio2 * $oppose['train'] / 100); //훈련 반영
                    if($ratio < $ratio2 && $opAvoid == 1) {
                        $msg .= "<C>●</>상대가 <R>회피</>했다!</><br>";
                        $opCrew /= 10; // 10%만 소모
                        $opAvoid = 0;
                    }

                    //랜타추가
                    $opCrew *= (rand() % 21 + 90)/100; // 90~110%
                    $myCrew *= (rand() % 21 + 90)/100; // 90~110%

                    $general[crew] -= round($myCrew);
                    $oppose[crew] -= round($opCrew);
                    $tempMyCrew = $myCrew; $tempOpCrew = $opCrew;
                    $tempGeneralCrew = $general[crew]; $tempOpposeCrew = $oppose[crew];
                    if($general[crew] <= 0 && $oppose[crew] <= 0) {
                        $r1 = $tempGeneralCrew / $tempMyCrew;
                        $r2 = $tempOpposeCrew / $tempOpCrew;

                        if($r1 > $r2) {
                            $offset = round($tempOpposeCrew*$tempMyCrew/$tempOpCrew);
                            $myCrew += $offset;
                            $general[crew] -= $offset;
                            $opCrew += $tempOpposeCrew;
                            $oppose[crew] = 0;
                        } else {
                            $offset = round($tempGeneralCrew*$tempOpCrew/$tempMyCrew);
                            $opCrew += $offset;
                            $oppose[crew] -= $offset;
                            $myCrew += $tempGeneralCrew;
                            $general[crew] = 0;
                        }
                    } elseif($general[crew] * $oppose[crew] <= 0) {
                        if($oppose[crew] < 0) {
                            $offset = round($tempOpposeCrew*$tempMyCrew/$tempOpCrew);
                            $myCrew += $offset;
                            $general[crew] -= $offset;
                            $opCrew += $tempOpposeCrew;
                            $oppose[crew] = 0;
                        }
                        if($general[crew] < 0) {
                            $offset = round($tempGeneralCrew*$tempOpCrew/$tempMyCrew);
                            $opCrew += $offset;
                            $oppose[crew] -= $offset;
                            $myCrew += $tempGeneralCrew;
                            $general[crew] = 0;
                        }
                    }

                    $exp += $opCrew;
                    $opexp += $myCrew;
                    $general[crew] = round($general[crew]);
                    $oppose[crew] = round($oppose[crew]);
                    $myCrew = round($myCrew);
                    $opCrew = round($opCrew);
                    $myAtt = round($myAtt, 2);
                    $myDef = round($myDef, 2);
                    $opAtt = round($opAtt, 2);
                    $opDef = round($opDef, 2);
                    $msg .= "<C>●</> $phase : <Y1>【공격장수】</> <C>$general[crew] (-$myCrew)</> VS <C>$oppose[crew] (-$opCrew)</> <Y1>【수비장수】</><br>";

                    $mykillnum += $opCrew; $mydeathnum += $myCrew;

                    if($oppose[crew] <= 0) { break; }
                    if($general[crew] <= 0) { break; }
                }

                $msg .= "<S>★</>병사수 변화 : <C>-$mydeathnum</> vs <C>-$mykillnum</><br>";
//                $msg2 .= "<S>★</>병사수 변화 : <C>-$mydeathnum</> vs <C>-$mykillnum</>　　　";
            }
        }

        // 공헌, 명성 상승
        $exp = round($exp / 50);
        $ricing = ($exp * 5 * getCrewtypeRice($game, $general[crewtype], $tech1));
        $msg .= "★ 【공격장수】공헌 상승 : $exp 쌀 소비 : {$exp}x5x".getCrewtypeRice($game, $general[crewtype], $tech1)." = $ricing<br>";
//        $msg2 .= "★ 【공격장수】공헌 상승 : $exp 쌀 소비 : {$exp}x5x".getCrewtypeRice($game, $general[crewtype], $tech1)." = $ricing<br>";

        $msg = ConvertLog($msg, 1);

        $mydeathnumSum += $mydeathnum;
        $mykillnumSum += $mykillnum;
        $expSum += $exp;
        $ricingSum += $ricing;
        $expSum2 += $dec;
        $ricingSum2 += $rice;
    }

    $mydeathnumSum /= $simulCount;
    $mykillnumSum /= $simulCount;
    $expSum /= $simulCount;
    $ricingSum /= $simulCount;
    $expSum2 /= $simulCount;
    $ricingSum2 /= $simulCount;
    if($isgen == "성벽평균") {
        $msg2 .= "{$simulCount}회 평균<br>";
        $msg2 .= "<S>★</>병사수 변화 : <C>-$mydeathnumSum</> vs <C>-$mykillnumSum</>　　　";
        $msg2 .= "<R>★</>【성벽】내정 감소량 : $expSum2 【성벽】쌀 소모 : $ricingSum2<br>";
        $msg2 .= "★ 【공격장수】공헌 상승 : $expSum 쌀 소비 : {$expSum}x5x".getCrewtypeRice($game, $general[crewtype], $tech1)." = $ricingSum<br>";
    } elseif($isgen == "장수평균") {
        $msg2 .= "{$simulCount}회 평균<br>";
        $msg2 .= "<S>★</>병사수 변화 : <C>-$mydeathnumSum</> vs <C>-$mykillnumSum</>　　　";
        $msg2 .= "★ 【공격장수】공헌 상승 : $expSum 쌀 소비 : {$expSum}x5x".getCrewtypeRice($game, $general[crewtype], $tech1)." = $ricingSum<br>";
    }

    $msg2 = ConvertLog($msg2, 1);
} else {
    $leader1 = 70;
    $power1 = 70;
    $intel1 = 10;
    $type1 = 0;
    $crew1 = 7000;
    $train1 = 100;
    $atmos1 = 100;
    $level1 = 1;
    $explevel1 = 20;

    $leader2 = 70;
    $power2 = 70;
    $intel2 = 10;
    $type2 = 0;
    $crew2 = 7000;
    $train2 = 100;
    $atmos2 = 100;
    $level2 = 1;
    $explevel2 = 20;

    $def = 7000;
    $wall = 7000;
    $train3 = $game[city_rate];
    $atmos3 = $game[city_rate];
}

if(!isset($level1)) $level1=0;
if(!isset($level2)) $level2=0;

if(!isset($type1)) $type1=0;
if(!isset($type2)) $type2=0;

$tch1 = isset($tech1)?min(max(0, floor($tech1/1000)), 13):0;
$tch2 = isset($tech2)?min(max(0, floor($tech2/1000)), 13):0;

$dx10 = findInvList(isset($dex10)?$dex10:0, $dexInfos, 1, false)[0];
$dx110 = findInvList(isset($dex110)?$dex110:0, $dexInfos, 1, false)[0];
$dx120 = findInvList(isset($dex120)?$dex120:0, $dexInfos, 1, false)[0];
$dx130 = findInvList(isset($dex130)?$dex130:0, $dexInfos, 1, false)[0];
$dx140 = findInvList(isset($dex140)?$dex140:0, $dexInfos, 1, false)[0];

$dx20 = findInvList(isset($dex20)?$dex20:0, $dexInfos, 1, false)[0];
$dx210 = findInvList(isset($dex210)?$dex210:0, $dexInfos, 1, false)[0];
$dx220 = findInvList(isset($dex220)?$dex220:0, $dexInfos, 1, false)[0];
$dx230 = findInvList(isset($dex230)?$dex230:0, $dexInfos, 1, false)[0];
$dx240 = findInvList(isset($dex240)?$dex240:0, $dexInfos, 1, false)[0];

?>

<html>
<head>
<meta HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=utf-8'>
<title>전투시뮬레이션</title>
<link rel=stylesheet href=stylesheet.php type=text/css>
<?php require('analytics.php'); ?>
</head>

<body oncontextmenu='return false'>
<form method=post action=_simul.php>
<table align=center width=1000 border=1 cellspacing=0 cellpadding=0 bordercolordark=gray bordercolorlight=black style=font-size:13;word-break:break-all; id=bg0>
    <tr id=bg1>
        <td>공격장수</td>
        <td>상대장수</td>
        <td>상대성벽</td>
    </tr>
    <tr>
        <td>관직
            <select name=level1 size=1>
<?php foreach($genPriv as $gen): ?>
                <option <?=($level1==$gen[0])?'selected=selected':''?> value=<?=$gen[0]?>><?=$gen[1]?></option>
<?php endforeach; ?>
            </select>
        </td>
        <td>관직
            <select name=level2 size=1>
<?php foreach($genPriv as $gen): ?>
                <option <?=($level2==$gen[0])?'selected=selected':''?> value=<?=$gen[0]?>><?=$gen[1]?></option>
<?php endforeach; ?>
            </select>
        </td>
        <td>-</td>
    <tr>
        <td>Lv <input size=2 maxlength=2 name=explevel1 value=<?=$explevel1?>></td>
        <td>Lv <input size=2 maxlength=2 name=explevel2 value=<?=$explevel2?>></td>
        <td>-</td>
    </tr>
    <tr>
        <td>통솔 <input size=3 maxlength=3 name=leader1 value=<?=$leader1?>></td>
        <td>통솔 <input size=3 maxlength=3 name=leader2 value=<?=$leader2?>></td>
        <td>-</td>
    </tr>
    <tr>
        <td>무력 <input size=3 maxlength=3 name=power1 value=<?=$power1?>></td>
        <td>무력 <input size=3 maxlength=3 name=power2 value=<?=$power2?>></td>
        <td>-</td>
    </tr>
    <tr>
        <td>지력 <input size=3 maxlength=3 name=intel1 value=<?=$intel1?>></td>
        <td>지력 <input size=3 maxlength=3 name=intel2 value=<?=$intel2?>></td>
        <td>-</td>
    </tr>
    <tr>
        <td>병종
            <select name=type1 size=1>
<?php foreach($armTypeInfo as $armType): ?>
    <?php if($armType[0] % 10 == 0): ?>
        <?php if($armType[0]!=0): ?>
            </optgroup>
        <?php endif; ?>
            <optgroup label='<?=$armType[1]?>'>
    <?php endif; ?>
                <option <?=($type1==$armType[0])?'selected="seletected"':''?> value='<?=$armType[0]?>'><?=$armType[1]?></option>
<?php endforeach; ?>
            </optgroup>
            </select>
        </td>

        <td>병종
            <select name=type2 size=1>
            <?php foreach($armTypeInfo as $armType): ?>
    <?php if($armType[0] % 10 == 0): ?>
        <?php if($armType[0]!=0): ?>
            </optgroup>
        <?php endif; ?>
            <optgroup label='<?=$armType[1]?>'>
    <?php endif; ?>
                <option <?=($type2==$armType[0])?'selected="seletected"':''?> value='<?=$armType[0]?>'><?=$armType[1]?></option>
<?php endforeach; ?>
            </optgroup>
            </select>
        </td>
        <td>성벽 <input size=4 maxlength=4 name=wall value=<?=$wall;?>></td>
    </tr>
    <tr>
        <td>병력 <input size=5 maxlength=5 name=crew1 value=<?=$crew1;?>></td>
        <td>병력 <input size=5 maxlength=5 name=crew2 value=<?=$crew2;?>></td>
        <td>수비 <input size=4 maxlength=4 name=def value=<?=$def;?>></td>
    </tr>
    <tr>
        <td>훈련 <input size=3 maxlength=3 name=train1 value=<?=$train1;?>></td>
        <td>훈련 <input size=3 maxlength=3 name=train2 value=<?=$train2;?>></td>
        <td>훈련 <input size=3 maxlength=3 name=train3 value=<?=$train3;?>></td>
    </tr>
    <tr>
        <td>사기 <input size=3 maxlength=3 name=atmos1 value=<?=$atmos1;?>></td>
        <td>사기 <input size=3 maxlength=3 name=atmos2 value=<?=$atmos2;?>></td>
        <td>사기 <input size=3 maxlength=3 name=atmos3 value=<?=$atmos3;?>></td>
    </tr>
    <tr>
        <td>기술
            <select name=tech1 size=1>
<?php for($tch=0;$tch<=13;$tch++): ?>
                <option <?=($tch1==$tch)?'selected="selected"':''?> value='<?=$tch?>'><?=$tch?>등급</option>
<?php endfor; ?>
            </select>
        </td>
        <td>기술
            <select name=tech2 size=1>
<?php for($tch=0;$tch<=13;$tch++): ?>
                <option <?=($tch2==$tch)?'selected="selected"':''?> value='<?=$tch?>'><?=$tch?>등급</option>
<?php endfor; ?>
            </select>
        </td>
        <td>-</td>
    </tr>
    <tr>
        <td>보
            <select name=dex10 size=1>
<?php foreach($dexInfos as $dexInfo): ?>
                <option <?=($dx10 == $dexInfo[0])?'selected="selected"':''?> value=<?=$dexInfo[1]?>><?=$dexInfo[2]?></option>
<?php endforeach; ?>
            </select>
            궁
            <select name=dex110 size=1>
<?php foreach($dexInfos as $dexInfo): ?>
                <option <?=($dx110 == $dexInfo[0])?'selected="selected"':''?> value=<?=$dexInfo[1]?>><?=$dexInfo[2]?></option>
<?php endforeach; ?>
            </select>
            기
            <select name=dex120 size=1>
<?php foreach($dexInfos as $dexInfo): ?>
                <option <?=($dx120 == $dexInfo[0])?'selected="selected"':''?> value=<?=$dexInfo[1]?>><?=$dexInfo[2]?></option>
<?php endforeach; ?>
            </select>
            귀
            <select name=dex130 size=1>
<?php foreach($dexInfos as $dexInfo): ?>
                <option <?=($dx130 == $dexInfo[0])?'selected="selected"':''?> value=<?=$dexInfo[1]?>><?=$dexInfo[2]?></option>
<?php endforeach; ?>
            </select>
            차
            <select name=dex140 size=1>
<?php foreach($dexInfos as $dexInfo): ?>
                <option <?=($dx140 == $dexInfo[0])?'selected="selected"':''?> value=<?=$dexInfo[1]?>><?=$dexInfo[2]?></option>
<?php endforeach; ?>
            </select>
        </td>
        <td>보
            <select name=dex20 size=1>
<?php foreach($dexInfos as $dexInfo): ?>
                <option <?=($dx20 == $dexInfo[0])?'selected="selected"':''?> value=<?=$dexInfo[1]?>><?=$dexInfo[2]?></option>
<?php endforeach; ?>
            </select>
            궁
            <select name=dex210 size=1>
<?php foreach($dexInfos as $dexInfo): ?>
                <option <?=($dx210 == $dexInfo[0])?'selected="selected"':''?> value=<?=$dexInfo[1]?>><?=$dexInfo[2]?></option>
<?php endforeach; ?>
            </select>
            기
            <select name=dex220 size=1>
<?php foreach($dexInfos as $dexInfo): ?>
                <option <?=($dx220 == $dexInfo[0])?'selected="selected"':''?> value=<?=$dexInfo[1]?>><?=$dexInfo[2]?></option>
<?php endforeach; ?>
            </select>
            귀
            <select name=dex230 size=1>
<?php foreach($dexInfos as $dexInfo): ?>
                <option <?=($dx230 == $dexInfo[0])?'selected="selected"':''?> value=<?=$dexInfo[1]?>><?=$dexInfo[2]?></option>
<?php endforeach; ?>
            </select>
            차
            <select name=dex240 size=1>
<?php foreach($dexInfos as $dexInfo): ?>
                <option <?=($dx240 == $dexInfo[0])?'selected="selected"':''?> value=<?=$dexInfo[1]?>><?=$dexInfo[2]?></option>
<?php endforeach; ?>
            </select>
        </td>
        <td>-</td>
    </tr>
    <tr>
        <td>-</td>
        <td>
            <input type=submit name=isgen value=장수공격>
            <?='<input type=submit name=isgen value=장수평균>';?>
        </td>
        <td>
            <input type=submit name=isgen value=성벽공격>
            <?='<input type=submit name=isgen value=성벽평균>';?>
        </td>
    </tr>
    <tr><td colspan=3>
<?
if($isgen == "장수공격" || $isgen == "성벽공격") {
    echo $msg;
} elseif($isgen == "장수평균" || $isgen == "성벽평균") {
    echo $msg2;
}
?>
    </td></tr>
</table>
<table align=center width=1000 border=1 cellspacing=0 cellpadding=0 bordercolordark=gray bordercolorlight=black style=font-size:13;word-break:break-all; id=bg0>
    <tr id=bg1>
        <td align=right></td>
        <td align=center>공격</td>
        <td align=center>방어</td>
        <td align=center>기동</td>
        <td align=center>회피</td>
        <td align=center>가격</td>
        <td align=center>군량</td>
        <td width=500 align=center>-</td>
    </tr>

<?
    for($i=0; $i <= 5; $i++) {
        printSimul($game, $i);
    }
    echo "
    <tr><td height=5 colspan=8 id=bg1></td></tr>";

    for($i=10; $i <= 14; $i++) {
        printSimul($game, $i);
    }
    echo "
    <tr><td height=5 colspan=8 id=bg1></td></tr>";

    for($i=20; $i <= 27; $i++) {
        printSimul($game, $i);
    }
    echo "
    <tr><td height=5 colspan=8 id=bg1></td></tr>";

    for($i=30; $i <= 38; $i++) {
        printSimul($game, $i);
    }
    echo "
    <tr><td height=5 colspan=8 id=bg1></td></tr>";

    for($i=40; $i <= 43; $i++) {
        printSimul($game, $i);
    }
    echo "
    <tr><td height=5 colspan=8 id=bg1></td></tr>";
?>
</table>
</form>
</body>
<? PrintElapsedTime(); ?>
</html>
<?

function printSimul($game, $i) {
    $att = $game["att{$i}"];
    $def = $game["def{$i}"];
    $spd = $game["spd{$i}"];
    $avd = $game["avd{$i}"];
    $cst = $game["cst{$i}"];
    $ric = $game["ric{$i}"];
    echo "
    <tr>
        <td align=right>".getTypename($i)."</td>
        <td align=center>$att</td>
        <td align=center>$def</td>
        <td align=center>$spd</td>
        <td align=center>$avd</td>
        <td align=center>$cst</td>
        <td align=center>$ric</td>
        <td align=center>-</td>
    </tr>";
}

?>
