常用框架
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
#include<conio.h>
#define WIDTH 20
#define HEIGHT 30
//定义函数
void init();//初始化游戏数据
void show();//显示
void updateWithoutInput();//与输入无关的更新
void updateWithInput();//与输入有关的更新
void hideCursor();//隐藏光标
void cursorGoto(int x, int y);//光标移动至
//全局变量
int position_x, position_y;//操作物坐标
int main() {
init();//初始化游戏数据
while (1) {
show();//显示
updateWithoutInput();//与输入无关的更新
updateWithInput();//与输入有关的更新
}
return 0;
}
/**
* 初始化游戏数据
*/
void init() {
hideCursor();//隐藏光标
}
/**
* 显示游戏内容
*/
void show() {
cursorGoto(0, 0);
for (size_t i = 0; i < HEIGHT; i++) {
for (size_t j = 0; j < WIDTH; j++) {
if (i == position_x && j == position_y) {
printf("A");
} else {
printf(" ");
}
}
printf("|\n");
}
for (size_t i = 0; i < WIDTH; i++) {
putchar('_');
}
printf("|\n");
}
/**
* 与输入有关的更新
*/
void updateWithInput() {
char input;
if (_kbhit()) {
input = _getch();
switch (input) {
case 'a':position_x = position_x - 1 < 0 ? WIDTH - 1 : position_x - 1;
break;
case 'd':position_x = position_x + 1 > WIDTH - 1 ? 0 : position_x + 1;
break;
case 'w':position_y = position_y - 1 < 0 ? 0 : position_y - 1;
break;
case 's':position_y = position_y + 1 > HEIGHT - 1 ? HEIGHT - 1 : position_y + 1;
break;
default:
break;
}
}
}
/**
* 与输入无关的更新
*/
void updateWithoutInput() {
}
/**
* 隐藏光标
*/
void hideCursor() {
CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };//第二个值为o表示隐藏光标
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
/**
* 光标移动至(x, y)
*/
void cursorGoto(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 };//第二个值为o表示隐藏光标
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
- 移动光标
/**
* 光标移动至(x, y)
*/
void cursorGoto(int x, int y) {
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle, pos);
}
常用输入
/**
* 与输入有关的更新
*/
void updateWithInput() {
char input;
if (_kbhit()) {
input = _getch();
switch (input) {
case 'a':positionX = positionX - 1 < 0? width-1: positionX-1;
break;
case 'd':positionX = positionX + 1 > width - 1 ? 0 : positionX + 1;
break;
case 'w':positionY = positionY - 1 < 0 ? 0 : positionY - 1;
break;
case 's':positionY = positionY + 1 > height-1 ? height - 1 : positionY + 1;
break;
default:
break;
}
}
}
网友评论