C++

C++ Random

Vetenir 2025. 1. 13. 21:41

<random>

C++ <random> 라이브러리를 사용하여 랜덤을 구현.

#include "Goblin.h"
#include <iostream>
#include <random>

using namespace std;

Goblin::Goblin(int Level) : Name("고블린")
{
    // 레벨에 따라 체력과 공격력을 랜덤하게 설정.
    random_device R;
    mt19937 Gen(R());
    uniform_int_distribution<int> DistHealth(20, 30);
    uniform_int_distribution<int> DistAttack(5, 10);
    int RandomHealth = DistHealth(Gen);
    int RandomAttack = DistAttack(Gen);

    Health = Level * RandomHealth;
    Attack = Level * RandomAttack;

    // 고블린 생성시 출력되는 메시지.
    cout << "낄낄낄" << endl;
}

 

랜덤 구현 방법

random_device R;

 random_device 로 시드값을 얻습니다.

 

컴퓨터가 제공하는 랜덤이라는 것은 실제로 랜덤이 아닙니다. 컴퓨터는 정해진 규칙에 의해서 작동하기에 랜덤 생성 또한 랜덤 처럼 보이는 규칙에 의해서 랜덤한 수를 선택하고 생성합니다.

자세한 것은 아래의 글을 참고하시길 바랍니다.

 

https://evan-moon.github.io/2019/07/14/what-is-random/

 

 

mt19937 Gen(R());

 

 mt19937은 위의 글에도 나오는 난수 생성 알고리즘인 메르센 트위스터 알고리즘을 사용합니다.

 

uniform_int_distribution<int> DistHealth(20, 30);

 uniform_int_distribution<int> DistHealth(20, 30); 은 20에서 30의 수 중에서 랜덤한 수를 고릅니다.


참고 구현 사항

랜덤을 이용해서 확률을 구현할 수도 있습니다.

 

해당 코드는 30퍼 센트 확률로  

2가지의 아이템 중에서 한 개의 아이템을 랜덤하게 생성합니다.

Item* Goblin::DropItem()
{
    // 체력 회복 포션과 공격력 증가 포션을 랜덤하게 드랍.
    random_device R;
    mt19937 Gen(R());
    uniform_int_distribution<int> DropChance(1, 100); // 1에서 100의 숫자 선택.
    uniform_int_distribution<int> ItemType(0, 1); // 0과 1 랜덤하게 선택.
    int Drop = DropChance(Gen);

    
    // 아이템 드랍 확률 30%
    if (Drop <= 30) // 1에서 30의 수가 선택되면 작동.
    {
        if (ItemType(Gen) == 0)	// 0 이 선택되면 체력 회복 포션 생성
        {
            return new HealthPotion();
        }
        else
        {
            return new AttackBoost(); // 1 이 선택되면 공격력 증가 포션 생성
        }
    }
}