Bay 12 Games Forum

Please login or register.

Login with username, password and session length
Advanced search  

Author Topic: Useful code  (Read 800 times)

alfie275

  • Bay Watcher
    • View Profile
Useful code
« on: December 09, 2009, 05:03:43 pm »

Ok this is a place to post useful code, I'll start off by posting this name generator:
Code: [Select]
//Mucking around program

#include <iostream>
#include <string>
#include <math.h>
#include <sstream>
#include <ctime> // For time()
#include <cstdlib> // For srand() and rand()
using namespace std;

int random (int Range)
{
int num;
num = rand() % (Range + 1);
return num;
}

char C(){
   char constinants[21] = {'b','c','d','f','g','h','j','k','l','m','n','p','r','s','t','v','w','x','y','z'};   
   return constinants[random(20)];
}

char V(){
 char vowels[5] = {'a','i','e','o','u'};
 return vowels[random(4)];
}

string Ending(){
    string endings[5] = {"ith", "ton", "on", "field", "man"};
    return endings[random(4)];
}

int main()
{
    srand(time(0));
   

stringstream Name;

Name << C() << V() << C() << Ending();
cout << Name.str();

   
while(1);
}
Logged
I do LP of videogames!
See here:
http://www.youtube.com/user/MrAlfie275

timmeh

  • Bay Watcher
    • View Profile
    • My Portfolio
Re: Useful code
« Reply #1 on: December 09, 2009, 05:34:25 pm »

Cool!  You may want to specify language and such though.  Here's a couple of my interesting C++ bits and pieces:

Code: (tokenize) [Select]
/**tokenize((const string& str, vector<string>& tokens, const string& delimiters)
Splits the string passed to it at every delimiter
and then puts each substr into the vector**/
void tokenize(const string& str, vector<string>& tokens, const string& delimiters)
{
    // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
    string::size_type pos     = str.find_first_of(delimiters, lastPos);

    while (string::npos != pos || string::npos != lastPos)
    {
        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiters, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
    }
}
Basically, if you called "tokenize("This is a simple sentence.", my_vector, " ");", it would split the string at each space, and put the results into my_vector:
0 "This"
1 "is"
2 "a"
3 "simple"
4 "sentence."


Code: (Text-wrapped) [Select]
/**Draws text, wrapping it at spaces to remain inside a box area.**/
void draw_text_wrap(string text, int x1,int y1, int x2,int y2)
{
    ///The int() conversion is to avoid a warning about comparing signed and unsigned integers.
    if(int(text.length()) < x2-x1)  //If it's short enough to fit on a single line
    {
        mvprintw(y1,x1, text.c_str());  //Just print it in the corner
    }
    else
    {
        vector<string> text_lines;  //A vector to hold individual lines

        while(int(text.length()) > x2-x1) //While the text is too long to fit on a single line
        {
            int curs_pos = x2-x1; //set the cursor position to the maximum line length

            while( text.at(curs_pos)!=' ' )  //While the cursor is not at a space
            {
                if(curs_pos!=0)  //If we haven't checked the whole string
                {
                    curs_pos--;  //Step one position back in the string.
                }
                else //if we have checked the entire string
                {
                    curs_pos = x2-x1; //It'll just have to be broken off at the end of the line
                    text.insert(curs_pos, " ");  //Add a space, so it's there to be removed later
                }
            }

            string line = text.substr(0, curs_pos);  //Cut out the section
            text.erase(0, curs_pos+1);  //Erase the copied section from the original, as well as the space after it
            text_lines.push_back(line);  //Push back the line onto the vector
        }

        text_lines.push_back(text);  //Push back the last line

        int lines = text_lines.size();  //Set the number of lines to the number of elements in text_lines
        if(lines>y2-y1) { lines=y2-y1; } //Limit 'lines' to the size of the box

        for(int i=0; i<lines; i++)  //Loop through the lines
        {
            mvprintw( y1+i,x1, text_lines.at(i).c_str() );  //And draw them one at a time, inside the box
        }
    }
}
This one is specific to PDCurses, but it should be easy enough to adapt to other places.  Basically, I pass it a string to write and the coordinates to wrap it inside and it prints as much of the string as will fit, wrapping automatically at spaces.  Really all you'd need to do to make it work outside a console is change the output functions, and have it use the width of the font you're using to find the maximum length given the width of the box you specified...

[EDIT]:  The second example had the x and y positions mixed up if the text fit on one line, fixed it.
« Last Edit: December 15, 2009, 12:17:18 pm by timmeh »
Logged
On the Wall is a Masterfully engraved carving of Urist McHardcastle and Goblins. Urist McHardcastle is surrounded by the Goblins. The Golbins are stamping on Urist McHardcastle. Urist McHardcaste is laughing at the Goblins. The carving related to the prolonged and bloody death of Urist McHardcastle in the Fall of 1659, the Winter of 1659, and the Spring of 1660. On the engraving is an image of Cheese.