🎮 迷路ゲーム - 解答と解説

課題4-1の要件

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

#include <stdio.h> #include <stdlib.h> #include <conio.h> #include <windows.h> // マップの要素を定義 #define WALL '#' #define SPACE ' ' #define PLAYER 'P' #define GOAL 'G' #define START 'S' #define MAP_HEIGHT 10 #define MAP_WIDTH 15 // プレイヤーの位置を管理する構造体 typedef struct { int x, y; int moves; } Player; // マップデータ char maze[MAP_HEIGHT][MAP_WIDTH] = { "###############", "S # # #", "##### # ### # #", "# # # # #", "# # ##### ### #", "# # # #", "# ##### ##### #", "# # # #", "##### ### # #G#", "###############" }; // 関数プロトタイプ void initializeGame(Player* player); void displayMaze(const Player* player); void handleInput(Player* player); int isValidMove(int x, int y); void clearScreen(); int isGoal(const Player* player); int main() { system("chcp 65001"); // 日本語表示対応 Player player; initializeGame(&player); while (!isGoal(&player)) { clearScreen(); displayMaze(&player); printf("\n移動回数: %d\n", player.moves); printf("WASDキーで移動、Qで終了\n"); handleInput(&player); } clearScreen(); displayMaze(&player); printf("\nゴール!おめでとうございます!\n"); printf("総移動回数: %d\n", player.moves); return 0; } void initializeGame(Player* player) { // スタート位置を探す for (int y = 0; y < MAP_HEIGHT; y++) { for (int x = 0; x < MAP_WIDTH; x++) { if (maze[y][x] == START) { player->x = x; player->y = y; player->moves = 0; return; } } } } void displayMaze(const Player* player) { for (int y = 0; y < MAP_HEIGHT; y++) { for (int x = 0; x < MAP_WIDTH; x++) { if (x == player->x && y == player->y) { printf("%c", PLAYER); } else { printf("%c", maze[y][x]); } } printf("\n"); } } void handleInput(Player* player) { char key = _getch(); int newX = player->x; int newY = player->y; switch (tolower(key)) { case 'w': newY--; break; // 上 case 's': newY++; break; // 下 case 'a': newX--; break; // 左 case 'd': newX++; break; // 右 case 'q': exit(0); // 終了 } if (isValidMove(newX, newY)) { player->x = newX; player->y = newY; player->moves++; } } int isValidMove(int x, int y) { // マップ範囲内かつ壁でない場所のみ移動可能 return x >= 0 && x < MAP_WIDTH && y >= 0 && y < MAP_HEIGHT && maze[y][x] != WALL; } void clearScreen() { system("cls"); } int isGoal(const Player* player) { return maze[player->y][player->x] == GOAL; }

2. プログラムの解説

2.1 主要なデータ構造

2.2 主要な関数

3. 改良のポイント

3.1 基本的な改良案

3.2 発展的な機能追加

よくある問題と解決策