• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Syerjchep

Trying to make an ingame text editor.

16 posts in this topic

Okay, third fourth try at writing this code:

 

[code] 

/*
Showing the applyText function here for reference:
void applyText(int x,int y,string text)
{
blitImage(TTF_RenderText_Solid( font, text.c_str(), fontcolor ),x,y);
}
 
 * also for reference:
 
void blitImage(SDL_Surface *in,int tx,int ty)
{
SDL_Rect tmp;
tmp.x = tx;
tmp.y = ty;
SDL_BlitSurface(in,NULL,screen,&tmp);
}
 */
 
int textOffset = 0;
 
void showString(const std::string &text)
{
    try
    {
unsigned int lineNum = 0;
        std::string lineText;
 
for(unsigned int i = 0; i < text.size(); i++)
{
//Check if it's the end of the line.
if(text[i] == '\n')
{
//Check if there's something to display.
if(!lineText.empty())
{
//Display the line.
applyText(20, (20 * lineNum), lineText);
 
//Clear the temporary string.
lineText.clear();
}
 
//Increase the line number.
lineNum++;
}
else
{
//Add this character to the temporary string.
lineText.push_back(text[i]);
}
}
 
//Display the final line (because there is no final endline).
if(!lineText.empty())
{
applyText(20, (20 * lineNum), lineText);
}
    }
    catch(exception& e)
    {
        cerr<<"Exception thrown "<<e.what()<<"\n";
    }
    catch(...)
    {
        cerr<<"other exception cought.\n";
    } 
}
 
int getCursorX(string whatToEdit, int cursor)
{
    int x = 0;
    int y = 0;
    for(int a = 0; a<cursor; a++)
    {
        if(whatToEdit[a] == 0 || whatToEdit[a] == '\n')
        {
            x = 0;
            y++;
        }
        else
            x++;
    }
    return x;
}
 
int getCursorY(string whatToEdit, int cursor)
{
    int x = 0;
    int y = 0;
    for(int a = 0; a<cursor; a++)
    {
        if(whatToEdit[a] == 0 || whatToEdit[a] == '\n')
        {
            x = 0;
            y++;
        }
        else
            x++;
    }
    return y;
}
 
int xToNextY(string whatToEdit,int cursor)
{
    int totalPos = 0;
    for(int a = cursor; a<whatToEdit.length(); a++)
    {
        totalPos++;
        if(whatToEdit[a] == 0 || whatToEdit[a] == '\n')
            break;
    }
    return totalPos;
}
 
int xToLastY(string whatToEdit,int cursor)
{
    int totalPos = 0;
    for(int a = cursor; a>0; a--)
    {
        totalPos++;
        if(whatToEdit[a] == 0 || whatToEdit[a] == '\n')
            break;
    }
    return totalPos;
}
 
bool cont = true;
 
void scriptingWindow(int mobID)
{
    try
    {
    //mob refers to a character in the game
    //the string we're probably editing is the characters ai script
    
    string whatToEdit = mobs[mobID].scriptL;
    
    textOffset = 0;
    int loopStartTime = 0;
    bool programcont = true;
    SDL_Event programEvent; //there's also another SDL_Event for the main loop
    int cursorPos = 0;
    Uint8 *keystates;
    
    while(programcont)
    {
        loopStartTime = SDL_GetTicks(); //get the time the loop started at
     
        keystates = SDL_GetKeyState(NULL);
        
        while(SDL_PollEvent(&programEvent))
        {
            if(programEvent.type == SDL_QUIT) //break both this loop, and the main loop
            {
                programcont = false;
                cont = false;
                break;
            }
            if(programEvent.type == SDL_KEYDOWN) //only break this loop
            {
                if(programEvent.key.keysym.sym == SDLK_ESCAPE)
                {
                    programcont = false;
                    break;
                }
                else if(programEvent.key.keysym.sym == SDLK_RIGHT)
                    cursorPos++;
                else if(programEvent.key.keysym.sym == SDLK_LEFT)
                    cursorPos--;
                else if(programEvent.key.keysym.sym == SDLK_DOWN)
                    cursorPos += xToNextY(whatToEdit,cursorPos);
                else if(programEvent.key.keysym.sym == SDLK_UP)
                {
                    cursorPos -= xToLastY(whatToEdit,cursorPos);
                    if(getCursorX(whatToEdit,cursorPos)-textOffset < 5 && textOffset > 0)
                        textOffset--;
                }
                else if(keystates[SDLK_LCTRL] && programEvent.key.keysym.sym == SDLK_s)
                {
                    mobs[mobID].scriptL = whatToEdit;
                    mobs[mobID].ready = false;
                    programcont = false;
                }
                else if(programEvent.key.keysym.unicode >= ' ' && programEvent.key.keysym.unicode <= '}')
                {
                    whatToEdit = whatToEdit.substr(0,cursorPos) + (char)programEvent.key.keysym.unicode + whatToEdit.substr(cursorPos,whatToEdit.length()-cursorPos);
                    cursorPos++;
                }
                else if(programEvent.key.keysym.sym == SDLK_BACKSPACE && cursorPos > 0)
                {
                    whatToEdit.erase(cursorPos-1,1);
                    cursorPos--;
                }
                else if(programEvent.key.keysym.sym == SDLK_DELETE && cursorPos < whatToEdit.length()-1)
                    whatToEdit.erase(cursorPos,1);
                else if(programEvent.key.keysym.sym == SDLK_RETURN)
                {
                    whatToEdit = whatToEdit.substr(0,cursorPos) + '\n' + whatToEdit.substr(cursorPos,whatToEdit.length()-cursorPos);
                    cursorPos++;
                }
            }
            else if(programEvent.type == SDL_MOUSEBUTTONDOWN)
            {
                if(programEvent.button.button == SDL_BUTTON_WHEELUP)
                {
                    cursorPos -= xToLastY(whatToEdit,cursorPos);
                    if(getCursorX(whatToEdit,cursorPos)-textOffset < 5 && textOffset > 0)
                        textOffset--;
                }
                else if(programEvent.button.button == SDL_BUTTON_WHEELDOWN)
                    cursorPos += xToNextY(whatToEdit,cursorPos);
            }
        }
        
        if(cursorPos < 0)
            cursorPos = 0;
        if(cursorPos > whatToEdit.length()-1)
            cursorPos = whatToEdit.length()-1;
        
        if(getCursorY(whatToEdit,cursorPos)-textOffset > 30)
            textOffset++;
        
        clearScreen();  //Paint a black rectangle over the whole screen.
        
        showString(whatToEdit); //show the lines of text
        applyTextRed(20+(getCursorX(whatToEdit,cursorPos)*10),20*(getCursorY(whatToEdit,cursorPos)-textOffset),"|");
                
        flipScreen();   //SDL_Flip(screen);
        
        if(SDL_GetTicks()-loopStartTime > 200)
        {
            cerr<<"Crash prevention executed.\n";
            programcont = false;
            cont = false;               //crash prevention
            break;                      //exit the program if this loop takes far longer than normal to complete
        }
    }
    }
    catch (exception& e)
    {
        cerr<<"Exception cought "<<e.what()<<"\n";
    }
    catch(...)
    {
        cerr<<"other exception cought.\n";
    }
}
[/code]
 
 
Still seems to crash.
Edited by Syerjchep
0

Share this post


Link to post
Share on other sites

Why are you wasting 1/3 of most lines with spaces so you have to sidescroll all the time?

Also there are so many magic numbers in there where one cannot know what those are.

I would also put some smaller parts of it into their own functions and use a switch statement.

0

Share this post


Link to post
Share on other sites
Why are you wasting 1/3 of most lines with spaces so you have to sidescroll all the time?

Also there are so many magic numbers in there where one cannot know what those are.

I would also put some smaller parts of it into their own functions and use a switch statement.

Well, the indents are because it's already inside a bunch of if and while statements, as it's just a small segment of the much larger program.

I'm not quite sure what you mean by magic numbers, but most of the variables are probably not relavant.

 

 

Can you comment this like just a little so we can follow the logic please thank you.

Sure.

0

Share this post


Link to post
Share on other sites

Magic numbers like those 20, 100, 1000, 999999 you repeatedly use, I would put into constants with an informative name thats defined only once to prevent errors and aid in understanding the program.

If thats a function that is even longer than shown and needs that much indentation its a sure sign its too huge, which makes it difficult to debug.

 

From reading your code I even get doubts if that is just C and not C++. So if this is C++, how about programming a class first that implements all logic to the console and then some other class to place, align and draw everything in a window on your screen that can be used from your main loop? And if its really C, why not use some similarly split up functions in separate files?

0

Share this post


Link to post
Share on other sites

Just because it's c++ doesn't mean I'm using a console? What on earth would make you think that?

And who said it's C?

 

And no, it's not a function, it's inside an if statement inside an events loop inside the main function.

0

Share this post


Link to post
Share on other sites

[quote name='Syerjchep' timestamp='1357767598' post='5019637']
Just because it's c++ doesn't mean I'm using a console? What on earth would make you think that?

And who said it's C?
[/quote]

console as in "that thing people build in their graphics mode game for typing in text" not console as in "guy makes text mode game that runs inside a shell window".

And noone said its C, but you are just using C constructs like C array, C style struct access, C style number twiddling loops, ...; theres nothing really looking C++ like using STL, method calls,... wink.png

[quote name='Syerjchep' timestamp='1357767598' post='5019637']
And no, it's not a function, it's inside an if statement inside an events loop inside the main function.
[/quote]

I know and thats whats wrong with it.smile.png

0

Share this post


Link to post
Share on other sites

Updated the origional post.

Even though I haven't even finished rewriting what I had before (you can't actually edit the text yet), it still seems to crash it.

0

Share this post


Link to post
Share on other sites

Why are you using a 'character grid' instead of an std::list<std::string>? You could check each string and split it when you encounter a newline, pushing back multiple substrings to the list, and popping the front of the list when you get beyond your desired buffer size (say, 100 lines or more).

 

Which function is crashing? Under what conditions does it crash?

 

Are you saying the program crashes before you even enter int main()? If so, it's probably because your "char charactergrid[1000][1000];" takes up almost a full megabyte on the stack. You shouldn't put that kind of memory on the stack, it's not made for that. Using a std::vector (not 2D!) or std::list of std::strings is a far superior and 'correct' solution.

0

Share this post


Link to post
Share on other sites
Why are you using a 'character grid' instead of an std::list<std::string>? You could check each string and split it when you encounter a newline, pushing back multiple substrings to the list, and popping the front of the list when you get beyond your desired buffer size (say, 100 lines or more).

 

Which function is crashing? Under what conditions does it crash?

 

Are you saying the program crashes before you even enter int main()? If so, it's probably because your "char charactergrid[1000][1000];" takes up almost a full megabyte on the stack. You shouldn't put that kind of memory on the stack, it's not made for that. Using a std::vector (not 2D!) or std::list of std::strings is a far superior and 'correct' solution.

After a bit of testing, I found It is the character show function.

Also, I can't just make the strings into smaller strings, as they are going to be edited, which may or may not include adding or removing newline characters that would move all the other rows around.

 

 

Also, apparently the loop doesn't immedently crash the program, rather, at some point something goes wrong a few seconds in randomly, and suddenly every single iteration of the loop takes over a second, so I was able to add a crash prevention of sorts, that will automatically shut down the whole program if a single iteration of the scripting loop takes over 200ms.

Edited by Syerjchep
0

Share this post


Link to post
Share on other sites
 Also, I can't just make the strings into smaller strings, as they are going to be edited, which may or may not include adding or removing newline characters that would move all the other rows around.

 
In that case, why not have the entire "buffer" be a single string, with newlines and all?
Then anytime the string changes in response to keypresses, you parse the the string into a std::vector<std::string> at every location there is a newline and at every location where a line is greater than 'n' characters wide.
 
The std::vector<std::string> is the formatted data ready for drawing and is generated from the huge std::string which is the text the user edits.
 

Also, apparently the loop doesn't immedently crash the program, rather, at some point something goes wrong a few seconds in randomly, and suddenly every single iteration of the loop takes over a second, so I was able to add a crash prevention of sorts, that will automatically shut down the whole program if a single iteration of the scripting loop takes over 200ms.

 
That sounds like you are hiding the problem rather than understanding and fixing the problem. wink.png

Edited by Servant of the Lord
0

Share this post


Link to post
Share on other sites
 Also, I can't just make the strings into smaller strings, as they are going to be edited, which may or may not include adding or removing newline characters that would move all the other rows around.

 
In that case, why not have the entire "buffer" be a single string, with newlines and all?
Then anytime the string changes in response to keypresses, you parse the the string into a std::vector<std::string> at every location there is a newline and at every location where a line is greater than 'n' characters wide.
 
The std::vector<std::string> is the formatted data ready for drawing and is generated from the huge std::string which is the text the user edits.
 

Also, apparently the loop doesn't immedently crash the program, rather, at some point something goes wrong a few seconds in randomly, and suddenly every single iteration of the loop takes over a second, so I was able to add a crash prevention of sorts, that will automatically shut down the whole program if a single iteration of the scripting loop takes over 200ms.

 
That sounds like you are hiding the problem rather than understanding and fixing the problem. wink.png

 

Well in my last rewrite (updated like 5 minutes ago) that's what I did, without the vectors.

It's all just one string, no more characterGrid.

 

But, for whatever reason, it still crashed.

I guess I'll try to isolate the function again.

0

Share this post


Link to post
Share on other sites

Random guess: applyText() doesn't like being passed empty strings?

Using a debugger, you can find out exactly where something is crashing and why.

 

void DisplayText(const std::string &text)
{
	unsigned int lineNum = 0;
    std::string lineText;
	
	for(unsigned int i = 0; i < text.size(); i++)
	{
		//Check if it's the end of the line.
		if(text[i] == '\n')
		{
			//Check if there's something to display.
			if(!lineText.empty())
			{
				//Display the line.
				applyText(20, (20 * lineNum), lineText);
				
				//Clear the temporary string.
				lineText.clear();
			}
			
			//Increase the line number.
			lineNum++;
		}
		else
		{
			//Add this character to the temporary string.
			lineText.push_back(text[i]);
		}
	}
	
	//Display the final line (because there is no final endline).
	if(!lineText.empty())
	{
		applyText(20, (20 * lineNum), lineText);
	}
}
0

Share this post


Link to post
Share on other sites

Random guess: applyText() doesn't like being passed empty strings?

Using a debugger, you can find out exactly where something is crashing and why.

 

void DisplayText(const std::string &text)
{
	unsigned int lineNum = 0;
    std::string lineText;
	
	for(unsigned int i = 0; i < text.size(); i++)
	{
		//Check if it's the end of the line.
		if(text[i] == '\n')
		{
			//Check if there's something to display.
			if(!lineText.empty())
			{
				//Display the line.
				applyText(20, (20 * lineNum), lineText);
				
				//Clear the temporary string.
				lineText.clear();
			}
			
			//Increase the line number.
			lineNum++;
		}
		else
		{
			//Add this character to the temporary string.
			lineText.push_back(text[i]);
		}
	}
	
	//Display the final line (because there is no final endline).
	if(!lineText.empty())
	{
		applyText(20, (20 * lineNum), lineText);
	}
}

This works, and I'm sure it's better.

Yet it's still crashing.

I added try catch statements, yet they return nothing.

 

Gonna try and figure out how to use a debugger now.

0

Share this post


Link to post
Share on other sites

try and catch() only catch exceptions when an exception is thrown with throw. They don't catch crashes in general. Debuggers are definitely the way to go.

0

Share this post


Link to post
Share on other sites

I finally fixed it after almost a week of fustration.

And I only had to add one like of code.

 

Guess what it was?

I forgot to free the textures created by applyText. e.g. it was just a memory leak

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0