Aug 22, 2011

How To Make A Shoutbox Using PHP & MYSQL | Create A Shout Box Using PHP MYSQL | Make A Simple Shout Box

First of all, let me explain you what is a shoutbox.

A Shoutbox is nothing but a chat program, where anyone can chat with any anonymous user.
You can read more about shoutbox at this link : http://en.wikipedia.org/wiki/Shoutbox

So lets make a shoutbox.

We will make this shoutbox in basic php and mysql.

First you need to make a database where you will store this chats, so from phpmyadmin you can create a databse.
Next we will add a table, so in sql query window, just paste the below code:

[php]
CREATE TABLE `shoutbox` (
`id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`email` VARCHAR(60) NOT NULL,
`post` TEXT NOT NULL,
`ipaddress` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`)
);
[/php]

PhpMyAdmin

Here we made a table with name, email, id and ipaddress fields, where all values is must, id is set to auto increement and we are using IP address to track the user.

Next we will create a file named as db.php, where we make our MYSQL Connection, so just paste the below code in your file db.php

[php][/php]


<?php
$host = 'localhost'; //Normally localhost
$username = 'root'; //Username which is added to your database, root is default
$password = ''; //Password for your user, for root password is null
$database = 'shoutbox'; //your database name
?>

[php][/php]

Now we will create our actual shoutbox code file, make a file and name it to index.php, and add following code in it

[html]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shoutbox From WebsTutorial</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="container">

<h1>Shoutbox</h1>
<h5><a href="http://www.webstutorial.com" title="WebsTutorial">WebsTutorial</a></h5>

<div id="boxtop"></div>
<div id="content">

<?php
$self = $_SERVER['PHP_SELF']; //the $self variable equals this file
$ipaddress = ("$_SERVER[REMOTE_ADDR]"); //the $ipaddress var equals users IP
include ('db.php'); // for db details

// defines a $connect variable, which when used
// will attempt to connect to the databse using
// details provided in config.php
// if it fails, will display error - or die();
$connect = mysql_connect($host,$username,$password) or die('<p>Unable to connect to the database server at this time.</p>');

// connect to database using details provided
// and uses the $connect variable above
// if it fails, will return error - or die();
mysql_select_db($database,$connect) or die('<p>Unable to connect to the database at this time.</p>');

// checks the POST to see if something has been submitted
if(isset($_POST['send'])) {
// are any of the fields empty? the || means 'or'
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['post'])) {
echo('<p>You did not fill in a required field.</p>');
} else {

// if there are no empty fields, insert into the database:

// escape special characters to stop xss and sql injecting
// we take the 'name' and 'post' parts from the POST
// and run it through htmlspecialchars()
// this stops users sending HTML code, as it could be malicious
//
// also runs through mysql_real_escape_string()
// stops users sending SQL code, which could be used to access the db
$name = htmlspecialchars(mysql_real_escape_string($_POST['name']));
$email = htmlspecialchars(mysql_real_escape_string($_POST['email']));
$post = htmlspecialchars(mysql_real_escape_string($_POST['post']));

// this is our SQL string to insert shouts into db
$sql = "INSERT INTO shouts SET name='$name', email='$email', post='$post', ipaddress='$ipaddress';";

// we run the SQL string now
// if it succeeds, display message
if (@mysql_query($sql)) {
echo('<p>Thanks for shouting!</p>');
} else {
// if it errors, send message
echo('<p>There was an unexpected error when posting your shout.</p>');
}
}
}

// now we retrieve the 8 latest shouts from the db
$query = "SELECT * FROM shouts ORDER BY `id` DESC LIMIT 8;";

// run the query. if it fails, display error
$result = @mysql_query("$query") or die('<p>There was an unexpected error grabbing shouts from the database.</p>');

?><ul><?php
// while we still have rows from the db, display them
while ($row = mysql_fetch_array($result)) {

$ename = stripslashes($row['name']);
$eemail = stripslashes($row['email']);
$epost = stripslashes($row['post']);

// Woop! We can use Gravatars aswell!!
$grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";

echo('<li><div><p>'.$ename.'</p><img src="'.$grav_url.'" alt="Gravatar" /></div><div><p style="padding:20px 0 0 0;">'.$epost.'</p></div></li>');

}
?></ul>

<!-- at the bottom of the page, we display our comment form -->
<form action="<?php $self ?>" method="post">
<h2>Shout!</h2>
<div><label for="name"><p>Name:</p></label><input name="name" type="text" cols="20" /></div>
<div><label for="email"><p>Email:</p></label><input name="email" type="text" cols="20" /></div>
<textarea name="post" rows="5" cols="40"></textarea>
<input name="send" type="hidden" />
<p><input type="submit" value="send" /></p>
</form>

</div><!--/content-->
<div id="boxbot"></div>

</div><!--/container-->

</body>
</html>
[/html]

Explanation:
OK, in this file first we get the IP address of the person and open the db connection by including our first created db.php file.

Then we pass a check condition to check the emptiness in the textboxes. And we also store the values in respective variables, here while storing them we are using php functions htmlspecialchars, to avoid html characters and mysql_real_escape_string to avoid sql statements, this two are very important in terms of security else anyone will pass html and sql codes and pamper the database or server.

After storing them, we finally code the insert query and echoes a custom message of successful execution.

Wait a minute, this is not the end, now we will also have to display the recently 8 shouts, so we fire a select query and  store the array in a variable.

And finally in a while loop we echo the email, name and the shout message.

Woila, done, but arghhhhhhhhhhh without CSS, its like image without color, so make a file style.css and add the following css code in it.

[css]
/* Shoutbox PHP tutorial from WebsTutorial */

* {
margin: 0;
padding: 0;
}

body {
background: #323f66 top center url("images/back.png") no-repeat;
color: #ffffff;
font-family: Helvetica, Arial, Verdana, sans-serif;
}

h1 {
font-size: 3.5em;
letter-spacing: -1px;
background: url("images/shoutbox.png") no-repeat;
width: 303px;
margin: 0 auto;
text-indent: -9999em;
color: #33ccff;
}

h2 {
font-size: 2em;
letter-spacing: -1px;
background: url("images/shout.png") no-repeat;
width: 119px;
text-indent: -9999em;
color: #33ccff;
clear: both;
margin: 15px 0;
}

h5 a:link, h5 a:visited {
color: #ffffff;
text-decoration: none;
}

h5 a:hover, h5 a:active, h5 a:focus {
border-bottom: 1px solid #fff;
}

p {
font-size: 0.9em;
line-height: 1.3em;
font-family: Lucida Sans Unicode, Helvetica, Arial, Verdana, sans-serif;
}

p.error {
background-color: #603131;
border: 1px solid #5c2d2d;
width: 260px;
padding: 10px;
margin-bottom: 15px;
}

p.success {
background-color: #313d60;
border: 1px solid #2d395c;
width: 260px;
padding: 10px;
margin-bottom: 15px;
}

#container {
width: 664px;
margin: 20px auto;
text-align: center;
}

#boxtop {
margin: 30px auto 0px;
background: url("images/top.png") no-repeat;
width: 663px;
height: 23px;
}

#boxbot {
margin: 0px auto 30px;
background: url("images/bot.png") no-repeat;
width: 664px;
height: 25px;
}

#content {
margin: 0 auto;
width: 664px;
text-align: left;
background: url("images/bg.png") repeat-y;
padding: 15px 35px;
}

#content ul {
margin-left: 0;
margin-bottom: 15px;
}

#content ul li {
list-style: none;
clear: both;
padding-top: 30px;
}

#content ul li:first-child {
padding-top:0;
}

.meta {
width: 85px;
text-align: left;
float: left;
min-height: 110px;
font-weight: bold;
}

.meta img {
padding: 5px;
background-color: #313d60;
}

.meta p {
font-size: 0.8em;
}

.shout {
width: 500px;
float: left;
margin-left: 15px;
min-height: 110px;
padding-top: 5px;
}

form {
clear: both;
margin-top: 135px !important;
}

.fname, .femail {
width: 222px;
float: left;
}

form p {
font-weight: bold;
margin-bottom: 3px;
}

form textarea {
width: 365px;
overflow: hidden; /* removes vertical scrollbar in IE */
}

form input, form textarea {
background-color: #313d60;
border: 1px solid #2d395c;
color: #ffffff;
padding: 5px;
font-family: Lucida Sans Unicode, Helvetica, Arial, Verdana, sans-serif;
margin-bottom: 10px;
}

ul li{
border: 1px solid #2A3556;
float: left;
margin-right: 10px;
padding: 10px;
position: relative;
right: 12px;
margin-bottom:5px;
}
[/css]

This was your last step by styling the shoutbox.
Feel free to ask any questions if you didn't understand any point or if I missed something

Final Layout:

WebsTutorial Shoutbox

download

Aug 16, 2011

Wordpress JQuery Slide Show | How To Add A Wordpress Jquery Slide Show | Wordpress JQuery Nivo Slider

So finally you reached here in search of adding a slide show in your wordpress site. Why to use flash if jquery can help you.


In this tutorial I am using the NIVO SLIDER.


So lets get started, just follow these simple steps:-


First mainly decide where you want to display this slide show in your blog or site? For this example we will use this slide show in the header, as an image banner.


So first you need to add some files in your theme, just that they don't get mixed up with your other files, we will create a folder in your theme directory, name it as slider, in that folder we will place some css files and images.(Download)
So after completion, your folder structure should be like the below image.
Slider folder


After this you need to add some js files in your folder js, if you don't have any folder named as js, then you can create one and place files into it.(Download)


The two js, files are:




  • jquery.nivo.slider.pack.js

  • jquery-1.6.1.min.js


Then you need to open your theme's header.php file, and paste the following code before wp_head();



[html]
<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/slider/default.css" type="text/css" media="screen" />
<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/slider/nivo-slider.css" type="text/css" media="screen" />
<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/slider/style5.css" type="text/css" media="screen" />

<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery.nivo.slider.pack.js"></script>
<script type="text/javascript">
jQuery(window).load(function() {
jQuery('#slider').nivoSlider();
});
</script>
[/html]

In the above code we are just telling the wordpress theme to pick the necessary style sheets, js files and JQuery.


So here we complete major part of the tutorial, now finally we will just paste some html code to appropriate section in the site.



As in this tutorial I am making a header banner so I ll paste this code in header.php.

[html]
<div class="slider-wrapper theme-default">
<div class="ribbon"></div>
<div id="slider">
<img src="<?php bloginfo('template_directory'); ?>/images/header1.jpg" alt=""/>
<img src="<?php bloginfo('template_directory'); ?>/images/header2.jpg" alt=""/>
<img src="<?php bloginfo('template_directory'); ?>/images/header3.jpg" alt=""/>
<img src="<?php bloginfo('template_directory'); ?>/images/header4.jpg" alt=""/>
<img src="<?php bloginfo('template_directory'); ?>/images/header5.jpg" alt=""/>
</div>
</div>
[/html]
Just in img src tag give your appropriate images location, in this tutorial I have kept the images into images folder of my wordpress theme directory.

You can paste the JQuery code in footer.php file just to avoid the conflict of javascripts.


In This tutorial I am using the header banner size, that is 995X288, so if your slider goes off screen, then you can customize our css files.
This Slider is IE7 compliant.


download

Aug 11, 2011

How To Make A GAME In HTML 5 | How To Build A Game With HTML 5

download



Final Output:


Running Ball

HTML 5 is growing at the lightning speed, none of the languages in web development has grew up in this speed. Today we are going to make a simple game in HTML 5 by using Box2D and HTML 5 Canvas.


But before that, the question is



What is BOX2D?
Box2D is an open source and popular engine that simulates 2D physics for making games and applications. Primarily written in C++, it has been converted to numerous languages by community contributors.

This tutorial is divided into 5 simple steps, so lets get started



STEP - 1 Folder Structure


First of all we need to download the box2d engine for our html 5, you can download it from here. Next we create the file and folder structure. Just follow the image of file folder structure and copy paste them in respective places.
Folder Structure


After the setup of files, we will add necessary files to the html file that is index.html



[html]
<!--[if IE]><script src="lib/excanvas.js"></script><![endif]--><script type="text/javascript" src="lib/prototype-1.6.0.2.js"></script>
<!-- box2djs -->
<script type="text/javascript" src="js/box2d/common/b2Settings.js"></script><script type="text/javascript" src="js/box2d/common/math/b2Vec2.js"></script>
<script type="text/javascript" src="js/box2d/common/math/b2Mat22.js"></script><script type="text/javascript" src="js/box2d/common/math/b2Math.js"></script>
<script type="text/javascript" src="js/box2d/collision/b2AABB.js"></script><script type="text/javascript" src="js/box2d/collision/b2Bound.js"></script>
<script type="text/javascript" src="js/box2d/collision/b2BoundValues.js"></script><script type="text/javascript" src="js/box2d/collision/b2Pair.js"></script>
<script type="text/javascript" src="js/box2d/collision/b2PairCallback.js"></script><script type="text/javascript" src="js/box2d/collision/b2BufferedPair.js"></script>
<script type="text/javascript" src="js/box2d/collision/b2PairManager.js"></script><script type="text/javascript" src="js/box2d/collision/b2BroadPhase.js"></script>
<script type="text/javascript" src="js/box2d/collision/b2Collision.js"></script><script type="text/javascript" src="js/box2d/collision/Features.js"></script>
<script type="text/javascript" src="js/box2d/collision/b2ContactID.js"></script><script type="text/javascript" src="js/box2d/collision/b2ContactPoint.js"></script>
<script type="text/javascript" src="js/box2d/collision/b2Distance.js"></script><script type="text/javascript" src="js/box2d/collision/b2Manifold.js"></script>
<script type="text/javascript" src="js/box2d/collision/b2OBB.js"></script><script type="text/javascript" src="js/box2d/collision/b2Proxy.js"></script>
<script type="text/javascript" src="js/box2d/collision/ClipVertex.js"></script><script type="text/javascript" src="js/box2d/collision/shapes/b2Shape.js"></script>
<script type="text/javascript" src="js/box2d/collision/shapes/b2ShapeDef.js"></script><script type="text/javascript" src="js/box2d/collision/shapes/b2BoxDef.js"></script>
<script type="text/javascript" src="js/box2d/collision/shapes/b2CircleDef.js"></script><script type="text/javascript" src="js/box2d/collision/shapes/b2CircleShape.js"></script>
<script type="text/javascript" src="js/box2d/collision/shapes/b2MassData.js"></script><script type="text/javascript" src="js/box2d/collision/shapes/b2PolyDef.js"></script>
<script type="text/javascript" src="js/box2d/collision/shapes/b2PolyShape.js"></script><script type="text/javascript" src="js/box2d/dynamics/b2Body.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/b2BodyDef.js"></script><script type="text/javascript" src="js/box2d/dynamics/b2CollisionFilter.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/b2Island.js"></script><script type="text/javascript" src="js/box2d/dynamics/b2TimeStep.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/contacts/b2ContactNode.js"></script><script type="text/javascript" src="js/box2d/dynamics/contacts/b2Contact.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/contacts/b2ContactConstraint.js"></script><script type="text/javascript" src="js/box2d/dynamics/contacts/b2ContactConstraintPoint.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/contacts/b2ContactRegister.js"></script><script type="text/javascript" src="js/box2d/dynamics/contacts/b2ContactSolver.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/contacts/b2CircleContact.js"></script><script type="text/javascript" src="js/box2d/dynamics/contacts/b2Conservative.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/contacts/b2NullContact.js"></script><script type="text/javascript" src="js/box2d/dynamics/contacts/b2PolyAndCircleContact.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/contacts/b2PolyContact.js"></script><script type="text/javascript" src="js/box2d/dynamics/b2ContactManager.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/b2World.js"></script><script type="text/javascript" src="js/box2d/dynamics/b2WorldListener.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/joints/b2JointNode.js"></script><script type="text/javascript" src="js/box2d/dynamics/joints/b2Joint.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/joints/b2JointDef.js"></script><script type="text/javascript" src="js/box2d/dynamics/joints/b2DistanceJoint.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/joints/b2DistanceJointDef.js"></script><script type="text/javascript" src="js/box2d/dynamics/joints/b2Jacobian.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/joints/b2GearJoint.js"></script><script type="text/javascript" src="js/box2d/dynamics/joints/b2GearJointDef.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/joints/b2MouseJoint.js"></script><script type="text/javascript" src="js/box2d/dynamics/joints/b2MouseJointDef.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/joints/b2PrismaticJoint.js"></script><script type="text/javascript" src="js/box2d/dynamics/joints/b2PrismaticJointDef.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/joints/b2PulleyJoint.js"></script><script type="text/javascript" src="js/box2d/dynamics/joints/b2PulleyJointDef.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/joints/b2RevoluteJoint.js"></script><script type="text/javascript" src="js/box2d/dynamics/joints/b2RevoluteJointDef.js"></script>
[/html]

Next, we will create two more scripts file inside the /js/ folder directory, named as  "box2dutils.js" and "game.js" respectively




  • box2dutils.js – This files is a copy and paste from some other online demos that come with box2dlib, and it is very important for drawing functions.

  • game.js – By the name it will be easy to recognize, it the actual game, where platform, keyboard input etc functions are set.


Copy paste the following code in "box2dutils.js" file



[html]
function drawWorld(world, context) {
for (var j = world.m_jointList; j; j = j.m_next) {
drawJoint(j, context);
}
for (var b = world.m_bodyList; b; b = b.m_next) {
for (var s = b.GetShapeList(); s != null; s = s.GetNext()) {
drawShape(s, context);
}
}
}
function drawJoint(joint, context) {
var b1 = joint.m_body1;
var b2 = joint.m_body2;
var x1 = b1.m_position;
var x2 = b2.m_position;
var p1 = joint.GetAnchor1();
var p2 = joint.GetAnchor2();
context.strokeStyle = '#00eeee';
context.beginPath();
switch (joint.m_type) {
case b2Joint.e_distanceJoint:
context.moveTo(p1.x, p1.y);
context.lineTo(p2.x, p2.y);
break;

case b2Joint.e_pulleyJoint:
// TODO
break;

default:
if (b1 == world.m_groundBody) {
context.moveTo(p1.x, p1.y);
context.lineTo(x2.x, x2.y);
}
else if (b2 == world.m_groundBody) {
context.moveTo(p1.x, p1.y);
context.lineTo(x1.x, x1.y);
}
else {
context.moveTo(x1.x, x1.y);
context.lineTo(p1.x, p1.y);
context.lineTo(x2.x, x2.y);
context.lineTo(p2.x, p2.y);
}
break;
}
context.stroke();
}
function drawShape(shape, context) {
context.strokeStyle = '#000000';
context.beginPath();
switch (shape.m_type) {
case b2Shape.e_circleShape:
{
var circle = shape;
var pos = circle.m_position;
var r = circle.m_radius;
var segments = 16.0;
var theta = 0.0;
var dtheta = 2.0 * Math.PI / segments;
// draw circle
context.moveTo(pos.x + r, pos.y);
for (var i = 0; i < segments; i++) {
var d = new b2Vec2(r * Math.cos(theta), r * Math.sin(theta));
var v = b2Math.AddVV(pos, d);
context.lineTo(v.x, v.y);
theta += dtheta;
}
context.lineTo(pos.x + r, pos.y);

// draw radius
context.moveTo(pos.x, pos.y);
var ax = circle.m_R.col1;
var pos2 = new b2Vec2(pos.x + r * ax.x, pos.y + r * ax.y);
context.lineTo(pos2.x, pos2.y);
}
break;
case b2Shape.e_polyShape:
{
var poly = shape;
var tV = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[0]));
context.moveTo(tV.x, tV.y);
for (var i = 0; i < poly.m_vertexCount; i++) {
var v = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[i]));
context.lineTo(v.x, v.y);
}
context.lineTo(tV.x, tV.y);
}
break;
}
context.stroke();
}

function createWorld() {
var worldAABB = new b2AABB();
worldAABB.minVertex.Set(-1000, -1000);
worldAABB.maxVertex.Set(1000, 1000);
var gravity = new b2Vec2(0, 300);
var doSleep = true;
var world = new b2World(worldAABB, gravity, doSleep);
return world;
}

function createGround(world) {
var groundSd = new b2BoxDef();
groundSd.extents.Set(1000, 50);
groundSd.restitution = 0.2;
var groundBd = new b2BodyDef();
groundBd.AddShape(groundSd);
groundBd.position.Set(-500, 340);
return world.CreateBody(groundBd)
}

function createBall(world, x, y) {
var ballSd = new b2CircleDef();
ballSd.density = 1.0;
ballSd.radius = 20;
ballSd.restitution = 1.0;
ballSd.friction = 0;
var ballBd = new b2BodyDef();
ballBd.AddShape(ballSd);
ballBd.position.Set(x,y);
return world.CreateBody(ballBd);
}

function createBox(world, x, y, width, height, fixed, userData) {
if (typeof(fixed) == 'undefined') fixed = true;
var boxSd = new b2BoxDef();
if (!fixed) boxSd.density = 1.0;

boxSd.userData = userData;

boxSd.extents.Set(width, height);
var boxBd = new b2BodyDef();
boxBd.AddShape(boxSd);
boxBd.position.Set(x,y);
return world.CreateBody(boxBd)
}
[/html]

Don't worry I ll explain the code further.


Now we move on to our next step



Step 2 - Game Development


Open the index.html file, which we created in the first step, after adding the head part, insert the canvas code between the body tag



[html]<canvas id="game" width="600" height="400"></canvas>[/html]

Next we have to add the reference of the two javascripts file which we created just now. So in index.html, within the head tag, add the following code in it.



[html]
<script type="text/javascript" src="js/box2dutils.js"></script><script type="text/javascript" src="js/game.js"></script>
[/html]

Now lets start developing our game, so open game.js file and add the following code in it.



[html]
// some variables that we gonna use in this demo
var initId = 0;
var player = function(){
this.object = null;
this.canJump = false;
};
var world;
var ctx;
var canvasWidth;
var canvasHeight;
var keys = [];

// HTML5 onLoad event
Event.observe(window, 'load', function() {
world = createWorld(); // box2DWorld
ctx = $('game').getContext('2d'); // 2
var canvasElm = $('game');
canvasWidth = parseInt(canvasElm.width);
canvasHeight = parseInt(canvasElm.height);
initGame(); // 3
step(); // 4

// 5
window.addEventListener('keydown',handleKeyDown,true);
window.addEventListener('keyup',handleKeyUp,true);
});
[/html]

OK, now its time for explanation of code now


BOX2DWorld is the available class from the core of box2d.Its major and simple function is to combine everything into one class. In this box2DWorld, we have the bodies definition and collisions manager of our game.


Now open the game.js and box2dutils.js and search for the function createWorld() in box2dutils.js file.



[html]
function createWorld() {
// here we create our world settings for collisions
var worldAABB = new b2AABB();
worldAABB.minVertex.Set(-1000, -1000);
worldAABB.maxVertex.Set(1000, 1000);
// set gravity vector
var gravity = new b2Vec2(0, 300);
var doSleep = true;
// init our world and return its value
var world = new b2World(worldAABB, gravity, doSleep);
return world;
}
[/html]

Its really simple to make such box2DWorld


Now again back to game.js file.


Now copy paste the following code in game.js file



[html]
function initGame(){
// create 2 big platforms
createBox(world, 3, 230, 60, 180, true, 'ground');
createBox(world, 560, 360, 50, 50, true, 'ground');

// create small platforms
for (var i = 0; i < 5; i++){
createBox(world, 150+(80*i), 360, 5, 40+(i*15), true, 'ground');
}

// create player ball
var ballSd = new b2CircleDef();
ballSd.density = 0.1;
ballSd.radius = 12;
ballSd.restitution = 0.5;
ballSd.friction = 1;
ballSd.userData = 'player';
var ballBd = new b2BodyDef();
ballBd.linearDamping = .03;
ballBd.allowSleep = false;
ballBd.AddShape(ballSd);
ballBd.position.Set(20,0);
player.object = world.CreateBody(ballBd);

}

Inside <code>box2dutils.js</code>, we've created a function, called <code>createBox</code>. This creates a static rectangle body.

function createBox(world, x, y, width, height, fixed, userData) {
if (typeof(fixed) == 'undefined') fixed = true;
//1
var boxSd = new b2BoxDef();
if (!fixed) boxSd.density = 1.0;
//2
boxSd.userData = userData;
//3
boxSd.extents.Set(width, height);

//4
var boxBd = new b2BodyDef();
boxBd.AddShape(boxSd);
//5
boxBd.position.Set(x,y);
//6
return world.CreateBody(boxBd)
}
[/html]

A Box2DBody has some unique characteristics:




  • It can be static (not affected by collisions impacts), kinematic (it isn't affected by collisions, but it can be moved by your mouse, for example), or dynamic (interacts with everything)

  • Must have a shape definition, and should indicate how the object appears

  • May have more than one fixture, which indicates how the object will interact with collisions

  • Its position is set by the center of your object, not the left top edge as many other engines do.


Reviewing the above code:



  1. Here we are creating a shape, which can be a square or rectangle or any other geometry shape. And also we setup the density(the actual movement of the object)

  2. We setup the userData, usually we setup graphics objects here, but for this game, we just setup strings that will be the identifier of the type of the object for collisions.

  3. Setup half of the size of our box.

  4. We create the body definition, and add to it the box shape definition.

  5. Setup the position.

  6. Create the body in the world and return its value.


Creating The Player Object


Paste the following code in game.js file



[html]
var ballSd = new b2CircleDef();
ballSd.density = 0.1;
ballSd.radius = 12;
ballSd.restitution = 0.5;
ballSd.friction = 1;
ballSd.userData = 'player';
var ballBd = new b2BodyDef();
ballBd.linearDamping = .03;
ballBd.allowSleep = false;
ballBd.AddShape(ballSd);
ballBd.position.Set(20,0);
player.object = world.CreateBody(ballBd);
[/html]

So now we have created body.
We have used simple steps




  1. Created Shape, Fixture and Sensor Definition.

  2. Created Body Definition

  3. Added body into the shape

  4. Created body in the world.


Simple isn't it?


So Now if we run our code, it will give us a blank white screen.


Don't panic, till now we have just setup Box2, and always remember



Box2D doesn't render; it only calculates physics.

Step 3 - Rendering Time


Now we will render the box2dworld.


Open game.js file and add the following code in it:



[html]
function step() {

var stepping = false;
var timeStep = 1.0/60;
var iteration = 1;
// 1
world.Step(timeStep, iteration);
// 2
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
drawWorld(world, ctx);
// 3
setTimeout('step()', 10);
}
[/html]

In the above code we have intructed box2dworld to achieve the following things




  1. To perform physics calculations.

  2. To clear the canvas screen and draw again on it.

  3. And to run the step() function in every 10 milliseconds.


Now if you run the code, you will see the canvas with a running ball.


Running Ball


drawWorld in box2dutils.js


Open box2dutils.js file and add the following code in it.



[html]
function drawWorld(world, context) {
for (var j = world.m_jointList; j; j = j.m_next) {
drawJoint(j, context);
}
for (var b = world.m_bodyList; b; b = b.m_next) {
for (var s = b.GetShapeList(); s != null; s = s.GetNext()) {
drawShape(s, context);
}
}
}
[/html]

The above written function is a debug function which will draw our world into the canvas, by using the graphics API provided by HTML5's Canvas API.


The very first loop will draw all joints.


The second loop will draw all bodies.



[html]
function drawShape(shape, context) {
context.strokeStyle = '#000000';
context.beginPath();
switch (shape.m_type) {
case b2Shape.e_circleShape:
{
var circle = shape;
var pos = circle.m_position;
var r = circle.m_radius;
var segments = 16.0;
var theta = 0.0;
var dtheta = 2.0 * Math.PI / segments;
// draw circle
context.moveTo(pos.x + r, pos.y);
for (var i = 0; i < segments; i++) {
var d = new b2Vec2(r * Math.cos(theta), r * Math.sin(theta));
var v = b2Math.AddVV(pos, d);
context.lineTo(v.x, v.y);
theta += dtheta;
}
context.lineTo(pos.x + r, pos.y);

// draw radius
context.moveTo(pos.x, pos.y);
var ax = circle.m_R.col1;
var pos2 = new b2Vec2(pos.x + r * ax.x, pos.y + r * ax.y);
context.lineTo(pos2.x, pos2.y);
}
break;
case b2Shape.e_polyShape:
{
var poly = shape;
var tV = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[0]));
context.moveTo(tV.x, tV.y);
for (var i = 0; i < poly.m_vertexCount; i++) {
var v = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[i]));
context.lineTo(v.x, v.y);
}
context.lineTo(tV.x, tV.y);
}
break;
}
context.stroke();
}
[/html]

Here we're looping through every vertices of the object and drawing it with lines.



Step 4 - Interactivity


In this step we will instruct the game by our keyboard events.
Add the following code to game.js file



[html]
function handleKeyDown(evt){
keys[evt.keyCode] = true;
}

function handleKeyUp(evt){
keys[evt.keyCode] = false;
}

// disable vertical scrolling from arrows</pre>
<img src="http://net.tutsplus.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" />
<pre>
document.onkeydown=function(){return event.keyCode!=38 && event.keyCode!=40}
[/html]

With the help of an array we are handling the UpKey and the DownKey event. With document.onkeydown, we disable the browser's native vertical scrolling function for up and down arrows.
If you have played a html5 game and jumped during the game, the game goes off screen, but in our game, it won't



[html]handleInteractions(); [/html]

And outside, declare the function:



[html]
function handleInteractions(){
// up arrow
// 1
var collision = world.m_contactList;
player.canJump = false;
if (collision != null){
if (collision.GetShape1().GetUserData() == 'player' || collision.GetShape2().GetUserData() == 'player'){
if ((collision.GetShape1().GetUserData() == 'ground' || collision.GetShape2().GetUserData() == 'ground')){
var playerObj = (collision.GetShape1().GetUserData() == 'player' ? collision.GetShape1().GetPosition() :  collision.GetShape2().GetPosition());
var groundObj = (collision.GetShape1().GetUserData() == 'ground' ? collision.GetShape1().GetPosition() :  collision.GetShape2().GetPosition());
if (playerObj.y < groundObj.y){
player.canJump = true;
}
}
}
}
// 2
var vel = player.object.GetLinearVelocity();
// 3
if (keys[38] && player.canJump){
vel.y = -150;
}

// 4
// left/right arrows
if (keys[37]){
vel.x = -60;
}
else if (keys[39]){
vel.x = 60;
}

// 5
player.object.SetLinearVelocity(vel);
}
[/html]

The most complicated code in the above function is the first one, where we are checking the collision and writing some if else condition to determine the shape one or shape two.


On the second commented line (2), we retrieve the LinearVelocity of the player.


The third and forth commented sections verify if arrows are being pressed, and adjust the velocity vector(speed), accordingly.


In the fifth section, we setup the player with the new velocity vector.


Till now interactions are done, but if you run it now, it will only keep on jumping.



Step 5 - "You Win" Message


Add the code below to the beginning of your LinearVelocity function:



[html]
if (player.object.GetCenterPosition().y > canvasHeight){
player.object.SetCenterPosition(new b2Vec2(20,0),0)
}
else if (player.object.GetCenterPosition().x > canvasWidth-50){
showWin();
return;
}
[/html]

In this the first condition determines that if the player falls then it should be placed agin to the starting point.


The second condition is used to state if the player is in the final platform then display the winning function, which is below



[html]
function showWin(){
ctx.fillStyle = '#000';
ctx.font = '30px verdana';
ctx.textBaseline = 'top';
ctx.fillText('Yes! you made it!', 30, 0);
ctx.fillText('Thank You, www.webstutorial.com', 30, 30);
ctx.fillText('HTML 5 Rocks', 30, 60);
}
[/html]

And that's it, you have just made your own simple adventure game in HTML5.


Credit:NetTuts

download

Aug 10, 2011

What Is Photoshop?

Over the past 21 years, Photoshop has meant many different things to many different people. Whether it is used to tell a story, put ideas into motion, imagine something new, visualize science or any of its other many uses – Photoshop has touched popular culture, business and artistry around the world.

In simple terms, Photoshop is a Professional Image / Graphics editing software package, developed & published by Adobe Systems Incorporated, that can be used by experts and novices alike.

HISTORY:

It all Started In 1987 where Thomas Knoll, a PhD student at the University of Michigan began writing a program, called Display, on his Macintosh Plus to display grayscale images on a monochrome display. His brother John Knoll convinced Thomas to turn it into a fully-fledged Image Editing Program. They renamed it ImagePro. Later that same year, Thomas renamed his program Photoshop and worked out a small short-term deal with scanner manufacturer Barneyscan to distribute copies of the program with a slide scanner. They were successful in shipping 200 copies.

After a successful demonstration Adobe decided to purchase the license to distribute for the program in September 1988. While John worked on the plug-ins, Thomas continued writing program code. Photoshop 1.0 was released in 1990 for Macintosh exclusively.

VERSIONS & ITS FEATURES:

Unlike many other file formats (e.g. .EPS or .GIF) that restrict content to provide streamlined, predictable functionality. Layers with masks, color spaces, ICC profiles, transparency, text, alpha channels and spot colors, clipping paths, and duotone settings; are all stored in the .PSD (Photoshop Document) format, Photoshop's native format. It also stores an image with support for most imaging options available in Photoshop. PSD format is limited to a maximum height and width of 30,000 pixels. The .PSB (Photoshop Big) format, also known as "large document format" within Photoshop, is the extension of PSD format to images up to 300,000 pixels in width or height. That limit was apparently chosen somewhat arbitrarily by Adobe, not based on computer arithmetic constraints but for ease of software testing.

The popularity of Photoshop means that the .PSD format is widely used, and it is supported to some extent by most competing software's.

Photoshop uses color models RGB, lab, CMYK, grayscale, binary bitmap, and duotone. Photoshop has the ability to read and write raster and vector image formats such as .EPS, .PNG, .GIF and .JPEG.

Version History :-

  • 0.63                         Macintosh                October 1988

  • 1.0                           Macintosh                February 1990

  • 2.0                           Macintosh                June 1991

  • 2.5                           Macintosh                November 1992
                                    Windows
                                    IRIX, Solaris            November 1993

  • 3.0                           Macintosh                September 1994
                                    Windows                  November 1994
                                    IRIX, Solaris

  • 4.0                           Macintosh                November 1996
                                    Windows

  • 5.0                           Macintosh                May 1998
                                    Windows

  • 5.5                           Macintosh                February 1999
                                    Windows

  • 6.0                           Macintosh                September 2000
                                    Windows

  • 7.0                           Mac OS X                March 2002
                                    Windows

  • CS(8.0)                   Mac OS X                October 2003
                                    Windows

  • CS2 (9.0)                Mac OS X                April 2005
                                    Windows 2k / XP 

  • CS3 (10.0)              Mac OS X                April 16, 2007
    Windows XP SP2

  • CS4 (11.0)              Mac OS X                October 15, 2008
    Windows 

  • CS5 (12.0)              Mac OS X                April 30, 2010
    Windows
     

  • CS6 (13.0)              Mac OS X                Beta - In Progress (July 2011)
    Windows


The Latest, much awaited Beta release, of CS6 was scheduled for July 2011 but was unfortunately postponed until further notice. Its referred to by its codename "Superstition".

I hope u liked this little info into Photoshop... Stay tuned for more :)

Aug 9, 2011

Wordpress Themes For Photographers | Best Wordpress Portfolio Themes

After a long search on google I finally found some really good and best wordpress themes for Photographers and Portfolio.
Now a days every photographer wants to make a portfolio website, but can't find any free portfolio wordpress themes, but after seeing this post your search will come to an end.


So get started and select a theme for portfolio.


WordPress The Unstandard


The Unstandard is a two-column WordPress theme featuring three widget enabled zones. The current 2.0 release is a complete re-write requiring WordPress 3.0 or better. Prior versions of the theme utilized a timthumb + custom fields setup to populate thumbnails for core pages. Thanks to the latest features offered by WordPress, assigning a thumbnail to a post is a simple two-step process. No more manual custom fields for post thumbnails.


Wordpress The Unstandard


download


Gallery 1.2


The original Gallery theme, released by Smashing Magazine, is a child theme of Thematic and is a great solution for anyone wanting a unique showcase or gallery website.


Gallery 1.2


download


WPFolio – Free Portfolio WordPress Theme


WPFolio – Free Portfolio WordPress Theme


download


Blue Bubble


BlueBubble is a Free, Clean, Simple Premium Portfolio Wordpress Theme for Designers, Photographer or any other creative minds! :-) It’s designed for easy showcasing your work and it comes with some very cool features.


Blue Bubble
download


Creative by Nature


A unique and flexible high-quality portfolio WordPress theme for artists, photographers and designers. The theme was designed by .css{mayo} and released especially for Smashing Magazine and its readers.


Creative by Nature


download


Linquist


Linquist


download


Work-a-holic


Work-a-holic
download


Fotofolio WordPress Theme


Fotofolio WordPress Theme
download


Portfolio WordPress Theme


Portfolio WordPress Theme
download


Irresistable


Irresistable
download


Sharpfolio: WordPress Portfolio Theme


Sharpfolio: WordPress Portfolio Theme
download


Snapshot


Snapshot
download


WP Coda


WP Coda
download


Infinity


Infinity
download


AutoFocus


AutoFocus
download