Jump to content

  • Log In with Google      Sign In   
  • Create Account

Trying to make an ingame text editor.


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
16 replies to this topic

#1 Syerjchep   Members   -  Reputation: 180

Like
0Likes
Like

Posted 07 January 2013 - 02:35 PM

Okay, third fourth try at writing this code:

 

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

Edited by Syerjchep, 11 January 2013 - 02:23 PM.


Sponsor:

#2 mholmes   Members   -  Reputation: 189

Like
0Likes
Like

Posted 07 January 2013 - 08:38 PM

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



#3 wintertime   Members   -  Reputation: 1727

Like
0Likes
Like

Posted 08 January 2013 - 11:00 AM

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.



#4 Syerjchep   Members   -  Reputation: 180

Like
0Likes
Like

Posted 09 January 2013 - 02:40 PM

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.



#5 wintertime   Members   -  Reputation: 1727

Like
0Likes
Like

Posted 09 January 2013 - 03:04 PM

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?



#6 Syerjchep   Members   -  Reputation: 180

Like
0Likes
Like

Posted 09 January 2013 - 03:39 PM

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.



#7 RobMaddison   Members   -  Reputation: 708

Like
0Likes
Like

Posted 09 January 2013 - 03:57 PM

Crashes? How?

#8 wintertime   Members   -  Reputation: 1727

Like
0Likes
Like

Posted 10 January 2013 - 06:24 AM

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?

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

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

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



#9 Syerjchep   Members   -  Reputation: 180

Like
0Likes
Like

Posted 10 January 2013 - 06:23 PM

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.



#10 Servant of the Lord   Crossbones+   -  Reputation: 19681

Like
0Likes
Like

Posted 10 January 2013 - 07:43 PM

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.


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]


#11 Syerjchep   Members   -  Reputation: 180

Like
0Likes
Like

Posted 10 January 2013 - 07:56 PM

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, 10 January 2013 - 07:57 PM.


#12 Servant of the Lord   Crossbones+   -  Reputation: 19681

Like
0Likes
Like

Posted 10 January 2013 - 08:17 PM

 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, 10 January 2013 - 08:18 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]


#13 Syerjchep   Members   -  Reputation: 180

Like
0Likes
Like

Posted 10 January 2013 - 09:07 PM

 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.



#14 Servant of the Lord   Crossbones+   -  Reputation: 19681

Like
0Likes
Like

Posted 10 January 2013 - 09:37 PM

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);
	}
}

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]


#15 Syerjchep   Members   -  Reputation: 180

Like
0Likes
Like

Posted 11 January 2013 - 02:22 PM

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.



#16 Servant of the Lord   Crossbones+   -  Reputation: 19681

Like
0Likes
Like

Posted 11 January 2013 - 03:27 PM

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.


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]


#17 Syerjchep   Members   -  Reputation: 180

Like
0Likes
Like

Posted 11 January 2013 - 03:38 PM

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






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