如果你要写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 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;
}
class screen {
private:
CHAR_INFO* buffer;
int width;
int height;
void draw(int x, int y, char ch, WORD color) {
if (x >= 0 && x < width && y >= 0 && y < height) {
int index = y * width + x;
buffer[index].Char.AsciiChar = ch;
buffer[index].Attributes = color;
}
}
public:
screen(int w, int h) : width(w), height(h) {
buffer = new CHAR_INFO[width * height];
}
~screen() {
delete[] buffer;
}
void clear() {
for (int i = 0; i < width * height; i++) {
buffer[i].Char.AsciiChar = ' ';
buffer[i].Attributes = default_color;
}
}
void text(int x, int y, const char* str, WORD color = default_color) {
int cur_x = x;
while (*str) {
draw(cur_x++, y, *str, color);
str++;
}
}
void render() {
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
COORD size = { (SHORT)width, (SHORT)height };
COORD pos = { 0, 0 };
SMALL_RECT rect = { 0, 0, (SHORT)(width - 1), (SHORT)(height - 1) };
WriteConsoleOutput(h, buffer, size, pos, &rect);
}
};
#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;
}