Top
プログラム課題集
軍艦ゲーム解答例
下記が解答例になります。
この解答についても、問題点は色々あります。
模範的な解答ではありません。
・数字以外の文字を入力されたら誤作動する
・数字の範囲チェックを行っていない
等々課題は沢山あります。
どうやればよりよくなるか、考えてみて下さい。
#include
"
stdio.h
"
#include
"
stdlib.h
"
#include
"
time.h
"
// 定数定義
#define
WAR_SHIP 3
#define
HIGHT 5
#define
WIDTH 5
// セル値設定
enum
CellValue
{
Nothing,
///< 何もなし
WarShip,
///< 軍艦
SmalWave,
///< 小波
BigWave,
///< 大波
Sink,
///< 撃沈
Miss,
///< はずれ
};
int
main()
{
int
cell[HIGHT][WIDTH];
int
sinkCount = 0;
int
height;
int
width;
srand((
unsigned
int
)time(NULL));
// 初期化
for
(
int
i = 0;i < HIGHT;i++)
{
for
(
int
j = 0; j < WIDTH; j++)
{
cell[i][j] = Nothing;
}
}
// 軍艦の位置を設定
int
count = 0;
while
(count < WAR_SHIP)
{
height = rand() % HIGHT;
width = rand() % WIDTH;
if
(cell[height][width] == Nothing)
{
cell[height][width] = WarShip;
count++;
}
}
// ゲーム
while
(sinkCount < WAR_SHIP)
{
printf("
縦の位置を示す1~%dの数字を入力してください。\n
", HIGHT);
scanf_s("
%d
",&height);
height--;
printf("
横の位置を示す1~%dの数字を入力してください。\n
", WIDTH);
scanf_s("
%d
", &width);
width--;
// 結果判定
CellValue result = Miss;
if
(cell[height][width] == WarShip)
{
cell[height][width] = Sink;
result = Sink;
sinkCount++;
}
if
(result == Miss)
{
// 大波判定
for
(
int
searchHeight = height - 1; searchHeight <= height + 1; searchHeight++)
{
for
(
int
searchWidth = width - 1; searchWidth <= width + 1; searchWidth++)
{
if
( (searchHeight >= 0) &&
(searchHeight < HIGHT) &&
(searchWidth >= 0) &&
(searchWidth < WIDTH) &&
( (searchHeight != height) || (searchWidth != width) ) )
{
if
(cell[searchHeight][searchWidth] == WarShip)
{
cell[height][width] = BigWave;
result = BigWave;
}
}
}
}
}
if
(result == Miss)
{
// 小波判定
for
(
int
searchHeight = height - 2; searchHeight <= height + 2; searchHeight++)
{
for
(
int
searchWidth = width - 2; searchWidth <= width + 2; searchWidth++)
{
if
((searchHeight >= 0) &&
(searchHeight < HIGHT) &&
(searchWidth >= 0) &&
(searchWidth < WIDTH) &&
(
(searchHeight > height + 1) || (searchHeight < height - 1) ||
(searchWidth > width + 1) || (searchWidth < width - 1)
))
{
if
(cell[searchHeight][searchWidth] == WarShip)
{
cell[height][width] = SmalWave;
result = SmalWave;
}
}
}
}
}
if
(result == Miss)
{
// はずれ判定
cell[height][width] = Miss;
}
switch
(result)
{
case
Sink:
printf("
撃沈\n
");
break
;
case
BigWave:
printf("
大波\n
");
break
;
case
SmalWave:
printf("
小波\n
");
break
;
case
Miss:
printf("
はずれ\n
");
break
;
default
:
break
;
}
for
(height = 0; height < HIGHT; height++)
{
for
(width = 0; width < WIDTH; width++)
{
switch
(cell[height][width])
{
case
Nothing:
case
WarShip:
printf("
");
break
;
case
BigWave:
printf("
◎
");
break
;
case
SmalWave:
printf("
〇
");
break
;
case
Sink:
printf("
※
");
break
;
case
Miss:
printf("
―");
break;
default:
break;
}
}
printf(
"\n"
);
}
}
return 0;
}