- 算法超簡單:趣味游戲帶你輕松入門與實踐
- 童晶
- 363字
- 2024-09-10 17:14:28
2.3 按空格鍵讓小球向上飛
本節(jié)講解如何實現(xiàn)按空格鍵讓小球向上飛,完整代碼參見配套資源中的2-3-2.cpp,掃描右側二維碼觀看視頻效果“2.3 按空格鍵讓小球向上飛”。

2.3 按空格鍵讓小球向上飛
_kbhit()函數(shù)可以響應鍵盤的輸入,當有鍵盤輸入時返回1,否則返回0。在2-3-1.cpp中,當用戶按下某個鍵時,執(zhí)行if (_kbhit())內的語句。首先獲得用戶輸入的字符,并存儲在變量input中,如果用戶按下的是空格鍵,則輸出提示文字。
2-3-1.cpp
1 #include <graphics.h> 2 #include <conio.h> 3 #include <stdio.h> 4 int main() 5 { 6 while (1) // 一直循環(huán) 7 { 8 if (_kbhit())// 當按鍵時 9 { 10 char input = _getch(); // 獲得輸入字符 11 if (input == ' ') // 當按下空格鍵時 12 printf("按下了空格!\n"); 13 } 14 } 15 return 0; 16 }
在2-2.cpp小球的自由落體程序中添加下方代碼,實現(xiàn)按下空格鍵后小球向上運動(賦予小球一個向上的初速度)。
2-3-2.cpp
24 while (1) // 一直循環(huán) 25 { 26 if (_kbhit()) // 當按鍵時 27 { 28 char input = _getch(); // 獲得輸入字符 29 if (input == ' ') // 當按下空格鍵時 30 bird.vy = -10; // 給小球一個向上的速度 31 }
推薦閱讀
- INSTANT Mock Testing with PowerMock
- Learning Bayesian Models with R
- oreilly精品圖書:軟件開發(fā)者路線圖叢書(共8冊)
- Vue.js 3.0源碼解析(微課視頻版)
- D3.js By Example
- PHP+MySQL動態(tài)網(wǎng)站開發(fā)從入門到精通(視頻教學版)
- Java 7 Concurrency Cookbook
- Python程序設計現(xiàn)代方法
- Server Side development with Node.js and Koa.js Quick Start Guide
- TensorFlow 2.0深度學習應用實踐
- TensorFlow程序設計
- VBA Automation for Excel 2019 Cookbook
- Metasploit for Beginners
- Machine Learning for the Web
- Python金融風控策略實踐