🎮 迷路ゲーム - 解答と解説
課題4-1の要件
- 2次元配列を使用した迷路の実装
- キーボードによる移動
- 壁との衝突判定
- ゴール判定
- 移動回数のカウント
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 主要なデータ構造
Player
構造体
- x, y: プレイヤーの位置座標
- moves: 移動回数
- マップデータ
- 2次元配列による迷路の表現
- 各種マップ要素の定義(WALL, SPACE, etc.)
2.2 主要な関数
initializeGame
: ゲームの初期化
displayMaze
: 迷路の表示
handleInput
: 入力処理
isValidMove
: 移動可能判定
3. 改良のポイント
3.2 発展的な機能追加
- ゲームシステムの拡張
- 追加要素
- 敵キャラクターの追加
- 特殊アイテム
- スコアシステム