배열과 난수를 이용한 미니 게임

Ryan Ham·2024년 5월 17일
1

C++

목록 보기
6/26

짝 맞추기 게임

  1. 1~10까지 숫자가 2개씩 존재한다.
  2. 숫자를 골고루 섞어준다.
  3. *을 10x2로 출력한다.
  4. 사용자는 2개의 인덱스를 입력해서 2개의 인덱스의 값이 같을 경우 해당 부분은 숫자로 출력한다.
  5. 10개의 페어를 맞추면 게임이 종료된다.
  6. -1을 입력하면 게임을 종료한다.

Step 1 - 난수 세팅 및 배열 shuffle

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;

int main() {

	int main_array1[10] = {1,2,3,4,5,6,7,8,9,10};
	int main_array2[10] = {1,2,3,4,5,6,7,8,9,10};

	string string_array1[10] = { "*", "*", "*", "*", "*", "*", "*", "*", "*", "*"};
	string string_array2[10] = { "*", "*", "*", "*", "*", "*", "*", "*", "*", "*" };

	int count = 0;
	int first_idx;
	int second_idx;
	int temp;
	int shuffle_num = 100000;

	//난수 초기화
	srand(time(0));
	rand();

	for (int i = 0; i < shuffle_num; i++) {
		int first_rand_idx = rand() % 10;
		int second_rand_idx = rand() % 10;
		int third_rand_idx = rand() % 10;
		int fourth_rand_idx = rand() % 10;

		//첫번째 array shuffle
		temp = main_array1[first_rand_idx];
		main_array1[first_rand_idx] = main_array1[second_rand_idx];
		main_array1[second_rand_idx] = temp;

		//두번째 array shuffle
		temp = main_array2[third_rand_idx];
		main_array2[third_rand_idx] = main_array2[fourth_rand_idx];
		main_array2[fourth_rand_idx] = temp;
	}

우선 1 ~ 10까지 들어있는 10x1 배열 2개를 준비한 다음, 각각을 rand()를 통해 shuffle해준다. 배열은 총 4개를 만드는데 추가적인 2개의 배열은 처음에는 모든 인덱스에 대해서 "*"값을 가지고 있다가 사용자가 index를 맞추면 하나씩 열리는 배열이다. 이 배열은 사용자가 trail할때마다 console창에 표시된다.


Step 2 - 게임 로직

	//사용자 게임 부분
	while (count<10) {

		for (int i = 0; i < 10; i++) {
			cout << string_array1[i] << " ";
		}

		cout << endl;

		for (int i = 0; i < 10; i++) {
			cout << string_array2[i] << " ";
		}

		cout << endl;

		cout << "Please enter two indexes(value is from 1 ~ 10) [Press -1 to terminate]" << endl;
		cin >> first_idx ;
		if (first_idx == -1) {
			break;
		}

		cin >> second_idx;

		//사용자 편의를 위해 입력받은 각 index값에서 1씩 빼기
		first_idx -= 1;
		second_idx -= 1;

		if (main_array1[first_idx] == main_array2[second_idx]) {
			
			string_array1[first_idx] = to_string(main_array1[first_idx]);
			string_array2[second_idx] = to_string(main_array2[second_idx]);
			count++;
		}


	}

	for (int i = 0; i < 10; i++) {
		cout << string_array1[i] << " ";
	}

	cout << endl;

	for (int i = 0; i < 10; i++) {
		cout << string_array2[i] << " ";
	}

	cout << endl;
	cout << "Game has ended!" << endl;



}

게임은 사용자가 두 배열의 인덱스를 모두 맞출때까지 진행한다. 사용자는 컴퓨터와 다르게 배열의 시작을 0이 아닌 1로 시작하기 때문에 input으로 받은 index에 -1 값을 해주어 코드 로직에 넘겨준다. 사용자가 모든 배열의 값을 해제하면 게임을 종료한다.


게임 플레이 화면

위는 게임 플레이 화면이다. 이미 사전에 1,3의 index 값을 넣어서 7이라는 숫자의 위치를 맞춘 후 다시 trial하여 10의 위치까지 맞춘 화면을 보여주었다. 마지막으로 모든 숫자를 맞추면 "Game has ended!"라는 문구를 표시한 후 게임을 종료한다.


cstdlib의 random을 사용해 난수 구현

다음 게임은 로또 프로그램을 cpp random library을 사용해서 작업한 코드이다. 프로그램은 다음과 같은 기능을 수행한다.

  1. 1 ~ 45 사이의 숫자가 있고 이를 섞어준다.
  2. 사용자는 원하는 게임 수를 입력한다.
  3. 그러면 프로그램은 해당 수만큼 번호 6개를 랜덤하게 뽑아준다.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <random>

using namespace std;

int main() {
	//Create a random device to seed the random number generator
	random_device rd; 
    //Create a random number generator and seed it with the random device
	mt19937 gen(rd()); 
    //Create a distribution for integers in the range
	uniform_int_distribution<> dis(1, 45);

	int times;

	cout << "몇 번의 로또를 생성할지 입력하시오" << endl;
	cin >> times;

	for (int i = 0; i < times; i++) {
		for (int j = 0; j < 6; j++) {
			cout << dis(gen) << " ";
		}

		cout << endl;
	}
	return 0;
}

아직 random을 사용하는게 낮설지만 범위도 함수내에서 지정할 수 있고 seed도 더 정교하게 넣을 수 있어서 rand()보다 더 유용하게 쓸 수 있을 듯 하다.

profile
🏦KAIST EE | 🏦SNU AI(빅데이터 핀테크 전문가 과정) | 📙CryptoHipsters 저자

0개의 댓글