我正在使用SFML 2.3
来控制程序中的图形。我需要一个类才能访问窗口,即使该类不是最初创建窗口的类(没有所有权)也可以绘制它。例如。 Battle
类需要能够绘制战斗场景并操纵角色,但World
类需要Battle
之前和之后的窗口来显示玩家的动作主要游戏。
如何处理窗口对象?我最初的想法是让一个GameMaster
类将窗口作为静态成员。但是,考虑到通常的共识是什么,我认为最好不要犯这种方法的错误。
我意识到我总是可以将窗口的引用传递给需要它的每个类,但这会使所有需要操作窗口的类的构造函数变得非常膨胀。
答案 0 :(得分:6)
我担心您必须决定在使用允许访问主窗口的Singleton(World
)之间做出选择,或者使用您的依赖类对象传递对它的引用。
我个人更喜欢后者(我不会考虑将另一个构造函数参数添加到几个类中作为 bloat ),因为类设计的整体灵活性会比使用< EM>辛格尔顿
您可以考虑将World
类汇编代码外包给单独的Factory
class。这个可以将必要的主窗口对象作为成员保存,并将其传递给组装Battle
所需的所有创建的World
,myList <- list(DataFrame1 = data.frame(matrix(rnorm(100), 10, 10)),
DataFrame2 = data.frame(matrix(rnorm(100), 10, 10)),
DataFrame3 = data.frame(matrix(rnorm(100), 10, 10)),
DataFrame4 = data.frame(matrix(rnorm(100), 10, 10)))
require(xlsx)
export <- createWorkbook()
lapply(seq_along(myList), function(i) {
ExcelExport <- function1(myList[[i]]) # Your code was incomplete here
# You don't have object 'ExcelExport' anywhere esle in your code
# so this step seems useless...
# Now you have a full access to myList inside lapply
nameDF <- names(myList)[i]
# Use another function and store the output
DF <- as.data.frame(function2(myList[[i]]))
wksht <- createSheet(wb=export, sheetName = paste("Dataset is ", nameDF, sep = ""))
addDataFrame(x=DF, sheet = wksht) # Btw, object 'wksht' is not defined in your code
})
# Save it to an excel file (either existing or new) under a given name
saveWorkbook(export, "Export1.xlsx")
等实例,分别启动游戏任务
答案 1 :(得分:3)
我在第一次申请时遇到了类似的设计问题,以下是我设置程序的方法:
class App{
public:
// Constructor simply creates main window, specify context settings
// and set position of main window to center of screen
App(sf::VideoMode mode);
~App();
// init functions for setting up windows / graphics beforehand
// The main loop of the program, while active, run calculates the delta time
// for game movement, handles window events for both the console and window,
void run();
private:
sf::Window d_main_window; // main window for program.
// other data ...
// bool for main loop , etc.. etc..
};
App是窗口处理类,包含用于初始化任何图形(openGL)或设置程序以便可以运行的任何函数。然后主循环以app.run()
class ParticleContainer {
public:
ParticleContainer(/* params */);
~ParticleContainer
// object specific functions
drawParticles();
private:
sf::Window *d_parent_window; // window is passed into the constr
// now we can draw from inside particle
// additional params
// vec of all particle objects
};
粒子容器对象包含指向父窗口的指针,因此它可以将粒子绘制到屏幕上。这种设计允许您创建能够将自己绘制到屏幕的离散对象,从而消除了一些杂乱的绘制类的问题。如果你创建一个新对象,你需要做的就是传递父窗口指针,使它能够绘制自己。