C++面向对象 其一 走迷宫

C++ :001 走迷宫

1.< fstream>头文件

流<<,>>可以想成往哪边开信息就流向那边

1.fsream是c++中用于从文件中读入输入文件的标准库头文件

std::instream:往文件输入内容

std::outstream读出文件内容

std::fstream又能输入又能输出

三者都是+**变量名 (“文件名”);**来实现

最后还是**变量名.close();**来关闭文件

2.fstream类

类:类就是一个模具,通过这个模具如fstream b(”a.txt”)这里,b就是通过这个类(模具)所塑造出来的一个对象,这个通过类塑造出来的对象有这个类的一切功能(公开public里面的功能,一些private可能没有),像是.close之类的

那这里,联想到c语言中的结构体,它把一堆属性组合起来,但是没有函数的功能(行为)

结构体的默认访问权限是共有的public,而类的默认访问权限则是private私有的

2.定义一个句柄,对光标的操作

3.控制循环:

1
2
3
4
5
6
7
8
9
10
11
while (1) {
if (GetAsyncKeyState(VK_UP) & 0x8000){
if (map[y-1][x] != '*'){

}
}
}

//GetAsyncKeyState() 检测指定虚拟键的状态,返回值为负数表示被按下
//& 0x8000 位运算提取高位信息,判断按键是否实际被按下
//

4.光标隐藏

1
2
3
4
5
6
7
8
9
10
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cursorInfo;
GetConsoleCursorInfo(h, &cursorInfo);
cursorInfo.bVisible = false;
SetConsoleCursorInfo(h, &cursorInfo);

//SetConsoleCursorInfo() 修改后的光标属性
//CONSOLE_CURSOR_INFO结构体包含dwSize(光标大小)和bVisible(可见性)成员

//SetConsoleCursorInfo() 修改后的光标属性

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include<iostream>
#include<fstream>
#include<windows.h>
using namespace std;

const int MAXN = 100;
char map[MAXN][MAXN];
int row = 0, col = 0;
//用键盘控制光标
void gotoxy(int x, int y){
COORD pos = { (SHORT)x, (SHORT)y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}

int main(){
ifstream in("地图.txt");
string s;
while(getline(in, s)){
for(int i = 0; i < s.size(); ++i){
map[row][i] = s[i];
}
++row;
col = max(col, (int)s.size());
}
//用map来实现墙体的效果
for(int i = 0; i < row; ++i){
cout<<"\t\t\t\t\t\t";
for(int j = 0; j < col; ++j){
cout << map[i][j];
}
cout << endl;
}

HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cursorInfo;
GetConsoleCursorInfo(h, &cursorInfo);
cursorInfo.bVisible = false;
SetConsoleCursorInfo(h, &cursorInfo);

int x = 30, y = 1; // 可根据地图起点调整
gotoxy(x, y);
cout << 'A';
while (1) {
// 上方向键
if (GetAsyncKeyState(VK_UP) & 0x8000){
if (map[y-1][x] != '*'){
gotoxy(x, y); cout << ' ';
y--;
gotoxy(x, y); cout << 'A';
Sleep(200);
}
}
if (GetAsyncKeyState(VK_DOWN) & 0x8000){
if (map[y+1][x] != '*'){
gotoxy(x, y); cout << ' ';
y++;
gotoxy(x, y); cout << 'A';
Sleep(200);
}
}
if (GetAsyncKeyState(VK_LEFT) & 0x8000){
if (map[y][x-1] != '*'){
gotoxy(x, y); cout << ' ';
x--;
gotoxy(x, y); cout << 'A';
Sleep(200);
}
}
if (GetAsyncKeyState(VK_RIGHT) & 0x8000){
if (map[y][x+1] != '*'){
gotoxy(x, y); cout << ' ';
x++;
gotoxy(x, y); cout << 'A';
Sleep(200);
}
}
}
}