【发布时间】:2018-10-12 15:27:34
【问题描述】:
我正在为我的学校项目(我必须使用 Turbo C++)制作一个非常简单的 Battleship 游戏,但遇到了问题。我基本上使用 5x5 2D 字符串作为我的板,并在其中隐藏了一个“船”。我想要做的是,每当用户做出错误的猜测时,我想用“X”替换板上的“O”,但是当我这样做时,下一个块中的“O”会被替换通过“/0”并在输出中显示为空格。我该如何解决?
代码如下:
#include<conio.h>
#include<iostream.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
#include<stdio.h>
//A function to initialize the board
void start_board(char a[5][5])
{
for(int i=0;i<5;i++)
{ for(int j=0;j<5;j++)
{ strcpy(&a[i][j],"O");
}
}
}
//A function to display the board
void display_board(char a[5][5])
{ for(int i=0;i<5;i++)
{ for(int j=0;j<5;j++)
{ cout<<a[i][j]<<" ";
}
cout<<endl;
}
}
class board
{ public:
char board[5][5];
void start()
{ start_board(board);
}
void display()
{ display_board(board);
}
};
class ship
{ public:
int ship_row, ship_col;
ship()//CONSTRUCTOR FOR PUTTING COORDINATES OF SHIP
{ randomize();
ship_row= random(5);
ship_col=random(5);
cout<<ship_row<<endl<<ship_col;
}
};
class guess: public board, public ship
{ public:
int guess_row,guess_col;
char vboard[5][5];
guess()
{ start_board(vboard);
}
void takeguess();
};
void guess:: takeguess()
{ int count=0;
while(count<3)
{
cout<<endl;
cout<<"Guess a row ";
cin>>guess_row;
cout<<"Guess a column ";
cin>>guess_col;
if(guess_row==ship_row && guess_col==ship_col)
{ cout<<"Congratulations! You sank the battleship!";
break;
}
else if(guess_row>4 || guess_col>4)
{ cout<<"invalid guess";
}
else
{ clrscr();
cout<<"Incorrect Guess!"<<endl;
strcpy(&vboard[guess_row][guess_col],"X");
display_board(vboard);
count+=1;
}
if(count==3)
{ cout<<"GAME OVER!";
}
}
}
void main()
{ clrscr();
board b;
b.start();
b.display();
guess g;
g.takeguess();
getch();
}
例如,如果用户猜测 0,2,而这不是船的位置,输出将显示:
OOX O
OOOOO
OOOOO
OOOOO
OOOOO
很抱歉代码混乱(它不完整)以及我在写这篇文章时犯的任何错误,这是我第一次使用 stackoverflow。感谢您的帮助!
【问题讨论】:
标签: c++ arrays string multidimensional-array