Mar 9 2010

Installing Cocos2D for the iphone

I have recently started working on some Iphone games only to discover a spectacular 2D game engine on the iphone called Cocos2D. After reading their very impressive feature list and some blogs on how Cocos2D works, I decided to try it out for myself. Low and behold however that it wasn’t the easiest thing to install manually for iphone development. If you try and install cocos manually, you will run into countless errors and hassles while getting it up and running.

However, Cocos2D now sports a fancy shell script to get some Cocos2D templates up and running directly in Xcode with all the files pre-configured to start. To install these templates all you have to do is navigate to the cocos2D root directory on your filesystem using the terminal and then run this command.

./install_template.sh

You can then open Xcode and you should see the following screen ready to use.


Dec 13 2009

Intro to PHP – Creating a Basic Login System

Using a little knowledge of PHP and HTML you can build a simple log in system for your site. In order to correctly follow this tutorial you may want to have a good idea of basic HTML/PHP syntax as well as knowing some CSS. You should also have a basic understanding of how to create and use sessions($_SESSIONS) in PHP.

Alright let’s get started by just creating a basic log in window and place it in the center of the screen. First the log in window.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>Sample Log In</title>
 
		<link rel="stylesheet" href="loginCSS.css" type="text/css" />
	</head>
	<body>
		<div id="outerLimit">
			<div id="container">
				<div id="innerLimit">
					<div id="loginBox">
						<form id="login" name="login" method="post" action="userAuth.php">
							<label for="username">Username:</label><br />
							<input type="text" id="username" name="username" size=40 /><br />
							<label for="password">Password:</label><br />
							<input type="password" id="password" name="password" size=40 /><br />
 
							<input type="submit" name="submit" value="Log In" />
						</form>
						<br />
					</div>
				</div>
			</div>
		</div>
	</body>
</html>

Next let’s move into a bit of the CSS. Basically we just want to create a window with a gray background so the fields are extremely easy to see. I called the CSS file in this case loginCSS.css but you can call it whatever you like as long as it’s referenced properly in the HTML section.

body
{
	background-color:white;
	min-height: 468px;
	min-width:552px;
	font-family:Helvetica;
}
 
a
{
	font-size:small;
}
 
#loginBox
{
	background-color: #e4e4e4;
	position:relative;
	top:25%;
	left:25%;
	width:300px;
	padding:15px;
}
 
#outerLimit
{
	height:100%;
	width:100%;
	display:table;
	vertical-align:middle;
}
 
#container
{
	position:relative;
	vertical-align:middle;
	display:table-cell;
	height:468px;
}
 
#innerLimit
{
	width:552px;
	height:468px;
	margin-left:auto;
	margin-right:auto;
}

As you can see, I just styled the page a little bit to make it a little bit easier for the user to use. Now that we have a basic page for the user to log in, we’ll also need a page, such as a dashboard, for the user to access when they enter in correct login criteria. In this case we’re just going to use a page that has a basic header telling the user they have logged in correctly. The page can look something like this.

 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>Sample Log In</title>
 
		<link rel="stylesheet" href="loginCSS.css" type="text/css" />
	</head>
	<body>
		<h1>You are now logged in!</h1>
		<a href="logout.php">Log Out Here</a>
	</body>
</html>

As you can see I have also included a log out link just below the h1 tag. If a user logs into the system we also want them to be able to log out. Next we’re going to create the SQL for our database. For this tutorial I’ll be using MySQL, however Oracle or SQL Server could also be used.

Note: If you’re going to use a different database then the code to connect to the database will be slightly different.

DROP TABLE IF EXISTS 'testDB'.'user'
 
CREATE TABLE 'testDB'.'user'
(
	'username' VARCHAR(10),
	'password' VARCHAR(10)
);
 
INSERT INTO 'testDB'.'user'
(username, password)
VALUES
('admin', 'password'),
('guest', 'password');

This is just a very simple database table that contains only a username and password. This script could obviously be modified to accept further fields of to encrypt the password field to increase the security of your system. Things like that will be out of the scope of this tutorial however.

Now that we have our environment set up we can start to use PHP to get data from the forms and compare them with the database. For the this tutorial we will only be using the POST method of retrieving data from forms. Using GET is often not recommended when getting sensitive data such as usernames and passwords. As you can see from the log in window, we have used the POST method to get the data, and when the form is submitted we are calling the userAuth.php file. Let’s go ahead and create that file now.

This block of code we will be using to check to see if the fields are blank. If they are we want to send them back to the login.html file to log back in again using the header() function. Next we want to enter all the configuration information to connect to the database and use some PHP functions to protect our site from SQL injection errors.

/*Create the variables to hold the database information*/
 
$dbName = "testDB";
 
/*Table name that we're checking against*/
 
$dbTable = "user";
 
/*Database username*/
 
$dbUsername = "DBUsername";
 
/*Database Password*/
 
$dbPassword = "DBPassword";
 
$username = $_POST(['username']);
$password = $_POST(['password']);
 
/*This next block is to prevent SQL injection hacks*/
$username = stripslashes($username);
$password = stripslashes($password);
 
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

I have put in default values into the variables. Variables such as $dbTable and $dbUsername will be subject to change based on your database configuration. These values will need to be filled in with correct values from your system. Next we’re going to be connecting to the database and opening a connection.

/*Connect to the Database*/
 
$connection = @mysql_connect("localhost", $dbUsername, $dbPassword) or die(mysql_error());
 
/*Select the database you want to access*/
 
$db = @mysql_select_db($dbName, $connection) or die(mysql_error());
 
/*Select statement from the database to see if the user is in the system*/
 
$sqlQuery = "SELECT COUNT(*) FROM $table_name WHERE username = '$username'
AND password = password('$password')";
 
/*Create a variable to hold the results of the SQL query*/
 
$result = @mysql_query($sqlQuery, $connection) or die(mysql_error());
 
/*Check the number of rows returned from the query*/
 
$num = mysql_num_rows($result);

Now we’re getting to the user authentication section. We’re now going to see if the number of rows that was selected is anything but 0. In theory it should ever only come back with 1 or 0 rows, however in systems where users can multiple accounts it’s good to keep it to != 0.

/*If the number of rows is not equal to 0 then authenticate the user*/
 
if ($num != 0)
{
	session_start();
 
	//Create a session for the username and password
	session_register($username);
	session_register($password);
 
	if(!session_is_registered($username))
	{
		header("location:login.html");
	}
	else
	{
		//because the user is authenticated move them to the dashboard
		header("Location: home.html");
	}
}
else
{
	header("Location: login.html");
	exit;
}
?>

We then register a session and store the username and password in the session. If the session has been registered correctly then you can send the user to the home screen. If the session is not registered correctly for some reason we don’t want the users accessing the system, so we send them back to the login screen to attempt to log in again.

That’s it, an entire login system. Of course this is just meant to give you the idea of the steps and should by no means be used in a real-world system as is. However you should have a firm understanding of how a basic login system works using PHP/MySQL and a little bit of HTML and CSS. As always if you have any questions/concerns feel free to leave a comment and I’ll get back to you asap.


Dec 10 2009

JQuery Part 4 – Intro to CSS Manipulation

JQuery is often used in websites to manipulate the CSS attributes of an HTML element upon the users request. For example, if a user wants to increase the size of the font immediately so that they can read your page, or you may just want to change up the CSS on the fly to make your page stand out a little more. All these things can be done in JQuery using the css() function and css manipulation techniques. Let’s get started by creating a basic page with a link and a paragraph with some links in it like so…

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html>
	<head>
		<script src="lib/jquery/jquery-1.3.2.js" type="text/javascript"></script>
 
		<title>JQuery CSS Manipulation</title>
 
	</head>
	<body>
		<a href="#">Click Me</a>
 
		<br>
			<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam sit amet elit vitae arcu interdum ullamcorper. Nullam ultrices, nisi quis scelerisque convallis, <a href="#">augue neque</a> tempor enim, et mattis justo nibh eu elit. Quisque ultrices gravida pede. Mauris accumsan vulputate tellus. Phasellus condimentum bibendum dolor. Mauris sed ipsum. Phasellus in diam. Nam sapien ligula, consectetuer id, <a href="#">hendrerit</a> in, cursus sed, leo. Nam tincidunt rhoncus urna. Aliquam id massa ut nibh bibendum imperdiet. Curabitur neque mauris, porta vel, lacinia quis, placerat ultrices, orci.</p>
 
	</body>
</html>

As you can see it’s a basic HTML page that references the JQuery script. We have also added a link that says “click me” along with a paragraph of lorem ipsum text with some links in it. Alright, now onto creating the CSS for the page. For this example I will be putting the CSS in the header but if you want to put it in an external file by all means go ahead and reference it in the header.

<style type="text/css">		
p a
{
	color: red;
}
</style>

As you can see, I just added an attribute to make all the links within the paragraph tags initially turn up as red. You can add as many CSS elements here as you would like to style the links however you like but for the purpose of this demonstration you will just need the color red as an attribute. Next let’s add the JQuery and introduce the .css() function.

<script type="text/javascript">
	$(function()
	{
		$('a').click(function()
		{
			$('p a').css('color', 'blue');
		});
	});
</script>

As you can see the JQuery code is pretty straight forward for what we’re doing. Basically we’re starting out by checking the DOM to make sure that the file is ready to be manipulated. Then, we perform a click function anytime an anchor tag is pressed. Inside of that click function is where we actually manipulate the CSS and change the color of the anchor tags to blue instead of red like we originally set. The css() function accepts two parameters that we’ll be using. The first is the attribute that you would like to change and the second is the attribute that you want to change it to. So for our example, the attribute is the color and we’re going to change it to blue. If of course you want to change the color of the link that was originally pressed instead of every link inside the paragraph tags you could use the “this” function instead of specifying a specific tag.

That’s the basics to CSS manipulation using JQuery, of course the example shown here is only a very basic example and can be greatly expanded upon. This is what the final code should look like…

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html>
	<head>
		<script src="lib/jquery/jquery-1.3.2.js" type="text/javascript"></script>
 
		<title>JQuery Test</title>
 
		<style type="text/css">		
			p a
			{
				color: red;
			}
		</style>
 
		<script type="text/javascript">
			$(function()
			{
				$('a').click(function()
				{
					$('p a').css('color', 'blue');
				});
			});
		</script>
	</head>
	<body>
		<div id="box"></div>
		<a href="#">Click Me</a>
		<br />
			<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam sit amet elit vitae arcu interdum ullamcorper. Nullam ultrices, nisi quis scelerisque convallis, <a href="#">augue neque</a> tempor enim, et mattis justo nibh eu elit. Quisque ultrices gravida pede. Mauris accumsan vulputate tellus. Phasellus condimentum bibendum dolor. Mauris sed ipsum. Phasellus in diam. Nam sapien ligula, consectetuer id, <a href="#">hendrerit</a> in, cursus sed, leo. Nam tincidunt rhoncus urna. Aliquam id massa ut nibh bibendum imperdiet. Curabitur neque mauris, porta vel, lacinia quis, placerat ultrices, orci.</p>
	</body>
</html>

Oct 31 2009

JQuery Part 3 – Intro to Functions

This is part 3 in a series of JQuery tutorials. I strongly recommend at least reading Part 1 before continuing with this tutorial. Part 2 is optional but would also be a great background before we get started. As for this tutorial, I will be going over creating an executing functions to make your code more efficient.

Often when writing JQuery code(especially for plugins) there are times when you need to execute the same block of code multiple times. Instead of writing them all out individually and making our code really terrible process wise, we can use functions and function calls to call the same block of code over and over.

Creating Functions

You can create a function in 2 different places. The first is in the same script tags, but not inside the document ready function. Or second, you could create a brand new script file and then reference that script file in your header. Inside this script file you could create your method and it would be able to be accessed by the main file.

To create a function, the syntax looks like this…

function nameOfFunction()
{
	//your code here
}

This tells the browser that there is a function called nameOfFunction that is not being passed any parameters. Passing parameters is something I’ll get into a little bit later. Now say you wanted to alert the user with a javascript pop-up box every time this function was run. You could add some code into the function to allow a dialog box to appear like so.

function nameOfFunction()
{
	alert("We are now alerting the user!");
}

Executing Functions

Now that we have a function created, we need to somehow call that function to execute. That’s where our javascript method calls come in. Let’s say we wanted to execute the previous function. The code would look like this.

$(document).ready(function(){
	nameOfFunction();
});

Of course this would call the function immediately after the page was ready. You can use a function call in JQuery in any function. So if you wanted to add it inside of a .click function you could do that as well. That’s all you need to do to execute functions in JQuery.

Passing Arguments to Functions

Let’s say you wanted a function to work with a piece of data from a form, but you didn’t want the function to retrieve that piece of data inside the function. You can use a piece of code called an argument to pass to the function. This allows you to pass values to a function so they can be used. To create a function with an argument then all you need to do is add the argument into the brackets in the function header. It looks like this.

function nameOfFunction(argument)
{
	//your code here
}

Now obviously since we have that argument in the argument ready to do something with it, we may also want to return a value back to the original function so that we can maybe display the result of a calculation or something like that. If we want to return a value all we have to do is insert a return value into our function.

function nameOfFunction(argument)
{
	var total = 10 + argument;
 
	return total;
}

This function will now accept a value, add 10 to that value and return it to the original function call. This way if we need to manipulate some data quite a few times, we could use a function to do that display the result.

Function Calls with Arguments

Now that we have a function made that’s accepting an argument and returning a value, we can use a function call and pass an argument to the function so it can do the calculation and we can then display the result. The function call looks something like this.

$(document).ready(function(){
	alert("The total is = " + nameOfFunction(10);
});

In our JQuery ready function we are now just displaying an alert. Inside the alert we are actually making the function call and passing a value of 10 to our function. The function is then going to add 10 to our passed argument and return a value of 20. The alert therefore is going to display – “The total is = 20″. And that’s all for basic functions and function calls.