今天,我们在欢迎首页的menu增加一个button,点击后弹出一个对话框窗口,显示 HelloWorld,效果如下:
要完成这个看起来很简单的小功能可没这么简单。这一篇文章,强烈建议大家动动手,对于掌握编译方法和熟悉项目的框架很有帮助,不过动手前,大家要有心理准备,可以先上一个洗手间、倒杯茶调整好心态,有任何问题欢迎评论区提出。
第一步,我们增加 菜单项目,名称为 HelloWorld
1、intro_gui.cpp , _nested_select_game_widgets[] 定义了菜单选项,我们在 Exit 退出按钮下面 增加一个Helloworld的button
2.~/OpenTTD/src/lang/english.txt 增加两行STRING定义,这里我们以英文为例,包括按钮的名称和悬浮的提示文字
按钮名称为 STR_INTRO_HELLOWORLD,
增加 悬浮提示 STR_INTRO_TOOLTIP_HELLOWORLD,这样鼠标悬浮在按钮上的时候,会显示 “Study how to create a windows box” 这一样提示
3、修改好这两个文件,到build目录下,make编译, ./openttd 启动游戏后,菜单项增加了这个按钮,但是点击这个按钮没有任何反应,我们还需要定义一个新的窗口
第二步、我们要创建新的窗口
1.~/OpenTTD/src/ 下面增加cpp和h 两个文件
首先,创建gui文件helloworld_gui.cpp
#include "stdafx.h"
#include "saveload/saveload.h"
#include "error.h"
#include "gui.h"
#include "gfx_func.h"
#include "command_func.h"
#include "network/network.h"
#include "network/network_content.h"
#include "strings_func.h"
#include "fileio_func.h"
#include "fios.h"
#include "helloworld.h" //tmpmod
#include "window_func.h"
#include "tilehighlight_func.h"
#include "querystring_gui.h"
#include "engine_func.h"
#include "landscape_type.h"
#include "date_func.h"
#include "core/geometry_func.hpp"
#include "gamelog.h"
#include "stringfilter_type.h"
#include "widgets/fios_widget.h"
#include "table/sprites.h"
#include "table/strings.h"
#include "safeguards.h"
static const NWidgetPart _nested_helloworld_dialog_widgets[] = {
NWidget(NWID_HORIZONTAL),
NWidget(WWT_CLOSEBOX, COLOUR_GREY),
NWidget(WWT_CAPTION, COLOUR_GREY, WID_SL_CAPTION),
NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
EndContainer(),
};
struct HelloworldWindow : public Window {
public:
HelloworldWindow(WindowDesc *desc)
: Window(desc)
{
this->CreateNestedTree(true);
this->FinishInitNested(0);
this->GetWidget<NWidgetCore>(WID_SL_CAPTION)->widget_data = STR_HELLOWORLD_CAPTION;
ResetObjectToPlace();
}
virtual ~HelloworldWindow()
{
}
};
static WindowDesc _load_helloworld_desc(
WDP_CENTER, "helloworld_game", 500, 294,
WC_HELLOWORLD, WC_NONE,
0,
_nested_helloworld_dialog_widgets, lengthof(_nested_helloworld_dialog_widgets)
);
void ShowHelloworldDialog()
{
DeleteWindowById(WC_HELLOWORLD, 0);
WindowDesc *sld;
sld = &_load_helloworld_desc;
new HelloworldWindow(sld);
}
创建头文件helloworld.h
#ifndef HELLOWORLD_H
#define HELLOWORLD_H
void ShowHelloworldDialog();
#endif /* HELLOWORLD_H */
2、~/OpenTTD/src/CmakeLists.txt 增加 这两个文件定义,为编译做准备
3、intro_game.cpp OnClick()增加按钮的响应
4、window_type.h 新增 窗口类型 WC_HELLOWORLD
5、intro_widget.h 增加 按钮定义
6、准备就绪,因为新增了两个文件,所以我们要在 build目录下,运行 cmake … 重新生成文件::
启动界面,点击HelloWorld按钮,弹出 Hello World 对话框,成功!!大家可以尝试把游戏的语言修改为中文(温馨提示:变更前记得录屏记住操作的位置,否则可能会造成遗憾。)
通过今天的学习,我们可以了解到OpenTTD的gui框架和如何使用界面控件,下一次课程我们将进入游戏的本体部分,看看游戏界面上面的这些小精灵Sprite是怎么生成并显示到屏幕上的。