- js24011 的博客
#include <conio.h>
- @ 2025-11-22 8:11:45
提前声明:AI写的
含义
#include <conio.h> 是 Console Input/Output(控制台输入/输出)的缩写,它是一个用于控制台操作的C语言头文件,一般与$$#include <windows.h>搭配使用。(做游戏用的)
主要包括以下函数:
-
_getch( ) 获取单个字符(无回显,更常用)
-
_getche( ) 获取单个字符(有回显)
-
_kbhit( ) 检查是否有按键按下
-
_putch( ) 输出单个字符
栗子
#include <windows.h>
#include <iostream>
#include <conio.h>
using namespace std;
const int HEIGHT=12,WIDTH=12;
char map[HEIGHT][WIDTH] = {
{'1', '1', '1', '1', '1', '1', '1', '1', '1', '1'},
{'1', '0', '0', '0', '0', '0', '0', '0', '0', '1'},
{'1', '0', '1', '1', '0', '1', '1', '1', '0', '1'},
{'1', '0', '1', '0', '0', '0', '0', '1', '0', '1'},
{'1', '0', '0', '0', '1', '1', '0', '0', '0', '1'},
{'1', '0', '1', '0', '0', '0', '0', '1', '0', '1'},
{'1', '0', '0', '0', '0', '0', '0', '0', '0', '1'},
{'1', '1', '1', '1', '1', '1', '1', '1', '1', '1'}
};
void DisplayMap(int x,int y){
for(int i=1;i<=WIDTH;i++){
for(int j=1;j<=HEIGHT;j++){
if(j==x&&i==y)cout<<"P";
else if(map[j][i]=='1')cout<<"1";
else if(map[j][i]=='0')cout<<"0";
cout<<" ";
}
cout<<endl;
}
return;
}
int main() {
// 玩家初始位置
int playerX = 1;
int playerY = 1;
cout << "=== 简单移动游戏 ===" << endl;
cout << "使用 W A S D 移动,Q 退出" << endl;
cout << "P=玩家, 0=空格(可走), 1=墙" << endl;
cout << "===================" << endl;
while (true) {
system("cls");
DisplayMap(playerX, playerY);
cout << "位置: (" << playerX << ", " << playerY << ")" << endl;
if (_kbhit()) {
char input = _getch();
input = toupper(input);
int newX = playerX;
int newY = playerY;
switch (input) {
case 'W': newY--; break; // 上
case 'S': newY++; break; // 下
case 'A': newX--; break; // 左
case 'D': newX++; break; // 右
case 'Q':
cout << "游戏结束!" << endl;
return 0;
}
if (newX >= 0 && newX < WIDTH && newY >= 0 && newY < HEIGHT) {
if (map[newY][newX] == '0') {
playerX = newX;
playerY = newY;
}
}
}
Sleep(50);
}
return 0;
}
该头文件的优点是可以直接读取键盘输入,特别适合游戏、菜单选择等需要立即响应的场景。