授業/C言語基礎/タイピング・ゲーム のバックアップソース(No.2)

*文字列の比較 [#i7591004]

string.h には、文字列を比較するstrcmp関数が用意されています。

strcmp関数は、引数として二つの文字列 s1 と s2 を受け取り、辞書式に比較します。
s1 > s2(辞書で s1 が s2 より後に載る場合)ならば正の値、s1 < s2(辞書で s1 が s2 より先に載る場合)ならば負の値、s1 = s2(s1 と s2 が同じ文字列の場合)ならば 0 を返します(プログラム1)。
#geshi(c){{
#include <stdio.h>
#include <string.h>
#include <time.h>

int main(void) {
  char s1[256], s2[256];

  printf("メール・アドレスを入力してください:\n");
  scanf("%s", s1)

  printf("もう一度入力してください:\n");
  scanf("%s", s2)

  if (strcmp(s1, s2) == 0) {
    printf("OK\n");
  } else {
    printf("NG\n");
  }

  return 0;
}
}}



*タイピング・ゲーム [#b5e294ed]

ランダムに文字列を出題し、キーボードから入力された文字列と比較して正解か間違いかを判定します(プログラム2)。
#geshi(c){{
/*
 *  タイピング・ゲーム
 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main(void) {
  char s[256];
  char ans[10][256] = {
    "cat",
    "dog",
    "lion",
    "bear",
    "tiger",
    "monkey",
    "giraffe",
    "elephant",
    "kangaroo",
    "hippopotamus"
  };

  srand((unsigned int) time(NULL));
  int r = rand() % 10;

  printf("%s:\n", ans[r]);
  scanf("%s", s);
  if (strcmp(s, ans[r]) == 0) {
    printf("正解!\n");
  } else {
    printf("間違い!\n");
  }

  return 0;
}
}}


*繰り返しタイピング・ゲーム [#a4a0a2cd]

タイピング・ゲームを改良し、10問出題して正解数を出力するようにしてみましょう。
#geshi(c){{
/*
 *  繰り返しタイピング・ゲーム
 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main(void) {
  char s[256];
  char ans[10][256] = {
    "cat",
    "dog",
    "lion",
    "bear",
    "tiger",
    "monkey",
    "giraffe",
    "elephant",
    "kangaroo",
    "hippopotamus"
  };

  srand((unsigned int) time(NULL));

  int score = 0;  // 得点
  int i;
  for (i = 1; i <= 10; i++) {
    int r = rand() % 10;

    printf("第%d問: %s:\n", i, ans[r]);
    scanf("%s", s);
    if (strcmp(s, ans[r]) == 0) {
      printf("正解!\n");
      score++;
    } else {
      printf("間違い!\n");
    }
  }
  printf("%d問正解\n", score);

  return 0;
}
}}


*スピード・タイピング・ゲーム [#zae0a50c]
次に、スピード計算ゲームと同じように、制限時間内に何問正解できるかを競うゲームにしてみましょう。
#geshi(c){{
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main(void) {
  char s[256];
  char ans[10][256] = {
    "cat",
    "dog",
    "lion",
    "bear",
    "tiger",
    "monkey",
    "giraffe",
    "elephant",
    "kangaroo",
    "hippopotamus"
  };

  srand((unsigned int) time(NULL));

  long limit = 30;      // 制限時間(秒)
  printf("制限時間: %d秒\n", limit);

  long t = time(NULL);  // 開始時刻
  int score = 0;        // 得点
  while (time(NULL) < t + limit) {
    int r = rand() % 10;

    printf("第%d問: %s:\n", score + 1, ans[r]);
    scanf("%s", s);

    if (time(NULL) > t + limit) { break; }  // 時間切れ

    if (strcmp(s, ans[r]) == 0) {
      printf("正解!\n");
      score++;
    } else {
      printf("間違い!\n");
    }
  }
  printf("%d問正解\n", score);

  return 0;
}
}}
トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS