mvaddch does not overwrites a character on the screen - c

I write a client for a console game, 1vs1. In the game one player have to catch the other, and every player is rappresented with a char, printed on the console. I use the mvaddch() to delete the old position, and to print the new position on the console.
My code generate 2 process:
Process A: It get the input from the keyboard and update the position on the screen;
Process B: it get the input from the server and update the position of the enemy on the screen;
My problem is the old position of the enemy is not deleted (overwriting with ' '), and so process B generates a snake of charactes on the screen. Process A work good.
initscr();
noecho();
curs_set(0);
//process A is created now
switch ( pid = fork() ) {
case -1: perror("fork() fallita"); exit(0);
case 0: {char c; struct pos old_position = {welcome_position.c, welcome_position.x, welcome_position.y};
struct pos position = {welcome_position.c, welcome_position.x, welcome_position.y};
mvaddch(position.y, position.x, position.c);
while (1) {
switch(c=getch()) {
case SU: if(position.y>0) { position.y-=1; } break;
case GIU: if(position.y<MAXY-1){ position.y+=1; } break;
case SINISTRA: if(position.x>0){ position.x-=1; } break;
case DESTRA: if(position.x<MAXX-1){ position.x+=1; } break;
default: break; }
if ((position.x != old_position.x) || (position.y != old_position.y)) {
send(sock, &position, sizeof(struct pos), 0);
mvaddch(old_position.y, old_position.x, ' ');
mvaddch(position.y, position.x, position.c);
refresh();
old_position.x = position.x;
old_position.y = position.y; }} }
default: break ; }
// Process B is here
struct pos position;
struct pos old_position={' ', -1,-1};
while (1) {
while ( recv(sock, &position, sizeof(struct pos), 0) < 1 )
mvaddch(old_position.y, old_position.x, ' '); // THE PROBLEM
mvaddch(position.y, position.x, position.c); // Works => snake
refresh();
old_position.x = position.x;
old_position.y = position.y;}
endwin();
kill(pid);
printf("\n-----------------------------\n");
}

If you don't want the entire trail showing, you have to keep a record of the previous position of each character (player) and arrange to write a blank at the old position and the correct mark at the new position. If you're feeling fancy, you might use a coloured blank, one colour for each player, so you can see where each has been, even though the current positions are marked differently.
Unfortunately, without the colouration mentioned, that looks like what you're doing.
You should make sure you don't use the -1 coordinates; mvaddch() is probably not error checked and will go trampling out of bounds, doing who knows what damage. Don't risk it. (Consider using 0, 0 as the old position; it won't matter if you write a blank over a blank. The only thing that matters is that the other player is not where you write the blank.)
Note that it is crucial that only one process is doing the drawing. If you have two processes attempting to do so, you will lose one or the other images some of the time. This is one reason reason why it is hard to add a clock, say, to the top right corner of a terminal screen. You do seem to have two processes trying to write to the screen.
Style-wise, you need to use more functions. That is, the different processes should each have their code in a separate function, so that it is easier to see what they are doing. Stacking close braces } three deep on a single line is not good style either.

Related

Each loop round progressively slows down my SDL game

I am working on a little sokoban game, using the SDL 1.2 library. The most interesting possibility of this program is to move a character on a map. However, I am facing some strange slowing-down problem which I fail to find the reason of.
I simplified the code so it is not too long.
Here is the loop that makes the character move:
The followings correspond to the blocks of the game (each case of the map) and its position on the screen. For example, bloc[3] is a pointer to the surface corresponding to the 4th case of the map.
SDL_Surface *bloc[256] = {NULL};
SDL_Rect pos_bloc[256];
while (on == 1)
{
SDL_WaitEvent(&event);
switch (event.type)
{
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_ESCAPE:
on = game_menu(screen);
refresh_screen(screen, bloc, pos_bloc, zone);
break;
case SDLK_UP:
if (zone[m - 16] == ' ') // m is the position of the character on
// the map. As the map is 16 blocks large,
// and the position in the map is registered
// in a string, m - 16 means: 1 case up.
// m + 16 means: 1 case down.
m = swap_2blocs(screen, bloc, pos_bloc, zone, m, -16, "up.bmp");
break;
case SDLK_DOWN:
if (zone[m + 16] == ' ')
m = swap_2blocs(screen, bloc, pos_bloc, zone, m, 16, "down.bmp");
break;
default:;
}
default:;
}
SDL_Flip(screen);
}
Whenever the keys up or down are pressed, it calls a function that swap 2 surfaces: it frees both SDL_Surface pointers concerned and then reallocates some memory for another surface:
int swap_2blocs(SDL_Surface *screen, SDL_Surface *bloc[256], SDL_Rect pos_bloc[256], char zone[257], int m, int n, char *character)
{
SDL_FreeSurface(bloc[m]); // The surface pointed to by `bloc[m]` is freed
bloc[m] = SDL_LoadBMP("empty_space.bmp"); // `bloc[m]` now points to another surface
SDL_BlitSurface(bloc[m], NULL, screen, &pos_bloc[m]);
zone[m] = ' '; // zone is the string that contains informations about each map block
// ' ' stands for an empty space, 'M' stands for the character
m += n;
zone[m] = 'M';
SDL_FreeSurface(bloc[m]); // The surface pointed to by `bloc[m]` is freed
bloc[m] = SDL_LoadBMP(character); // `bloc[m]` now points to another surface
SDL_BlitSurface(bloc[m], NULL, screen, &pos_bloc[m]);
return m;
}
There are several things to be known:
The problem randomly appears 1 out of 3 times.
After 15-25 events (key up or key down), the slowing-down effect begins to be felt. After something like 30 events, it starts being really slow (there are around 300ms between the moment when the key is pressed, and the moment when the characters move on the screen).
It does slow down more than these approximative 300ms.
When the problem appears, going back to the main menu (which implies to free all the surfaces pointed to by each pointer contained in bloc) and starting a new game doesn't reset the speed of the game. To reset it, the program must be exited and then launched again.
I would like to understand this mysterious behaviour: where does it come from? What is happening?

ncurses forms: Show editing cursor / highlight active field

I’m new to programming and I’d like to realise the following with ncurses in C:
A form with fields to fill out and underneath this form, there is a continuously changing sensor value to be observed by the user during filling out the form, which results in the desired actions.
I’m glad I made it that far, that I can put the field buffer into my variables now, by pressing return, but now I’m facing a problem which seems to be not googleable.
My program started off from the example, which I posted underneath. In the original example I just added two lines and it already demonstrates my problem very well.
I set timeout(1); so the getch() function won’t wait for user input in the form before it prints the fresh sensor values.
Into the while-loop I put in the sennsor value with mvprint.
Now the sensor values are always up-to-date and it is still possible to move from one field to the other with the arrow keys and type into the fields.
But the visible Cursor always stays at the sensor value, which makes sense to me, because it is continuously moved there for printing. The forms driver seems to remember the position which was edited lastly, so that editing the fields will still function, but without any optical hint at which position the typing will be. The documentation refers to this position as the “editing-cursor” at one point.
Am I doing something completely wrong? Or is there a way to highlight the field, or even make the editing-cursor visible?
Thank you!
/* gcc -Wall -pthread -g -o formncurses formncurses.c -lform -lncurses */
#include <form.h>
int main()
{ FIELD *field[3];
FORM *my_form;
int ch;
/* Initialize curses */
initscr();
cbreak();
noecho();
keypad(stdscr, TRUE);
timeout(1);
/* Initialize the fields */
field[0] = new_field(1, 10, 4, 18, 0, 0);
field[1] = new_field(1, 10, 6, 18, 0, 0);
field[2] = NULL;
/* Set field options */
set_field_back(field[0], A_UNDERLINE); /* Print a line for the option */
field_opts_off(field[0], O_AUTOSKIP); /* Don't go to next field when this */
/* Field is filled up */
set_field_back(field[1], A_UNDERLINE);
field_opts_off(field[1], O_AUTOSKIP);
/* Create the form and post it */
my_form = new_form(field);
post_form(my_form);
refresh();
mvprintw(4, 10, "Value 1:");
mvprintw(6, 10, "Value 2:");
refresh();
/* Loop through to get user requests */
while((ch = getch()) != KEY_F(1))
{ switch(ch)
{ case KEY_DOWN:
/* Go to next field */
form_driver(my_form, REQ_NEXT_FIELD);
/* Go to the end of the present buffer */
/* Leaves nicely at the last character */
form_driver(my_form, REQ_END_LINE);
break;
case KEY_UP:
/* Go to previous field */
form_driver(my_form, REQ_PREV_FIELD);
form_driver(my_form, REQ_END_LINE);
break;
default:
/* If this is a normal character, it gets */
/* Printed */
form_driver(my_form, ch);
break;
}
mvprintw(12, 10, "Here stands the changing sensor value");
}
/* Un post form and free the memory */
unpost_form(my_form);
free_form(my_form);
free_field(field[0]);
free_field(field[1]);
endwin();
return 0;
}
The getch call essentially tells ncurses to leave the cursor where your mvprintw has left it — on the standard screen. To get it to move to your form, you would have to tell it to use wgetch, passing the WINDOW* pointer for the current form (which in turn holds a window's position for the field).
Further reading:
FIELD *current_field(const FORM *);
WINDOW *form_win(const FORM *form);
One thing that #Thomas's answer does not provide is how to highlight the active field (as indicated by the title of the question). For completion's sake, I am going to add a function here that will allow you to do just that:
void highlight_current_field(FORM *form, FIELD *fields[])
{
FIELD *cfield = current_field(form);
FIELD *currfield;
int i = 0;
while ((currfield = fields[i]) != NULL)
{
if (currfield == cfield)
set_field_back(currfield, A_STANDOUT);
else if (i >= 4)
set_field_back(currfield, A_UNDERLINE);
++i;
}
}
I hope this helps fellow travelers. For more information on the attributes provide, check out this site.

Moving cursor in C using atmega16

We're trying to make a project using atmega 16 and C language. The problem is that whenever we want to move a cursor, it goes to random places instead of moving one character right/left.
Our first idea was just
LCD_command(0x10);
for going left. It didn't work although we are sure it should (turning off the cursor works in the same function). We also tried:
uint8_t position = 0;
[...]
void whichButton(){
whatsPressed = keybord();
switch (whatsPressed):
case 1:
{
position = position + 1;
GoToXY (position, 0);
}
case 2:
{
position = position - 1;
GoToXY (position, 0); //for going left
}
}
Has anybody got any idea how to move it?

Ncurses "mvaddch()" Moves Diagonal

I'm trying to create an Etch-n-sketch game and when I move the arrow keys up and down, the cursor moves to the right and in what ever direction I pressed. I can move right, though it appears to be skipping a spot and I cant move left
Code for moving and drawing:
void moveCursor(char input)
{
int cursorX_Pos;
int cursorY_Pos;
int arrows;
getyx(stdscr, cursorY_Pos, cursorX_Pos);
arrows = 1;
switch(input)
{
case UP:
cursorY_Pos--;
arrows = 0;
break;
case DOWN:
cursorY_Pos++;
arrows = 0;
break;
case RIGHT:
cursorX_Pos++;
arrows = 0;
break;
case LEFT:
cursorX_Pos--;
arrows = 0;
break;
default:
arrows = 1;
break;
}
if (arrows == 0)
{
draw(cursorY_Pos,cursorX_Pos);
}
}
void draw(int y, int x)
{
mvaddch(y, x, '#');
refresh();
}
I'm not really sure where the code is trying to move diagonal. I tried splitting up the mvaddch into move and addch. I tried them at diffrent times and the move works (doesnt appear to be skipping) but when I enable the addch part, it skips and goes diagonal. How do I do fix this?
When you add a character to the screen, the cursor moves to the position after it. So, when you then fetch the current cursor position, it's one cell to the right of where you moved to, before adding the character. Thus, when trying to move left, for instance: you're subtracting 1 in moveCursor(), and adding 1 back in draw().
Either subtract 1 from cursorX_pos after the getyx(), or perhaps, maintain your coordinate values independent of curses' idea of where the cursor is (i.e. just leave out the getyx()).
For bonus points, realize that the target coordinates (for the next draw) and the current position are two different things, and optimize accordingly. (Hint: moving right shouldn't require a move() at all.)

Print doesn't show in printed array although specified

I'm working a simple candy crush game for my year 1 assignment.
I am at this stage where I need to show my self-made simple marker( *box made of '|' and '_'* ) on the center of the board ( board[5][5] ) once the program is executed.
Here is the current code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//FUNCTION: Draw the Board
int drawBoard()
{
//Declare array size
int board[9][9];
//initialize variables
int rows, columns, randomNumber, flag;
//random number seed generator
srand(time(NULL));
for ( rows = 0 ; rows < 9 ; rows++ )
{
for ( columns = 0 ; columns < 9 ; columns++ )
{
flag = 0;
do
{
//generate random numbers from 2 - 8
randomNumber = rand() %7 + 2;
board[rows][columns] = randomNumber;
//Checks for 2 adjacent numbers.
if ( board[rows][columns] == board[rows - 1][columns] || board[rows][columns] == board[rows][columns - 1] )
{
flag = 0;
continue;
}
else
{
flag = 1;
printf( " %d ", board[rows][columns] );
}
} while ( flag == 0 );
}//end inner for-loop
printf("\n\n");
}//end outer for-loop
//call FUNCTION marker() to display marker around board[5][5]
marker( board[5][5] );
}//end FUNCTION drawBoard
//FUNCTION: Mark the surrounding of the number with "|" and "_" at board[5][5]
void marker( int a )
{
printf( " _ \n" );
printf( "|%c|\n", a );
printf( " _ \n" );
}
int main()
{
drawBoard();
}
At the end of function drawBoard(), I placed the code marker( board[5][5] ).
This should have printed the markers around the number printed at coordinate board[5][5]..but for some reason it displays right after the board has been printed.
So why doesn't it print at that coordinate although I specified it at board[5][5]?
What could be the problem here?
so in your marker function you need to pass the board and the coordinate you want to print at
void marker( int x, int y, int** board )
{
board[x][y-1]="_";
board[x-1][y]="|";
board[x+1][y]="|";
board[x][y+1]="_";
}
then after the call to marker(5,5,board), call drawboard again
my code's a bit off but that's the logic, except you need to check for the case that the marker is at the edge of the board
in other words, you need to keep board around, and any time you make a change to it, clear the screen and print the whole board out again.
There is no persistent drawing in the way that you are doing this. You are just printing straight to the shell/command prompt. The way that you trying to do things will not work. You can't edit something drawn to the prompt after you have drawn it, you need to basically clear the screen and then draw again but with your indicated maker.
I don't know if you are able to use libraries in your assignment, but a very good library that WILL let you do is ncurses
EDIT Full rewrite of answer
Drawing Things On Top of One Another In CMD
Alright, I had some downtime at work, so I wrote a project to do what you need and I'm going to post code and explain what it does and why you need it along the way.
First thin that you are going to need a basically a render buffer or a render context. Whenever you are programming in a graphics API such as OpenGL, you don't just render straight to the screen, you render each object that you have to a buffer that rasterizes your content and turns it into pixels. Once it's in that form, the API shoves the rendered picture onto the screen. We are going to take a similar approach where instead of drawing to a pixel buffer on the GPU, we are going to draw to a character buffer. Think about each character as a pixel on the screen.
Here is a pastebin of the complete source:
Complete Source of Project
RenderContext
Our class to do this will be the RenderContext class. It has fields to hold width and height as well as an array of chars and a special char that we fill our buffer with whenever we clear it.
This class simply holds an array and functions to let us render to it. It makes sure that when we draw to it, we are within bounds. It is possible for an object to try to draw outside of the clipping space (off screen). However, whatever is drawn there is discarded.
class RenderContext {
private:
int m_width, m_height; // Width and Height of this canvas
char* m_renderBuffer; // Array to hold "pixels" of canvas
char m_clearChar; // What to clear the array to
public:
RenderContext() : m_width(50), m_height(20), m_clearChar(' ') {
m_renderBuffer = new char[m_width * m_height];
}
RenderContext(int width, int height) : m_width(width), m_height(height), m_clearChar(' ') {
m_renderBuffer = new char[m_width * m_height];
}
~RenderContext();
char getContentAt(int x, int y);
void setContentAt(int x, int y, char val);
void setClearChar(char clearChar);
void render();
void clear();
};
The two most important functions of this class are setContentAt and render
setContentAt is what an object calls to fill in a "pixel" value. To make this a little more flexible, our class uses a pointer to an array of chars rather than a straight array (or even a two dimensional array). This lets us set the size of our canvas at runtime. Because of this, we access elements of this array with x + (y * m_width) which replaces a two dimensional dereference such as arr[i][j]
// Fill a specific "pixel" on the canvas
void RenderContext::setContentAt(int x, int y, char val) {
if (((0 <= x) && (x < m_width)) && ((0 <= y) && (y < m_height))) {
m_renderBuffer[(x + (y * m_width))] = val;
}
}
render is what actually draws to the prompt. All it does is iterate over all the "pixels" in it's buffer and place them on screen and then moves to the next line.
// Paint the canvas to the shell
void RenderContext::render() {
int row, column;
for (row = 0; row < m_height; row++) {
for (column = 0; column < m_width; column++) {
printf("%c", getContentAt(column, row));
}
printf("\n");
}
}
I_Drawable
Our next class is an Interface that lets us contract with objects that they can draw to our RenderContext. It is pure virtual because we don't want to actually be able to instantiate it, we only want to derive from it. It's only function is draw which accepts a RenderContext. Derived classes use this call to receive the RenderContext and then use RenderContext's setContentAt to put "pixels" into the buffer.
class I_Drawable {
public:
virtual void draw(RenderContext&) = 0;
};
GameBoard
The first class to implement the I_Drawable, thus being able to render to our RenderContext, is the GameBoard class. This is where a majority of the logic comes in. It has fields for width, height, and a integer array that holds the values of the elements on the board. It also has two other fields for spacing. Since when you draw your board using your code, you have spaces between each element. We don't need to incorporate this into the underlying structure of the board, we just need to use them when we draw.
class GameBoard : public I_Drawable {
private:
int m_width, m_height; // Width and height of the board
int m_verticalSpacing, m_horizontalSpacing; // Spaces between each element on the board
Marker m_marker; // The cursor that will draw on this board
int* m_board; // Array of elements on this board
void setAtPos(int x, int y, int val);
void generateBoard();
public:
GameBoard() : m_width(10), m_height(10), m_verticalSpacing(5), m_horizontalSpacing(3), m_marker(Marker()) {
m_board = new int[m_width * m_height];
generateBoard();
}
GameBoard(int width, int height) : m_width(width), m_height(height), m_verticalSpacing(5), m_horizontalSpacing(3), m_marker(Marker()) {
m_board = new int[m_width * m_height];
generateBoard();
}
~GameBoard();
int getAtPos(int x, int y);
void draw(RenderContext& renderTarget);
void handleInput(MoveDirection moveDirection);
int getWidth();
int getHeight();
};
It's key functions are generateBoard, handleInput, and the derived virtual function draw. However, do note that in its constructor it creates a new int array and gives it to its pointer. Then its destructor automatically removes the allocated memory whenever the board goes away.
generateBoard is what we use to actual create the board and fill it with numbers. It will iterate over each location on the board. Each time, it will look at the elements directly to the left and above and store them. Then it will generate a random number until the number it generates does not match either of the stored elements, then it stores the number in the array. I rewrote this to get rid of the flag usage. This function gets called during the construction of the class.
// Actually create the board
void GameBoard::generateBoard() {
int row, column, randomNumber, valToLeft, valToTop;
// Iterate over all rows and columns
for (row = 0; row < m_height; row++) {
for (column = 0; column < m_width; column++) {
// Get the previous elements
valToLeft = getAtPos(column - 1, row);
valToTop = getAtPos(column, row - 1);
// Generate random numbers until we have one
// that is not the same as an adjacent element
do {
randomNumber = (2 + (rand() % 7));
} while ((valToLeft == randomNumber) || (valToTop == randomNumber));
setAtPos(column, row, randomNumber);
}
}
}
handleInput is what deals with moving the cursor around on the board. It's basically a freebie and your next step after getting the cursor to draw over the board. I needed a way to test the drawing. It accepts an enumeration that we switch on to know where to move our cursor to next. If you maybe wanted to have your cursor wrap around the board whenever you reach an edge, you would want to do that here.
void GameBoard::handleInput(MoveDirection moveDirection) {
switch (moveDirection) {
case MD_UP:
if (m_marker.getYPos() > 0)
m_marker.setYPos(m_marker.getYPos() - 1);
break;
case MD_DOWN:
if (m_marker.getYPos() < m_height - 1)
m_marker.setYPos(m_marker.getYPos() + 1);
break;
case MD_LEFT:
if (m_marker.getXPos() > 0)
m_marker.setXPos(m_marker.getXPos() - 1);
break;
case MD_RIGHT:
if (m_marker.getXPos() < m_width - 1)
m_marker.setXPos(m_marker.getXPos() + 1);
break;
}
}
draw is very important because it's what gets the numbers into the RenderContext. To summarize, it iterates over every element on the board, and draws in the correct location on the canvas placing an element under the correct "pixel". This is where we incorporate the spacing. Also, take care and note that we render the cursor in this function.
It's a matter of choice, but you can either store a marker outside of the GameBoard class and render it yourself in the main loop (this would be a good choice because it loosens the coupling between the GameBoard class and the Marker class. However, since they are fairly coupled, I chose to let GameBoard render it. If we used a scene graph, as we probably would with a more complex scene/game, the Marker would probably be a child node of the GameBoard so it would be similar to this implementation but still more generic by not storing an explicit Marker in the GameBoard class.
// Function to draw to the canvas
void GameBoard::draw(RenderContext& renderTarget) {
int row, column;
char buffer[8];
// Iterate over every element
for (row = 0; row < m_height; row++) {
for (column = 0; column < m_width; column++) {
// Convert the integer to a char
sprintf(buffer, "%d", getAtPos(column, row));
// Set the canvas "pixel" to the char at the
// desired position including the padding
renderTarget.setContentAt(
((column * m_verticalSpacing) + 1),
((row * m_horizontalSpacing) + 1),
buffer[0]);
}
}
// Draw the marker
m_marker.draw(renderTarget);
}
Marker
Speaking of the Marker class, let's look at that now. The Marker class is actually very similar to the GameBoard class. However, it lacks a lot of the logic that GameBoard has since it doesn't need to worry about a bunch of elements on the board. The important thing is the draw function.
class Marker : public I_Drawable {
private:
int m_xPos, m_yPos; // Position of cursor
public:
Marker() : m_xPos(0), m_yPos(0) {
}
Marker(int xPos, int yPos) : m_xPos(xPos), m_yPos(yPos) {
}
void draw(RenderContext& renderTarget);
int getXPos();
int getYPos();
void setXPos(int xPos);
void setYPos(int yPos);
};
draw simply puts four symbols onto the RenderContext to outline the selected element on the board. Take note that Marker has no clue about the GameBoard class. It has no reference to it, it doesn't know how large it is, or what elements it holds. You should note though, that I got lazy and didn't take out the hard coded offsets that sort of depend on the padding that the GameBoard has. You should implement a better solution to this because if you change the padding in the GameBoard class, your cursor will be off.
Besides that, whenever the symbols get drawn, they overwrite whatever is in the ContextBuffer. This is important because the main point of your question was how to draw the cursor on top of the GameBoard. This also goes to the importance of draw order. Let's say that whenever we draw our GameBoard, we drew a '=' between each element. If we drew the cursor first and then the board, the GameBoard would draw over the cursor making it invisible.
If this were a more complex scene, we might have to do something fancy like use a depth buffer that would record the z-index of an element. Then whenever we drew, we would check and see if the z-index of the new element was closer or further away than whatever was already in the RenderContext's buffer. Depending on that, we might skip drawing the "pixel" altogether.
We don't though, so take care to order your draw calls!
// Draw the cursor to the canvas
void Marker::draw(RenderContext& renderTarget) {
// Adjust marker by board spacing
// (This is kind of a hack and should be changed)
int tmpX, tmpY;
tmpX = ((m_xPos * 5) + 1);
tmpY = ((m_yPos * 3) + 1);
// Set surrounding elements
renderTarget.setContentAt(tmpX - 0, tmpY - 1, '-');
renderTarget.setContentAt(tmpX - 1, tmpY - 0, '|');
renderTarget.setContentAt(tmpX - 0, tmpY + 1, '-');
renderTarget.setContentAt(tmpX + 1, tmpY - 0, '|');
}
CmdPromptHelper
The last class that I'm going to talk about is the CmdPromptHelper. You don't have anything like this in your original question. However, you will need to worry about it soon. This class is also only useful on Windows so if you are on linux/unix, you will need to worry about dealing with drawing to the shell yourself.
class CmdPromptHelper {
private:
DWORD inMode; // Attributes of std::in before we change them
DWORD outMode; // Attributes of std::out before we change them
HANDLE hstdin; // Handle to std::in
HANDLE hstdout; // Handle to std::out
public:
CmdPromptHelper();
void reset();
WORD getKeyPress();
void clearScreen();
};
Each one of the functions is important. The constructor gets handles to the std::in and std::out of the current command prompt. The getKeyPress function returns what key the user presses down (key-up events are ignored). And the clearScreen function clears the prompt (not really, it actually moves whatever is already in the prompt up).
getKeyPress just makes sure you have a handle and then reads what has been typed into the console. It makes sure that whatever it is, it is a key and that it is being pressed down. Then it returns the key code as a Windows specific enum usually prefaced by VK_.
// See what key is pressed by the user and return it
WORD CmdPromptHelper::getKeyPress() {
if (hstdin != INVALID_HANDLE_VALUE) {
DWORD count;
INPUT_RECORD inrec;
// Get Key Press
ReadConsoleInput(hstdin, &inrec, 1, &count);
// Return key only if it is key down
if (inrec.Event.KeyEvent.bKeyDown) {
return inrec.Event.KeyEvent.wVirtualKeyCode;
} else {
return 0;
}
// Flush input
FlushConsoleInputBuffer(hstdin);
} else {
return 0;
}
}
clearScreen is a little deceiving. You would think that it clears out the text in the prompt. As far as I know, it doesn't. I'm pretty sure it actually shifts all the content up and then writes a ton of characters to the prompt to make it look like the screen was cleared.
An important concept that this function brings up though is the idea of buffered rendering. Again, if this were a more robust system, we would want to implement the concept of double buffering which means rendering to an invisible buffer and waiting until all drawing is finished and then swap the invisible buffer with the visible one. This makes for a much cleaner view of the render because we don't see things while they are still getting drawn. The way we do things here, we see the rendering process happen right in front of us. It's not a major concern, it just looks ugly sometimes.
// Flood the console with empty space so that we can
// simulate single buffering (I have no idea how to double buffer this)
void CmdPromptHelper::clearScreen() {
if (hstdout != INVALID_HANDLE_VALUE) {
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD cellCount; // How many cells to paint
DWORD count; // How many we painted
COORD homeCoord = {0, 0}; // Where to put the cursor to clear
// Get console info
if (!GetConsoleScreenBufferInfo(hstdout, &csbi)) {
return;
}
// Get cell count
cellCount = csbi.dwSize.X * csbi.dwSize.Y;
// Fill the screen with spaces
FillConsoleOutputCharacter(
hstdout,
(TCHAR) ' ',
cellCount,
homeCoord,
&count
);
// Set cursor position
SetConsoleCursorPosition(hstdout, homeCoord);
}
}
main
The very last thing that you need to worry about is how to use all these things. That's where main comes in. You need a game loop. Game loops are probably the most important thing in any game. Any game that you look at will have a game loop.
The idea is:
Show something on screen
Read input
Handle the input
GOTO 1
This program is no different. The first thing it does is create a GameBoard and a RenderContext. It also makes a CmdPromptHelper which lets of interface with the command prompt. After that, it starts the loop and lets the loop continue until we hit the exit condition (for us that's pressing escape). We could have a separate class or function do dispatch input, but since we just dispatch the input to another input handler, I kept it in the main loop. After you get the input, you send if off to the GameBoard which alters itself accordingly. The next step is to clear the RenderContext and the screen/prompt. Then rerun the loop if escape wasn't pressed.
int main() {
WORD key;
GameBoard gb(5, 5);
RenderContext rc(25, 15);
CmdPromptHelper cph;
do {
gb.draw(rc);
rc.render();
key = cph.getKeyPress();
switch (key) {
case VK_UP:
gb.handleInput(MD_UP);
break;
case VK_DOWN:
gb.handleInput(MD_DOWN);
break;
case VK_LEFT:
gb.handleInput(MD_LEFT);
break;
case VK_RIGHT:
gb.handleInput(MD_RIGHT);
break;
}
rc.clear();
cph.clearScreen();
} while (key != VK_ESCAPE);
}
After you have taken into consideration all of these things, you understand why and where you need to be drawing your cursor. It's not a matter of calling a function after another, you need to composite your draws. You can't just draw the GameBoard and then draw the Marker. At least not with the command prompt. I hope this helps. It definitely alleviated the down time at work.

Resources