如果你要写c++控制台游戏,但最终看起来多余的代码很多,可以试试jgm.h(jj_189805 game),这里面有写游戏常用的常量和函数。
如何使用
将下面代码保存为jgm.h,然后放到和你的游戏文件相同的文件夹里面,如果使用时报错,请立即检查目录中是否有jgm.h.gch,如果有请立即删除,我就是因为它排查了很久。
#ifndef JGM_H
#define JGM_H
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
const WORD default_color = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
const WORD red = FOREGROUND_RED | FOREGROUND_INTENSITY;
const WORD green = FOREGROUND_GREEN | FOREGROUND_INTENSITY;
const WORD blue = FOREGROUND_BLUE | FOREGROUND_INTENSITY;
const WORD yellow = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY;
const WORD cyan = FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
const WORD gray = FOREGROUND_INTENSITY;
inline void set_cursor_visible(bool visible) {
CONSOLE_CURSOR_INFO cursorInfo;
GetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo);
cursorInfo.bVisible = visible ? TRUE : FALSE;
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo);
}
inline void set_window_size(int width, int height) {
char cmd[50];
sprintf(cmd, "mode con cols=%d lines=%d", width, height);
system(cmd);
}
inline bool has_key() {
return _kbhit() != 0;
}
inline int get_key() {
if (_kbhit()) return _getch();
return 0;
}
#define MAX_BUF 4000
class screen {
private:
int width;
int height;
char text_buf[MAX_BUF];
WORD color_buf[MAX_BUF];
public:
screen(int w, int h) : width(w), height(h) {}
void clear() {
int total = width * height;
for (int i = 0; i < total; i++) {
text_buf[i] = ' ';
color_buf[i] = default_color;
}
}
void text(int x, int y, const char* str, WORD color = default_color) {
int cur_x = x;
while (*str) {
if (cur_x >= 0 && cur_x < width && y >= 0 && y < height) {
int index = y * width + cur_x;
text_buf[index] = *str;
color_buf[index] = color;
}
cur_x++;
str++;
}
}
void render() {
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos = {0, 0};
SetConsoleCursorPosition(h, pos);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int index = y * width + x;
SetConsoleTextAttribute(h, color_buf[index]);
putchar(text_buf[index]);
}
if (y < height - 1) {
putchar('\n');
}
}
}
};
#endif示例代码:
#include "jgm.h"
int main() {
//设置窗口大小
set_window_size(20, 5);
set_cursor_visible(false); //隐藏光标
//创建画布
screen canvas(20, 5);
//清空画布
canvas.clear();
//画字(前两个数字是坐标)
canvas.text(1, 1, "R", red);
canvas.text(3, 1, "G", green);
canvas.text(5, 1, "B", blue);
canvas.text(7, 1, "Y", yellow);
canvas.text(9, 1, "D", default_color);
// 刷新到屏幕
canvas.render();
//检测按键并获取(按任意键退出)
while (!has_key()) {
Sleep(10);
}
get_key();
//恢复光标
set_cursor_visible(true);
return 0;
}