Thursday, June 14, 2007

Const in C++

The const keyword in C++ is a very useful keyword . Apart from declaring constants it is useful in declaring few important things . Lets talk about two important const advantages
  1. pointer to a const
  2. const reference
Pointer to a const:
Pointer to a const basically says that the object being pointed to by the pointer should remain const and the pointer should not try to change the contents of that object . But this does not mean that that value of the object will not get changed m it just says the given pointer is not going to change the value of the object.

e.g String(const char * = ""){
.....
}

a simple rule of thumb is that if the function is not going to modify the object it should accept a const object

const reference:


void do_something(const Thing &);

This is analogous to pointers , the only advantage is that by declaring a reference const you prevent unnamed temporaries . Basically its the same concept which says if your not gonna change it then pass it as a const .

cannot use do_something(get_something()) // un named temporary not allowed

Things get_something();

Thing t(get_something());
void do_something(Thing&);

Const member functions:
const member function are member function in which the argument list is followed by the const keyword. In a const instance of an object only const member functions can be invoked.
From non const member functions unnamed temporaries can be invoked.

Implementing operator as member or nonmember functions

The answer to implementing an operator as a member or a non member lies in the following simple points
  • if any operand of an operator is susceptible to implicit type conversion , implement it as a member function
  • if the result of an operation does not effect the two operands or an operand implement it as a non-member function.

Sunday, June 10, 2007

Tutorial: Writing a Tetris Clone using XNA

One of the Hello World programs in game programming is Tetris . I am making the assumption that you the reader have played tetris and know the rules of this simple game knows C# and under stands Object Oriented Concepts . Tetris is a very simple game , simple graphics simple collision detection and animation if you want to call the rotation of blocks as animation . So lets not any more time and lets get started with the code and step by step explanation of how to create a Tetris Using XNA .

Step 1:
Step 1 is figuring out all the the blocks that are used in the Tetris game . If you think about the game it consists of the following blocks
  1. a line
  2. a square shaped block
  3. a L shaped block
  4. a J shaped block
  5. a S shaped block
  6. a T shaped block
  7. a Z shaped block
Now each of these blocks contain exactly 4 squares . So the basic unit is a square and we build blocks out of these squares .

Step 2:
In step 2 ,we will try to see as to how we can map these blocks to their corresponding images and as to how we can rotate the blocks and their corresponding images .Since we saw that each block is made up of 4 squares , we can label the squares as 1 , 2 ,3 ,4 correspondingly . Out of these 4 squares , 1 square we will mark as the pivot around which the block can rotate .
See the image below for a clear understanding of this:



If you look at the blocks they have different names , like L , J , S which basically identify their shape . Each square in a block is numbered and one of the square is circled . The circled square is the pivot for the given block . If you look carefully at block S , that block on rotation looks like the block mentioned directly below it .


Step 3

Now that we understand the basics of the representation and requirements we can get down to some coding , i ll try to avoid the XNA related code till the end . I will try to explain how this simple representation of blocks can be represented using code.

Since we have a number of blocks and each block can rotate and move left , right , down. Also each block has a direction and a current position . So basically every object in this simple game is block and since all these blocks have few things in common , we can take that common functionality and create a simple abstract class called Block . We can then have each one of the blocks extends from this base class called Block . Since the next block that falls from the top should be randomized , we can create BlockFactory that generates these blocks for us . This factory can create an instance of each type of block and cache it . So that we can reuse the block instances . Now that i have explained how Block , BlockFactory fit together lets look at the code for Block :

public abstract class Block
{
// the background image used by the game
protected Texture2D backgroundTexture;

// the current position of the block
protected Vector2 position;

// the 4 squares used by each block
protected Square square1;
protected Square square2;
protected Square square3;
protected Square square4;

// before we rotate the block and calculate the new position for the squares
// we'll use the following variables to store the old positions
protected Vector2 _oldSquare1Position;
protected Vector2 _oldSquare2Position;
protected Vector2 _oldSquare3Position;
protected Vector2 _oldSquare4Position;

// the game field where the actual game is being played
// i ll talk about this later
protected GameField gameField;

// the direction of the block
private Direction direction;

// the movement of the block
private Movements.Movements movements;

// this constructor for the block , this is where the block gets created
// it is given an initial position and a direction , based on this starting
// position the 4 squares get initialized
public Block(GameField gameField, Texture2D backgroundTexture, Vector2 origin , Direction direction)
{
this.backgroundTexture = backgroundTexture;
this.position = origin;
this.direction = direction;
this.gameField = gameField;

square1 = new Square(this.backgroundTexture, position);
square2 = new Square(this.backgroundTexture, position);
square3 = new Square(this.backgroundTexture, position);
square4 = new Square(this.backgroundTexture, position);

movements = new Movements.Movements(this,gameField);

// ignore this for while i ll talk about this
setupBlock();
}

// the code that will respond when a block of a given shape is rotatated to
// the North ,
public abstract void RotateTo(North north);

// similarly it also works for East , West , South

// the core rotating logic is here , first of all we save the positions of
// the 4 squares , then based on the current direction we try to rotate
// the current block , this gives us a new set of positions for the 4 squares
// and a new direction for the block , then we make a final check if we can
// possible rotate if not we revert back to the saved positions .
public void Rotate()
{
savePositions();
this.direction = direction.Rotate(this);
if (!canRotate())
revertPositions();
}

// Similar to rotation we first of all save all the positions of the 4
// squares , based on the current movement we check if we can move to the
// left the given number of units , if the block can move we move else
// we revert back to the saved positions .
public virtual void MoveLeft(int units)
{
savePositions();
if (movements.LEFT.CanMove(units))
{
square1.MoveLeft(units);
square2.MoveLeft(units);
square3.MoveLeft(units);
square4.MoveLeft(units);
}
else
revertPositions();
}

// similar logic applies for Right and Down

// the draw method for the block draws the block , by drawing all the 4
// squares , ignore the SpriteBatch i ll talk about that later
public virtual void Draw(SpriteBatch batch)
{
// draw the given square at the given position
batch.Draw(square1.Texture, square1.Position, Color.White);
batch.Draw(square2.Texture, square2.Position, Color.White);
batch.Draw(square3.Texture, square3.Position, Color.White);
batch.Draw(square4.Texture, square4.Position, Color.White);
}


protected void savePositions()
{
_oldSquare1Position = square1.Position;
_oldSquare2Position = square2.Position;
_oldSquare3Position = square3.Position;
_oldSquare4Position = square4.Position;
}

protected bool canRotate()
{
return canRotate(square1) &&
canRotate(square2) &&
canRotate(square3) &&
canRotate(square4);
}

protected void revertPositions()
{
square1.Position = _oldSquare1Position;
square2.Position = _oldSquare2Position;
square3.Position = _oldSquare3Position;
square4.Position = _oldSquare4Position;
}

// ask the gameField if the given square can rotate
private bool canRotate(Square square)
{
return gameField.CanRotate(square);
}
}
Step 3 was big , indeed it was a mini Leap . But it was needed . In Step i will be talking about the classes that are used by above code .

Step 4:
Lets start with the Square class . A block uses 4 squares . The code for the Square class is pretty simple and looks like this :

public class Square
{
.....

// move the position of the square to the left by given units
public void MoveLeft(int units)
{
position.X = position.X - units;
}

...

// move the position down by given unite
public void MoveDown(int units)
{
position.Y = position.Y + units;
}

...


The square class is pretty simple . Next there is an interface called Direction .
which looks like this

public interface Direction
{
Direction Rotate(Block block);
}


I have 4 classes implementing this interface . The classes being East , West , South and North . Lets look at the code for the East class .

// East implements the Direction class
public class East : Direction
{
// the rotate method tells the block to rotate itself in the east
// direction . Remember the abstract method in Block that rotate in
// different direction , this is where they are used . Why i did this
// well depending upon the shape of the block and using this type of
// reverse delegation helps in keeping the code managable
public Direction Rotate(Block block)
{
block.RotateTo(this);

// since the next direction in clockwise manner is South return that .
return Directions.SOUTH;
}
}


Directions is not a true factory , but just holds static references to different
types of directions . The movement class is also similar in nature to the direction
class . The movement class is an abstract class and there are classes like Left ,
Right , Down that inherit from Movement . Again Movements is similar in nature to
Directions .

To be continued ....

Saturday, June 09, 2007

Casting in C++

Type casting in c++ can be done in two ways , using the traditional explicit ( ) cast operator or the new cast operators in c++ . The new operators in C++ are

  1. static_cast <>
  2. const_cast <>
  3. dynamic_cast <>
  4. reinterpret_cast

Implicit Type Conversion in C++

An implicit type conversion process in C++ , happens in two cases .

Case 1:
If there is a type T and another type F . An the type T has a constructor that takes in a Type F , in that case in expressions which involve the usage of Type T and an object of type F is passed . The type F is automatically converted to an object of type T . Lets see this is as example


class String {
char * string;
public:
String(const char * str = "");
};

void print(String & str);
Now here if print is invoked with "Hello , world" i.e print("Hello , world") is called then since we have a constructor for String that takes in an array of characters . So array of characters are automatically converted into a String object which is then passed to then print function .

Case 2:
Using
the conversion operator it is possible to implicitly convert one object to another type. If the String class had the following operator defined

operator const char* ( ) const { return string; }

and somewhere in some function if the following code was used

String s("hello world");
cout << style="font-weight: bold;">So, with that also an implicit type conversion happens . Implicit type conversion can get confusing , so should be used with care . Explicit case or function calls are much better as they indicate the intended operation more clearly .



Friday, June 08, 2007

Little Sugar (Compound Assignment operator And Implicit Type Conversion)

x += i

'+=' This is what is called the compound assignment operator in Java . An interesting thing about this operator is that , this operator automatically casts the type of expression on the right , which in this case is i to the type of the expression on the left which being x .

Wednesday, June 06, 2007

Little Sugar (Algorithm)

I came across an interesting property about numbers . If u have a number a and you consider multiples of the number , then for some number a the sum of the digits of the multiple is divisible by the number a

More than this , if you just check till the first 4 digit number , in that base then you get to know that for all multiple of the number the above mentioned property holds.

given a sequence [1 .. N] and a base ( b) , and number a . generating the multiples is as simple as doing 1 + a , 2 + a ....

finding the sum of the digits is a given base (b) is same as finding the sum of digits for base 10 that except for base 10 , base (b) is used

in code that looks like

while(n){
sum += n % base;
n = n/base;
}

the maximum 3 digit number is a given base is
base * base * base

Tuesday, June 05, 2007

Little Sugar 1 ( Java)

So often i come across something cool , but important so i thought using blogging about them would be nice idea , so here is my Little Sugar 1

when converting from 1 type to another , sign extension is performed if the source data is signed
eg

byte b = 0xff;
char c = (char) b

if the type is char , no sign conversion is peformed .

if converting from byte to char if no sign conversion is required than bitwise AND with 0xff is nice idea.


char c = (char) b & 0xff

Contract of Object.Hashcode in Java

In continuation with my ongoing summary series , today i am going to write about hashcode and objects in java . So lets get started .

The contract of hashcode in java
  • Inrrespective of the number of times hashcode is invoked on an object , it should return the same value.
  • If two objects are equal then the hashcode values should also be the same.
Generally , it s a good practise to store the implement the hashcode of two objects when you implement the equals of an object . You ask why ??

Well if you dont do that , then different instances of the object when stored into the hashtable , hashmap will be stored into the same hash bucket and when that happens all objects actually end up being stored in a linked list and hence cause drastically effect the performance of the program.

So what would be a good way of implementing the hashcode , well a simple way would be to pick a prime number and multiply it with the hashcode of all the fields , for primitive fields this would be their values

So let me give you a simple example , so if u have a class that has say two fields , field1 and field2 then the hashcode for that object can be

public int hashCode(){
int result = 17;
result += 37 * field1;
result += 37 * field2;
return result;
}

Choosing an i odd prime number reduces the chances of overflows . For immutable objects where calculating hashcode , might be an expensive process it makes sense to store the hashcode locally and to return the pre calculated hashcode value.

Monday, June 04, 2007

Implementing the Assignment operator for your class in C++

The other day i was reading about the assignment operator in C++ . Here is my small understanding of it . The job of the assignment operator is to overwrite the members of your class , with the new provided members.

Contract of the assignment operator
  • The assignment operator must work properly when an object is assigned to itself.
  • Since assignment is going to overwrite data for data of your object , the resources external to the object need to be free.
  • The assignment operator should return a constant reference to the assigned object.
Let me give you a reference implementation first . Then we can discuss about the contract.

1 const String& String::operator= (const String& other){
2 if(&other != this){
3 delete[] characters;
4 characters = new char[strlen(other.characters)+1];
5 strcpy(characters,other.characters);
}
}

Now lets discuss the implementation step by step .
if(&other != this)

We need to make sure that the object we are assigning is not the same object , other wise we would end up over writing the data members of the same object.

eg String s
s = s // this would not work if the above mentioned line is not there

Now lets move on to second point of the contract . Since the String class we have here is using characters which is something external to it . We need to delete it , re allocate it and then re initialize it .

// delete the characters
delete[] characters

// reallocate the characters
characters = new char[strlen(other.characters)+1];
// re initialize the characters
strcpy(characters,other.characters);

Now the third point is its important that we return a const reference to the object
being assigned . Thats the reason we are returning *this and thats the reason why
function signature reads .

const String& String::operator= (const String& other)

The reason we need this is to prevent users from trreating assignments as lvalue .
Basically

String s;
(a = b ) = s

something like this should be illegal .

Saturday, June 02, 2007

How to override the equals method in Java

Well the other day i was reading about how to override the equals method in java . Here is brief summary of what i learnt .

Never Assume Anything:
First things first if you are writing a class whose equals method u have not overridden assumi ng that the equals method would never be called . never assume anything and atleast throw a UnsupportedOperationException to prevent others from doing a equality check on the instance of your class.

In terms of Code the equals method in your class should look like ,


public boolean equals(Object other){
throw new UnsupportedOperationException();
}
Contract of Equals Method:
The equals method must be
  • reflexive
  • transitive
  • symmetric
  • comapring with a null object should be false
So say if we want to compare two Point Objects


public class Point {
private Object x;

public Point( Object x ) {
this.x = x;
}

public boolean equals(Object point){
if(point == this)
return true;
if(!point instanceof Point)
return false;
Point other = (Point) point;
boolean result = true;
result = result && (x == other.x || (x != null && x.equals(other.x)));
return result;
}
}


Now ok i ve implemented a hypothetical Point class that has only 1 member entity called x . That entity is an Object rather than being a primitive type.

if(point == this)
return true;

In this line i check the references are equals , if they are then can we can skip other checking cause basically they are the same two references .

if(!point instanceof Point)
return false;

Second we make sure the object that we are comparing against is of the same type and is not null . The not null is implicit in the behaviour of instanceof operator . The instanceof operator makes sure that object on the left is not null othwerise it returns false.

Point other = (Point) point;

Next we perform the casting to the type of this object so that we can check each and every field .

boolean result = true;
result = result &&amp;amp; (x != null && x.equals(other.x));

Next since x is the field being used here , we check if x is not null and if its not null we see if its equal to the x field in the other Object.

return result;

Finally we return the result

Dividing a Sequence into K ranges

Problem Statement:
Say you have a sequence of N numbers and you want to partition the sequence into K groups such that after applying a cost function c(i) for each group the sum of all cost functions over all groups is minimized or maximized?

Approach:
To divide the sequence into ranges , we will use K keys . The key used to divide the group can be indices or values . If its values then numbers in the
sequence can be used along with values in the sequence to partition values into groups whose key is K.

One way to do this is to use K-for loops , if the key is value based then probable something like this would work:


for i = 1 to n
for j = 1 to n
for k = 1 to n
for l = 1 to n{
key1 = seq[i]
key2 = seq[j]
key3 = seq[k]
key4 = seq[l]

}


After dividing the sequence into keys, use the keys to apply and aggregate the result of individual cost functions . Depending upon the requirement reduce the cost functions using functions like min , max depending upon if you want to minimize or maximize your result.

There you go , now u have 1 simple way of dividing a sequence into groups

Thursday, November 16, 2006

binding Source n Combo box initialization problem



I was trying to bind a combo box to a list of items . Now each item is a domain object .

myBindingSource.DataSource = my list of domain objects

i create a binding between the SelectedItem property of the combo box and the property Value of my domain object in the binding source .

now initially when the value of my domain object is null , i want an empty row to appear in the combo box , which works fine . Now as i choose different domain object values in the combo box , the value of the domain object is not refreshed .

I was using myComboBox_SelectedIndexChanged event to notify of the change in domain object value , but it was not helping the refreshing of other entities that depended on the values of the domain object .

So now instead of the SelectedIndexChanged Event now i use the
myBindingSource_CurrentChanged event and it works like a charm

Monday, November 06, 2006

a neat ToString for c++




template <class T>
string to_string(T toBeConverted){

// create an out string stream
ostringstream buffer;
// write the value to be converted to the output stream
buffer << toBeConverted;
// get the string value
return buffer.str();
}

Monday, September 18, 2006

as in C#

The keyword as in c# prevents the InvalidCastException From happening , its default behaviour is to nullify the object being casted . When the object being casted is used it thwrows a Null Exception .

Thursday, September 14, 2006

splitting strings in c++ using stringstream

of if you need to split a string "10 20 30 40 " in c++

You can do that using istringstream

all u need to do is

#include < sstream >

Assuming s is "10 20 30 40"

istringstream iss(s) ;

int ten , twenty , thirty , forty ;
iss >> ten >> twenty >> thirty >> forty;

converting 2D array into single array

This piece of snippet is written in c++ , converts a 2 dimensional Array into a single array
//
provide the size of the array to be converted with T being the data type
// invoke the function like


// int * arr = Covert2DTo1DimensionalArray ( source_array , 3 , 3 )



template < class T , int SIZE >
T* Covert2DTo1DimensionalArray( T source[SIZE][SIZE] , int width , int height ){

// the width of the new single dimensional array would be width * height
int length = width * height;

// create a new single simensional array on the heap
T * _array = new T[length];

// push values into the single dimensional array

int ctr = 0;

for(int y = 0; y <= height ; y++) {
for( int x = 0; x <= width; x++) {
_array[ctr++] = source[y][x];
}
}
return _array;
}

Wednesday, September 06, 2006

ComboBox DataSource And Refresh Issues

How many times have you been frustrated by the fact , that you set the DataSource on a
ComboBox and it does Not show up or it does not Refresh .

basically,
code like
myComboBox.DataSource = value

does not update the values on screen

the workaround to get this working though not elegant is :

BindingManagerBase manager = myComboBox.BindingContext(value);
manager.SuspendBinding();
myComboBox.DataSource = value;
manager.ResumeBinding();

Sunday, August 27, 2006

Generating uniqu GUIDS in MS Sql Server

Use NewId() to generate new unique guids .

Stupid MS Sql Server Logon failure

The So called MS Sql Server throws up a ERROR 1069 : Logon failure everytime you change indows password .

The way to get it working is :

o correct the password in Microsoft Windows 2000 Server and Microsoft Windows XP:
1.Click Start, point to Settings, and then click Control Panel.
2.Double-click Administrative Tools, and then double-click Services.
3.Use one of the following steps based on your instance type:
For a default instance of SQL Server, double-click MSSQLServer, and then click the Log On tab.
For a named instance of SQL Server, double-click MSSQL$YourInstanceName, and then click the Log On tab. Replace YourInstanceName with the actual name of the SQL Server instance.
For a default instance of SQL Server Agent, double-click SQLAgent, and then click the Log On tab.
For a named instance of SQL Server Agent, double-click SQLAgent$YourInstanceName, and then click the Log On tab. Replace YourInstanceName with the actual name of the SQL Server instance.
4.Type the correct password in the Password and Confirm password textbox, and then click OK.