Most expensive game to develop: GTA IV - $100,000,000

Oct 2, 2009

Arrays and Strings - Part 2/2

Previously we talked about arrays and the way it works. A few information back there and once you had understood, we'll be able to talk now about strings.

Strings

Strings are a sequence of characters (char). Useful to provide or store information in the user-program interaction, like saving the user's name or sending an error message. And in C++ we have two ways to deal with them. One is called C-style string way and the other is based on the string class library (new in C++). Let's talk about the old-fashioned way.

-> C-style string

String, as said before, is a sequence of chars. And how can we store a sequence? Yes, with arrays. But the string has one interesting feature. The last element of a string is the null character, symbolized as "\0" and it sets the end of a string. Also, it defines if the array is a string or not. You have to add this null character if you define a sequence of chars and want it to be a string. Otherwise, it'll be just a char array. But creating a string with double quotes (" ") already add the null character for you.

char myName[] = "kamikkaze"; // correct, string created!
char myName[] = {'k','a','m','i','k','k','a','z','e'.'\0'}; // correct, it's a string
char yourName[] = {'u','s','e','r'}; // also correct, but not a string

By not defining the array size, it leaves the compiler calculated it for you, it's good when you want create a constant string. This is the didatic part of strings. Now let's see how they work when we use them.

In C++ we have cin and cout for reading and printing data. Check the examples:

cout << "Helo Mars!"; // we're printing a string

char myName[] = "kamikkaze";
cout << myName;
  // here we're also printing a string. But why we don't use the brackets here? This is related how the array's name and the cin/cout objects work inside and I'll explain it later

char youName[20]; // we have to define the maximum array size - always counting the null character!
cout << "Type your name:" << endl;
cin >> youName;
cout << Your name is " << youName << endl;



Simple examples. At the last one, I defined the size of the array. This is because I didn't specified what elements it'll stored so the compiler couldn't save a space in the memory to allocate them. When doing it, we take the risk to waste memory if the entire array isn't fulfilled. The way to bypass such wasting is doing dynamic allocation but I'll not going further into this subject now.

Now, you may find an error when you type more than one word in the last example above. If you write your full name and you press ENTER just the first name you wrote will be stored at the array. Why did that happen? As you know, the last character of a string is the null character. But the cin command reads whitespaces - like SPACE and TAB, as it's a null character and the rest of the name you wrote is gonna wait in the input queue. So the next cin command will read the rest of the name, no matter what you asked the user to do. See the example :

#include < iostream >
#define size 50
#define hnum 10
using namespace std;

void main(){
    char myName[size];
    char height[hnum];
    cout << "Type your name: " << endl;
    cin >> myName;
    cout << "Now type your height: " << endl;
    cin >> height;
    cout << "Your name is " << myName << " and your height is " << height << endl;
}


Output:

Type your name:
kamikkaze theMighty
Now type your height:
Your name is kamikkaze and your height is theMighty



There are some ways to avoid this. In C++ we have the cin.get(array_name,array_size) and cin.getline(array_name,array_size) functions.

The cin.getline takes two parameters. One is the name of the array that will store the string; and the other is the size of that array. What getline do is read all the characters, including whitespaces and replace the ENTER (newline character) you had typed at the end with the null character. So, as it's name says, it gets the line you're typing at and store in the array.

The cin.get function takes the same parameters and do almost the same things as cin.getline. The catch here is that this function puts the newline character (ENTER) in the input queue. It means, the next input order will read the ENTER from the queue and messing with your program. A way to overcome it is to add a cin.get() after (each) cin.get you use, to discard the ENTER from the queue. A not so pretty solution, I agree.

Now two major problems you might find using these function:
1-> empty line --> This problem just happens with cin.get function. If it tries to read an empty line, a failbit situation occurs, blocking the input queue. This means, no more data will be read in your program. To solve this problem just use cin.clear() :)

2-> many characters, few space --> When the string is bigger then the array size, both function leave the remaining chars in the input queue, but getline() sets a failbit and block incoming input.

Also we have strings related functions, They are strcmp(), strlen() and strcpy():

strcmp(string1, string2) -> this function compares two strings. Returns an integer value: 0 if they are equal; >0 if the first char that doesn't match has a greater value in string1 than in string2; <0 if the first char that doesn't match has a lower value in string1 than in string2. Note: values are based in the ASCII table;

strlen(string_name) -> determines the lenght of a string. It doesn't count the null character;

strcpy(string_destination, string_source) -> copy the string_source into the string_destination;

Note: You may have to use #include < string.h > to use these function for strings.

-> String Class

The C++ provide us with this new class. Instead of creating an array, now, for making a string, we just have to use the string object. See the example:

#include < string > // make the class available

string myName = "kamikkaze"; // string initialized!

Now we use the string type. We don't have to specify the size for the string, the class do it for us and in addition, it also resize it if any changes is make. But the notation of array still exists. You can acess any position like myName[2] or myName[0].

With string as object, operations like concatenation and assignment turn out to be easy. Unlike the char array, string class allows us to do this:

string str1 = "Hello";
string str2;
str1 = str2; // YES, WE CAN do it


And joining two or more arrays couldn't be easier now:

string str1 = "Hello";
string str2 = "World";
string str3;
str3 = str1 + str2; // valid operation :)
str1 += str2; // also valid operation (str1 = str1 + str2)


Along the cin.strlen() and cin.getline() functions, the string class provides us the string_name.size() and getline(input,string_name):

string Name = "World";
int lenght = World.size();
// x = 5

string name;
cout << "Enter your name: ";
getline (cin,name);
// as the string class already set the necessary size our string, unlike the cin.getline() function, we just have to enter the input source and the name of the string.

The string class has more features and I don't intent to write the entire documentation here. My goal was to point the most visible facilities the usage of this method when working with strings but it's up to you decide what is good for your program.


Note 2: < string.h > is different from < string > ! The first is for strings operations used in C-style strings ; and the second is for the class string !!


That's it. A simple introduction of arrays and strings in C++. In games, both of these subjects are used with thousands of other functions in the middle of a endless code page. But I always find interesting and useful, as a programmer, to know how functions, variables, etc work in the memory, when I compile and so. It's a lovely world of abstraction when you deal with a little more complex thing like pointers and OOP...So much pain :)
...ok cya XD

Sep 29, 2009

Arrays and Strings - Part 1/2

Some people, specially the beginners in programming, find this subject quite complex due the amount of details it has. But understand the principles and rules for using them is the basic if you want to be a programming expert (XD). Things get very difficult in C++ when you have to work with arrays and pointers together. The possibilities for errors increase and knowing how they work may help you to fix possible issues. Here I'll talk about Arrays and Strings and later I'll enter into the Pointers subject.

Array

You can use arrays to store n elements of the the same type under one name:

type name_of_your_choice [number_of_elements]

Quite simple declaration. But let's learn how they work here:

type -> you can choose the type for entire elements in the array. If you pick integer (int), all the elements will be integers, if you choose float, you will have an array of n float elements. But you can use other type than the
fundamental's one, like if you create this struct:

struct sExample{
     int x;
     float y;
     bool choice;
}

and create the array sExample[10] means that each entry of the array will store an int, a float and a bool value. Other words you will have 10 integers, 10 floatings numbers and 10 booleans variables, all of them in a 10-lenght array. Also, the type you choose will determine the amount of memory that will be used to store the values. Integers, in C++/Windows x86 enviroment, uses 4 bytes or 32 bits to store a value. So Array[20] is gonna use 4x20=80 bytes in memory AND this space is reserved once you declare the array - if you don't use all the 20 entrys, you're wasting memory. The math of sExample is 10x4(int) + 10x4(float) + 10x1(bool) = 90 bytes of memory used to store the array.

name_of_your_choice -> the name of your array. You can use any name, but the reserved words of C++. Also, respect the naming rules, like don't start the name with numbers.

number_of_elements (or index) -> always come between two brackets ([ ]). It defines how many elements you want in your array. Only accept integer values like 1, 10, 100 ,500. Don't even bother to use 1.35 or 'c', it won't work :). You guys can test how many integer elements you can use in an array before the compile  give an exception message. My 2GB PC allowed me to use 320M integers - int MyArray[320000000]. Pretty huge number, that I guess I'll never use, again :) A crucial detail: The first element of an array is stored in [0], and not [1]. So the last index of a n-elements array is [n-1]!!!

You also can use multidimensional arrays. The declaration consists in add another pair of brackets after the fisrt one like this:

char myArray[10][50];

You can add as many pair of bracket as you want, but be aware that the size of the array will increase. Take a look at the math:

int hehe[10] = 10 integers  -----> 40 bytes
int hehe2[10][10] = 100 integers -----> 400 bytes
int hehe3[10][10][10] = 1,000 integers -----> 4,000 bytes

"It seems to not a problem at all, what 4,000 bytes can do anyway..."
Well, in big projects and program you have to pay attention what types and the amount of items are being used. To be considered a well-developed program - or game, one of the factor is it has to use less memory as possible, saving precious resources at realtime running. Well let's go to the part of declaring and using an array.

Note: I'm pretty sure I forgot something that I would like to mention XD

To declare an array is simple. See the examples:

int myValues[10];
char myName[25];
float myPI[50];
bool myChoice[5];
int LOL[10][15], LOL2[20];

-> You have to declare the size of the array with integer numbers or using a constant previously declared in #define or with const qualifier :

#define size 50
(...)
const int array_size = 10;
float myArray[array_size];
int noneArray[size];

To initialize the array couldn't be more simple. You have two ways:

1. int myArray[3];      // this is the "hard way"
   myArray[0] = 1;
   myArray[1] = 2;
   myArray[2] = 3;

2. int yourArray[3] = {1,2,3}     // this is the "easy way" - use of braces to declare the values!
   or
   int yourArray[] = {1,2,3}   // here, you don't have to declare the size of the array, once you gonna define how many and what elements there will be

These ways also work for multidimensiaonal arrays. Let's use a 3x3:

int myArray[3][3];
myArray[0][0] = 1;
myArray[2][3] = 23;
myArray[1][0] = 1256;

or

int myArray[3][3] = { 1,2,3,4,5,6,7,8,9 }// the assignment is done linearly. This means the first entry is [0][0], the second is [0][1], the third is [0][2] and goes on, [1][0], [1][1], [1][2], [2][0], etc...

for purpose of beaty, I like to do this:

int myArray[3][3] = { {1,2,3},
                                  {4,5,6},
                                  {7,8,9}
                                };


Sure, you can initialize long arrays with loops but the elements have to be in some sort of linear or geometrical progression or be result of an equation.

Now this is not allowed:

int arrayful[5];
arrayful[5] = {1,2,3,4,5}; // initialize the array after declaration using this method: can't do it!

float A[5]; float B[5];
A=B;     //  perform such operation between arrays: can't do it!


Initialization Hints:
::::: You also can initialize part of the array:

int ourArray[5] = {1,2,3};

Here we initialized the first 3 elements of the array ([0][1][2]). The rest of array is set to 0 value automatically - ourArray[3] = 0
and ourArray[4] = 0;

::::: To set entire array with 0 (zero) value just do this:

int Test[500] = {0};

But putting another value different than 0 (zero), you will initialize just the first element with this value! As we saw before, the other 449 elements will be assigned with the zero value.


But how the arrays are stored in the memory buffer? Here's a didatic vision:




And this is part 1, guys.
Soon I'll post the second part, about strings and the ways to use it in C++. Cya  o/

Sep 27, 2009

game programming

If you want to enter into the world of game programming, C++ is the language you HAVE TO learn. A lot of games and engines out there are written in C or C++. Sure, there are some games that uses scripting languages like Lua for custom content creation, but for hardcore programmers, who wants to go deep into programming games, C++ is essential.

Following my studies of game programming, I'll regularly post stuff about this area, as articles about C++,  news in the games industry and when I run out of ideas, a something-related-to-games - like the previous posts about Modern Warfare 2 and Splinter Cell... :) 

cout << "See you all around!" ;

Sep 25, 2009

Stealth Assault - Splinter Cell

I made this post a long time ago but I didn't have published it, so here it goes :)

In the middle of a larger amount of shooter and sports games, born one of the most acclaimed game since Pitfall. Splinter Cell series, with 4 games released and with over 20 millions copies sold, is a stealth-based action game starring Sam Fisher, a direct rival of Solid Snake in the world of deadly spies. Despite of carrying the latest and best gadgetry, Fisher makes use of the enviroment shadow to accomplish his misson as quiet and invisible as possible.



At his first apperance, in Tom Clancy's Splinter Cell (2002), Sam Fischer, a reformed agent of NSA, is called back to work in a secret division called Third Echelon. His first misson was to investigate the desapperance of two CIA officers in Georgia. But he uncovers a campaign of mass murder against the neighboring muslim population of Azerbaijan waged by Gerogian president, Nikoladze.

Back to work in Tom Clancy's Splinter Cell - Pandora Tomorrow (2004), Sam Fisher is now sent to Indonesia to infiltrate the U.S. Embassy, ocupied by Suhadi Sadono - leader of Darah Dan Do, an Indonesian militia, and gather intelligence on the invasors. The U.S. Army retook the place but Sadono had fled. Also, Fisher uncovered that Sadono masterminded a project called "Pandora Tomorrow", by placing biological bombs in American soil.

Fisher returns in one more episode entitled Tom Clancys's Splinter Cell: Chaos Theory (2005) to investigate the location of computer programming who had worked on the Philipe Masses's algorithm (Masses appears in the first Splinter Cell). As usual, Fisher went deeper in the investigation and a world crisis, involving his old friend Douglas Shetland, an algorithm considered a superweapon, Koreas and Japan may lead to World War III.

 
In the lastest game released of the serie, Tom Clancy's Splinter Cell: Double Agent (2006), Sam Fisher go on undercover assignment which requires him to pose as a criminal to infiltrate a terrorist organization based in U.S. This time, Fisher plays in both sides, in a very dangerous gray area where the line between right and wrong is blurred,  with thousands of innocents lives in the balance.

The next game of the serie, expected to release in Feb, 2010, called Tom Clancy's Splinter Cell: Conviction, brings our spy agent to the next-gen consoles one more time. Sam Fisher will be back, faster and mortal than ever, in a game with new features and a non-linear missions - you can choose the way you want to accomplish them.





For the purpose of fun, I didn't' post the whole story of the game, so if you want to know, you gonna have to put the night vision goggles on, turn on your stealth mode and begin the crusade to save the world on the command of the deadly agent Sam Fisher :)


         
















Videos: 


                                                     

Sep 22, 2009

Upcoming War - Modern Warfare 2

This is one of the the most antecipated game of the year. Since it's first annoucement, in Q4/2008, Modern Warfare 2 is expected by an entire mass of FPS players around the world. Officially announced in Feb 11,2009, this sequal of Call of Duty 4: Modern Warfare returns to the hands of Infinity Ward, after the Treyarch's Call of Duty 5: World at War.


The story is set several years after the end of CoD4. Now the Russian Ultranationalist, lead by a new bad guy, Vladimir Makarov, has returned. With Vladimir's growing influence and strong power base set in Russia, forced the world community to create the Task Force 141 to counter the thread posed by the ultranationalists.

On the control of a new soldier named  Sergeant Gary "Roach" Sanderson, the player will face battles around the world, from Russia to Brazil, under the command of your known-old-friend "Soap" MacTavish, now promoted to captain of SAS.



New featues are expected in this sequal, like use of vehicles (like the snowmobile in the trailer) and the dual wielding handgun and a lot of "old" ones from MW1 will be back like weapons and multiplayer content (like favorite maps, perks, airstrikes, helicopters and UAVs). There also a few (bad and/or good) changes, but nothing that takes away the glow of MW2.

Modern Warfare 2 is set to release in November 10, 2009 worldwide.
You can pre-order now Modern Warfare 2 (PC/PS3/XBOX360), Modern Warfare 2 Hardened Edition (PS3/XBOX360) or Modern Warfare 2 Prestige Edition (PS3/XBOX360). I'm particulary disappointed for the special editions just for console, but maybe later they release them for PC too :)

Official Trailer:


E3 Demo:



 Multiplayer Movie by Game On:
 

Hello there!

Hey guys, a brand new blog is out and ready to rock :)
Right now, I'm working on the edition of this page and I'm not familiar with web coding but I'll give my best.
I'll also try to perform a daily update of interesting news that I find on Internet, this amazing big world.  Ok, now let me work here.

PS.: I like simple templates, but later, with time, I'm going to work on the visual. Hope the template helps. XD