开发环境搭建完了,也尝试了几个示例程序,有没有感觉到 devkitPro 的 libnds 的强大?我们现在就来开发一个小游戏感受感受。
这是一个算不上游戏的游戏:在区间 [0,1000]
中随机生成一个数字,玩家来猜。游戏会对每次猜测的数字给出“过大”或“过小”的提示。这绝对是一个入门级别的小程序,稍稍熟悉 C/C++ 的朋友大概一两分钟就能写完吧。为了在 NDS 上运行这样一个小游戏,我们需要编写比 PC 机上稍多一点的代码。
怎么样?是不是应该先自己尝试尝试呢?这里给出一些小提示: example/nds
下的 input/keyboard/keyboard_stdin
、hello_world
、Graphics/Printing/print_both_screens
目录中给出了我们需要用到的代码的相当充分的示例。是不是发现非常的简单呢?我这里也给出一份速成的参考代码,建议使用方式是直接对hello_world
进行修改。
#include <nds.h>
#include <ctime>
#include <cstdio>
#include <cstdlib>
void OnKeyPressed(int key);
int main(void)
{
PrintConsole topScreen;
videoSetMode(MODE_0_2D);
videoSetModeSub(MODE_0_2D);
vramSetBankA(VRAM_A_MAIN_BG);
consoleInit(&topScreen, 3, BgType_Text4bpp, BgSize_T_256x256, 31, 0, true, true);
consoleSelect(&topScreen);
srand(time(NULL));
int round = 1;
Keyboard *kbd = keyboardDemoInit();
kbd->OnKeyPressed = OnKeyPressed;
iprintf("\n\nGreat Number Guessing Game for DSi!\n\n");
iprintf("All numbers are between 0 and 1000!\n\n");
for( ; ;)
{
int target = rand() % 1001;
int in;
int tried = 1;
iprintf("Round %d!\n", round);
reinput:
iprintf("Input a number: ");
scanf("%d", &in);
if (in == target)
{
iprintf("Bingo!!! You've tried %d times.\n\n", tried);
round++;
continue;
}
else if (in < target)
{
iprintf("Too low!\n");
tried++;
goto reinput;
}
else
{
iprintf("Too high!\n");
tried++;
goto reinput;
}
}
return 0;
}
void OnKeyPressed(int key)
{
if (key > 0)
iprintf("%c", key);
}
编译,运行。
事实上,要在DS上实现这样的程序,并不简单。然而devkitPro为我们简化掉了大量的工作,使得高效的NDS开发成为了可能。