O duelo de armas futurista

73

O futuro do fundo

No ano de 2017, você e seu oponente enfrentarão uma batalha futurista em que apenas um poderá sobreviver. Você é experiente o suficiente para derrotar seu oponente? Agora é a hora de aprimorar suas habilidades com armas na sua linguagem de programação favorita e lutar contra todas as probabilidades!

Resultados do Torneio

Este torneio terminou no UTC manhã de Feburary 2 nd , 2017. Graças aos nossos concorrentes, nós tivemos um torneio futurista emocionante!

O MontePlayer é o vencedor final depois de batalhas fechadas com CBetaPlayer e StudiousPlayer. Os três principais duelos de guen tiraram uma foto comemorativa:

                MontePlayer                         - by TheNumberOne
              +------------+
  CBetaPlayer |            |                        - by George V. Williams
 +------------+    #  1    | StudiousPlayer         - by H Walters
 |                         +----------------+
 |    #  2                        #  3      |       
 +------------------------------------------+
    The Futurustic Gun Duel @ PPCG.SE 2017

Parabéns aos vencedores! O cabeçalho detalhado é visto no final deste post.

Orientação Geral

  • Visite o repositório oficial para obter o código fonte usado neste torneio.
  • Entradas em C ++: por favor, herde a Playerclasse.
  • Entradas não C ++: selecione uma interface na seção Interface para envios não C ++ .
  • Linguagens não C ++ atualmente permitidas: Python 3, Java.

O duelo

  • Cada jogador começa com uma arma descarregada que pode carregar uma quantidade infinita de munição.
  • A cada turno, os jogadores escolherão simultaneamente uma das seguintes ações:
    • 0 - Coloque 1 munição na arma.
    • 1- Disparar uma bala no oponente; custa 1 munição carregada.
    • 2- Disparar um feixe de plasma no oponente; custa 2 munição carregada.
    • - - Defenda a bala recebida usando um escudo de metal.
    • = - Defenda o feixe de plasma recebido usando um defletor térmico.
  • Se ambos os jogadores sobreviver após a 100 ª vez, ambos de escape para a morte, o que resulta em um empate .

Um jogador perde o duelo de armas se

  • Será que não usar a blindagem metálica para defender uma bala de entrada.
  • Será que não usar o deflector térmica para defender um plasma de entrada.
  • Dispara uma arma sem carregar munição suficiente, na qual a arma explode e mata o proprietário.

Ressalvas

De acordo com o Manual para proprietários de armas futuristas :

  • Um escudo de metal NÃO PODE defender do feixe de plasma recebido. Da mesma forma, um defletor térmico NÃO PODE defender da bala recebida.
  • O feixe de plasma domina a bala (porque a primeira requer mais munição carregada). Portanto, se um jogador dispara um raio de plasma no oponente que dispara uma bala no mesmo turno, o oponente é morto.
  • Se os dois jogadores disparam uma bala um no outro no mesmo turno, as balas são canceladas e os dois sobrevivem. Da mesma forma, se os dois jogadores disparam um feixe de plasma um no outro no mesmo turno, os dois sobrevivem.

Também é digno de nota que:

  • Você NÃO conhecerá a ação do seu oponente até que ela termine.
  • Desviar os feixes de plasma e balas de proteção NÃO prejudicará seu oponente.

Portanto, há um total de 25 combinações de ações válidas a cada turno:

+-------------+---------------------------------------------+
|   Outcome   |               P L A Y E R   B               |
|    Table    +--------+-----------------+------------------+
| for Players | Load   | Bullet   Plasma | Metal    Thermal |
+---+---------+--------+--------+--------+--------+---------+
| P | Load    |        | B wins | B wins |        |         |
| L +---------+--------+--------+--------+--------+---------+
| A | Bullet  | A wins |        | B wins |        | A wins  |
| Y |         +--------+--------+--------+--------+---------+
| E | Plasma  | A wins | A wins |        | A wins |         |
| R +---------+--------+--------+--------+--------+---------+
|   | Metal   |        |        | B wins |        |         |
|   |         +--------+--------+--------+--------+---------+
| A | Thermal |        | B wins |        |        |         |
+---+---------+--------+--------+---------------------------+

Note: Blank cells indicate that both players survive to the next turn.

Duelo de exemplo

Aqui está um duelo que tive com um amigo. Naquela época, não sabíamos muito sobre programação, então usamos gestos com as mãos e sinalizamos na velocidade de dois turnos por segundo. Da esquerda para a direita, nossas ações foram por sua vez:

    Me: 001-000-1201101001----2
Friend: 00-10-=1-==--0100-1---1

De acordo com as regras acima, eu perdi. Você vê o porquê? É porque eu disparei o feixe de plasma final quando eu tinha apenas 1 munição carregada, fazendo com que minha arma explodisse.


O jogador C ++

Você , como programador futurista civilizado, não vai lidar diretamente com as armas. Em vez disso, você codifica um Playerque luta contra os outros. Ao herdar publicamente a classe no projeto GitHub, você pode começar a escrever sua legenda urbana.

Player.hpp can be found in Tournament\Player.hpp
An example of a derived class can be found in Tournament\CustomPlayer.hpp

O que você deve ou pode fazer

  • Você deve herdar a Playerclasse por herança pública e declarar sua classe final.
  • Você deve substituir Player::fight, que retorna um válido Player::Actiontoda vez que é chamado.
  • Opcionalmente, substitua Player::perceivee Player::declaredfique de olho nas ações de seu oponente e acompanhe suas vitórias.
  • Opcionalmente, use membros e métodos estáticos privados em sua classe derivada para executar cálculos mais complexos.
  • Opcionalmente, use outras bibliotecas padrão do C ++.

O que você NÃO deve fazer

  • Você NÃO deve usar nenhum método direto para reconhecer seu oponente que não seja o identificador de oponente fornecido, que é embaralhado no início de cada torneio. Você só pode adivinhar quem é um jogador durante o jogo dentro de um torneio.
  • Você NÃO deve substituir nenhum método na Playerclasse que não seja declarado virtual.
  • Você NÃO deve declarar ou inicializar nada no escopo global.
  • Desde a estreia de (agora desclassificado) BlackHatPlayer, os jogadores NÃO têm permissão para espiar ou modificar o estado do seu oponente.

Um exemplo de duelo

O processo de um duelo de armas é realizado usando a GunDuelclasse. Para um exemplo de luta, consulte a Source.cppseção Iniciando um duelo .

Nós mostrar GunClubPlayer, HumanPlayerea GunDuelclasse, que pode ser encontrado no Tournament\diretório do repositório.

Em cada duelo, GunClubPlayercarregará uma bala; demiti-lo; enxague e repita. Durante cada turno, HumanPlayervocê será solicitado a executar uma ação contra seu oponente. Seus controles do teclado são os personagens 0, 1, 2, -e =. No Windows, você pode usar HumanPlayerpara depurar seu envio.

Iniciando um duelo

É assim que você pode depurar seu player através do console.

// Source.cpp
// An example duel between a HumanPlayer and GunClubPlayer.

#include "HumanPlayer.hpp"
#include "GunClubPlayer.hpp"
#include "GunDuel.hpp"

int main()
{
    // Total number of turns per duel.
    size_t duelLength = 100;

    // Player identifier 1: HumanPlayer.
    HumanPlayer human(2);
    // Player identifier 2: GunClubPlayer.
    GunClubPlayer gunClub(1);

    // Prepares a duel.
    GunDuel duel(human, gunClub, duelLength);
    // Start a duel.
    duel.fight();
}

Jogos de exemplo

A menor quantidade de turnos que você precisa derrotar GunClubPlayeré 3. Aqui está o replay do jogo 0-1contra GunClubPlayer. O número entre parênteses é o número de munição carregada para cada jogador quando o turno termina.

 :: Turn 0
    You [0/12/-=] >> [0] load ammo (1 ammo)
    Opponent selects [0] load ammo (1 ammo)
 :: Turn 1
    You [0/12/-=] >> [-] defend using metal shield (1 ammo)
    Opponent selects [1] fire a bullet (0 ammo)
 :: Turn 2
    You [0/12/-=] >> [1] fire a bullet (0 ammo)
    Opponent selects [0] load ammo (1 ammo)
 :: You won after 3 turns!
 :: Replay
    YOU 0-1
    FOE 010
Press any key to continue . . .

A maneira mais rápida de ser derrotado GunClubPlayersem fazer movimentos inválidos é a sequência 0=, porque a bala dispara através do defletor térmico. A repetição é

 :: Turn 0
    You [0/12/-=] >> [0] load ammo (1 ammo)
    Opponent selects [0] load ammo (1 ammo)
 :: Turn 1
    You [0/12/-=] >> [=] defend using thermal deflector (1 ammo)
    Opponent selects [1] fire a bullet (0 ammo)
 :: You lost after 2 turns!
 :: Replay
    YOU 0=
    FOE 01
Press any key to continue . . .

O torneio

O torneio segue o formato "Último jogador em pé". Em um torneio, todos os envios válidos (incluindo o GunClubPlayer) são colocados em um pool. A cada envio é atribuído um identificador aleatório, porém único, que permanecerá o mesmo durante todo o torneio. Durante cada rodada:

  • Cada envio começa com 0 pontos e jogará 100 duelos contra todos os outros pedidos.
  • Cada duelo vitorioso concederá 1 ponto; desenhar e perder dá 0 pontos.
  • No final da rodada, as inscrições com o mínimo de pontos deixam o torneio. Em caso de empate, o jogador com a menor quantidade de pontos ganhos desde o início do torneio sairá.
  • Se restar mais de um jogador, a próxima rodada começará.
  • Os pontos NÃO são transferidos para a próxima rodada.

Submissão, obediência, inscrição, candidatura

Você enviará um jogador por resposta. Você pode enviar vários arquivos para um jogador, desde que NÃO interfira com outros envios. Para manter as coisas fluindo, por favor:

  • Nomeie seu arquivo de cabeçalho principal como <Custom>Player.hpp,
  • Nomeie seus outros arquivos como <Custom>Player*.*, por exemplo, MyLittlePlayer.txtse o nome da sua classe é MyLittlePlayerou EmoPlayerHates.cppse o nome da sua classe é EmoPlayer.
  • Se o seu nome contiver Shooterou palavras semelhantes que se encaixem no contexto deste torneio, você não precisará adicionar Playerno final. Se você acha que o nome do seu envio funciona melhor sem o sufixo Player, também não é necessário adicioná-lo Player.
  • Verifique se o seu código pode ser compilado e vinculado no Windows.

Você pode comentar para pedir esclarecimentos ou identificar brechas. Espero que você goste deste duelo futurista de armas e deseje um feliz ano novo!

Esclarecimento

  • Você tem permissão para ter um comportamento aleatório.
  • Ações inválidas (disparar quando munição carregada não são suficientes) são permitidas.
  • Se um jogador fizer uma entrada inválida, sua arma explodirá imediatamente.
  • Você tem permissão para estudar as respostas.
  • Você tem permissão explícita para registrar o comportamento do oponente em cada torneio.
  • Cada rodada, você jogará 100 duelos contra cada oponente; a ordem dos 100 duelos, no entanto, é aleatória - você não tem garantia de lutar contra o mesmo oponente por 100 duelos consecutivos.

Recursos adicionais

O @flawr traduziu a fonte C ++ fornecida para Java como uma referência, se você quiser enviar entradas C ++.

Interface para envios não C ++

Atualmente aceito: Python 3, Java.

Siga uma das especificações abaixo:

Especificação da interface 1: código de saída

Seu envio será executado uma vez por turno.

Expected Command Line Argument Format:
    <opponent-id> <turn> <status> <ammo> <ammo-opponent> <history> <history-opponent>

Expected Return Code: The ASCII value of a valid action character.
    '0' = 48, '1' = 49, '2' = 50, '-' = 45, '=' = 61

<opponent-id> is an integer in [0, N), where N is size of tournament.
<turn> is 0-based.
If duel is in progress, <status> is 3.
If duel is draw / won / lost, <status> is 0 / 1 / 2.
<history> and <history-opponent> are strings of actions, e.g. 002 0-=
If turn is 0, <history> and <history-opponent> are not provided.
You can ignore arguments you don't particularly need.

Você pode testar sua submissão PythonPlayer\e JavaPlayer\diretórios.

Especificação da interface 2: stdin / stdout

(Crédito para H Walters)

Sua inscrição será realizada uma vez por torneio.

Há um requisito fixo para todas as entradas sobre como fazer E / S, já que stdin e stdout estão conectados ao driver do torneio. Violar isso pode levar a um impasse. Todas as entradas devem seguir este algoritmo EXATO (em pseudo-código):

LOOP FOREVER
    READ LINE INTO L
    IF (LEFT(L,1) == 'I')
        INITIALIZE ROUND
        // i.e., set your/opponent ammo to 0, if tracking them
        // Note: The entire line at this point is a unique id per opponent;
        // optionally track this as well.
        CONTINUE LOOP
    ELSE IF (LEFT(L,1) == 'F')
        WRITELN F // where F is your move
    ELSE IF (LEFT(L,1) == 'P')
        PROCESS MID(L,2,1) // optionally perceive your opponent's action.
    END IF
CONTINUE LOOP
QUIT

Aqui, F é um dos 0, 1, 2, -, ou =para load / bullet / plasma / metal / thermal. PROCESSO significa responder opcionalmente ao que o seu oponente fez (incluindo rastrear a munição do seu oponente, se você estiver fazendo isso). Observe que a ação do oponente também é '0', '1', '2', '-' ou '=' e está no segundo caractere.

Painel Final

08:02 AM Tuesday, February 2, 2017 Coordinated Universal Time (UTC)
| Player             | Language   | Points |     1 |     2 |     3 |     4 |     5 |     6 |     7 |     8 |     9 |    10 |    11 |    12 |    13 |    14 |    15 |    16 |
|:------------------ |:---------- | ------:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:|
| MontePlayer        | C++        |  11413 |  1415 |  1326 |  1247 |  1106 |  1049 |   942 |   845 |   754 |   685 |   555 |   482 |   381 |   287 |   163 |   115 |    61 |
| CBetaPlayer        | C++        |   7014 |   855 |   755 |   706 |   683 |   611 |   593 |   513 |   470 |   414 |   371 |   309 |   251 |   192 |   143 |   109 |    39 |
| StudiousPlayer     | C++        |  10014 |  1324 |  1233 |  1125 |  1015 |   907 |   843 |   763 |   635 |   555 |   478 |   403 |   300 |   201 |   156 |    76 |
| FatedPlayer        | C++        |   6222 |   745 |   683 |   621 |   655 |   605 |   508 |   494 |   456 |   395 |   317 |   241 |   197 |   167 |   138 |
| HanSoloPlayer      | C++        |   5524 |   748 |   668 |   584 |   523 |   490 |   477 |   455 |   403 |   335 |   293 |   209 |   186 |   153 |
| SurvivorPlayer     | C++        |   5384 |   769 |   790 |   667 |   574 |   465 |   402 |   354 |   338 |   294 |   290 |   256 |   185 |
| SpecificPlayer     | C++        |   5316 |   845 |   752 |   669 |   559 |   488 |   427 |   387 |   386 |   340 |   263 |   200 |
| DeceptivePlayer    | C++        |   4187 |   559 |   445 |   464 |   474 |   462 |   442 |   438 |   369 |   301 |   233 |
| NotSoPatientPlayer | C++        |   5105 |   931 |   832 |   742 |   626 |   515 |   469 |   352 |   357 |   281 |
| BarricadePlayer    | C++        |   4171 |   661 |   677 |   614 |   567 |   527 |   415 |   378 |   332 |
| BotRobotPlayer     | C++        |   3381 |   607 |   510 |   523 |   499 |   496 |   425 |   321 |
| SadisticShooter    | C++        |   3826 |   905 |   780 |   686 |   590 |   475 |   390 |
| TurtlePlayer       | C++        |   3047 |   754 |   722 |   608 |   539 |   424 |
| CamtoPlayer        | C++        |   2308 |   725 |   641 |   537 |   405 |
| OpportunistPlayer  | C++        |   1173 |   426 |   420 |   327 |
| GunClubPlayer      | C++        |    888 |   500 |   388 |
| PlasmaPlayer       | C++        |    399 |   399 |

O torneio durará até 1º de fevereiro de 2017, salvo indicação em contrário.

Frenzy Li
fonte
15
Primeiro desafio impressionante, a propósito!
Martin Ender
3
Se você estiver disposto a executar outros idiomas, poderá permitir uma Playerimplementação que invoque outro processo para calcular a curva atual. Isso permitiria que as pessoas participassem de qualquer idioma que você tenha prazer em executar em sua máquina.
Martin Ender
5
Aleatoriedade permitida? (
Turnos
2
Ponto técnico; "Você deve herdar Player::fight" / "você pode herdar Player::perceive" ... nos dois casos, o termo é substituído , não herdado .
H Walters
3
Eu acho que você tem um bug GunDuel.hpp, tanto validAe validBuse #actionA
AlexRacer 30/12/16

Respostas:

9

MontePlayer

Este jogador usa o algoritmo de pesquisa de árvore desacoplada do Monte Carlo UCT para decidir quais escolhas ele deve fazer. Ele rastreia o que o inimigo faz para prever suas ações. Ele simula o inimigo como ele mesmo, se não houver dados.

Este bot se sai muito bem contra todos os outros bot, exceto cβ. Em uma partida de 10000 duelos contra cβ, Monte venceu 5246 duelos. Com um pouco de matemática, isso significa que Monte vencerá um duelo contra cβ 51,17% a 53,74% das vezes (99% de confiança).

#ifndef __Monte_PLAYER_HPP__
#define __Monte_PLAYER_HPP__

#include "Player.hpp"
#include <cstdlib>
#include <ctime>
#include <memory>
#include <iostream>


class MontePlayer final : public Player
{
    static const int MAX_TURNS = 100;
    static const int TOTAL_ACTIONS = 5;

    //Increase this if number of players goes above 20.
    static const int MAX_PLAYERS = 20;

    //The number of simulated games we run every time our program is called.
    static const int MONTE_ROUNDS = 1000;


    /**
    * Represents the current state of the game.
    */
    struct Game
    {
        int turn;
        int ammo;
        int opponentAmmo;
        bool alive;
        bool opponentAlive;

        Game(int turn, int ammo, int opponentAmmo, bool alive, bool opponentAlive)
            : turn(turn), ammo(ammo), opponentAmmo(opponentAmmo), alive(alive), opponentAlive(opponentAlive) {}
        Game() : turn(0), ammo(0), opponentAmmo(0), alive(false), opponentAlive(false) {}
    };

    struct Stat
    {
        int wins;
        int attempts;

        Stat() : wins(0), attempts(0) {}
    };

    /**
    * A Monte tree data structure.
    */
    struct MonteTree
    {
        //The state of the game.
        Game game;

        //myStats[i] returns the statistic for doing the i action in this state.
        Stat myStats[TOTAL_ACTIONS];
        //opponentStats[i] returns the statistic for the opponent doing the i action in this state.
        Stat opponentStats[TOTAL_ACTIONS];
        //Total number of times we've created statistics from this tree.
        int totalPlays = 0;
        //The action that led to this tree.
        int myAction;
        //The opponent action that led to this tree.
        int opponentAction;

        //The tree preceding this one.
        MonteTree *parent = NULL;

        //subtrees[i][j] is the tree that would follow if I did action i and the
        //opponent did action j.
        MonteTree *subtrees[TOTAL_ACTIONS][TOTAL_ACTIONS] = { { NULL } };

        MonteTree(int turn, int ammo, int opponentAmmo) :
            game(turn, ammo, opponentAmmo, true, true) {}


        MonteTree(Game game, MonteTree *parent, int myAction, int opponentAction) :
            game(game), parent(parent), myAction(myAction), opponentAction(opponentAction)
        {
            //Make sure the parent tree keeps track of this tree.
            parent->subtrees[myAction][opponentAction] = this;
        }

        //The destructor so we can avoid slow ptr types and memory leaks.
        ~MonteTree()
        {
            //Delete all subtrees.
            for (int i = 0; i < TOTAL_ACTIONS; i++)
            {
                for (int j = 0; j < TOTAL_ACTIONS; j++)
                {
                    auto branch = subtrees[i][j];

                    if (branch)
                    {
                        branch->parent = NULL;
                        delete branch;
                    }
                }
            }
        }
    };

    //The previous state.
    Game prevGame;
    //The id of the opponent.
    int opponent;
    //opponentHistory[a][b][c][d] returns the number of times
    //that opponent a did action d when I had b ammo and he had c ammo.
    static int opponentHistory[MAX_PLAYERS][MAX_TURNS][MAX_TURNS][TOTAL_ACTIONS];

public:
    MontePlayer(size_t opponent = -1) : Player(opponent)
    {
        srand(time(NULL));
        this->opponent = opponent;
    }

public:

    virtual Action fight()
    {
        //Create the root tree. Will be auto-destroyed after this function ends.
        MonteTree current(getTurn(), getAmmo(), getAmmoOpponent());

        //Set the previous game to this one.
        prevGame = current.game;

        //Get these variables so we can log later if nessecarry.
        int turn = getTurn(),
            ammo = getAmmo(),
            opponentAmmo = getAmmoOpponent();

        for (int i = 0; i < MONTE_ROUNDS; i++)
        {
            //Go down the tree until we find a leaf we haven't visites yet.
            MonteTree *leaf = selection(&current);

            //Randomly simulate the game at the leaf and get the result.
            int score = simulate(leaf->game);

            //Propagate the scores back up the root.
            update(leaf, score);
        }

        //Get the best move.
        int move = bestMove(current);

        //Move string for debugging purposes.
        const char* m;

        //We have to do this so our bots state is updated.
        switch (move)
        {
        case Action::LOAD:
            load();
            m = "load";
            break;
        case Action::BULLET:
            bullet();
            m = "bullet";
            break;
        case Action::PLASMA:
            plasma();
            m = "plasma";
            break;
        case Action::METAL:
            metal();
            m = "metal";
            break;
        case Action::THERMAL:
            thermal();
            m = "thermal";
            break;
        default: //???
            std::cout << move << " ???????\n";
            throw move;
        }

        return (Action)move;
    }

    /**
    * Record what the enemy does so we can predict him.
    */
    virtual void perceive(Action action)
    {
        Player::perceive(action);
        opponentHistory[opponent][prevGame.ammo][prevGame.opponentAmmo][action]++;
    }
private:

    /**
    * Trickle down root until we have to create a new leaf MonteTree or we hit the end of a game.
    */
    MonteTree * selection(MonteTree *root)
    {
        while (!atEnd(root->game))
        {
            //First pick the move that my bot will do.

            //The action my bot will do.
            int myAction;
            //The number of actions with the same bestScore.
            int same = 0;
            //The bestScore
            double bestScore = -1;

            for (int i = 0; i < TOTAL_ACTIONS; i++)
            {
                //Ignore invalid or idiot moves.
                if (!isValidMove(root->game, i, true))
                {
                    continue;
                }

                //Get the score for doing move i. Uses
                double score = computeScore(*root, i, true);

                //Randomly select one score if multiple actions have the same score.
                //Why this works is boring to explain.
                if (score == bestScore)
                {
                    same++;
                    if (Random(same) == 0)
                    {
                        myAction = i;
                    }
                }
                //Yay! We found a better action.
                else if (score > bestScore)
                {
                    same = 1;
                    myAction = i;
                    bestScore = score;
                }
            }

            //The action the enemy will do.
            int enemyAction;

            //The number of times the enemy has been in this same situation.
            int totalEnemyEncounters = 0;
            for (int i = 0; i < TOTAL_ACTIONS; i++)
            {
                totalEnemyEncounters += opponentHistory[opponent][root->game.ammo][root->game.opponentAmmo][i];
            }

            //Assume the enemy will choose an action it has chosen before if we've
            //seen it in this situation before. Otherwise we assume that the enemy is ourselves.
            if (totalEnemyEncounters > 0)
            {
                //Randomly select an action that the enemy has done with
                //weighted by the number of times that action has been done.
                int selection = Random(totalEnemyEncounters);
                for (int i = 0; i < TOTAL_ACTIONS; i++)
                {
                    selection -= opponentHistory[opponent][root->game.ammo][root->game.opponentAmmo][i];
                    if (selection < 0)
                    {
                        enemyAction = i;
                        break;
                    }
                }
            }
            else
            {
                //Use the same algorithm to pick the enemies move we use for ourselves.
                same = 0;
                bestScore = -1;
                for (int i = 0; i < TOTAL_ACTIONS; i++)
                {
                    if (!isValidMove(root->game, i, false))
                    {
                        continue;
                    }

                    double score = computeScore(*root, i, false);
                    if (score == bestScore)
                    {
                        same++;
                        if (Random(same) == 0)
                        {
                            enemyAction = i;
                        }
                    }
                    else if (score > bestScore)
                    {
                        same = 1;
                        enemyAction = i;
                        bestScore = score;
                    }
                }
            }

            //If this combination of actions hasn't been explored yet, create a new subtree to explore.
            if (!(*root).subtrees[myAction][enemyAction])
            {
                return expand(root, myAction, enemyAction);
            }

            //Do these actions and explore the next subtree.
            root = (*root).subtrees[myAction][enemyAction];
        }
        return root;
    }

    /**
    * Creates a new leaf under root for the actions.
    */
    MonteTree * expand(MonteTree *root, int myAction, int enemyAction)
    {
        return new MonteTree(
            doTurn(root->game, myAction, enemyAction),
            root,
            myAction,
            enemyAction);
    }

    /**
    * Computes the score of the given move in the given position.
    * Uses the UCB1 algorithm and returns infinity for moves not tried yet.
    */
    double computeScore(const MonteTree &root, int move, bool me)
    {
        const Stat &stat = me ? root.myStats[move] : root.opponentStats[move];
        return stat.attempts == 0 ?
            HUGE_VAL :
            double(stat.wins) / stat.attempts + sqrt(2 * log(root.totalPlays) / stat.attempts);
    }

    /**
    * Randomly simulates the given game.
    * Has me do random moves that are not stupid.
    * Has opponent do what it has done in similar positions or random moves if not
    * observed in those positions yet.
    *
    * Returns 1 for win. 0 for loss. -1 for draw.
    */
    int simulate(Game game)
    {
        while (!atEnd(game))
        {
            game = doRandomTurn(game);
        }

        if (game.alive > game.opponentAlive)
        {
            return 1;
        }
        else if (game.opponentAlive > game.alive)
        {
            return 0;
        }
        else //Draw
        {
            return -1;
        }
    }

    /**
    * Returns whether the game is over or not.
    */
    bool atEnd(Game game)
    {
        return !game.alive || !game.opponentAlive || game.turn > MAX_TURNS;
    }

    /**
    * Simulates the given actions on the game.
    */
    Game doTurn(Game game, int myAction, int enemyAction)
    {
        game.turn++;

        switch (myAction)
        {
        case Action::LOAD:
            game.ammo++;
            break;
        case Action::BULLET:
            if (game.ammo < 1)
            {
                game.alive = false;
                break;
            }
            game.ammo--;
            if (enemyAction == Action::LOAD || enemyAction == Action::THERMAL)
            {
                game.opponentAlive = false;
            }
            break;
        case Action::PLASMA:
            if (game.ammo < 2)
            {
                game.alive = false;
                break;
            }
            game.ammo -= 2;
            if (enemyAction != Action::PLASMA && enemyAction != Action::THERMAL)
            {
                game.opponentAlive = false;
            }
            break;
        }

        switch (enemyAction)
        {
        case Action::LOAD:
            game.opponentAmmo++;
            break;
        case Action::BULLET:
            if (game.opponentAmmo < 1)
            {
                game.opponentAlive = false;
                break;
            }
            game.opponentAmmo--;
            if (myAction == Action::LOAD || myAction == Action::THERMAL)
            {
                game.alive = false;
            }
            break;
        case Action::PLASMA:
            if (game.opponentAmmo < 2)
            {
                game.opponentAlive = false;
            }
            game.opponentAmmo -= 2;
            if (myAction != Action::PLASMA && myAction != Action::THERMAL)
            {
                game.alive = false;
            }
            break;
        }

        return game;
    }

    /**
    * Chooses a random move for me and my opponent and does it.
    */
    Game doRandomTurn(Game &game)
    {
        //Select my random move.
        int myAction;
        int validMoves = 0;

        for (int i = 0; i < TOTAL_ACTIONS; i++)
        {
            //Don't do idiotic moves.
            //Select one at random.
            if (isValidMove(game, i, true))
            {
                validMoves++;
                if (Random(validMoves) == 0)
                {
                    myAction = i;
                }
            }
        }

        //Choose random opponent action.
        int opponentAction;

        //Whether the enemy has encountered this situation before
        bool enemyEncountered = false;

        validMoves = 0;

        //Weird algorithm that works and I don't want to explain.
        //What it does:
        //If the enemy has encountered this position before,
        //then it chooses a random action weighted by how often it did that action.
        //If they haven't, makes the enemy choose a random not idiot move.
        for (int i = 0; i < TOTAL_ACTIONS; i++)
        {
            int weight = opponentHistory[opponent][game.ammo][game.opponentAmmo][i];
            if (weight > 0)
            {
                if (!enemyEncountered)
                {
                    enemyEncountered = true;
                    validMoves = 0;
                }
                validMoves += weight;
                if (Random(validMoves) < weight)
                {
                    opponentAction = i;
                }
            }
            else if (!enemyEncountered && isValidMove(game, i, false))
            {
                validMoves++;
                if (Random(validMoves) == 0)
                {
                    opponentAction = i;
                }
            }
        }

        return doTurn(game, myAction, opponentAction);
    }

    /**
    * Returns whether the given move is valid/not idiotic for the game.
    */
    bool isValidMove(Game game, int move, bool me)
    {
        switch (move)
        {
        case Action::LOAD:
            return true;
        case Action::BULLET:
            return me ? game.ammo > 0 : game.opponentAmmo > 0;
        case Action::PLASMA:
            return me ? game.ammo > 1 : game.opponentAmmo > 1;
        case Action::METAL:
            return me ? game.opponentAmmo > 0 : game.ammo > 0;
        case Action::THERMAL:
            return me ? game.opponentAmmo > 1 : game.ammo > 1;
        default:
            return false;
        }
    }

    /**
    * Propagates the score up the MonteTree from the leaf.
    */
    void update(MonteTree *leaf, int score)
    {
        while (true)
        {
            MonteTree *parent = leaf->parent;
            if (parent)
            {
                //-1 = draw, 1 = win for me, 0 = win for opponent
                if (score != -1)
                {
                    parent->myStats[leaf->myAction].wins += score;
                    parent->opponentStats[leaf->opponentAction].wins += 1 - score;
                }
                parent->myStats[leaf->myAction].attempts++;
                parent->opponentStats[leaf->opponentAction].attempts++;
                parent->totalPlays++;
                leaf = parent;
            }
            else
            {
                break;
            }
        }
    }

    /**
    * There are three different strategies in here.
    * The first is not random, the second more, the third most.
    */
    int bestMove(const MonteTree &root)
    {
        //Select the move with the highest win rate.
        int best;
        double bestScore = -1;
        for (int i = 0; i < TOTAL_ACTIONS; i++)
        {
            if (root.myStats[i].attempts == 0)
            {
                continue;
            }

            double score = double(root.myStats[i].wins) / root.myStats[i].attempts;
            if (score > bestScore)
            {
                bestScore = score;
                best = i;
            }
        }

        return best;

        ////Select a move weighted by the number of times it has won the game.
        //int totalScore = 0;
        //for (int i = 0; i < TOTAL_ACTIONS; i++)
        //{
        //  totalScore += root.myStats[i].wins;
        //}
        //int selection = Random(totalScore);
        //for (int i = 0; i < TOTAL_ACTIONS; i++)
        //{
        //  selection -= root.myStats[i].wins;
        //  if (selection < 0)
        //  {
        //      return i;
        //  }
        //}

        ////Select a random move weighted by win ratio.
        //double totalScore = 0;
        //for (int i = 0; i < TOTAL_ACTIONS; i++)
        //{
        //  if (root.myStats[i].attempts == 0)
        //  {
        //      continue;
        //  }
        //  totalScore += double(root.myStats[i].wins) / root.myStats[i].attempts;
        //}
        //double selection = Random(totalScore);
        //for (int i = 0; i < TOTAL_ACTIONS; i++)
        //{
        //  if (root.myStats[i].attempts == 0)
        //  {
        //      continue;
        //  }
        //  selection -= double(root.myStats[i].wins) / root.myStats[i].attempts;
        //  if (selection < 0)
        //  {
        //      return i;
        //  }
        //}
    }

    //My own random functions.
    int Random(int max)
    {
        return GetRandomInteger(max - 1);
    }
    double Random(double max)
    {
        static auto seed = std::chrono::system_clock::now().time_since_epoch().count();
        static std::default_random_engine generator((unsigned)seed);
        std::uniform_real_distribution<double> distribution(0.0, max);
        return distribution(generator);
    }
};
//We have to initialize this here for some reason.
int MontePlayer::opponentHistory[MAX_PLAYERS][MAX_TURNS][MAX_TURNS][TOTAL_ACTIONS]{ { { { 0 } } } };

#endif // !__Monte_PLAYER_HPP__
O número um
fonte
25

o BlackHatPlayer

O BlackHat Player sabe que balas e escudos são coisa do passado; as guerras reais são vencidas por aqueles que podem invadir os programas do oponente.

Então, ele coloca um escudo de metal fixo e começa a fazer suas coisas.

A primeira vez que ele é solicitado fight, ele tenta localizar seu inimigo na memória. Dada a estrutura da arena de luta, é quase certo que o compilador acabará colocando seu endereço (envolto em um unique_ptr) e o do oponente apenas um ao lado do outro.

Portanto, o BlackHat caminha com cuidado pela pilha, usando algumas heurísticas simples para garantir que ela não fique submersa até encontrar um ponteiro para si mesmo; depois verifica se os valores nas posições adjacentes são plausivelmente seu oponente - endereço semelhante, endereço semelhante da tabela, plausível typeid.

Se conseguir encontrá-lo, ele chupa o cérebro e os substitui pelos de um idiota. Na prática, isso é feito substituindo o ponteiro do oponente na mesa de exibição pelo endereço da Idiotmesa - um jogador burro que sempre dispara.

Se tudo isso der certo (e nos meus testes - gcc 6 no Linux de 64 bits, MinGW 4.8 no wine de 32 bits - isso funciona com bastante confiabilidade), a guerra está vencida. Tudo o que o oponente fez no primeiro round não é importante - na pior das hipóteses ele atirou em nós, e nós tínhamos o escudo de metal.

A partir de agora, temos um idiota apenas atirando; sempre temos nosso escudo, então estamos protegidos, e ele explodirá em 1 a 3 rodadas (dependendo do que o bot original fez em sua primeira fightchamada).


Agora: tenho quase certeza de que isso deve ser desqualificado imediatamente, mas é engraçado não estar violando explicitamente nenhuma das regras acima:

O que você NÃO deve fazer

  • Você NÃO deve usar nenhum método direto para reconhecer seu oponente que não seja o identificador de oponente fornecido, que é completamente aleatório no início de cada torneio. Você só pode adivinhar quem é um jogador durante o jogo em um torneio.

BlackHat não tenta reconhecer o oponente - na verdade, é completamente irrelevante quem é o oponente, já que seu cérebro é substituído imediatamente.

  • Você NÃO deve substituir nenhum método na classe Player que não seja declarado virtual.
  • Você NÃO deve declarar ou inicializar nada no escopo global.

Tudo acontece localmente na fightfunção virtual.


// BlackHatPlayer.hpp

#ifndef __BLACKHAT_PLAYER_HPP__
#define __BLACKHAT_PLAYER_HPP__

#include "Player.hpp"
#include <stddef.h>
#include <typeinfo>
#include <algorithm>
#include <string.h>

class BlackHatPlayer final : public Player
{
public:
    using Player::Player;

    virtual Action fight()
    {
        // Always metal; if the other is an Idiot, he only shoots,
        // and if he isn't an Idiot yet (=first round) it's the only move that
        // is always safe
        if(tricked) return metal();
        // Mark that at the next iterations we don't have to do all this stuff
        tricked = true;

        typedef uintptr_t word;
        typedef uintptr_t *pword;
        typedef uint8_t *pbyte;

        // Size of one memory page; we use it to walk the stack carefully
        const size_t pageSize = 4096;
        // Maximum allowed difference between the vtables
        const ptrdiff_t maxVTblDelta = 65536;
        // Maximum allowed difference between this and the other player
        ptrdiff_t maxObjsDelta = 131072;

        // Our adversary
        Player *c = nullptr;

        // Gets the start address of the memory page for the given object
        auto getPage = [&](void *obj) {
            return pword(word(obj) & (~word(pageSize-1)));
        };
        // Gets the start address of the memory page *next* to the one of the given object
        auto getNextPage = [&](void *obj) {
            return pword(pbyte(getPage(obj)) + pageSize);
        };

        // Gets a pointer to the first element of the vtable
        auto getVTbl = [](void *obj) {
            return pword(pword(obj)[0]);
        };

        // Let's make some mess to make sure that:
        // - we have an actual variable on the stack;
        // - we call an external (non-inline) function that ensures everything
        //   is spilled on the stack
        // - the compiler actually generates the full vtables (in the current
        //   tournament this shouldn't be an issue, but in earlier sketches
        //   the compiler inlined everything and killed the vtables)
        volatile word i = 0;
        for(const char *sz = typeid(*(this+i)).name(); *sz; ++sz) i+=*sz;

        // Grab my vtable
        word *myVTbl = getVTbl(this);

        // Do the stack walk
        // Limit for the stack walk; use i as a reference
        word *stackEnd = getNextPage((pword)(&i));
        for(word *sp = pword(&i);       // start from the location of i
            sp!=stackEnd && c==nullptr;
            ++sp) {                     // assume that the stack grows downwards
            // If we find something that looks like a pointer to memory
            // in a page just further on the stack, take it as a clue that the
            // stack in facts does go on
            if(getPage(pword(*sp))==stackEnd) {
                stackEnd = getNextPage(pword(*sp));
            }
            // We are looking for our own address on the stack
            if(*sp!=(word)this) continue;

            auto checkCandidate = [&](void *candidate) -> Player* {
                // Don't even try with NULLs and the like
                if(getPage(candidate)==nullptr) return nullptr;
                // Don't trust objects too far away from us - it's probably something else
                if(abs(pbyte(candidate)-pbyte(this))>maxObjsDelta) return nullptr;
                // Grab the vtable, check if it actually looks like one (it should be
                // decently near to ours)
                pword vtbl = getVTbl(candidate);
                if(abs(vtbl-myVTbl)>maxVTblDelta) return nullptr;
                // Final check: try to see if its name looks like a "Player"
                Player *p = (Player *)candidate;
                if(strstr(typeid(*p).name(), "layer")==0) return nullptr;
                // Jackpot!
                return p;
            };

            // Look around us - a pointer to our opponent should be just near
            c = checkCandidate((void *)sp[-1]);
            if(c==nullptr) c=checkCandidate((void *)sp[1]);
        }

        if(c!=nullptr) {
            // We found it! Suck his brains out and put there the brains of a hothead idiot
            struct Idiot : Player {
                virtual Action fight() {
                    // Always fire, never reload; blow up in two turns
                    // (while we are always using the metal shield to protect ourselves)
                    return bullet();
                }
            };
            Idiot idiot;
            // replace the vptr
            (*(word *)(c)) = word(getVTbl(&idiot));
        }
        // Always metal shield to be protected from the Idiot
        return metal();
    }
private:
    bool tricked = false;
};

#endif // !__BLACKHAT_PLAYER_HPP__
Matteo Italia
fonte
6
@ TheNumberOne: também, conforme o primeiro (e mais votado) comentário ao tópico de brechas: "Brechas são parte do que torna o jogo interessante. Mesmo as mais comuns podem ser engraçadas ou inteligentes, dependendo do contexto". OMI é original (pelo menos, nunca vi nada parecido aqui) e decentemente interessante, em termos de engenharia; é por isso que compartilhei aqui.
Matteo Italia
3
#ifdef __BLACKHAT_PLAYER_HPP__O que você #error "Dependency issue; to compile, please include this file before BlackHatPlayer.hpp"precisa #elsesaber #define __BLACKHAT_PLAYER_HPP__é o #endifseguinte
H Walters -
11
@MatteoItalia BlackHat sempre aumenta nosso conhecimento sobre brechas padrão :-) #
Frenzy Li
2
@HWalters: Eu acho que vou ter que mudar para #pragma once;-) #
Matteo Italia
3
Parece bastante simples executar cada jogador em um processo separado e usar soquetes para se comunicar com o árbitro.
Jasen
19

Em seguida, a mais temida de todas as criaturas, foi ao inferno e lutou com literalmente 900000 outros bots , seus ...

o BotRobot

O BotRobot foi nomeado, treinado e construído automaticamente por um algoritmo genético muito básico.

Duas equipes de 9 foram montadas uma contra a outra, em cada geração, cada robô da equipe 1 é colocado contra cada robô da equipe 2. Os robôs com mais vitórias do que perdas, mantiveram a memória e o outro voltaram ao último passo , e teve a chance de esquecer algo, espero que ruim. Os bots em si são tabelas de pesquisa glorificadas, onde se encontrassem algo que não tinham visto antes, simplesmente escolheriam uma opção válida aleatória e a salvariam na memória. A versão C ++ não faz isso, deveria ter aprendido . Como dito anteriormente, os bots vencedores mantêm essa nova memória encontrada, como claramente funcionou. Perder bots não, e manter o que eles começaram.

No final, as brigas de bot foram bastante próximas, raramente obsoletas. O vencedor foi escolhido a partir de uma piscina das duas equipes postar evolução, que foi 100000 gerações.

O BotRobot, com seu nome gerado aleatoriamente e BONITO , foi o sortudo.

Gerador

bot.lua

Revisão: Embora o robô fosse bastante inteligente contra ele e outros robôs gerados de maneira semelhante, ele se mostrou bastante inútil em batalhas reais. Então, eu regenerei seu cérebro contra alguns dos bots já criados.

Os resultados, como podem ser facilmente vistos, são um cérebro muito mais complexo, com opções para o jogador inimigo ter 12 munições.

Eu não tenho certeza do que ele estava lutando que chegou a 12 munições, mas algo aconteceu.

E, claro, o produto acabado ...

// BotRobot
// ONE HUNDRED THOUSAND GENERATIONS TO MAKE THE ULTIMATE LIFEFORM!

#ifndef __BOT_ROBOT_PLAYER_HPP__
#define __BOT_ROBOT_PLAYER_HPP__

#include "Player.hpp"

class BotRobotPlayer final : public Player
{
public:
    BotRobotPlayer(size_t opponent = -1) : Player(opponent) {}

public:
    virtual Action fight()
    {
        std::string action = "";
        action += std::to_string(getAmmo());
        action += ":";
        action += std::to_string(getAmmoOpponent());

        int toDo = 3;

        for (int i = 0; i < int(sizeof(options)/sizeof(*options)); i++) {
            if (options[i].compare(action)==0) {
                toDo = outputs[i];
                break;
            }
        }

        switch (toDo) {
            case 0:
                return load();
            case 1:
                return bullet();
            case 2:
                return plasma();
            case 3:
                return metal();
            default:
                return thermal();
        }
    }

private:
    std::string options[29] =
    {
        "0:9",
        "1:12",
        "1:10",
        "0:10",
        "1:11",
        "0:11",
        "0:6",
        "2:2",
        "0:2",
        "2:6",
        "3:6",
        "0:7",
        "1:3",
        "2:3",
        "0:3",
        "2:0",
        "1:0",
        "0:4",
        "1:4",
        "2:4",
        "0:0",
        "3:0",
        "1:1",
        "2:1",
        "2:9",
        "0:5",
        "0:8",
        "3:1",
        "0:1"
    };

    int outputs[29] =
    {
        0,
        1,
        1,
        4,
        1,
        0,
        0,
        4,
        4,
        0,
        0,
        3,
        0,
        1,
        3,
        0,
        1,
        4,
        0,
        1,
        0,
        1,
        0,
        3,
        4,
        3,
        0,
        1,
        0
    };
};

#endif // !__BOT_ROBOT_PLAYER_HPP__

Eu odeio C ++ agora ...

ATaco
fonte
@FrenzyLi Não sei como eu não percebi isso, corrigi-lo agora.
ATaco 29/12/16
Bem, após esta atualização, o bot parece ter uma abertura fixa de 00.
Frenzy Li
Entendo por que agora ... "1: 1" dá "0".
Frenzy Li
11
vários jogadores aqui fixaram todo o seu jogo baseado em turnos, então eu não acho que uma abertura fixa deve ser um problema
eis
10

CBetaPlayer (cβ)

Equilíbrio aproximado de Nash.

Este bot é apenas matemática sofisticada com um invólucro de código.

Podemos reformular isso como um problema da teoria dos jogos. Indique uma vitória por +1 e uma perda por -1. Agora seja B (x, y) o valor do jogo em que temos x munição e nosso oponente tem y munição. Observe que B (a, b) = -B (b, a) e então B (a, a) = 0. Para encontrar os valores de B em termos de outros valores de B, podemos calcular o valor da matriz de payoff. Por exemplo, temos que B (1, 0) é dado pelo valor do seguinte sub-jogo:

       load      metal
load    B(0, 1)   B(2, 0)
bullet  +1        B(0, 0)

(Eu removi as opções "ruins", também conhecidas como estritamente dominadas pelas soluções existentes. Por exemplo, não tentaríamos disparar plasma, pois temos apenas 1 munição. Da mesma forma, nosso oponente nunca usaria um defletor térmico, pois nunca atiraremos plasma.)

A teoria dos jogos nos permite saber como encontrar o valor dessa matriz de pagamento, assumindo certas condições técnicas. Entendemos que o valor da matriz acima é:

                B(2, 0)
B(1, 0) = ---------------------
          1 + B(2, 0) - B(2, 1)

Prosseguindo para todos os jogos possíveis e observando que B (x, y) -> 1 como x -> infinito com y fixo, podemos encontrar todos os valores de B, o que, por sua vez, permite calcular os movimentos perfeitos!

Obviamente, a teoria raramente se alinha com a realidade. Resolver a equação para valores pequenos de x e y rapidamente se torna muito complicado. Para lidar com isso, introduzi o que chamo de aproximação cβ. Existem 7 parâmetros para esta aproximação: c0, β0, c1, β1, c, β e k. Supus que os valores B assumissem a seguinte forma (formas mais específicas primeiro):

B(1, 0) = k
B(x, 0) = 1 - c0 β0^x
B(x, 1) = 1 - c1 β1^x
B(x, y) = 1 - c β^(x - y)   (if x > y)

Algum raciocínio aproximado sobre por que escolhi esses parâmetros. Primeiro, eu sabia que definitivamente queria lidar com munições 0, 1 e 2 ou mais separadamente, pois cada uma delas abre opções diferentes. Também pensei que uma função geométrica de sobrevivência seria a mais apropriada, porque o jogador defensivo está essencialmente adivinhando o que fazer. Achei que ter 2 ou mais munição era basicamente o mesmo, então concentrei-me na diferença. Eu também queria tratar B (1, 0) como um caso super especial, porque pensei que apareceria muito. O uso dessas formas aproximadas simplificou os cálculos dos valores B.

Resolvi aproximadamente as equações resultantes para obter cada valor B, que depois coloquei de volta na matriz para obter as matrizes de pagamento. Então, usando um solucionador de programação linear, encontrei as probabilidades ideais para fazer cada movimento e as coloquei no programa.

O programa é uma tabela de pesquisa glorificada. Se ambos os jogadores tiverem entre 0 e 4 munição, ela usará a matriz de probabilidade para determinar aleatoriamente qual movimento deve fazer. Caso contrário, ele tenta extrapolar com base em sua tabela.

Ele tem problemas contra bots determinísticos estúpidos, mas se sai muito bem contra bots racionais. Por causa de toda a aproximação, isso ocasionalmente perde para o StudiousPlayer quando realmente não deveria.

Obviamente, se eu fizesse isso de novo, provavelmente tentaria adicionar parâmetros mais independentes ou talvez uma forma melhor de ansatz e encontrar uma solução mais exata. Também eu (propositalmente) ignorei o limite de turnos, porque tornava as coisas mais difíceis. Uma modificação rápida pode ser feita para disparar sempre no plasma se tivermos munição suficiente e não houver curvas suficientes.

// CBetaPlayer (cβ)
// PPCG: George V. Williams

#ifndef __CBETA_PLAYER_HPP__
#define __CBETA_PLAYER_HPP__

#include "Player.hpp"
#include <iostream>

class CBetaPlayer final : public Player
{
public:
    CBetaPlayer(size_t opponent = -1) : Player(opponent)
    {
    }

public:
    virtual Action fight()
    {
        int my_ammo = getAmmo(), opp_ammo = getAmmoOpponent();

        while (my_ammo >= MAX_AMMO || opp_ammo >= MAX_AMMO) {
            my_ammo--;
            opp_ammo--;
        }

        if (my_ammo < 0) my_ammo = 0;
        if (opp_ammo < 0) opp_ammo = 0;

        double cdf = GetRandomDouble();
        int move = -1;
        while (cdf > 0 && move < MAX_MOVES - 1)
            cdf -= probs[my_ammo][opp_ammo][++move];

        switch (move) {
            case 0: return load();
            case 1: return bullet();
            case 2: return plasma();
            case 3: return metal();
            case 4: return thermal();
            default: return fight();
        }
    }

    static double GetRandomDouble() {
        static auto seed = std::chrono::system_clock::now().time_since_epoch().count();
        static std::default_random_engine generator((unsigned)seed);
        std::uniform_real_distribution<double> distribution(0.0, 1.0);
        return distribution(generator);
    }

private:
    static const int MAX_AMMO = 5;
    static const int MAX_MOVES = 5;

    double probs[MAX_AMMO][MAX_AMMO][5] =
        {
            {{1, 0, 0, 0, 0}, {0.58359, 0, 0, 0.41641, 0}, {0.28835, 0, 0, 0.50247, 0.20918}, {0.17984, 0, 0, 0.54611, 0.27405}, {0.12707, 0, 0, 0.56275, 0.31018}},
            {{0.7377, 0.2623, 0, 0, 0}, {0.28907, 0.21569, 0, 0.49524, 0}, {0.0461, 0.06632, 0, 0.53336, 0.35422}, {0.06464, 0.05069, 0, 0.43704, 0.44763}, {0.02215, 0.038, 0, 0.33631, 0.60354}},
            {{0.47406, 0.37135, 0.1546, 0, 0}, {0.1862, 0.24577, 0.15519, 0.41284, 0}, {0, 0.28343, 0.35828, 0, 0.35828}, {0, 0.20234, 0.31224, 0, 0.48542}, {0, 0.12953, 0.26546, 0, 0.605}},
            {{0.33075, 0.44563, 0.22362, 0, 0}, {0.17867, 0.20071, 0.20071, 0.41991, 0}, {0, 0.30849, 0.43234, 0, 0.25916}, {0, 0.21836, 0.39082, 0, 0.39082}, {0, 0.14328, 0.33659, 0, 0.52013}},
            {{0.24032, 0.48974, 0.26994, 0, 0}, {0.14807, 0.15668, 0.27756, 0.41769, 0}, {0, 0.26804, 0.53575, 0, 0.19621}, {0, 0.22106, 0.48124, 0, 0.2977}, {0, 0.15411, 0.42294, 0, 0.42294}}
        };


};

#endif // !__CBETA_PLAYER_HPP__
George V. Williams
fonte
Como você não passa um parâmetro para GetRandomDouble, você pode remover o argumento max.
Frenzy Li
@FrenzyLi, whoops, obrigado!
George V. Williams
Você se importaria de adicionar um pouco mais de informação sobre o seu aparelho, como como chegou à probabilidade ... tensor?
Frenzy Li
2
Eu amo esse bot. Eu acho que SP tem a vantagem até agora apenas devido ao determinismo das outras entradas; quanto mais bots aleatórios (com peso não ideal) forem adicionados, melhores tarifas de CBP. Isso é apoiado por testes; nos meus testes internos com os suspeitos habituais, o SP sempre vence com o CBP em segundo lugar ... no entanto, em um mini concurso envolvendo CBP, SP e FP, o CBP avança 55% das vezes, com SP e FP se saindo uniformemente.
H Walters
11
A propósito, esta é uma aproximação impressionantemente precisa do equilíbrio nash. Monte não tenta encontrar a estratégia de equilíbrio, mas a melhor jogada contra qualquer oponente. O fato de vencer apenas 52% dos duelos entre ele e cβ significa que cβ está bem perto do equilíbrio nash.
TheNumberOne
8

Não tenho o comentário certo em todos os lugares, por isso ainda não posso fazer minhas perguntas. Portanto, este é um jogador muito básico para vencer o primeiro bot.

[Editar] Obrigado, agora o status anterior não é mais verdadeiro, mas acho que é melhor mantê-lo para que possamos entender o contexto desse bot.

o Opportunist

O oportunista frequenta o mesmo clube de armas que os GunClubPlayers, no entanto, ele apostou para um novato que poderia vencer todos os GunClubPlayers. Então, ele explora o hábito que há muito percebe e se força a não atirar, mas espera um pouco para vencer.

#ifndef __OPPORTUNIST_PLAYER_HPP__
#define __OPPORTUNIST_PLAYER_HPP__

#include <string>
#include <vector>

class OpportunistPlayer final: public Player
{
public:
    OpportunistPlayer(size_t opponent = -1) : Player(opponent) {}

public:
    virtual Action fight()
    {
        switch (getTurn() % 3)
        {
        case 0:
            return load();
            break;
        case 1:
            return metal();
            break;
        case 2:
            return bullet();
            break;
        }
        return plasma();
    }
};
#endif // !__OPPORTUNIST_PLAYER_HPP__
ColdK
fonte
7

o BarricadePlayer

O Barricade Player carrega uma bala na primeira rodada e depois mantém um escudo apropriado (ainda um pouco aleatório). Ele também carrega outro tiro a cada quinta rodada. A cada rodada, há 15% de chance de ignorar o algoritmo (exceto para recarregar o primeiro turno) e disparar uma bala. Quando o inimigo não tem munição, ele carrega. Se de alguma forma tudo der errado, oh garoto, ele apenas atira.

Alterações mais recentes:

Números aleatórios aprimorados (obrigado Frenzy Li).

// BarricadePlayer by devRicher
// PPCG: http://codegolf.stackexchange.com/a/104909/11933

// BarricadePlayer.hpp
// A very tactical player.

#ifndef __BARRICADE_PLAYER_HPP__
#define __BARRICADE_PLAYER_HPP__

#include "Player.hpp"
#include <cstdlib>
#include <ctime>

class BarricadePlayer final : public Player
{
public:
    BarricadePlayer(size_t opponent = -1) : Player(opponent) {}

public:
    virtual Action fight()
    {
        srand(time(NULL));
        if (getTurn() == 0) { return load(); }
        int r = GetRandomInteger(99) + 1; //Get a random
        if ((r <= 15) && (getAmmo() > 0)) { return bullet(); } //Override any action, and just shoot
        else
        {
            if (getTurn() % 5 == 0) //Every first and fifth turn
                return load();
            if (getAmmoOpponent() == 1) return metal();
            if (getAmmoOpponent() > 1) { return r <= 50 ? metal() : thermal(); }
            if (getAmmoOpponent() == 0) return load();

        }
        return bullet();
    }
};

#endif // !__BARRICADE_PLAYER_HPP__
devRicher
fonte
11
Você quer pelo menos verificar se há munição antes de disparar?
Pavel
8
Não. Eu vivo a vida perigosa. @Pavel
devRicher
11
Não é inútil usar o defletor térmico no segundo turno? Você não pode carregar duas balas no primeiro turno. Eu acho que mesmo que você queira que seja aleatório, você deve evitar o uso do escudo térmico se as balas do oponente forem 1 (ou menos).
Southpaw Hare
11
Obrigado por todas as sugestões, editei muito a classe. @SouthpawHare
devRicher
2
É getAmmoOpponentnão getOpponentAmmo. Você também está perdendo#endif // !__BARRICADE_PLAYER_HPP__
Azul
7

o StudiousPlayer

O jogador estudioso estuda sua presa, modelando cada oponente que encontra. Este jogador começa com uma estratégia básica, conduzida aleatoriamente em alguns lugares, e progride para estratégias adaptativas simples, baseadas em medidas freqüentes de resposta do oponente. Ele usa um modelo simples de oponentes com base em como eles reagem às combinações de munição.

#ifndef __STUDIOUS_PLAYER_H__
#define __STUDIOUS_PLAYER_H__

#include "Player.hpp"
#include <unordered_map>

class StudiousPlayer final : public Player
{
public:
   using Player::GetRandomInteger;
   // Represents an opponent's action for a specific state.
   struct OpponentAction {
      OpponentAction(){}
      unsigned l=0;
      unsigned b=0;
      unsigned p=0;
      unsigned m=0;
      unsigned t=0;
   };
   // StudiousPlayer models every opponent that it plays,
   // and factors said model into its decisions.
   //
   // There are 16 states, corresponding to
   // 4 inner states (0,1,2,3) and 4 outer states
   // (0,1,2,3). The inner states represent our
   // (SP's) ammo; the outer represents the
   // Opponent's ammo.  For the inner or outer
   // states, 0-2 represent the exact ammo; and
   // 3 represents "3 or more".
   //
   // State n is (4*outer)+inner.
   //
   // State 0 itself is ignored, since we don't care
   // what action the opponent takes (we always load);
   // thus, it's not represented here.
   //
   // os stores states 1 through 15 (index 0 through 14).
   struct Opponent {
      std::vector<OpponentAction> os;
      Opponent() : os(15) {}
   };
   StudiousPlayer(size_t opponent)
      : Player(opponent)
      , strat(storedLs()[opponent])
      , ammoOpponent()
   {
   }
   Player::Action fight() {
      // Compute the current "ammo state".
      // For convenience here (aka, readability in switch),
      // this is a two digit octal number.  The lso is the
      // inner state, and the mso the outer state.
      unsigned ss,os;
      switch (ammoOpponent) {
      default: os=030; break;
      case 2 : os=020; break;
      case 1 : os=010; break;
      case 0 : os=000; break;
      }
      switch (getAmmo()) {
      default: ss=003; break;
      case 2 : ss=002; break;
      case 1 : ss=001; break;
      case 0 : ss=000; break;
      }
      // Store the ammo state.  This has a side effect
      // of causing actn() to return an OpponentAction
      // struct, with the opponent's history during this
      // state.
      osa = os+ss;
      // Get the opponent action pointer
      const OpponentAction* a=actn(osa);
      // If there's no such action structure, assume
      // we're just supposed to load.
      if (!a) return load();
      // Apply ammo-state based strategies:
      switch (osa) {
      case 001:
         // If opponent's likely to load, shoot; else load
         if (a->l > a->m) return bullet();
         return load();
      case 002:
      case 003:
         // Shoot in the way most likely to kill (or randomly)
         if (a->t > a->m+a->l) return bullet();
         if (a->m > a->t+a->l) return plasma();
         if (GetRandomInteger(1)) return bullet();
         return plasma();
      case 010:
         // If opponent tends to load, load; else defend
         if (a->l > a->b) return load();
         return metal();
      case 011:
         // Shoot if opponent tends to load
         if (a->l > a->b+a->m) return bullet();
         // Defend if opponent tends to shoot
         if (a->b > a->l+a->m) return metal();
         // Load if opponent tends to defend
         if (a->m > a->b+a->l) return load();
         // Otherwise randomly respond
         if (!GetRandomInteger(2)) return metal();
         if (!GetRandomInteger(1)) return load(); 
         return bullet();                         
      case 012:
      case 013:
         // If opponent most often shoots, defend
         if (a->b > a->l+a->m+a->t) return metal();
         // If opponent most often thermals, use bullet
         if (a->t > a->m) return bullet();
         // If opponent most often metals, use plasma
         if (a->m > a->t) return plasma();
         // Otherwise use a random weapon
         return (GetRandomInteger(1))?bullet():plasma();
      case 020:
         // If opponent most often loads or defends, load
         if (a->l+a->m+a->t > a->b+a->p) return load();
         // If opponent most often shoots bullets, raise metal
         if (a->b > a->p) return metal();
         // If opponent most often shoots plasma, raise thermal
         if (a->p > a->b) return thermal();
         // Otherwise raise random defense
         return (GetRandomInteger(1))?metal():thermal();
      case 021:
      case 031:
         // If opponent loads more often than not,
         if (a->l > a->m+a->b+a->p) {
            // Tend to shoot (67%), but possibly load (33%)
            return (GetRandomInteger(2))?bullet():load();
         }
         // If opponent metals more often than loads or shoots, load
         if (a->m > a->l+a->b+a->p) return load();
         // If opponent thermals (shrug) more often than loads or shoots, load
         if (a->t > a->l+a->b+a->p) return load();
         // If opponent tends to shoot bullets, raise metal
         if (a->b > a->p) return metal();
         // If opponent tends to shoot plasma, raise thermal
         if (a->p > a->b) return thermal();
         // Raise random shield
         return (GetRandomInteger(2))?metal():thermal();
      case 022:
         // If opponent loads or thermals more often than not, shoot bullet
         if (a->l+a->t > a->b+a->p+a->m) return bullet();
         // If opponent loads or metals more often than not, shoot plasma
         if (a->l+a->m > a->b+a->p+a->t) return plasma();
         // If opponent shoots more than loads or defends, defend
         if (a->b+a->p > a->l+a->m+a->t) {
            if (a->b > a->p) return metal();
            if (a->p > a->b) return thermal();
            return (GetRandomInteger(1))?metal():thermal();
         }
         // If opponent defends more than opponent shoots, load
         if (a->m+a->t > a->b+a->p) return load();
         // Use random substrategy;
         // load(33%)
         if (GetRandomInteger(2)) return load();
         // defend(33%)
         if (GetRandomInteger(1)) {
            if (a->b > a->p) return metal();
            if (a->b > a->b) return thermal();
            return (GetRandomInteger(1))?metal():thermal();
         }
         // Shoot in a way that most often kills (or randomly)
         if (a->m > a->t) return plasma();
         if (a->t > a->m) return bullet();
         return (GetRandomInteger(1))?bullet():plasma();
      case 023:
         // If opponent loads or raises thermal more often than not, shoot bullets
         if (a->l+a->t > a->b+a->p+a->m) return bullet();
         // If opponent loads or raises metal more often than not, shoot plasma
         if (a->l+a->m > a->b+a->p+a->t) return plasma();
         // If opponent shoots more than loads or defends, defend
         if (a->b+a->p > a->l+a->m+a->t) {
            if (a->b > a->p) return metal();
            if (a->p > a->b) return thermal();
            return (GetRandomInteger(1))?metal():thermal();
         }
         // If opponent defends more than shoots, shoot
         if (a->m+a->t > a->b+a->p) {
            if (a->m > a->t) return plasma();
            if (a->t > a->m) return bullet();
            return GetRandomInteger(1)?bullet():plasma();
         }
         // 50% defend
         if (GetRandomInteger(1)) {
            if (a->b > a->p) return metal();
            return thermal();
         }
         // 50% shoot
         if (a->m > a->t) return plasma();
         if (a->t > a->m) return bullet();
         return (GetRandomInteger(1))?bullet():plasma();
      case 030:
         // If opponent loads or shields more often than not, load
         if (a->l+a->m+a->t > a->b+a->p) return load();
         // If opponent tends to shoot, defend
         if (a->b+a->p >= a->l+a->m+a->t) {
            if (a->b > a->p) return metal();
            if (a->p > a->b) return thermal();
            return (GetRandomInteger(1))?metal():thermal();
         }
         // Otherwise, randomly shield (50%) or load
         if (GetRandomInteger(1)) {
            return (GetRandomInteger(1))?metal():thermal();
         }
         return load();
      case 032:
         // If opponent loads or thermals more often than not, shoot bullets
         if (a->l+a->t > a->b+a->p+a->m) return bullet();
         // If opponent loads or metals more often than not, shoot plasma
         if (a->l+a->m > a->b+a->p+a->t) return plasma();
         // If opponent shoots more often than loads or shields, defend
         if (a->b+a->p > a->l+a->m+a->t) {
            if (a->b > a->p) return metal();
            if (a->p > a->b) return thermal();
            return (GetRandomInteger(1))?metal():thermal();
         }
         // If opponent shields more often than shoots, load
         if (a->m+a->t > a->b+a->p) return load();
         // Otherwise use random strategy
         if (GetRandomInteger(2)) return load();
         if (GetRandomInteger(1)) {
            if (a->b > a->p) return metal();
            return thermal();
         }
         if (a->m > a->t) return plasma();
         if (a->t > a->m) return bullet();
         return (GetRandomInteger(1))?bullet():plasma();
      case 033:
         {
            // At full 3 on 3, apply random strategy
            // weighted by opponent's histogram of this state...
            // (the extra 1 weights towards plasma)
            unsigned sr=
               GetRandomInteger
               (a->l+a->t+a->p+a->b+a->m+1);
            // Shoot bullets proportional to how much
            // opponent loads or defends using thermal
            if (sr < a->l+a->t) return bullet();
            sr-=(a->l+a->t);
            // Defend with thermal proportional to how
            // much opponent attacks with plasma (tending to
            // waste his ammo)
            if (sr < a->p) return thermal();
            // Shoot plasma proportional to how
            // much opponent shoots bullets or raises metal
            return plasma();
         }
      }
      // Should never hit this; but rather than ruin everyone's fun,
      // if we do, we just load
      return load();
   }
   // Complete override; we use our opponent's model, not history.
   void perceive(Player::Action action) {
      // We want the ammo but not the history; since
      // the framework (Player::perceive) is "all or nothing", 
      // StudiousPlayer just tracks the ammo itself
      switch (action) {
      default: break;
      case Player::LOAD:   ++ammoOpponent; break;
      case Player::BULLET: --ammoOpponent; break;
      case Player::PLASMA: ammoOpponent-=2; break;
      }
      // Now we get the opponent's action based
      // on the last (incoming) ammo state
      OpponentAction* a = actn(osa);
      // ...if it's null just bail
      if (!a) return;
      // Otherwise, count the action
      switch (action) {
      case Player::LOAD    : ++a->l; break;
      case Player::BULLET  : ++a->b; break;
      case Player::PLASMA  : ++a->p; break;
      case Player::METAL   : ++a->m; break;
      case Player::THERMAL : ++a->t; break;
      }
   }
private:
   Opponent& strat;
   OpponentAction* actn(unsigned octalOsa) {
      unsigned ndx = (octalOsa%4)+4*(octalOsa/8);
      if (ndx==0) return 0;
      --ndx;
      if (ndx<15) return &strat.os[ndx];
      return 0;
   }
   unsigned osa;
   unsigned ammoOpponent;
   // Welcome, non-C++ persons, to the "Meyers style singleton".
   // "theMap" is initialized (constructed; initially empty)
   // the first time the declaration is executed.
   static std::unordered_map<size_t, Opponent>& storedLs() {
      static std::unordered_map<size_t, Opponent> theMap;
      return theMap;
   }
};

#endif

Observe que isso rastreia informações sobre os oponentes de acordo com as regras do desafio; consulte o método "Meyers style singleton" com escopo "storedLs ()" na parte inferior. (Algumas pessoas estavam se perguntando como fazer isso; agora você sabe!)

H Walters
fonte
11
Eu não tinha ideia de que era chamado de singleton estilo Meyers até que vi isso!
Frenzy Li
11
Não leve o termo muito a sério - é um tipo de abuso de termos, pois o "singleton" é mais uma instanciação de modelo do que uma estrutura declarada, mas é a mesma técnica.
H Walters
6

o GunClubPlayer

Recorte da pergunta original. Isso serve como um exemplo de implementação minimalista de um player derivado. Este jogador participará do torneio.

É GunClubPlayercomo ir ao clube das armas. Durante cada duelo, eles primeiro carregavam munição, depois disparavam uma bala e repetiam esse processo até o final do duelo mundial . Na verdade, eles não se importam se vencem ou não e se concentram exclusivamente em ter uma experiência agradável.

// GunClubPlayer.hpp
// A gun club enthusiast. Minimalistic example of derived class

#ifndef __GUN_CLUB_PLAYER_HPP__
#define __GUN_CLUB_PLAYER_HPP__

#include "Player.hpp"

class GunClubPlayer final: public Player
{
public:
    GunClubPlayer(size_t opponent = -1) : Player(opponent) {}

public:
    virtual Action fight()
    {
        return getTurn() % 2 ? bullet() : load();
    }
};

#endif // !__GUN_CLUB_PLAYER_HPP__
Frenzy Li
fonte
11
Você não precisa do outro após uma declaração de retorno, certo? Eu sei que não é código de golfe, mas parece errado.
Pavel
2
@ Pavel Bem, OK, então ... é ... meio que jogado agora.
Frenzy Li
5

o PlasmaPlayer

O jogador de plasma gosta de disparar seus raios de plasma. Ele tentará carregar e disparar o máximo possível. No entanto, enquanto o oponente tiver munição de plasma, ele usará seu escudo térmico (as balas são para os fracos).

#ifndef __PLASMA_PLAYER_HPP__
#define __PLASMA_PLAYER_HPP__

#include "Player.hpp"

class PlasmaPlayer final : public Player
{
public:
    PlasmaPlayer(size_t opponent = -1) : Player(opponent) {}

    virtual Action fight()
    {
        // Imma Firin Mah Lazer!
        if (getAmmo() > 1) return plasma();

        // Imma Block Yur Lazer!
        if (getAmmoOpponent() > 1) return thermal();

        // Imma need more Lazer ammo
        return load();
    }
};

#endif // !__PLASMA_PLAYER_HPP__
Brian J
fonte
@FrenzyLi obrigado pelo construtor! Meu C ++ está um pouco enferrujado e não tenho um compilador nesta máquina.
Brian J
De nada! Ainda estou adicionando mais código (imprimir placar, ler script externo etc.) ao projeto e é muita sorte que nenhum dos envios esteja quebrado ainda.
Frenzy Li
Isso funcionará bem para qualquer oponente além do GunClub. Sim, ele matará o SadisticShooter (melhor). @BrianJ
devRicher
5

O muito SadisticShooter

Ele prefere vê-lo sofrer a matá-lo. Ele não é estúpido e se cobrirá conforme necessário.

Se você é totalmente chato e previsível, ele simplesmente o mata imediatamente.

// SadisticShooter by muddyfish
// PPCG: http://codegolf.stackexchange.com/a/104947/11933

// SadisticShooter.hpp
// A very sad person. He likes to shoot people.

#ifndef __SAD_SHOOTER_PLAYER_HPP__
#define __SAD_SHOOTER_PLAYER_HPP__

#include <cstdlib>
#include "Player.hpp"
// #include <iostream>

class SadisticShooter final : public Player
{
public:
    SadisticShooter(size_t opponent = -1) : Player(opponent) {}
private:
    bool historySame(std::vector<Action> const &history, int elements) {
        if (history.size() < elements) return false;

        std::vector<Action> lastElements(history.end() - elements, history.end());

        for (Action const &action : lastElements)
            if (action != lastElements[0]) return false;
        return true;
    }
public:
    virtual Action fight()
    {
        int my_ammo = getAmmo();
        int opponent_ammo = getAmmoOpponent();
        int turn_number = getTurn();
        //std::cout << " :: Turn " << turn_number << " ammo: " << my_ammo << " oppo: " << opponent_ammo << std::endl;

        if (turn_number == 90) {
            // Getting impatient
            return load();
        }
        if (my_ammo == 0 && opponent_ammo == 0) {
            // It would be idiotic not to load here
            return load();
        }
        if (my_ammo >= 2 && historySame(getHistoryOpponent(), 3)) {
            if (getHistoryOpponent()[turn_number - 1] == THERMAL) return bullet();
            if (getHistoryOpponent()[turn_number - 1] == METAL) return thermal();
        }
        if (my_ammo < 2 && opponent_ammo == 1) {
            // I'd rather not die thank you very much
            return metal();
        }
        if (my_ammo == 1) {
            if (opponent_ammo == 0) {
                // You think I would just shoot you?
                return load();
            }
            if (turn_number == 2) {
                return thermal();
            }
            return bullet();
        }
        if (opponent_ammo >= 2) {
            // Your plasma weapon doesn't scare me
            return thermal();
        }
        if (my_ammo >= 2) {
            // 85% more bullet per bullet
            if (turn_number == 4) return bullet();
            return plasma();
        }
        // Just load the gun already
        return load();
    }
};

#endif // !__SAD_SHOOTER_PLAYER_HPP__
Azul
fonte
Vejo que você consertou.
devRicher
4

o TurtlePlayer

TurtlePlayeré um covarde. Ele passa a maior parte do tempo se escondendo atrás de seus escudos - daí o nome. Às vezes, ele pode sair da sua concha (sem trocadilhos) e dar um tiro, mas normalmente fica quieto enquanto o inimigo tem munição.


Este bot não é particularmente bom - no entanto, todo KOTH precisa de algumas entradas iniciais para executá-lo :)

Testes locais descobriram que este ganha tanto contra GunClubPlayere Opportunist100% do tempo. Uma batalha contra BotRobotPlayerparecia sempre resultar em empate, pois ambos se escondiam atrás de seus escudos.

#include "Player.hpp"

// For randomness:
#include <ctime>
#include <cstdlib>

class TurtlePlayer final : public Player {

public:
    TurtlePlayer(size_t opponent = -1) : Player(opponent) { srand(time(0)); }

public:
    virtual Action fight() {
        if (getAmmoOpponent() > 0) {
            // Beware! Opponent has ammo!

            if (rand() % 5 == 0 && getAmmo() > 0) 
                // YOLO it:
                return getAmmo() > 1 ? plasma() : bullet();

            // Play it safe:
            if (getAmmoOpponent() == 1) return metal();
            return rand() % 2 ? metal() : thermal();
        }

        if (getAmmo() == 0) 
            // Nobody has ammo: Time to load up.
            return load();

        else if (getAmmo() > 1) 
            // We have enough ammo for a plasma: fire it!
            return plasma();

        else 
            // Either load, or take a shot.
            return rand() % 2 ? load() : bullet();
    }
};
FlipTack
fonte
4

o DeceptivePlayer

O Deceptive Player tenta carregar duas balas e depois dispara uma.

// DeceiverPlayer.hpp
// If we have two shoots, better shoot one by one

#ifndef __DECEPTIVE_PLAYER_HPP__
#define __DECEPTIVE_PLAYER_HPP__

#include "Player.hpp"

class DeceptivePlayer final: public Player
{
public:
    DeceptivePlayer(size_t opponent = -1) : Player(opponent) {}

public:
    virtual Action fight()
    {
        int ammo = getAmmo();
        int opponentAmmo = getAmmoOpponent();
        int turn = getTurn();

        // Without ammo, always load
        if (ammo == 0)
        {
            return load();
        }

        // Every 10 turns the Deceiver goes crazy
        if (turn % 10 || opponentAmmo >= 3)
        {
            // Generate random integer in [0, 5)
            int random = GetRandomInteger() % 5;
            switch (random)
            {
            case 0:
                return bullet();
            case 1:
                return metal();
            case 2:
                if (ammo == 1)
                {
                    return bullet();
                }

                return plasma();
            case 3:
                return thermal();
            case 4:
                return load();
            }
        }

        // The Deceiver shoots one bullet
        if (ammo == 2)
        {
            return bullet();
        }

        // Protect until we can get bullet 2
        if (opponentAmmo == 0)
        {
            return load();
        }

        if (opponentAmmo == 1)
        {
            return metal();
        }

        if (opponentAmmo == 2)
        {
            return thermal();
        }
    }
};

#endif // !__DECEPTIVE_PLAYER_HPP__

Como não codifico em c ++, quaisquer melhorias no código serão bem-vindas.

Sxntk
fonte
Minha edição está na definição de módulo e macro. Não sabe se vai gostar, mas talvez DeceptivePlayerseja um nome melhor?
Frenzy Li
@FrenzyLi Sim, eu gosto, vou mudar o nome #
Sxntk
11
@Sxntk Gosto da ironia em que esse jogador espera que pessoas com 2 munições atinjam plasma, mas ele mesmo terá duas munições e disparará uma bala.
Brian J
@Sxntk Você não tem a possibilidade de não retornar nada atualmente. Um jogador tem permissão para mais de duas munições. Portanto, se seu oponente tiver mais de 3 munições, você não fará nada. Você pode acabar com uma arma explodida em algum lugar. (é claro, que poderia ser o seu plano mestre de qualquer maneira :))
Brian J
@BrianJ Obrigado, vou pensar nisso, enquanto isso deixarei o Deceptive enlouquecer e decidirei o que fazer quando o oponnent tiver mais de 3 munições #
Sxntk
2

HanSoloPlayer

Atira primeiro! Ainda estou trabalhando na revisão, mas isso é muito bom.

// HanSoloPlayer.hpp
// A reluctant rebel. Always shoots first.

// Revision 1: [13HanSoloPlayer][17] | 6 rounds | 2863

#ifndef __HAN_SOLO_PLAYER_HPP__
#define __HAN_SOLO_PLAYER_HPP__

#include "Player.hpp"

class HanSoloPlayer final: public Player
{
public:
    HanSoloPlayer(size_t opponent = -1) : Player(opponent) {}

public:
    virtual Action fight()
    {
        if(getTurn() == 0){
            // let's do some initial work
            agenda.push_back(bullet());     // action 2--han shot first!
            agenda.push_back(load());       // action 1--load a shot
        } else if(getTurn() == 2){
            randomDefensive();
        } else if(getRandomBool(2)){
            // go on the defensive about 1/3rd of the time
            randomDefensive();
        } else if(getRandomBool(5)){
            // all-out attack!
            if(getAmmo() == 0){
                // do nothing, let the agenda work its course
            } else if(getAmmo() == 1){
                // not quite all-out... :/
                agenda.push_back(load());   // overnext
                agenda.push_back(bullet()); // next
            } else if(getAmmo() == 2){
                agenda.push_back(load());   // overnext
                agenda.push_back(plasma()); // next
            } else {
                int ammoCopy = getAmmo();
                while(ammoCopy >= 2){
                    agenda.push_back(plasma());
                    ammoCopy -= 2;
                }
            }
        }

        // execute the next item on the agenda
        if(agenda.size() > 0){
            Action nextAction = agenda.back();
            agenda.pop_back();
            return nextAction;
        } else {
            agenda.push_back(getRandomBool() ? thermal() : bullet()); // overnext
            agenda.push_back(load());                                 // next
            return load();
        }
    }
private:
    std::vector<Action> agenda;
    bool getRandomBool(int weight = 1){
        return GetRandomInteger(weight) == 0;
    }
    void randomDefensive(){
        switch(getAmmoOpponent()){
            case 0:
                // they most likely loaded and fired. load, then metal shield
                agenda.push_back(metal());  // action 4
                agenda.push_back(load());   // action 3
                break;
            case 1:
                agenda.push_back(metal());
                break;
            case 2:
                agenda.push_back(getRandomBool() ? thermal() : metal());
                break;
            default:
                agenda.push_back(getRandomBool(2) ? metal() : thermal());
                break;
        }
        return;
    }
};

#endif // !__HAN_SOLO_PLAYER_HPP__
Conor O'Brien
fonte
2

o CamtoPlayer

CamtoPlayer DEIA empates e vai sair de loops não importa o que é preciso. (exceto suicídio)

É o meu primeiro programa C ++ que faz qualquer coisa, por isso não julgue muito.

Eu sei que poderia ser melhor, mas por favor não edite.
Se você deseja modificar o código, basta comentar uma sugestão.

#ifndef __CAMTO_HPP__
#define __CAMTO_HPP__

#include "Player.hpp"
#include <iostream>

class CamtoPlayer final : public Player
{
public:
    CamtoPlayer(size_t opponent = -1) : Player(opponent) {}
        int S = 1; // Switch between options. (like a randomness function without any randomness)
        bool ltb = false; // L.ast T.urn B.locked
        bool loop = false; // If there a loop going on.
        int histarray[10]={0,0,0,0,0,0,0,0,0,0}; // The last ten turns.
        int appears(int number) { // How many times a number appears(); in histarray, used for checking for infinite loops.
            int things = 0; // The amount of times the number appears(); is stored in things.
            for(int count = 0; count < 10; count++) { // For(every item in histarray) {if its the correct number increment thing}.
                if(histarray[count]==number) {things++;}
            }
            return things; // Return the result
        }
    virtual Action fight()
    {
        int ammo = getAmmo(); // Ammo count.
        int bad_ammo = getAmmoOpponent(); // Enemy ammo count.
        int turn = getTurn(); // Turn count.
        int pick = 0; // This turn's weapon.

        if(appears(2)>=4){loop=true;} // Simple loop detection
        if(appears(3)>=4){loop=true;} // by checking if
        if(appears(4)>=4){loop=true;} // any weapong is picked a lot
        if(appears(5)>=4){loop=true;} // except for load();

        if(ammo==0&&bad_ammo==1){pick=4;} // Block when he can shoot me.
        if(ammo==0&&bad_ammo>=2){S++;S%2?(pick=4):(pick=5);} // Block against whatever might come!
        if(ammo==0&&bad_ammo>=1&&ltb){pick=1;} // If L.ast T.urn B.locked, then reload instead.
        if(ammo==1&&bad_ammo==0){pick=2;} // Shoot when the opponent can't shoot.
        if(ammo==1&&bad_ammo==1){S++;S%2?(pick=2):(pick=4);} // No risk here.
        if(ammo==1&&bad_ammo>=2){S++;S%2?(pick=4):(pick=5);} // Block!
        if(ammo==1&&bad_ammo>=1&&ltb){pick=2;} // If ltb shoot instead.
        if(ammo>=2){S++;S%2?(pick=2):(pick=3);} // Shoot something!

        /* debugging
            std :: cout << "Turn data: turn: ";
            std :: cout << turn;
            std :: cout << " loop: ";
            std :: cout << loop;
            std :: cout << " ";
            std :: cout << "ltb: ";
            std :: cout << ltb;
            std :: cout << " ";
        */

        // Attempt to break out of the loop. (hoping there is one)
        if(ammo==0&&loop){pick=1;} // After many turns of waiting, just load();
        if(ammo==1&&bad_ammo==0&&loop){loop=false;pick=1;} // Get out of the loop by loading instead of shooting.
        if(ammo==1&&bad_ammo==1&&loop){loop=false;pick=4;} // Get out of the loop (hopefully) by blocking.
        if(ammo>=2&&loop){loop=false;S++;S%2?(pick=2):(pick=3);} // Just shoot.
        if(turn==3&&(appears(1)==2)&&(appears(2)==1)){pick=4;} // If it's just load();, shoot();, load(); then metal(); because it might be a loop.
        // End of loop breaking.

        if(turn==1){pick=2;} // Shoot right after reloading!
        if(ammo==0&&bad_ammo==0){pick=1;} // Always load when no one can shoot.

        for(int count = 0; count < 10; count++) {
            histarray[count]=histarray[count+1]; // Shift all values in histarray[] by 1.
        }
        histarray[9] = pick; // Add the picked weapon to end of histarray[].

        /*  more debugging
            std :: cout << "history: ";
            std :: cout << histarray[0];
            std :: cout << histarray[1];
            std :: cout << histarray[2];
            std :: cout << histarray[3];
            std :: cout << histarray[4];
            std :: cout << histarray[5];
            std :: cout << histarray[6];
            std :: cout << histarray[7];
            std :: cout << histarray[8];
            std :: cout << histarray[9];

            std :: cout << " pick, ammo, bammo: ";
            std :: cout << pick;
            std :: cout << " ";
            std :: cout << ammo;
            std :: cout << " ";
            std :: cout << bad_ammo;
            std :: cout << "\n";
        */
        switch(pick) {
            case 1:
                ltb = false; return load();
            case 2:
                ltb = false; return bullet();
            case 3:
                ltb = false; return plasma();
            case 4:
                ltb = true;return metal();
            case 5:
                ltb = true;return thermal();
        }

    }
};

#endif // !__CAMTO_HPP__
Benjamin Philippe
fonte
Você está esquecendo um ##endif // ! __CAMTO_HPP__
Blue
@muddyfish Obrigado por me dizer, eu tenho vários símbolos que impediram a renderização do código! XD
Benjamin Philippe
Ainda não está aparecendo. Eu recomendaria abandonar as tags HTML completamente e apenas usar a marcação (o botão "Exemplo de código" que contém "{}"). Citar manualmente <>&é uma dor.
H Walters
@HWalters Obrigado pela dica!
Benjamin Philippe
Obrigado por participar. E uma coisa: remova using namespace stdporque interfere com o torneio. Se você deseja depurar, você pode usar std::coutetc.
Frenzy Li
1

o SurvivorPlayer

O jogador sobrevivente se comporta da mesma maneira que o jogador tartaruga e barricada. Ele nunca tomará uma ação que poderia levar à sua morte e preferiria aplicar um empate a perder a luta.

// SurvivorPlayer.hpp
// Live to fight another day

#ifndef __SURVIVOR_PLAYER_HPP__
#define __SURVIVOR_PLAYER_HPP__

#include "Player.hpp"

class SurvivorPlayer final : public Player
{
public:
SurvivorPlayer(size_t opponent = -1) : Player(opponent)
{
}

public:
    virtual Action fight()
    {
        int myAmmo = getAmmo();
        int opponentAmmo = getAmmoOpponent();
        int turn = getTurn();
        if (turn == 0) {
            return load();
        }
        switch (opponentAmmo) {
        case 0:
            if (myAmmo > 2) {
                return GetRandomInteger(1) % 2 ? bullet() : plasma();
            }
            return load();
        case 1:
            if (myAmmo > 2) {
                return plasma();
            }
            return metal();
        default:
            if (myAmmo > 2) {
                return plasma();
            }
            return GetRandomInteger(1) % 2 ? metal() : thermal();
        }
    }
};

#endif // !__SURVIVOR_PLAYER_HPP__
Turamarth
fonte
1

o FatedPlayer

Feito por Clotho, marcado por Lachesis e morto por Atropos ; A única estratégia deste jogador é usar o que sabe sobre munição para determinar quais ações são razoáveis.

No entanto, ele não consegue escolher a ação; essa parte é deixada para os deuses.

#ifndef __FATEDPLAYER_H__
#define __FATEDPLAYER_H__

#include "Player.hpp"
#include <functional>
class FatedPlayer final : public Player
{
public:
   FatedPlayer(size_t o) : Player(o){}
   Action fight() {
      std::vector<std::function<Action()>>c{[&]{return load();}};
      switch(getAmmo()){
      default:c.push_back([&]{return plasma();});
      case 1 :c.push_back([&]{return bullet();});
      case 0 :;}
      switch(getAmmoOpponent()){
      default:c.push_back([&]{return thermal();});
      case 1 :c.push_back([&]{return metal();});
      case 0 :;}
      return c[GetRandomInteger(c.size()-1)]();
   }
};

#endif

... porque eu gostaria de ver como um jogador aleatório classifica.

H Walters
fonte
1

SpecificPlayer

O SpecificPlayer segue um plano simples de escolher algumas ações aleatórias (válidas). No entanto, sua principal característica é que ele procura determinadas situações, analisando a contagem de munição e o movimento anterior do oponente.

Esta é minha primeira vez escrevendo algo em C ++ e tentando fazer qualquer tipo de escrita competitiva de bot. Então, espero que minha escassa tentativa faça pelo menos algo interessante. :)

// SpecificPlayer by Charles Jackson (Dysnomian) -- 21/01/2017
// PPCG: http://codegolf.stackexchange.com/a/104933/11933

#ifndef __SPECIFIC_PLAYER_HPP__
#define __SPECIFIC_PLAYER_HPP__

#include "Player.hpp"

class SpecificPlayer final : public Player
{
public:
    SpecificPlayer(size_t opponent = -1) : Player(opponent) {}

    //override
    virtual Action fight()
    {
        returnval = load(); //this should always be overwritten

        // if both players have no ammo we of course load
        if (oa == 0 && ma == 0) { returnval = load(); }

        // if (opponent has increased their ammo to a point they can fire something) then shield from it
        else if (oa == 1 && op == LOAD) { returnval = metal(); }
        else if (oa == 2 && op == LOAD) { returnval = thermal(); }
        else if (op == LOAD) { returnval = randomBlock(oa); }

        // if we have a master plan to follow through on do so, unless a defensive measure above is deemed necessary
        else if (nextDefined) { returnval = next; nextDefined = false; }

        // if opponent didn't fire their first shot on the second turn (turn 1) then we should block
        else if (t == 2 && oa >= 1) { returnval = randomBlock(oa); }

        //if opponent may be doing two attacks in a row
        else if (oa == 1 && op == BULLET) { returnval = metal(); }
        else if (oa == 2 && op == PLASMA) { returnval = thermal(); }

        // if we had no ammo last turn and still don't, load
        else if (ma == 0 && pa == 0) { returnval = load(); }

        // if we have just collected enough ammo to plasma, wait a turn before firing
        else if (ma == 2 && pa == 1) { 
            returnval = randomBlock(oa); next = plasma(); nextDefined = true; }

        // time for some random actions
        else
        {
            int caseval = GetRandomInteger(4) % 3; //loading is less likely than attacking or blocking
            switch (caseval) 
            {
            case 0: returnval = randomBlock(oa); break; // 40%
            case 1: returnval = randomAttack(ma); break; // 40%
            case 2: returnval = load(); break; // 20%
            }
        }

        pa = ma; //update previous ammo then update our current ammo
        switch (returnval)
        {
        case LOAD:
            ma += 1;
            break;
        case BULLET:
            ma -= 1;
            break;
        case PLASMA:
            ma -= 2;
            break;
        }
        t++; //also increment turn counter

        return returnval;
    }

    //override
     void perceive(Action action)
    {
         //record what action opponent took and update their ammo
         op = action;
         switch (action)
         {
         case LOAD:
             oa += 1;
             break;
         case BULLET:
             oa -= 1;
             break;
         case PLASMA:
             oa -= 2;
             break;
         }
    }

private:
    Action returnval; //our action to return
    Action next; //the action we want to take next turn - no matter what!
    bool nextDefined = false; //flag for if we want to be taking the "next" action.
    int t = 0; //turn number
    int ma = 0; //my ammo
    int oa = 0; //opponent ammo
    int pa = 0; //my previous ammo
    Action op; //opponent previous action

    Action randomBlock(int oa)
    {
        Action a;
        if (oa == 0) { a = load(); }
        else if (oa == 1) { a = metal(); }
        else
        {
            // more chance of ordianry block than laser block
            a = GetRandomInteger(2) % 2 ? metal() : thermal();
        }
        return a;
    }

    Action randomAttack(int ma)
    {
        Action a;
        if (ma == 0) { a = load(); }
        else if (ma == 1) { a = bullet(); }
        else
        {
            // more chance of ordianry attack than plasma
            a = GetRandomInteger(2) % 2 ? bullet() : plasma();
        }
        return a;
    }
};

#endif // !__SPECIFIC_PLAYER_HPP__
Dysnomian
fonte
1

NotSoPatientPlayer

A história de sua criação virá mais tarde.

// NotSoPatientPlayer.hpp

#ifndef __NOT_SO_PATIENT_PLAYER_HPP__
#define __NOT_SO_PATIENT_PLAYER_HPP__

#include "Player.hpp"
#include <iostream>

class NotSoPatientPlayer final : public Player
{
    static const int TOTAL_PLAYERS = 50;
    static const int TOTAL_ACTIONS = 5;
    static const int MAX_TURNS = 100;
public:
    NotSoPatientPlayer(size_t opponent = -1) : Player(opponent)
    {
        this->opponent = opponent;
    }

public:
    virtual Action fight()
    {
        /*Part which is shamelessly copied from MontePlayer.*/
        int turn = getTurn(),
            ammo = getAmmo(),
            opponentAmmo = getAmmoOpponent();
        int turnsRemaining = MAX_TURNS - turn;
        //The bot starts to shoot when there is enough ammo to fire plasma at least (turnsRemaining-2) times.
        //Did you know that you cannot die when you shoot plasma?
        //Also chooses 1 or 2 move(s) in which will shoot bullet(s) or none if there is plenty of ammo.
        //Also check !burstMode because it needs to be done only once.
        if (!burstMode && ammo + 2 >= turnsRemaining * 2)
        {
            burstMode = true;
            if (!(ammo == turnsRemaining * 2)) {
                turnForBullet1 = GetRandomInteger(turnsRemaining - 1) + turn;
                if (ammo + 2 == turnsRemaining * 2) {
                    //turnForBullet1 should be excluded in range for turnForBullet2
                    turnForBullet2 = GetRandomInteger(turnsRemaining - 2) + turn;
                    if (turnForBullet2 >= turnForBullet1) turnForBullet2++;
                }
            }
        }
        if (burstMode) {
            if (turn == turnForBullet1 || turn == turnForBullet2) {
                return bullet();
            }
            else return plasma();
        }

        //if opponent defended last 3 turns, the bot tries to go with something different
        if (turn >= 3) {
            auto historyOpponent = getHistoryOpponent();
            //if opponent used metal last 3 turns
            if (METAL == historyOpponent[turn - 1] && METAL == historyOpponent[turn - 2] && METAL == historyOpponent[turn - 3]) {
                if (ammo >= 2) return plasma();
                else return load();
            }
            //if opponent used thermal last 3 turns
            if (THERMAL == historyOpponent[turn - 1] && THERMAL == historyOpponent[turn - 2] && THERMAL == historyOpponent[turn - 3]) {
                if (ammo >= 1) return bullet();
                else return load();
            }
            //if the opponent defends, but not consistently
            if ((historyOpponent[turn - 1] == METAL || historyOpponent[turn - 1] == THERMAL)
                && (historyOpponent[turn - 2] == METAL || historyOpponent[turn - 2] == THERMAL)
                && (historyOpponent[turn - 3] == METAL || historyOpponent[turn - 3] == THERMAL)) {
                if (ammo >= 2) return plasma();
                else if (ammo == 1) return bullet();
                else return load();
            }
        }

        /*else*/ {
            if (opponentAmmo == 0) return load();
            if (opponentAmmo == 1) return metal();
            //if opponent prefers bullets or plasmas, choose the appropriate defence
            if (opponentMoves[opponent][BULLET] * 2 >= opponentMoves[opponent][PLASMA]) return metal();
            else return thermal();
        }
    }

    virtual void perceive(Action action)
    {
        Player::perceive(action);
        opponentMoves[opponent][action]++;
    }

    /*virtual void declared(Result result)
    {
        currentRoundResults[opponent][result]++;
        totalResults[opponent][result]++;
        int duels = 0;
        for (int i = 0; i < 3; i++) duels += currentRoundResults[opponent][i];
        if (duels == 100) {
            std::cout << "Score against P" << opponent << ": " <<
                currentRoundResults[opponent][WIN] << "-" << currentRoundResults[opponent][DRAW] << "-" << currentRoundResults[opponent][LOSS] << "\n";
            for (int i = 0; i < 3; i++) currentRoundResults[opponent][i] = 0;
        }
    };*/

private:
    static long opponentMoves[TOTAL_PLAYERS][TOTAL_ACTIONS];
    int opponent;
    //When it becomes true, the bot starts shooting.
    bool burstMode = false;
    //turnForBullet1 and turnForBullet2,
    //the 2 turns in which the bot will shoot bullets
    int turnForBullet1 = -1, turnForBullet2 = -1;
    //For debugging purposes
    //Reminder: enum Result { DRAW, WIN, LOSS };
    static int currentRoundResults[TOTAL_PLAYERS][3], totalResults[TOTAL_PLAYERS][3];
};
long NotSoPatientPlayer::opponentMoves[TOTAL_PLAYERS][TOTAL_ACTIONS] = { { 0 } };
int NotSoPatientPlayer::currentRoundResults[TOTAL_PLAYERS][3] = { { 0 } };
int NotSoPatientPlayer::totalResults[TOTAL_PLAYERS][3] = { { 0 } };
#endif // !__NOT_SO_PATIENT_PLAYER_HPP__
AlexRacer
fonte
"A história de sua criação chegará mais tarde" já faz mais de 3 meses :) #
HyperNeutrino 19/17/17