🎮 じゃんけんゲーム - 解答と解説

課題2-1の要件

1. プログラムの実装 (rock_paper_scissors.c)

#include <stdio.h> #include <stdlib.h> #include <time.h> // 手の種類を列挙型で定義 typedef enum { ROCK = 0, SCISSORS = 1, PAPER = 2 } Hand; // 戦績を記録する構造体 typedef struct { int wins; int losses; int draws; } Record; // 関数のプロトタイプ宣言 void displayHands(); const char* getHandName(Hand hand); int judgeWinner(Hand player, Hand computer); void displayResult(int result); void displayRecord(Record record); int main() { system("chcp 65001"); // 日本語表示対応 srand((unsigned int)time(NULL)); Record record = {0, 0, 0}; char continue_game; printf("===じゃんけんゲーム===\n"); do { displayHands(); // プレイヤーの手を入力 Hand player_hand; do { printf("あなたの手を選んでください (0-2): "); if (scanf_s("%d", (int*)&player_hand) != 1) { while (getchar() != '\n'); printf("無効な入力です。\n"); continue; } } while (player_hand < ROCK || player_hand > PAPER); // コンピュータの手を決定 Hand computer_hand = (Hand)(rand() % 3); // 手の表示 printf("\nあなた: %s\n", getHandName(player_hand)); printf("コンピュータ: %s\n", getHandName(computer_hand)); // 勝敗判定と結果表示 int result = judgeWinner(player_hand, computer_hand); displayResult(result); // 戦績を更新 if (result == 1) record.wins++; else if (result == -1) record.losses++; else record.draws++; // 戦績表示 displayRecord(record); // 継続確認 printf("\nもう一度プレイしますか? (y/n): "); while (getchar() != '\n'); continue_game = getchar(); } while (continue_game == 'y' || continue_game == 'Y'); printf("\nゲームを終了します。\n"); return 0; } void displayHands() { printf("\n0: グー\n1: チョキ\n2: パー\n\n"); } const char* getHandName(Hand hand) { switch (hand) { case ROCK: return "グー"; case SCISSORS: return "チョキ"; case PAPER: return "パー"; default: return "不明"; } } int judgeWinner(Hand player, Hand computer) { if (player == computer) return 0; // 引き分け return ((player == ROCK && computer == SCISSORS) || (player == SCISSORS && computer == PAPER) || (player == PAPER && computer == ROCK)) ? 1 : -1; } void displayResult(int result) { if (result == 1) printf("あなたの勝ち!\n"); else if (result == -1) printf("コンピュータの勝ち!\n"); else printf("引き分け!\n"); } void displayRecord(Record record) { printf("\n===戦績===\n"); printf("勝ち: %d\n", record.wins); printf("負け: %d\n", record.losses); printf("引き分け: %d\n", record.draws); int total_games = record.wins + record.losses + record.draws; if (total_games > 0) { float win_rate = (float)record.wins / total_games * 100; printf("勝率: %.1f%%\n", win_rate); } }

2. プログラムの解説

2.1 データ構造

2.2 主要な関数

3. 改良のポイント

3.1 基本的な改良案

3.2 発展的な機能追加

よくある間違いと注意点