====================
STEP #1:
首先打開VC++ 2008 Express,新增一個方案與專案,設置為Win32主控台應用程式的空專案。
在專案內新增main.cpp,輸入程式如下:
#include <stdio.h>
#include <conio.h>
int main(){
int curLineNum = 0;
int totLineNum = 3;
printf("Press any key to start game...\n");
while(1){
printf("curLineNum is: %d \n", curLineNum);
getch();
if(curLineNum == (totLineNum - 1)){
break;
}
else{
curLineNum = curLineNum + 1;
}
}
return 0;
}
程式解說:
- #5,#6我們宣告了兩個整數,curLineNum將會用於紀錄目前說的是哪一號(句)台詞;而totLineNum用來記錄台詞總數。
- 接著我們使用while做了一個無限迴圈。在迴圈中,使用了<conio.h>所提供的getch()函數偵測鍵盤是否有輸入。
- getch()與getchar()最大的不同在於:getch()不須使用者按ENTER才行動作,而是玩家按了任何鍵都會主動解析並且返回。
- 當偵測到任何輸入的時候,倘若還沒輪到最後一句話,就將目前的句號+1。
按<CTRL>+F5運行,結果如下:
======================
STEP #2:
修改程式。
#include <stdio.h>
#include <conio.h>
int main(){
int curLineNum = 0;
const int totLineNum = 3;
char *lines[totLineNum]={
"今天天氣真好。",
"想吃甚麼呢?",
"吃牛肉麵好了。"
};
printf("Press any key to start game...\n");
getch();
while(1){
printf(lines[curLineNum]);
printf("\n");
getch();
if(curLineNum == (totLineNum - 1)){
break;
}
else{
curLineNum = curLineNum + 1;
}
}
return 0;
}
程式解說:
- #6將totLineNum設為const int,轉為不可變動的常量。要不然下方宣告陣列時會出錯。
- #8~#12定義一個lines陣列用以儲存字串,裡面存放台詞。
- 無窮迴圈裡#19依照目前台詞號,將台詞輸出到主控台。
======================
STEP #3:
修改程式。
運行測試,現在可以做劇情分叉了!
#include <stdio.h>
#include <conio.h>
int main(){
int curLineNum = 0;
const int totLineNum = 8;
char tempGetch;
char *lines[totLineNum]={
"今天天氣真好。",
"想吃甚麼呢?",
"吃牛肉麵好了。",
"吃吧!",
"",
"",
"",
"難吃"
};
printf("Press any key to start game...\n");
getch();
while(1){
printf(lines[curLineNum]);
printf("\n");
//getch();
if(curLineNum == (totLineNum - 1)){
break;
}
else{
if(curLineNum == 2){
printf("A.吃 B.不吃");
printf("\n");
tempGetch = getch();
if(tempGetch=='a'){
curLineNum = 3;
continue;
}
else if(tempGetch =='b'){
curLineNum = 7;
continue;
}
}
else if(curLineNum == 3){
break;
}
else if(curLineNum == 7){
break;
}
else{
getch();
curLineNum++;
}
}
}
return 0;
}
運行測試,現在可以做劇情分叉了!