C言語:ループと分岐(数字当てゲーム)

  1. 分岐文

(1)if文

if(条件式) // 条件式が0の場合は偽、非0の場合は真。&&で論理積、||で論理和を使用
{
            // 実行する内容、複数行ある場合は中括弧が必要
}
else if // 以前の条件が満たされない場合に実行。elseの後にifをネスト可能
{


}

elseの関連付けに注意。elseは最も近いifと組み合わされます。必要に応じて中括弧を使用してください。

(2)switch文

int num = 0;
switch(num) // 括弧内は整数式
{
case 1: // numが1の場合に実行
{
        // コード
break; // breakでswitch分岐を抜ける
}

case 2:
{
      // コード
}

default: // いずれのcaseにも該当しない場合に実行。defaultは省略可能
{
       // コード
}
}
  1. ループ文

(1)whileループ

#include<stdio.h>
while(1)   // 括弧内は条件式。1は真、0は偽。1を指定すると無限ループ、0でループを抜ける
{            // 中括弧内にループ処理を記述
 printf("こんにちは");           // 例:"こんにちは"と表示
}

(2) do-whileループ

do
{

            // ループ処理を記述



}
while(条件式)  // 括弧内は判定条件。0で停止、1で継続

(3)forループ

int counter = 0;
for (counter=0;counter<10;counter++)// 初期化値、条件式、ループ終了時の操作を記述。セミコロンで区切る
{
       // ループ処理


}
  1. break,goto

breakは通常、ループの1層またはswitch文を抜けるために使用されます。gotoはより広範囲で使用でき、通常は分岐とループの両方で使用可能です。

while(1)
{

if(条件)
goto escape;       // gotoで「出口」を作成
}


escape:
       // 上記のif条件が満たされると、以下のescapeラベルにジャンプしてループを抜ける
  1. 数字当てゲーム

(1)メニューの作成

void displayMenu()// 戻り値なしの関数を定義し、メイン関数で使用
{
    printf("数字当てゲーム(1-100)\n");
    printf("***********\n");
    printf("**1.プレイ***\n");
    printf("**0.終了***\n");
    printf("***********\n");
}

(2)メイン関数の骨子作成

int main()
{
    int userInput = 0;
    do
    {
        displayMenu(); // メニューを表示
        scanf("%d", &userInput);// メニューに従って数値を入力
        switch (userInput)
        {
        case 1:
            printf("ゲーム開始\n");// 1でゲーム開始
            break;
        case 0:
            break;// 0でゲーム終了
        default:
            printf("入力エラー。再入力してください\n");// 0でも1でもない場合はループに戻る
            break;
        }
    } while (userInput);// whileの条件が0になるとループを抜ける
    printf("ゲームを終了しました\n");
    return 0;
}

(3)ゲーム本体の構築

void playGame()
{
	int targetNum = rand() % 100 + 1;// rand関数で擬似乱数を生成し、%で範囲を1-100に限定
	int playerGuess = 0;
	while (1)
	{
	printf("数字を入力してください:");// 推測する数字を入力
		scanf("%d", &playerGuess);
	if (playerGuess > targetNum)
			printf("大きすぎます\n");
	else if (playerGuess < targetNum)
		{
			printf("小さすぎます\n");
		}
	else
	    {
			printf("正解です!\n");
			break;// 正解でループを抜ける
		}
	}	
}

(4)

しかし、毎回プレイ時に乱数を変えたい場合は、プレイ中ではなくプログラム開始時にsrand関数を使用する必要があります。

#include<stdio.h>
#include<time.h>
void displayMenu()
{

	printf("数字当てゲーム(1-100)\n");
	printf("***********\n");
	printf("**1.プレイ***\n");
	printf("**0.終了***\n");
	printf("***********\n");
}

void playGame()
{
	int targetNum = rand() % 100 + 1;
	int playerGuess = 0;
	while (1)
	{
		printf("数字を入力してください:");
		scanf("%d", &playerGuess);
		if (playerGuess > targetNum)
			printf("大きすぎます\n");
		else if (playerGuess < targetNum)
		{
			printf("小さすぎます\n");
		}
		else
		{
			printf("正解です!\n");
			break;
		}
	}	
}

int main()
{
	int userInput = 0;
	srand((unsigned int)time(NULL));// メイン関数内に配置し、毎回実行時に乱数を初期化
do
{
	displayMenu();
	scanf("%d", &userInput);
	switch (userInput)
	{
	case 1:
	{
		printf("ゲーム開始");
		playGame();
		break;
	}
	case 0:
		break;
	default:
		printf("入力エラー。再入力してください");
		break;
	}
	} while (userInput);
	printf("ゲームを終了しました");
	return 0;
	}

(5)難易度を上げる(間違えるたびにタイマーが減る仕組み)

void playGame()
{
    int targetNum = rand() % 100 + 1;
    int playerGuess = 0;
    int timeLimit = 120; // 初期タイムリミット120秒

    while (timeLimit > 0)
    {
        printf("数字を入力してください:");
        scanf("%d", &playerGuess);

        if (playerGuess > targetNum)
        {
            printf("大きすぎます\n");
            if (timeLimit > 0)
            {
                system("shutdown -a");// 既存のシャットダウン予約をキャンセル
                char command[50];// コマンド文字列を定義
                sprintf(command, "shutdown -s -t %d", timeLimit);// シャットダウン時間をフォーマット
                system(command); // シャットダウン時間を更新
            }
            else
            {
                printf("時間切れです。ゲーム終了\n");
                break; // 時間切れでゲーム終了
            }
        }
        else if (playerGuess < targetNum)
        {
            printf("小さすぎます\n");// 上記と同様の処理
            if (timeLimit > 0)
            {
                system("shutdown -a");
                char command[50];
                sprintf(command, "shutdown -s -t %d", timeLimit);
                system(command); // シャットダウン時間を更新
            }
            else
            {
                printf("時間切れです。ゲーム終了\n");
                break; // 時間切れでゲーム終了
            }
        }
        else
        {
            printf("正解です!\n");
            system("shutdown -a"); // 正解したらシャットダウンをキャンセル
            break;
        }

        timeLimit -= 10; // 間違えるたびに10秒減らす
        
    }
}

(5)最終的な完全コード(さらに最適化可能です。想像力を働かせてください)

#include<stdlib.h>
#include<stdio.h>
#include<time.h>

void displayMenu()
{
    printf("数字当てゲーム(1-100)\n");
    printf("***********\n");
    printf("**1.プレイ***\n");
    printf("**0.終了***\n");
    printf("***********\n");
}

void playGame()
{
    int targetNum = rand() % 100 + 1;
    int playerGuess = 0;
    int timeLimit = 120; // 初期タイムリミット120秒

    while (timeLimit > 0)
    {
        printf("数字を入力してください:");
        scanf("%d", &playerGuess);

        if (playerGuess > targetNum)
        {
            printf("大きすぎます\n");
            if (timeLimit > 0)
            {
                system("shutdown -a");
                char command[50];
                sprintf(command, "shutdown -s -t %d", timeLimit);
                system(command); // シャットダウン時間を更新
            }
            else
            {
                printf("時間切れです。ゲーム終了\n");
                break; // 時間切れでゲーム終了
            }
        }
        else if (playerGuess < targetNum)
        {
            printf("小さすぎます\n");
            if (timeLimit > 0)
            {
                system("shutdown -a");
                char command[50];
                sprintf(command, "shutdown -s -t %d", timeLimit);
                system(command); // シャットダウン時間を更新
            }
            else
            {
                printf("時間切れです。ゲーム終了\n");
                break; // 時間切れでゲーム終了
            }
        }
        else
        {
            printf("正解です!\n");
            system("shutdown -a"); // シャットダウンをキャンセル
            break;
        }

        timeLimit -= 10; // 間違えるたびに10秒減らす
        
    }
}

int main()
{
    int userInput = 0;
    srand((unsigned int)time(NULL));
    do
    {
        displayMenu();
        scanf("%d", &userInput);
        switch (userInput)
        {
        case 1:
            printf("ゲーム開始\n");
            playGame();
            break;
        case 0:
            break;
        default:
            printf("入力エラー。再入力してください\n");
            break;
        }
    } while (userInput);
    printf("ゲームを終了しました\n");
    return 0;
}

タグ: C言語 ループ 分岐 数字当てゲーム プログラミング入門

6月20日 22:52 投稿