gpt4 book ai didi

c++ - 如何为所有类函数声明一个 SFML 窗口?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:03:31 25 4
gpt4 key购买 nike

这可能是一个菜鸟问题,但我正在尝试让一个简单的玩家在 SFML 的二维网格中移动。我正在创建一个 while 循环来渲染正在发生的事情,我可以让它工作,但我想为网格和播放器等使用类。问题是当我创建一个名为“窗口”的窗口时,我不不知道如何实现类,因为它们不知道“窗口”是什么。我希望我已经充分描述了我的问题,如果我的方法已经很糟糕并且应该更改为另一种方法,我希望对如何进行这项工作有任何回应。这是我的类代码片段和未声明的窗口错误。

class myEvents {
public:
//Variables
int tSize = 40;
int tileCount = 20;
int width = tileCount * tSize;
int height = tileCount * tSize;

//Function to create a grid with RectangleShapes
void grid() {
for (int i = 0; i < tileCount; i++)
{
for (int j = 0; j < tileCount; j++)
{
sf::RectangleShape tile(sf::Vector2f(40, 40));
tile.setFillColor(sf::Color::Magenta);
tile.setPosition(i*tSize, j*tSize);
window.draw(tile); //Problem occurs here, 'window' is not declared, it is in the next function
//window.draw(tile); must execute in the loop to render a full grid
}
}
}

//Includes while loop for rendering and events. Could be written without class, but I'd still like a class for the grid and later on a player.
//So I need the window to work with my classes.
void loop() {
sf::RenderWindow window(sf::VideoMode(width, height), "Game"); //'window' declared here. Can I move this statement
//somewhere so that my funcions know where it comes from?
while (window.isOpen) {

sf::Event event;
while (window.pollEvent(e))
{
//to be further developed
}
}
}
};

最佳答案

尝试让窗口成为​​类成员:

class myEvents {
public:
//Variables
int tSize = 40;
int tileCount = 20;
int width = tileCount * tSize;
int height = tileCount * tSize;
sf::RenderWindow window{sf::VideoMode(width, height), "Game"};

void grid() {
for (int i = 0; i < tileCount; i++)
{
for (int j = 0; j < tileCount; j++)
{
sf::RectangleShape tile(sf::Vector2f(40, 40));
tile.setFillColor(sf::Color::Magenta);
tile.setPosition(i*tSize, j*tSize);
window.draw(tile);
}
}
}

void loop() {
while (window.isOpen) {

sf::Event event;
while (window.pollEvent(e))
{
//to be further developed
}
}
}
};

或者,传递窗口:

class myEvents {
public:
//Variables
int tSize = 40;
int tileCount = 20;
int width = tileCount * tSize;
int height = tileCount * tSize;

void grid(sf::RenderWindow& window) {
for (int i = 0; i < tileCount; i++)
{
for (int j = 0; j < tileCount; j++)
{
sf::RectangleShape tile(sf::Vector2f(40, 40));
tile.setFillColor(sf::Color::Magenta);
tile.setPosition(i*tSize, j*tSize);
window.draw(tile);
}
}
}

void loop() {
sf::RenderWindow window{sf::VideoMode(width, height), "Game"};

while (window.isOpen) {

sf::Event event;
while (window.pollEvent(e))
{
//to be further developed
// call grid(window)
}
}
}
};

关于c++ - 如何为所有类函数声明一个 SFML 窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55070452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com