가위, 바위, 보

1 minute read


컴퓨터와 가위, 바위, 보

  1. 컴퓨터는 가위, 바위, 보 중 무작위로 하나를 선택한다.
  2. 플레이어는 문자를 입력하여 컴퓨터와 승부를 낸다.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main()
{
	
	char inputChar[5] = { 0 };
	char computer[5] = { 0 };
	char charList[3][5] = {"가위", "바위", "보" };
	int isGameover = 1;
	int randNum;
	int playerNum = 0;

	while (isGameover)
	{
		printf("**** 가위, 바위, 보 중 하나를 선택하세요 ****\n\n");

		srand(unsigned int(time(NULL)));
		randNum = rand() % 3;

		for (int i = 0; i < 3; i++)
		{
			if (randNum == i)
			{
				strcpy_s(computer, charList[i]);
			}
		}

		scanf_s("%s", &inputChar, 5);
		
		if (strcmp(inputChar, "가위") == 0)
		{
			playerNum = 0;
		}
		else if (strcmp(inputChar, "바위") == 0)
		{
			playerNum = 1;
		}
		else if (strcmp(inputChar, "보") == 0)
		{
			playerNum = 2;
		}

		if (playerNum == randNum)
		{
			printf("=============================\n");
			printf("플레이어 : %s\n컴퓨터 : %s\n", &inputChar, &computer);
			printf("비겼습니다.\n");
			printf("=============================\n\n");
		}

		else if (playerNum == 0 && randNum == 2 || playerNum == 1 && randNum == 0 || playerNum == 2 && randNum == 1)
		{
			printf("=============================\n");
			printf("플레이어 : %s\n컴퓨터 : %s\n", &inputChar, &computer);
			printf("이겼습니다!\n");
			printf("=============================\n\n");
		}

		else
		{
			printf("=============================\n");
			printf("플레이어 : %s\n컴퓨터 : %s\n", &inputChar, &computer);
			printf("졌습니다...\n");
			printf("=============================\n\n\n\n\n");
			isGameover = 0;
		}
	}
}

example_game_result

  • scanf_s로 문자열을 입력받을 때는 정수로 버퍼의 크기를 명시해주어야한다.
  • 당장 사용하지 않는 문자 배열을 선언할 때 0으로 초기화를 해준다.

처음에는 문자열 비교하여 조건문으로 결과를 내려했는데 하다보니 숫자로 바꿔서 비교하는게 낫겠다 싶어서 중구난방으로 코드가 만들어진거같다.