c++ - Cout 在控制台中只显示黑屏
问题描述
为我的考试写“蛇游戏”。我决定让用户选择字段大小,理论上,在这个阶段它必须显示一些东西,但功能“图形”只显示黑屏。我怀疑,问题可能是当图形引用结构高度和宽度定义时,也许它没有看到我改变了这些定义,并将其计为零和零,因此字段的大小分别为零和零......无论如何我不知道,有人可以帮忙吗?
#include <iostream>
#include <stdlib.h>
bool GameOver;
struct GameData
{
int x{ 0 };
int y{ 0 };
int Width;
int Height;
int AppleX;
int AppleY;
int Score;
};
enum SnakeDirection {Stop = 0, Up, Down, Left, Right};
SnakeDirection Way;
void EnterFieldSize()
{
GameData GMD;
int Width{ 0 };
int Height{ 0 };
std::cout << "Enter field size (Min 10, Max 100): \n";
std::cout << "Width: "; std::cin >> Width;
std::cout << "Height: "; std::cin >> Height;
GMD.Width = Width;
GMD.Height = Height;
if (Width < 10 || Width > 100) //Если ширина меньше 10 или больше 100, повторить ввод
{
std::cout << "Unaccetable width! Enter again:\n ";
return EnterFieldSize();
}
if (Height < 10 || Height > 100)
{
std::cout << "Unaccetable height! Enter again:\n ";
return EnterFieldSize();
}
return;
}
void Settings()
{
EnterFieldSize();
GameData GMD;
Way = Stop;
GMD.x = rand() % GMD.Width; и
GMD.y = rand() % GMD.Height;
GMD.AppleX = rand() % GMD.Height;
GMD.AppleY = rand() % GMD.Width;
GMD.Score = 0 ;
return;
}
void GameLogic()
{
}
void Graphics() //This part doesn't show
{
GameData GMD;
system("cls");
for (int i{ 0 }; i < GMD.Width; i++) //Upper border
{
std::cout << "#";
}
for (int i{ 0 }; i < GMD.Height; i++) //Side borders
{
for (int q{ 0 }; q < GMD.Width; q++)
{
if (q == 0 || q == GMD.Width)
std::cout << "#"; std::cout << " ";
}
std::cout << std::endl;
}
for (int i = 0; i < GMD.Width; i++) //Lower border
{
std::cout << "#";
}
return ;
}
void Controller()
{
}
int main()
{
std::cout << "Welcome to \"Snake\"\n";
Settings();
while (!GameOver)
{
Graphics(); // THis moment, console just dark screen
GameLogic();
Controller();
}
return 0;
}
解决方案
你有几个变量叫做GMD
. 一进Settings
一进Graphics
一进EnterFieldSize
。这些都是不同的变量。
不同函数中的两个变量即使同名也是不同的变量。您的Settings
函数正在更改一个变量,但您的Graphics
函数使用的是完全不同的变量。
您应该在其中声明一个GMD
变量,main
并将其作为引用参数传递给所有需要使用它的函数。
您可能需要阅读 C++ 基础知识。参数传递是几乎所有编程语言中的一项基本技能,变量作用域的概念也是如此。
推荐阅读
- python - 代码永远不会进入 'with Pool(processes=4) as pool: block
- azure - 对话式 Bot SDK 可以与自定义机器学习模型一起使用吗?
- php - 表单提交更新数据库记录后,HTML文本框未更新
- google-bigquery - BigQuery 中的每日数据更新是否可行?
- r - 计算分组矩阵中唯一值的数量
- javascript - 如何在模式中保存的表单上插入页面内保存的元素的 innerText?
- css - 当元素在左侧被固定边距偏移时计算元素的纵横比
- javascript - 如何在 Nodejs Replit 中播放 mp3 文件?
- javascript - 如何从渲染它的组件中销毁一个 backdraft 组件?
- python-3.x - datetime.date - 无法在脚本中创建正确的输入