Jump to content

  • Log In with Google      Sign In   
  • Create Account

Annoying flickering of screen and holding the control key problem.


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
12 replies to this topic

#1 Meerul264   Members   -  Reputation: 130

Like
0Likes
Like

Posted 01 January 2013 - 09:59 AM

Hello.

I just made a simple game - where you just go around evading the bombs and stuff.

The game works fine, except 2 things:

1. When I hold down the arrow keys that control the character's movement, the character (printed as '@') disappear, and then reappear upon releasing the key.
So in the end I just have to tap the arrow keys furiously just move the character around. I have no idea how to fix this.

2. The game flickering (is this what you call screen refresh rate) is annoying. How do I make it less flicker, or don't appear to flicker at all? Does this
have something to do with the Sleep() or System("cls") function?

If it may help, here's the source code for the game.


#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <time.h>


using namespace std;

//=========================WORD MASTER CLASS===========================================

class word_master
{
    public:
        int w_horizontal;
        int w_vertical;

        char w_image;

        word_master();


};

word_master::word_master()
{
  w_horizontal = 1;
  w_vertical = 9;

  w_image = '@';
}

//================================SHOW MAP FUNCTION=======================================
void show_map(char map[][20])
{
    for (int row=0;row<20;row++)
    {
        for(int col=0;col<20;col++)
        {
            std::cout << map[row][col] << " ";
        }
        std::cout << endl;
    }
}

//=====================================BOMB CLASS============================================
class bomb
{
    public:
        int b_horizontal;
        int b_vertical;

        char b_image;

        bomb();

        int setHorizontal();
        int setVertical();

};

int bomb::setHorizontal()
{
    int tempHorizontal = (rand()%17);
    return tempHorizontal;
}

int bomb::setVertical()
{
    int tempVertical = (rand()%17);
    return tempVertical;
}



bomb::bomb()
{
    b_horizontal = setHorizontal();
    b_vertical = setVertical();

    b_image = '!';
}

void move_bomb(bomb &bomb_move, char map[][20])
{
   int  newHorizontal = (rand()%2);
   int newVertical = (rand()%2);

    map[bomb_move.b_vertical][bomb_move.b_horizontal] = ' ';


        bomb_move.b_horizontal += newHorizontal;
        bomb_move.b_vertical += newVertical;



    if(bomb_move.b_vertical > 17 || bomb_move.b_horizontal > 17 || bomb_move.b_vertical < 3 || bomb_move.b_horizontal < 3 ) //prevent bomb from escaping out of field
    {
        bomb_move.b_vertical = newVertical+1;
        bomb_move.b_horizontal = newHorizontal+1;
    }

    map[bomb_move.b_vertical][bomb_move.b_horizontal] = bomb_move.b_image;

}

//=================================================ROCKET CLASS=============================================

class Rocket
{
    public:
        int r_horizontal;
        int r_vertical;
        int r_randomFallPosition;

        char r_image;

        Rocket();

};

Rocket::Rocket()
{
    r_horizontal = 7;
    r_vertical = 1;

    r_image = 'V';
}


void move_rocket(Rocket &launch, char map[][20])
{
    launch.r_randomFallPosition = ((rand()%16)+2);

    map[launch.r_vertical][launch.r_horizontal] = ' ';
    launch.r_vertical +=1;


    map[launch.r_vertical][launch.r_horizontal] = launch.r_image;

    if(launch.r_vertical > 17)
    {
        map[launch.r_vertical][launch.r_horizontal] = ' ';
        launch.r_vertical = 1;
        launch.r_horizontal = launch.r_randomFallPosition; //random potential fall position
    }
}

//=========================================FOOD CLASS============================================

class treasure
{
    public:
        int t_horizontal;
        int t_vertical;

        char t_image;

        treasure();
        int setHorizontal();
        int setVertical();

};

int treasure::setHorizontal()
{
    int tempHorizontal = (rand()%17)+1;
    return tempHorizontal;
}

int treasure::setVertical()
{
    int tempVertical = (rand()%17)+1;
    return tempVertical;
}

treasure::treasure()
{
    t_horizontal = setHorizontal();
    t_vertical = setVertical();

    t_image = 'X';
}

void generate_treasure(int &collected,word_master hero,treasure &treasure_location, char map[][20])//apply this function during start game and after the treasure is taken
{
    int newHorizontal = (rand()%17)+1;
    int newVertical = (rand()%17)+1;

    map[treasure_location.t_vertical][treasure_location.t_horizontal] = treasure_location.t_image;

    if(hero.w_horizontal == treasure_location.t_horizontal && hero.w_vertical == treasure_location.t_vertical) //if hero take treasure, add new treasure at random location
    {
        map[treasure_location.t_vertical][treasure_location.t_horizontal] = ' ';

       treasure_location.t_vertical = newVertical;
       treasure_location.t_horizontal = newHorizontal;
       collected++;
    }


}

//==========================================BOOL CHECK IF HIT FUNCTION=======================================================

bool checkHit(bomb bomb_move,word_master hero, Rocket launch)
{
    if(hero.w_vertical == bomb_move.b_vertical && hero.w_horizontal == bomb_move.b_horizontal ||
       hero.w_vertical == launch.r_vertical && hero.w_horizontal == launch.r_horizontal)
    return true;

    return false;
}

//========================================INT MAIN=================================
int main()
{
    srand(time(NULL));

    char playagain;
    char userContinue;
    int time = 0;
    int collected = 0; //count how many treasure collected.

    bool gameover(false);
    bool end_instruction(false);

    char map[20][20] {"###################",
                      "#                 #",
                      "#                 #",
                      "#                 #",
                      "#                 #",
                      "#                 #",
                      "#                 #",
                      "#                 #",
                      "#                 #",
                      "#                 #",
                      "#                 #",
                      "#                 #",
                      "#                 #",
                      "#                 #",
                      "#                 #",
                      "#                 #",
                      "#                 #",
                      "#                 #",
                      "#                 #",
                      "###################"};

    word_master hero;
    bomb bomb_move;
    Rocket launch;
    treasure treasure_location;


        //===================tell lore==============================
        std::cout << "=============LORE============\n";
        std::cout << endl;
        std::cout << "You, a cat burglar, infiltrated an island that is owned by the most\n";
        std::cout << "notorious pirate in Southern Mosby, known as the Bomber Pirate. You are caught\n";
        std::cout << "infiltrating their base and now all their crews are alerted about your presence.\n";
        std::cout << "Their rocket launchers and bombs are all trained at you, so watch out!\n\n";

        std::cout << "PRESS 'ENTER' TO CONTINUE\n";
        cin.get();
        cin.clear();
        system("cls");
        //===========================instruction=====================
        std::cout << "===========HOW=TO=PLAY=========\n";
        std::cout << "You control @.\n";
        std::cout << "Press the arrow keys to move in their corresponding direction.\n";
        std::cout << "Evade the bombs, and steal as many treasures as you can!\n\n";

        std::cout << "PRESS 'ENTER' KEY YO PLAY!\n";
        cin.get();
        cin.clear();






    while(!gameover)
    {
        system("cls");
        show_map(map);

        map[hero.w_vertical][hero.w_horizontal] = hero.w_image;

        move_bomb(bomb_move,map);
        move_rocket(launch,map);
        generate_treasure(collected, hero,treasure_location,map);

        time++;
        std::cout << "Time spent playing: ";
        std::cout << setprecision(2);
        std:cout << time/38.00;
        std::cout << " seconds.";
        std::cout << endl;

        std::cout << "Treasure stolen: ";
        std::cout << collected;
        std::cout << endl;

        if(checkHit(bomb_move,hero,launch))
        {
            system("cls");
            for(int i=0;i<10;i++){ std::cout << endl;}
            std::cout << "                         ===YOU=GOT=HIT=BY=THE=BOMB!!===\n";
            std::cout << "                         Would you like to play again? y/n \n";
            std::cin >> playagain;
            if (playagain == 'y')
            {
                time = 0;      //set time played back to 0
                collected = 0;  //set treasure collected back to 0
                //set hero to starting point--
                hero.w_horizontal = 1;
                hero.w_vertical = 9;
                //set treasure location to random--
                map[treasure_location.t_vertical][treasure_location.t_horizontal] = ' ';
                treasure_location.t_horizontal = (rand()%17)+1;
                treasure_location.t_vertical = (rand()%17)+1;


            }
            else
            gameover = true;
        }


        if(GetAsyncKeyState(VK_UP))
        {
            map[hero.w_vertical][hero.w_horizontal] = ' ';
            hero.w_vertical -=1;
            if(hero.w_vertical < 1)
            {
                hero.w_vertical = 1;
            } // prevent hero from going through the wall
        }
        else if(GetAsyncKeyState(VK_DOWN))
        {
            map[hero.w_vertical][hero.w_horizontal] = ' ';
            hero.w_vertical +=1;
            if(hero.w_vertical > 17)
            {
                hero.w_vertical = 17;
            }
        }
        else if(GetAsyncKeyState(VK_RIGHT))
        {
            map[hero.w_vertical][hero.w_horizontal] = ' ';
            hero.w_horizontal +=1;
            if(hero.w_horizontal > 17 )
            {
                hero.w_horizontal = 17;
            }
        }
        else if(GetAsyncKeyState(VK_LEFT))
        {
            map[hero.w_vertical][hero.w_horizontal] = ' ';
            hero.w_horizontal -=1;
            if(hero.w_horizontal < 1 )
            {
                hero.w_horizontal = 1;
            }
        }


    }
    Sleep(300);


    return 0;
}


Sponsor:

#2 Servant of the Lord   Crossbones+   -  Reputation: 21021

Like
3Likes
Like

Posted 01 January 2013 - 11:09 AM

'@' symbol disapearing problem:

 

Let's mentally remove all the code that's unrelated to drawing the player, and see if we can spot the problem in the reduced code.

 

while(!gameover)
{
        system("cls");
        show_map(map);
 
        map[hero.w_vertical][hero.w_horizontal] = hero.w_image;
 
        //...removed alot of code here just for visuallizing....
 
        if(GetAsyncKeyState(VK_UP))
        {
            map[hero.w_vertical][hero.w_horizontal] = ' ';
            hero.w_vertical -=1;
        }
 
       //...
}
 
See the problem?
 
Let's mark the major events:
while(...)
{
        show_map(map); //DRAW MAP
 
        map[hero.w_vertical][hero.w_horizontal] = hero.w_image; //ADD PLAYER TO MAP
 
        if(...moving...) //IF MOVING
        {
            map[hero.w_vertical][hero.w_horizontal] = ' '; //REMOVE PLAYER FROM MAP
        }
}
 
The code says:
  • Draw map.
  • Add player to map.
  • If moving, remove player from map.
 
Since we're looping, that means the drawing happens like this:
  • Draw map.
  • Add player to map.
  • If moving, remove player from map.
  • Draw map.
  • Add player to map.
  • ...etc...
 
Let me highlight it:
  • Draw map.
  • Add player to map.
  • If moving, remove player from map.
  • Draw map.
  • Add player to map.
  • ...etc...
 
If we're moving, the player is continually added to, and then removed from, the map in-between draws.
 
The solution is to add the player to the map before the map is drawn. wink.png

Edited by Servant of the Lord, 01 January 2013 - 11:10 AM.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]


#3 Meerul264   Members   -  Reputation: 130

Like
0Likes
Like

Posted 01 January 2013 - 11:24 AM

Thanks! I didn't think about this that way :o I guess I should adopt to think like this.



#4 Servant of the Lord   Crossbones+   -  Reputation: 21021

Like
4Likes
Like

Posted 01 January 2013 - 11:29 AM

Flickering problem:

 

It has to do with 'system("cls")', yes. The command console isn't made for real-time graphics, so that flickering is kinda unavoidable. I'd just leave it as is.

 

I say 'kinda' unavoidable, because you *can* fix it, but it'd almost require redoing your entire game using some slightly more advanced features. It'd be better to use those "more advanced" features for your next game that you start from scratch, in my opinion.

 

But, here's how you do it:

std::cout is standard C++. The command console that std::cout happens to be printing to (in this situation; but it can print whereever you tell it to) is Microsoft Windows's command console. Other operating systems have their own consoles.

 

So standard C++ has std::cout. 'system("cls")' isn't standard C++ either. system() is standard, but 'cls' is actually starting a separate program that clears your command console. This is why it's so slow - it loads up an entirely new program, runs it, then closes it. Because it's slow, the delay between clearing the screen and your next draw is noticeable as an unwanted flickering.

 

So how can that be avoided? You can use non-standard Microsoft functions to interact with Microsoft's command console yourself, instead of calling another program to do so. These Microsoft functions let you: Set the color of individual characters (A huge selection of 16 colors! happy.png), use the mouse and find out what character the mouse is over or clicked on, and *manually place letters where you want on the console, instead of placing entire lines at a time*.

 

The downside is that the functions are a bit complicated and ugly. I haven't used them in over four years, but here's the old code I was using back then (I wrapped them in convenience functions):

 

Console.h

 

#include <windows.h> 
 
#ifndef TEXT_CONSOLE_H
#define TEXT_CONSOLE_H
 
#ifndef MOUSE_HWHEELED
#define MOUSE_HWHEELED 0x0008
#endif
#define MOUSE_CLICK 0
 
#define COLOR_WHITE (FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_INTENSITY)
#define COLOR_GREY (FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN)
#define COLOR_DARKGREY (0|FOREGROUND_INTENSITY)
#define COLOR_BLACK (0)
#define COLOR_CYAN (FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_INTENSITY)
#define COLOR_AQUA (FOREGROUND_BLUE|FOREGROUND_GREEN)
#define COLOR_YELLOW (FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_INTENSITY)
#define COLOR_GOLD (FOREGROUND_RED|FOREGROUND_GREEN)
#define COLOR_MAGENTA (FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_INTENSITY)
#define COLOR_PURPLE (FOREGROUND_RED|FOREGROUND_BLUE)
#define COLOR_DARKBLUE (FOREGROUND_BLUE)
#define COLOR_BLUE (FOREGROUND_BLUE|FOREGROUND_INTENSITY)
#define COLOR_DARKGREEN (FOREGROUND_GREEN)
#define COLOR_GREEN (FOREGROUND_GREEN|FOREGROUND_INTENSITY)
#define COLOR_DARKRED (FOREGROUND_RED)
#define COLOR_RED (FOREGROUND_RED|FOREGROUND_INTENSITY)
 
#define BG_COLOR_WHITE (BACKGROUND_RED|BACKGROUND_BLUE|BACKGROUND_GREEN|BACKGROUND_INTENSITY)
#define BG_COLOR_GREY (BACKGROUND_RED|BACKGROUND_BLUE|BACKGROUND_GREEN)
#define BG_COLOR_DARKGREY (0|BACKGROUND_INTENSITY)
#define BG_COLOR_BLACK (0)
#define BG_COLOR_CYAN (BACKGROUND_BLUE|BACKGROUND_GREEN|BACKGROUND_INTENSITY)
#define BG_COLOR_AQUA (BACKGROUND_BLUE|BACKGROUND_GREEN)
#define BG_COLOR_YELLOW (BACKGROUND_RED|BACKGROUND_GREEN|BACKGROUND_INTENSITY)
#define BG_COLOR_GOLD (BACKGROUND_RED|BACKGROUND_GREEN)
#define BG_COLOR_MAGENTA (BACKGROUND_RED|BACKGROUND_BLUE|BACKGROUND_INTENSITY)
#define BG_COLOR_PURPLE (BACKGROUND_RED|BACKGROUND_BLUE)
#define BG_COLOR_DARKBLUE (BACKGROUND_BLUE)
#define BG_COLOR_BLUE (BACKGROUND_BLUE|BACKGROUND_INTENSITY)
#define BG_COLOR_DARKGREEN (BACKGROUND_GREEN)
#define BG_COLOR_GREEN (BACKGROUND_GREEN|BACKGROUND_INTENSITY)
#define BG_COLOR_DARKRED (BACKGROUND_RED)
#define BG_COLOR_RED (BACKGROUND_RED|BACKGROUND_INTENSITY)
 
int ConsoleStartup();
void ConsoleShutdown();
 
int ConsolePollMessages(INPUT_RECORD *eventBuffer, int bufferSize);
 
int CreateBuffer(int width, int height);
void DestroyBuffer();
 
int ResizeConsole(int width, int height);
void ConsoleSize(int *width, int *height);
int ShowCursor(bool show);
 
void Color(int x, int y, WORD color);
void FillColor(int x, int y, int w, int h, WORD color);
void Write(int x, int y, char *character, WORD color);
void WriteTextCentered(int x, int y, char *text, WORD color);
void WriteText(int x, int y, char *text, WORD color);
void Fill(int x, int y, int w, int h, char *character, WORD color);
void UpdateScreen();
 
int ErrorBox(char *message, char *title);
 
#endif /* TEXT_CONSOLE_H */
 
Console.cpp
#include "Console.h"
#include "main.h"
 
CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
WORD OldConsoleColors;
DWORD OldConsoleMode;
HANDLE hStdout, hStdin;
 
CHAR_INFO *Buffer = NULL;
 
DWORD ConsoleMode;
 
int ConsoleStartup()
{
hStdin = GetStdHandle(STD_INPUT_HANDLE);
    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
 
    if(hStdin == INVALID_HANDLE_VALUE || hStdout == INVALID_HANDLE_VALUE) 
        return ErrorBox("Startup: GetStdHandle", "Console Error");
 
if(!GetConsoleScreenBufferInfo(hStdout, &consoleInfo))
return ErrorBox("Startup: GetConsoleScreenBufferInfo", "Console Error");
 
if(!GetConsoleMode(hStdin, &OldConsoleMode)) 
       return ErrorBox("Startup: GetConsoleMode", "Console Error");
 
    ConsoleMode = OldConsoleMode & ~(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT); //|ENABLE_MOUSE_INPUT|ENABLE_WINDOW_INPUT
    if(!SetConsoleMode(hStdin, ConsoleMode)) 
       return ErrorBox("Startup: SetConsoleMode", "Console Error");
 
if(!SetConsoleMode(hStdin, ConsoleMode)) 
       return ErrorBox("Startup: SetConsoleMode", "Console Error");
 
CreateBuffer(consoleInfo.dwSize.X, consoleInfo.dwSize.Y);
 
OldConsoleColors = consoleInfo.wAttributes;
 
ShowCursor(false);
SetConsoleTitle("Text ORPG");
}
 
void ConsoleShutdown()
{
    SetConsoleMode(hStdin, OldConsoleMode);
    SetConsoleTextAttribute(hStdout, OldConsoleColors);
ShowCursor(true);
DestroyBuffer();
}
 
int ConsolePollMessages(INPUT_RECORD *eventBuffer, int bufferSize)
{
DWORD numEvents = 0;
 
if(!ReadConsoleInput(hStdin, eventBuffer, bufferSize, &numEvents))
ErrorBox("ConsolePollMessages: ReadConsoleInput", "Console Error");
 
return numEvents;
}
 
int CreateBuffer(int width, int height)
{
if(Buffer)
DestroyBuffer();
 
Buffer = new CHAR_INFO[width*height];
}
 
void DestroyBuffer()
{
delete[] Buffer;
Buffer = NULL;
}
 
int ResizeConsole(int width, int height)
{
SMALL_RECT consoleWindow = {0, 0, 0, 0};
COORD consoleBuffer = {0, 0};
COORD tempBuffer = {0, 0};
COORD maxWindowSize = GetLargestConsoleWindowSize(hStdout);
 
if(width >= maxWindowSize.X)
width = maxWindowSize.X;
if(height >= maxWindowSize.Y)
height = maxWindowSize.Y;
 
consoleWindow.Right = width-1;
consoleWindow.Bottom = height-1;
consoleBuffer.X = width;
consoleBuffer.Y = height;
 
tempBuffer.X = consoleInfo.dwSize.X;
if(tempBuffer.X < consoleWindow.Right)
tempBuffer.X = consoleWindow.Right;
 
tempBuffer.Y = consoleInfo.dwSize.Y;
if(tempBuffer.Y < consoleWindow.Bottom)
tempBuffer.Y = consoleWindow.Bottom;
 
if(!SetConsoleScreenBufferSize(hStdout, tempBuffer))
return ErrorBox("ResizeConsole: SetConsoleScreenBufferSize (tempBuffer)", "Console Error");
 
if(!SetConsoleWindowInfo(hStdout, true, &consoleWindow))
return ErrorBox("ResizeConsole: SetConsoleWindowInfo", "Console Error");
 
if(!SetConsoleScreenBufferSize(hStdout, consoleBuffer))
return ErrorBox("ResizeConsole: SetConsoleScreenBufferSize (consoleBuffer)", "Console Error");
 
if(!GetConsoleScreenBufferInfo(hStdout, &consoleInfo))
return ErrorBox("ResizeConsole: GetConsoleScreenBufferInfo", "Console Error");
 
//Secondary buffer, for double buffering.
CreateBuffer(consoleBuffer.X, consoleBuffer.Y);
}
 
void ConsoleSize(int *width, int *height)
{
if(width)
*width = consoleInfo.dwSize.X;
if(height)
*height = consoleInfo.dwSize.Y;
}
 
int ShowCursor(bool show)
{
CONSOLE_CURSOR_INFO cursorInfo;
if(!GetConsoleCursorInfo(hStdout, &cursorInfo))
return ErrorBox("Startup: GetConsoleCursorInfo", "Console Error");
 
//Hide the cursor
cursorInfo.bVisible = show;
if(!SetConsoleCursorInfo(hStdout, &cursorInfo))
return ErrorBox("Startup: GetConsoleCursorInfo", "Console Error");
}
 
void Color(int x, int y, WORD color)
{
COORD pos;
pos.X = x; pos.Y = y;
if(x > consoleInfo.dwSize.X)
return;
if(y > consoleInfo.dwSize.Y)
return;
 
Buffer[y * consoleInfo.dwSize.X + x].Attributes = color;
}
 
void FillColor(int x, int y, int w, int h, WORD color)
{
const int SCREEN_WIDTH = consoleInfo.dwSize.X;
const int SCREEN_HEIGHT = consoleInfo.dwSize.Y;
 
int height = SCREEN_HEIGHT - y;
if(height < 1)
return;
if(height > h)
height = h;
 
int width = SCREEN_WIDTH - x;
if(width < 1)
return;
if(width > w)
width = w;
 
for(int Y = y; Y < (y+height); Y++)
{
for(int X = x; X < (x+width); X++)
{
Buffer[Y * consoleInfo.dwSize.X + X].Attributes = color;
}
}
}
 
void Write(int x, int y, char *character, WORD color)
{
COORD pos;
pos.X = x; pos.Y = y;
if(x > consoleInfo.dwSize.X)
return;
if(y > consoleInfo.dwSize.Y)
return;
 
Buffer[y * consoleInfo.dwSize.X + x].Char.AsciiChar = *character;
Buffer[y * consoleInfo.dwSize.X + x].Attributes = color;
}
 
void WriteTextCentered(int x, int y, char *text, WORD color)
{
WriteText(x - (strlen(text)/2), y, text, color);
}
 
void WriteText(int x, int y, char *text, WORD color)
{
COORD pos;
pos.X = x; pos.Y = y;
 
int textLength = strlen(text);
int length = consoleInfo.dwSize.X - pos.X;
if(length < 1)
return;
if(length > textLength)
length = textLength;
 
for(int i = 0; i < length; i++)
{
Buffer[y * consoleInfo.dwSize.X + (x+i)].Char.AsciiChar = text[i];
Buffer[y * consoleInfo.dwSize.X + (x+i)].Attributes = color;
}
}
 
void Fill(int x, int y, int w, int h, char *character, WORD color)
{
const int SCREEN_WIDTH = consoleInfo.dwSize.X;
const int SCREEN_HEIGHT = consoleInfo.dwSize.Y;
 
int height = SCREEN_HEIGHT - y;
if(height < 1)
return;
if(height > h)
height = h;
 
int width = SCREEN_WIDTH - x;
if(width < 1)
return;
if(width > w)
width = w;
 
for(int Y = y; Y < (y+height); Y++)
{
for(int X = x; X < (x+width); X++)
{
Buffer[Y * consoleInfo.dwSize.X + X].Char.AsciiChar = *character;
Buffer[Y * consoleInfo.dwSize.X + X].Attributes = color;
}
}
}
 
void UpdateScreen()
{
COORD dwBufferSize = {consoleInfo.dwSize.X, consoleInfo.dwSize.Y}; 
COORD dwBufferCoord = {0, 0}; 
SMALL_RECT rcRegion = {0, 0, consoleInfo.dwSize.X-1, consoleInfo.dwSize.Y-1}; 
 
WriteConsoleOutput(hStdout, (CHAR_INFO*)Buffer, dwBufferSize, dwBufferCoord, &rcRegion);
}
 
int ErrorBox(char *message, char *title)
{
MessageBox(NULL, TEXT(message), TEXT(title), MB_OK);
return -1;
}

 

Warning: The code is poorly written - that was while I was a newbie programmer. Now I've leveled up twice to a novice programmer. laugh.png

 

Here's a screenshot from the project I was working on at the time: (February 25th, 2008)

screenshotfeb25.png

 

Here's a screenshot another GameDev.net user gave me (JTippets or JBourne I think?) of what the colors look like:

consolecolors.png

 

Here's a chart of the different characters for the console:

asciichart.gif

 

Enjoy!


Edited by Servant of the Lord, 01 January 2013 - 11:32 AM.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]


#5 Meerul264   Members   -  Reputation: 130

Like
0Likes
Like

Posted 01 January 2013 - 11:55 AM

Thanks! I'm going to have fun with these. BTW, I have problem printing out the character 2A. It produce an error: invalid suffix 'A' on integer constant.

 

t_image = 2A;

 

t_image has type char.



#6 Servant of the Lord   Crossbones+   -  Reputation: 21021

Like
1Likes
Like

Posted 01 January 2013 - 11:57 AM

The numbers are in hexadecimal, so the correct format is 0x2A or 0x2a. All hexadecimal numbers are prefixed with 0x in C++, or # in some other languages.

This lets the compiler know the difference between a decimal '20' which means is 20 (we use decimal normally in english), and a hexadecimal '20' (0x20) which means 32 in decimal.


Edited by Servant of the Lord, 01 January 2013 - 12:00 PM.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]


#7 Paradigm Shifter   Crossbones+   -  Reputation: 5435

Like
1Likes
Like

Posted 01 January 2013 - 11:58 AM

They are hex numbers, use 0x2A
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

#8 Meerul264   Members   -  Reputation: 130

Like
0Likes
Like

Posted 01 January 2013 - 09:11 PM

another noob question; the console.h and console.cpp you gave me.

 

To use it, do I have to create a new class and copy paste each file to the class's header file and class's cpp file respectively?



#9 Servant of the Lord   Crossbones+   -  Reputation: 21021

Like
0Likes
Like

Posted 01 January 2013 - 09:24 PM

They aren't a class, just a collection of functions. You can copy the code into a new empty header file and a new empty source file.
You need to make sure the files are "added" to your "project" in whatever way your IDE (Visual Studio?) requires that.
 
Then, any source file that wants to use any of the functions in Console.h must #include "Console.h".
 
Your project needs to then call "ConsoleStartup()" when you enter "main()", and "ConsoleShutdown()" before you exit main(). I think. smile.png
 
Something like this:
 
int main()
{ 
    if(ConsoleStartup() == -1)
        return -1;
    
    ResizeConsole(CONSOLE_WIDTH, CONSOLE_HEIGHT);
 
    //setup anything else here.
 
    while(playingGame)
    { 
        //Handle any events.
        //Do any time-based updates.
        //Do any drawing.

        Sleep(20);
    }
    
    ConsoleShutdown();
    
    return 0;
}

Silly enough, it appears that I hard-code the console's caption text in the ConsoleStartup() function, so you'll want to edit that as well.

Edited by Servant of the Lord, 01 January 2013 - 09:34 PM.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]


#10 Meerul264   Members   -  Reputation: 130

Like
0Likes
Like

Posted 02 January 2013 - 05:51 AM

Hmm I already put the console.cpp into a new empty cpp file and the console.h into a new header file.

 

I also put the #include "console.h" into the main.cpp and console.cpp. But I get this error:

 

C:\Program Files (x86)\CodeBlocks\Projects\TexORPG\src\Console.cpp|1|error: Console.h: No such file or directory|

C:\Program Files (x86)\CodeBlocks\Projects\TexORPG\src\Console.cpp|2|error: main.h: No such file or directory|

 

C:\Program Files (x86)\CodeBlocks\Projects\TexORPG\src\Console.cpp|2|error: main.h: No such file or directory| <- more of this same error over and over,



#11 Servant of the Lord   Crossbones+   -  Reputation: 21021

Like
0Likes
Like

Posted 02 January 2013 - 10:28 AM

In my console.cpp, I had a "main.h", which you don't. You can remove that #include from console.cpp.

 

Are you sure you named "console.h" correctly? Maybe you typo'd the file name as consle.h or something by mistake. Check if you saved it to the right location.


It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]


#12 Meerul264   Members   -  Reputation: 130

Like
0Likes
Like

Posted 02 January 2013 - 11:42 AM

Okay, figured how to fix that error. Sorry the "more of this error over and over" was a not the correct error. Actually, I got this error over and over: include\Console.h|2|error: stray '\240' in program| BTW, may I ask why you don't use this code anymore? Is it because you "leveled-up"?

#13 Servant of the Lord   Crossbones+   -  Reputation: 21021

Like
0Likes
Like

Posted 02 January 2013 - 12:01 PM

No, it's because I canceled the project and started something else. laugh.png

Back then, I canceled and started a new project probably every other month. It was horrible, since I never finished anything.

 

Now, being much wiser, I've been working on the same project for two and a half years. And I haven't finished anything. dry.png

 

The stray \240 is probably a non-visible character that was accidentally copied when you copied the code from the forum post. Try going to the very very first character of the file, and hitting 'backspace' several times to get rid of any non-visible characters at the front, then go to the very end of the file and hit 'delete' several times to remove any from the end.

 

Or, here's the entire project, I don't know if it compiles or not.

The executable appears to work, and wow, does it looks pretty cool. I half want to return to this project now! happy.png


It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS