はじめての C

0 から 9までの間の乱数をつくるプログラムを作成せよ。
乱数の種 (seed) はキーボードから入力できるように。

  1. /* zeroto9 */
  2. #include
  3. #include
  4. main()
  5. {
  6. int seed, random;
  7. printf("Input seed = ");
  8. scanf("%d", &seed);
  9. srand(seed);
  10. random = rand() % 10;
  11. printf("random : %d\n", random);
  12. }

「ゲーム」

  • 乱数の種 (seed) はキーボードから入力させる。

  • 敵は 10 離れたところから 1つずつ前進してくる。

  • 敵との距離が 0 になったところで 敗北 → ゲームは終了。

  • 敵は 0 から 5 の 6つのコースのどこかにいる。

  • 敵は 1つずつ進むごとにコースを 1つ変える (または静止する) ことができる。

  • レーダーとレーザ砲とを使えるが 一度にどちらかしか操作できない。

  • レーザが命中したら つぎのステージに移る。

  • 全部で 5回戦あるが ステージが上がると敵のスピードも速くなる。

  1. /* game */
  2. #include
  3. #include
  4. main()
  5. {
  6. int seed, distance, cource, goal, round, laser, speed = 0;
  7. printf("Input seed = ");
  8. scanf("%d", &seed);
  9. srand(seed);
  10. printf("/n");
  11. for ( round = 1 ; round < 6 ; round++ ) {
  12. printf("+++ stage %d +++\n\n", round);
  13. cource = rand() % 6;
  14. speed++;
  15. for ( distance = 10 ; ; distance -= speed ) {
  16. if (distance <= 0) {
  17. printf("=== you lose (>_<) ===\n");
  18. exit(0);
  19. }
  20. if (cource == 0) {
  21. cource += rand() % 2;
  22. } else if (cource == 5) {
  23. cource += rand() % 2 - 1;
  24. } else {
  25. cource += rand() % 3 - 1;
  26. }
  27. printf("(current distance = %d)\n\n", distance);
  28. printf("select '1'(radar) or '2'(fight)\n);
  29. printf("Input your choice = ");
  30. scanf("%d", &laser);
  31. printf("\n");
  32. if (laser == 1) {
  33. printf("enemy cource >> %d <<\n",cource);
  34. } else if (laser == 2) {
  35. printf("select laser cource 0 - 5\n");
  36. printf("Input your choice = ");
  37. scanf("%d", &goal);
  38. if (goal == cource) {
  39. printf("\n");
  40. printf("=== you win ! ===\n\n");
  41. break;
  42. }
  43. printf("\n");
  44. printf("== miss the target ==\n\n");
  45. } else {
  46. printf("set '1' or '2' only\n");
  47. }
  48. }
  49. }
  50. }

main() のなかで %d と %c とを併用すると 関数 scanf() のうち scanf("%c", &lazer) のほうが お亡くなりになるみたい。
しかたなく すべて変数を int に変更しました。
text: 金山典世さん(稚内北星)のページ