为了学习更多关于C++的知识,我正在用C++编写一个蛇游戏。我使用面向对象编程的范例制作了游戏,但是drawGame函数的设计不能正常工作。
测试drawGame函数时,我得到的结果是:
void Game::drawGame(int fruitxpos, int fruitypos, std::vector<int>& xposition, std::vector<int>& yposition, int snakesize){
system("cls");
int printedflag = 0;
for(int j = 1; j <= ysize; j++){
if(j == 1 || j == ysize){
for(int i = 1; i <= xsize; i++){
std::cout << "#";
}
std::cout << "\n";
}
else{
for(int i = 1; i <= xsize; i++){
if(i == 1 || i == xsize){
std::cout << "#";
}
else{
for(int n = 0; n <= snakesize; n++){
if(i == xposition[n] && j == yposition[n]){
std::cout << "o";
printedflag = 1;
}
else{
printedflag = 0;
}
}
if(!printedflag){
if(i == fruitxpos && j == fruitypos){
std::cout << "F";
}
else{
std::cout << " ";
}
}
}
}
std::cout << "\n";
}
}
}
正如您所看到的,它在每个蛇形块之后打印一个空格。有人能给我解释一下出了什么问题吗?
发布于 2019-07-17 03:30:47
如果你的程序使用二维字符矩阵会更好。您的主程序将写入矩阵中。打印函数将打印矩阵。这消除了必须在控制台上使用X,Y定位的担忧。
如果将矩阵设计为{连续}字符数组,则可以为换行符添加额外的列。矩阵的最后一个单元将是nul字符'\0‘。这允许您打印矩阵,就像它是一个很长的C样式字符串一样。
一些示例代码:
const unsigned int MAX_COLUMNS = 20U + 1U; // +1 column for newline
const unsigned int MAX_ROWS = 20U;
char game_board[MAX_ROWS][MAX_COLUMNS];
void Clear_Board()
{
// Fill the board with spaces (blanks).
memset((char *) &game_board[0][0], ' ', sizeof(game_board));
// Draw the top and bottom borders
for (unsigned int column = 0; column < MAX_COLUMNS; ++column)
{
game_board[0][column] = '#';
game_board[MAX_ROWS - 1][column] = '#';
}
// Draw the side borders
const unsigned int LEFT_COLUMN = 0U;
const unsigned int RIGHT_COLUMN = MAX_COLUMNS - 2U;
const unsigned int NEWLINE_COLUMN = MAX_COLUMNS - 1U;
for (unsigned int row = 0; row < MAX_ROWS; ++row)
{
game_board[row][LEFT_COLUMN] = '#';
game_board[row][RIGHT_COLUMN] = '#';
game_board[row][NEWLINE_COLUMN] = '\n';
}
// Set the terminating nul character
game_board[MAX_ROWS - 1][MAX_COLUMNS - 1] = '\0';
}
打印电路板:
std::cout << game_board;
或
std::cout.write(&game_board[0][0], sizeof(game_board) - 1U); // Don't print terminating nul.
检查水果是否相遇
unsigned int snake_head_row = 10U; // Example position.
unsigned int snake_head_column = 5u;
const char FRUIT_CHAR = 'F';
//...
if (game_board[snake_head_row][snake_head_column] == FRUIT_CHAR)
{
//...
}
请注意,水果遇到不需要打印。
我的意思是,你应该让蛇作为坐标(行,列)的容器。每个正文单元格都是容器中的一个项。如果蛇生长,请将坐标附加到容器。绘制蛇涉及到遍历容器,将蛇角色放置在适当的game_board
位置(然后绘制棋盘)。
游戏棋盘有助于记住蛇身的位置和棋盘上的任何其他物品。您可以使用控制台定位库,并将字符放在它们的坐标上。
发布于 2019-07-17 03:07:48
建议将您的Game::drawGame
拆分为子功能。此外,该方法可能不应该获得您传递给它的所有参数,因为它们都应该是类成员。
void Game::drawGame() {
drawBoard();
drawSnake();
drawFruits();
}
然后,您可能想要使用可在web上找到的gotoxy
,例如here,例如windows:
void gotoxy(int x, int y) {
HANDLE hc = GetStdHandle(STD_OUTPUT_HANDLE); // get console handle
COORD cursor = { x, y };
SetConsoleCursorPosition(hc, cursor); // set new cursor position
}
https://stackoverflow.com/questions/57063718
复制相似问题