Recently, when writing a Snake game, you need to use the cursor to locate the game.
Method 1:
1 # Include <windows. h> 2 # Include <stdio. h> 3 4 Handle Hout = Getstdhandle (std_output_handle ); 5 Coord; 6 Void Locate ( Int X, Int Y) 7 { 8 Coord. x = X; 9 Coord. Y = Y; 10 Setconsolecursorposition (Hout, coord ); 11 12 }; 13 14 Int Main () 15 16 { 17 Locate ( 2 , 2 ); 18 Printf ( " Hello world \ n "); 19 Return 0 ; 20 }
Method 2: Use the Goto () function
1 # Include <stdio. h>2 # Include <windows. h> 3 4 Void Gotoxy ( Int X, Int Y) 5 { 6 Coord = {X, y }; 7 Setconsolecursorposition (getstdhandle (std_output_handle), coord ); 8 } 9 10 Void Main () 11 { 12 Gotoxy ( 3 , 3 ); 13 Printf ( " Hello world! \ N " ); 14 }
In snake games, the cursor is often used to locate and hide the cursor.
1 /* ** Cursor positioning ** */ 2 Handle Hout = Getstdhandle (std_output_handle ); 3 Coord; 4 Void Locate ( Int X, Int Y) 5 { 6 Coord. x =X; 7 Coord. Y = Y; 8 Setconsolecursorposition (Hout, coord ); 9 }; 10 /* ** Hide the cursor ** */ 11 Void Hide () 12 { 13 Console_cursor_info cursor_info = { 1 , 0 }; 14 Setconsolecursorinfo (Hout ,& Cursor_info ); 15 }
In this way, it is easier to make a character version of Tetris or a snake game.
1 # Include <windows. h> 2 3 Void Hidecursor () 4 { 5 Console_cursor_info cursor_info = { 1 , 0 }; 6 Setconsolecursorinfo (getstdhandle (std_output_handle ),& Cursor_info ); 7 } 8 9 Both functions and schemas are defined in windows. H, so the function usage is simple. 10 Lele_cursor_info struct is defined as follows: 11 Typedef Struct 12 {DWORD dwsize; 13 Bool bvisible; // 0 Time Label invisible 14 } Console_cursor_info ,* Pconsole_cursor_info; 15 16 No problem in both VC and mingw.
Crood is like this:
Typedef struct _ coord {
Short X;
Short y;
} Coord, * pcoord;
Obviously, this structure can be used to record coordinates.
Getstdhandle ()The function obtains the handle and parameters of the standard input and output.Std_output_handleIs a macro, representing the standard output, can be seen as a display
Setconsolecursorposition (Hout, coord); function name: Set the console cursor coordinate. The parameter is the device handle and coordinate. Then, pass the standard output handle to the function, you can position the cursor at the corresponding position (the position in the upper left corner is 0, 0, and then extend to the left)
The following sectionCodeOutput "Hello World" in 10th rows and 30th columns on the screen"
1 # Include <windows. h> 2 # Include <iostream> 3 Using Namespace STD; 4 Int Main () 5 { 6 Handle Hout; 7 Coord; 8 Coord. x = 30 ; 9 Coord. Y = 10 ; 10 Hout = Getstdhandle (std_output_handle ); 11 Setconsolecursorposition (Hout, coord ); 12 13 Cout <" Hello world! \ N " ; 14 Return 0 ; 15 }