飛機大戰git
由玩家操控飛機進行遊戲並累計得分。ide
void gotoxy(int x,int y) { HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE); COORD pos; pos.X = x; pos.Y = y; SetConsoleCursorPosition(handle,pos); }
void HideCursor() { CONSOLE_CURSOR_INFO cursor_info = {1, 0}; // 第二個值爲0表示隱藏光標 SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info); }
3.數據初始化設計
void startup() { high = 20; width = 30; position_x = high/2; position_y = width/2; bullet_x = -2; bullet_y = position_y; enemy_x = 0; enemy_y = position_y; score = 0; HideCursor(); // 隱藏光標 }
4.顯示畫面code
void show() { gotoxy(0,0); // 光標移動到原點位置,如下重畫清屏 int i,j; for (i=0;i<high;i++) { for (j=0;j<width;j++) { if ((i==position_x) && (j==position_y)) printf("*"); // 輸出飛機* else if ((i==enemy_x) && (j==enemy_y)) printf("@"); // 輸出敵機@ else if ((i==bullet_x) && (j==bullet_y)) printf("|"); // 輸出子彈| else printf(" "); // 輸出空格 } printf("\n"); } printf("得分:%d\n",score); }
void updateWithoutInput() { if (bullet_x>-1) bullet_x--; if ((bullet_x==enemy_x) && (bullet_y==enemy_y)) // 子彈擊中敵機 { score++; // 分數加1 enemy_x = -1; // 產生新的飛機 enemy_y = rand()%width; bullet_x = -2; // 子彈無效 } if (enemy_x>high) // 敵機跑出顯示屏幕 { enemy_x = -1; // 產生新的飛機 enemy_y = rand()%width; } // 用來控制敵機向下移動的速度。每隔幾回循環,才移動一次敵機 // 這樣修改的話,用戶按鍵交互速度仍是保持很快,但咱們NPC的移動顯示能夠降速 static int speed = 0; if (speed<20) speed++; if (speed == 20) { enemy_x++; speed = 0; } }
6.與用戶輸入有關的更新blog
void updateWithInput() { char input; if(kbhit()) // 判斷是否有輸入 { input = getch(); // 根據用戶的不一樣輸入來移動,沒必要輸入回車 if (input == 'a') position_y--; // 位置左移 if (input == 'd') position_y++; // 位置右移 if (input == 'w') position_x--; // 位置上移 if (input == 's') position_x++; // 位置下移 if (input == ' ') // 發射子彈 { bullet_x = position_x-1; // 發射子彈的初始位置在飛機的正上方 bullet_y = position_y; } } }
截圖
遊戲
代碼託管鏈接 https://gitee.com/wjx0229/difficult_team/blob/master/飛機遊戲終極版.cpp
實驗總結:
第一次作該類型的實驗設計,不少東西不明白,只能根據書本照貓畫虎。get