// File: console.cpp // Console routines #include "console.h" /*To use console.h, copy it to the c:\Prrogram Files\Microsoft Visual Studio\VC98\include directory Place #include "console.h" in your program clrscr() -- clears the screen and places the cursor in the upper left corner. Note that I implemented this in two different ways, and that the long method has been commented out. void gotoxy(int, int) -- positions the cursor on the screen, with (1,1) being the upper left corner. void randomize() -- seeds the random number table according to the clock tick timer. int random(int) -- returns a random integer in the range 0 to int-1. int getch() -- waits for a keypress, returns the keypress, then moves on. Does NOT echo keypress to the screen (does NOT use iostreams). Does NOT wait for the user to press the Enter key. int getche() -- same as getch() except it echoes the character typed to the screen. void delay(long) -- long is the number of milliseconds to delay. Code: */ // console.h // contains functions to translate Borland C++ // console operations to Microsoft Visual C++ // console.h by Gary Frankenbery // Grants Pass High School // Grants Pass, OR #include // for console operations #include // for rand(), srand() #include // for time() #include // for _getch() and _getche() #include using namespace std; // gotoxy() Positions cursor relative to the upper // left corner of the screen. In Borland's // conio.h, the upper left corners is (1,1), // while in Microsoft's // SetConsoleCursorPosition()the coordinates // of the upper left corner are (0,0). Note // the adjustment to x and y below to use // Borland's scheme. void gotoxy(int x, int y) { HANDLE hdl; COORD coords; // get the console handle hdl = GetStdHandle(STD_OUTPUT_HANDLE); coords.X = x-1; coords.Y = y-1; // set cursor position SetConsoleCursorPosition(hdl, coords); } // clrscr() Clears the screen, and sets the cursor // to position (1,1), the upper left // corner. void clrscr() { system("CLS"); } void delay(long msecs) // delay 'msecs' milliseconds {clock_t now = clock(); // get current time clock_t then = now + CLOCKS_PER_SEC * (double)msecs / 1000.0; while(now < then) now = clock(); } // randomize() Seeds the random number generator. // void randomize() {srand( (unsigned)time(NULL) );} // returns a random number in range 0 to num-1 int random(int num) {return rand() % num;} // Waits for and returns a keypress (no echo) int getch() {int ch; HANDLE hdl; cout.flush(); ch = _getch(); hdl = GetStdHandle(STD_INPUT_HANDLE); FlushConsoleInputBuffer(hdl); return ch; } // Waits for and returns a keypress with echo int getche() {int ch; HANDLE hdl; ch = _getche(); hdl = GetStdHandle(STD_INPUT_HANDLE); FlushConsoleInputBuffer(hdl); return ch; }