Shock! There are people who don't know the necessary functions to write console games!

Posted by misterm on Wed, 02 Feb 2022 21:08:03 +0100

These functions are learned from other authors. I summarize. Thank them very much!

1, Output at the specified location on the console

#include<stdio.h>
#include<windows.h>
int main(void)
{
	COORD pos={10,10};
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
			printf("I love you!");	
}

First, you need to include the header file windows h. Secondly, you need to define a variable of COORD type. What is a variable of COORD type?

1. COORD type

COORD is a structure defined in the Windows API, which represents the coordinates of a character on the console screen. It is defined as:

typedef struct _COORD {

SHORT X; // horizontal coordinate

SHORT Y; // vertical coordinate

} COORD;

2.GetStdHandle()

sketch
GetStdHandle is a Windows API function. It is used to obtain a handle (a value used to identify different devices) from a specific standard device (standard input, standard output or standard error). Because many API functions need handles, GetStdHandle is a very important function.
  
Function prototype (included in the header file windows.h)
ANDLE WINAPI GetStdHandle( In DWORD nStdHandle);

parameter
The parameters of the GetStdHandle function can be one of the following

parametermeaning
STD_INPUT_HANDLEStandard input handle
STD_OUTPUT_HANDLEStandard output handle
STD_ERROR_HANDLEStandard error handle

Note: only these three parameters. Different parameters are used to get handles to different standard devices.

Return value
We all know that GetStdHandle() is used to obtain a handle, so its return value is of course a handle. This can also be seen from the function prototype.
Reference articles

3,SetConsoleCursorPosition()

Setconsolecursor position() comes from the file "windows.h". Remember to refer to this header file when using it.

The function of this function literally means to move the cursor position in the command line. It should be noted here that every time this function is called, it is offset from the upper left corner by default, regardless of the current cursor position.

We checked the definition and found that calling this function requires passing in two parameters, both of which are custom types, namely HANDLE and cool.

SetConsoleCursorPosition(In HANDLE hConsoleOutput,In COORD dwCursorPosition);
dwCursorPosition parameter is the POS structure in the sample program, which means moving the cursor to the abscissa pos.X and ordinate pos.Y. the first parameter is the handle, which is obtained from the standard output by calling GetStdHandle().
Reference articles

2, Mouse operation

We know that windows The H header file provides us with the method to obtain the relative screen position of the mouse and the relative screen position of the window, but we need to obtain the coordinates of the mouse relative to the window.
According to the mathematical relationship: the abscissa of the mouse relative to the window = the abscissa of the mouse relative to the screen - the coordinate of the left side of the window relative to the screen

1. Get the relative screen coordinates of the mouse

Type used: POINT
The POINT structure class stores the horizontal and vertical coordinates (mouse.x,mouse.y) of the mouse

BOOL GetCursorPos(LPPOINT lpPoint)

Function prototype: BOOL GetCursorPos (LPPOINT lpPoint)
Parameter: IpPoint: pointer to the POINT structure, which receives the screen coordinates of the cursor.
Function: obtain the relative screen coordinates of the mouse and store them in the variable of POINT type.

#include<stdio.h>
#include<windows.h>
#include<stdbool.h>
#include<stdlib.h>
int main(void)
{
	COORD pos={0,0};
	POINT *mouse;
	mouse=(POINT*)malloc(sizeof(POINT)+64);//Why add 64? I don't know
	while(true)
	{
 		GetCursorPos(mouse);//Return the coordinates corresponding to the mouse and store them in ptrpos
 		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
			printf("Mouse relative to screen;\nmouse->x=%d mouse->y=%d    \n",mouse->x,mouse->y);
		Sleep(100);
	}	
}

2. Get the relative screen coordinates of the console

You can directly look at the program. The specific information of these functions can not be mastered. You can use them.
Type used: LPRECT
The LPRECT structure class stores the position (top, bottom, left, right) of a specified window (such as console window) relative to the screen
Functions used:

1,BOOL WINAPI SetConsoleTitle(__in LPCTSTR lpConsoleTitle)

Function prototype: bool WinAPI setconsoletitle (_in lpctstr lpconsoletitle);
Parameter: String address
Function: set the title of the console window

2,HWND FindWindow(LPCSTR lpClassName,LPCSTR lpWindowName);

Function prototype
HWND FindWindow(LPCSTR lpClassName,LPCSTR lpWindowName);
parameter
lpClassName
Points to a NULL terminated string used to specify the class name or an atom that can determine the class name string. If this parameter is an atom, it must be a global atom that has been created through the GlobalAddAtom function before calling this function. This atom (a 16 bit value) must be placed in the low byte of lpClassName and the high byte of lpClassName is set to zero.
If this parameter is null, any window matching the lpWindowName parameter will be found.
lpWindowName
Points to a NULL terminated string that specifies the window name (that is, the window title). If this parameter is NULL, all window names are matched.
Return value
If the function is executed successfully, the return value is the handle of the window with the specified window class name or window name.
If the function fails, the return value is NULL. You can get more detailed error information by calling the GetLastError function.

3,BOOL GetWindowRect(HWND hWnd,LPRECT lpRect)

Function prototype
BOOL GetWindowRect(HWND hWnd,LPRECT lpRect);
In Visual Studio 2005, the function prototype is void GetWindowRect(LPRECT lpRect) const; Is a function belonging to CWnd class
parameter
HWND: window handle.
lpRect: pointer to a RECT structure that receives the screen coordinates of the upper left and lower right corners of the window.
Variable:
left ;top; right;bottom;
Represents the / left / top / right / bottom coordinates of the window respectively
Return value:
If the function succeeds, the return value is non-zero; if the function fails, the return value is zero. For more error information, call the GetLastError function.

#include<stdio.h>
#include<windows.h>
#include<stdbool.h>
#include<stdlib.h>
int main(void)
{
	COORD pos={0,0};
	SetConsoleTitle("Like attention, don't get lost");//Set window title
	LPRECT console;//The LPRECT structure class stores the position (top, bottom, left, right) of a specified window (such as console window) relative to the screen
	console=(LPRECT)malloc(sizeof(LPRECT)+64);//Allocate memory space for structure pointers
	while(true)
	{
		HWND hwnd=FindWindow(NULL,"Like attention, don't get lost");//According to the title set above, the first parameter is set to NULL, which means to find all handles in the system. Because the window position needs to be obtained dynamically, it needs to be written in the loop body
		GetWindowRect(hwnd,console);//According to the handle obtained by looking up the title "greedy snake", the coordinates of the window are returned and stored in the console
 		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
			printf("Window relative to screen;\nconsole->left=%d console->top=%d    \n",console->left,console->top);
		Sleep(100);
	}	
}

Drag the window to see the coordinate change. You may find that a series of inexplicable numbers are output on the left. I don't know what it is
Combining the above two procedures, you can obtain the coordinates of the mouse relative to the console:

#include<stdio.h>
#include<windows.h>
#include<time.h>
#include<stdbool.h>
#define length 10
#define wide 5
void Eage(void);
int main(void)
{
	Eage();
	
	SetConsoleTitle("Like attention, don't get lost");//Set window title
	int x,y;
	POINT *mouse;//The POINT structure class stores the abscissa and ordinate of the number scale (mouse.x,mouse.y)
	LPRECT console;//The LPRECT structure class stores the position (top, bottom, left, right) of a specified window (such as console window) relative to the screen
  	mouse=(POINT*)malloc(sizeof(POINT)+64);
 	console=(LPRECT)malloc(sizeof(LPRECT)+64);//Allocate memory space for structure pointers

   while(true)
   {
		HWND hwnd=FindWindow(NULL,"Like attention, don't get lost");//It means that the first handle in the above handle is set to NULL, which means that the system will find all the parameters according to the first handle
	   	
		 /*Get mouse position dynamically*/
		GetWindowRect(hwnd,console);//According to the handle obtained by looking up the title "greedy snake", the coordinates of the window are returned and stored in the console
		GetCursorPos(mouse);//Return the coordinates corresponding to the mouse and store them in ptrpos
  	 	x=mouse->x-console->left;//Mouse abscissa - the abscissa at the left end of the console window to obtain the abscissa of the mouse relative to the console window
	    y=mouse->y-console->top;//Similarly, the relative ordinate of the mouse is obtained
  	    COORD pos={0,wide+1};
   	    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
			printf("Relative coordinates: x=%d y=%d    \n",x,y);
		if(GetAsyncKeyState(VK_RBUTTON))//The left button should be the default pause
		{
			//If the left mouse button is pressed, VK_LBUTTON is windows The macro defined in the H library corresponds to the ASCII value corresponding to the left mouse button
   	     	if((7<=x&&x<96)&&(y>=37&&y<123))//The boundary is determined according to the dynamically obtained coordinates
   	     	{
   	     		puts("Exit successfully");
        		break;
   	     	}
		}
		Sleep(100);
	}

}
void Eage(void)
{
	COORD pos;
	for(int i=0;i<length;i++)
	{
		pos={i,0};
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
			printf(".");
		pos={i,wide};
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
			printf(".");
	}
	pos={1,wide/2};
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
			printf("Right click to exit");
	for(int i=0;i<wide;i++)
	{
		pos={0,i};
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
			printf(".");
		pos={length,i};
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
			printf(".");
	}
}

The above procedure involves the function: GetAsyncKeyState() to judge whether a key is pressed
Reference articles

3, Keyboard operation

kbhit()

#include<stdio.h>
#include<conio.h>
#include<windows.h>
#include<time.h>
int main(void)
{
	COORD pos={10,5};
	char ch;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
		printf("#");
	while(true)
	{
		
		if(kbhit())
		{
			switch(ch=getch())
			{
				case 'w':pos.Y--;break;
				case 'a':pos.X--;break;	
				case 's':pos.Y++;break;
				case 'd':pos.X++;break;
			}
		}
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
			printf("#");
		Sleep(100);
	}
}

kbhit() is a C and C + + function that responds non blocking to keyboard input events.
Prototype: int kbhit(void)
Header file: conio h
Function and return value: check whether there is keyboard input at present. If yes, a non-0 value will be returned; otherwise, 0 will be returned.
Note: if you want to delete the output character, you can output a space at the coordinates of the character.