Archive for the ‘Programming’ Category

Picking the first language to learn for novice programmers can be a daunting task. For many, they simply have no clear where to start, and don’t know any of the merits and drawbacks of the various choices they have. Even among experienced programmers, the debate on what new programmers should start with is long and has many different sides. In this article I will give my side.

My Perspective

Before I talk about which language people should start trying to learn first, I will discuss where I am coming from when I make that choice. The first language someone learns in my opinion should be fairly easy to develop with, and be able to give the programmer results fairly quickly. The main problem I generally see with fledgling programmers just starting out is that they get very frustrated with error messages, and in general struggle to connect the concepts they are working with to an actual useful program. I keep these things in mind when making my choice.

 

My Opinion

For new programmers, I highly recommend starting with a web development related language, namely Javascript or PHP, PHP being the first recommendation. The reason I say this is simple. PHP is a very easy language to program in. As a scripting language,  development goes much faster (no having to recompile upon changing a single line of code), and the language itself is much more forgiving. A new user doesn’t have to memorize many different syntactical rules, so all they have to focus on is understanding the concepts, and getting practice with solving problems. Also, PHP (and to an extent, Javascript) comes right out of the box with many various helper functions and algorithms that in other languages you need to either import a library, or write the function yourself. This allows novice programmers to solve problems much faster and easier. However, this comes with a drawback. A programmer who gets used to PHP having a lot of functionality built in that other languages don’t have by default may make it difficult for the programmer to migrate to different languages/platforms. On the other hand, while the programmer may become too reliant on these built in functions, they do know to some extent how to solve a similar problem with another language. The new problem becomes finding out how the other language implements the functionality used in the built in PHP function, or how to write it themselves.

The second reason I suggest PHP (or Javascript), and web development in general is because it makes using the various concepts they’ve learned in practice more rewarding. It is much easier to make an interactive GUI with PHP combined with HTML/CSS than with a programming language like C++, Java, or even Python. Because of this, its much easier to make a “cool” application even with only basic skills. Making a website where you can log in and see a welcome screen is extremely easy with PHP and HTML, but would be much more difficult for a novice in, say, C++ or Java.

 

Drawbacks

While learning PHP (or web development in general) first is not a bad idea, there are some drawbacks. One thing, which I mentioned earlier in this post, was that many novice users who use PHP may become dependent on the built in functions that aren’t available in other languages without either importing a library, or writing the code yourself. This can make transitioning to a more difficult language even harder. This type of problem isn’t unique to PHP either, but common to people who start with most scripting languages, and than transition to a more difficult, stricter language. For example, in my school, the introductory programming class used Python, while the next class (Object Oriented Programming) is taught using C++. Many of the students who go from the first class to the second struggle early in the class with the unavailability of certain functionality that they got so used to using in Python.

Another issue is bad habits that are easy to form with scripting languages. Since most scripting languages have no explicit typing, the concept of a variable with a type can be difficult to understand, especially if you have been programming for a good amount of time.

In general, since scripting languages or usually much easier than stricter programming languages, novice programmers are able to progress faster and without much frustration, but they can pick up bad habits, like the expectation of the language to provide certain functionality, or the expectation of the program to handle many things in the background that you have to set up yourself in stricter languages. The example that one may come to think of first is garbage collection, which is available in most scripting languages, and even some strict programming languages (most notable being Java), but not in, say, C++. Scripting languages also hide many of the core functionality that is inherent in the language from the user. This can create programmers who know how to do something a certain way, but have no idea of the concept behind what allows them to accomplish whatever goal they have. This makes it much harder for these programmers to solve more complex problems that require knowledge of how programs and the underlying code actually works. For example, a novice may figure out how to stop a certain PHP notice from occurring by using the notice suppression operator (the @ operator), but may have no clue why that operator actually fixes (well it doesn’t actually fix the error, but rather stops it from being reported) the error.

However, these problems can be resolved by going from learning an easy scripting language to learning a more difficult, stricter programming language like C++ (in fact, I highly recommend starting with PHP/Javascript and even MySQL if you are adventurous, and then learning C++ in depth). This way, the programmer gets the benefits of learning a very strict language like C++, where you essentially have full control over your program and therefore have to know not only how to solve problems, but why certain code and concepts solve the problem. Also, the programmer won’t be nearly as frustrated since they already have a language under their belt. The learning curve of C++ is high enough, but some of that difficulty can be mitigated if you already have practice with most or all of the basic programming concepts.

 

In short, for anyone who wishes to learn how to program and make applications, I suggest starting with web design, namely PHP (but Javascript, ASP, or any other web based language would work) because development is faster and easier for a novice programmer, and seeing the results of your knowledge and making cool, useful applications is much easier, especially if you want to incorporate some sort of GUI elements.

As a side note, since not everyone is interested in web design, or has the means to purchase a server (although you can always download software like LAMP, or WAMP to turn your computer into a local web server), other scripting languages will work as well. If you are going to go this route, I suggest Python personally.

 

If you have any questions or comments, or disagree with what I say, leave a comment below! I would love to have a discussion with someone who has a differing opinion from mine.

Out of boredom I decided to create a very simple wrapper class for mysql database management. This class, as I mentioned, is extremely simple. However, for those wishing to learn more about Object Oriented programming, and how to implement a class that is useful, this is a good place to start. Anyone wishing to learn more about OOP could take this basic class, and make it into something that is much more useful.

Note: This class is untested. I haven’t actually ran the code, but I reviwed it to make sure any simple syntax/conceptual errors were removed.

If there is a syntax error or anything you see, leave a comment below so I can fix it!

Functionality

The class has very limited functionality. It basically provides normal mysql functionality (like querying, fetching rows, and fetching all the rows of a result set) and has a built in sanitizing function.

Improvements

This class is by no means complete or even useful. However, there are many improvements that someone could add to this that would not only make this class fairly useful, but is also great practice. Some obvious improvements could be as follows:

  • function to build and execute a query based on function parameters (like table, what to select, and where/order by statements(s)
  • an insert function that builds and executes a query based on parameters (table to insert, array of columns, and an array of corresponding values
  • stronger validation/sanitization

There are many many more things you could add to this class. A little competition for the readers: Submit your version of the class below with added features. The best/coolest class will get a free page with links/advertisement to their website (or a website of their choice)


<?php
class DB_manager {
 private $database;//database you wish to connect to
 private $username;//mysql username
 private $password;//myysql password
 private $server;//mysql server to connect to
 private $link;//variable to hold mysql connection link
 private $currentResult = false;

 private $query;

 //simple error reporting function.
 private function reportError($error){
 echo $error;
 }

 //constructor
 public function __construct($username, $password, $server="localhost"){
 $this->server = $server;
 $this->username = $username;
 $this->password = $password;
 }

 //connect
 public function connect($database){
 $this->link=mysql_connect($this->server,$this->user,$this->pass);
 //make sure we connected correctly
 if (!$this->link) {//open failed
 $this->reportError("Could not connect to server: <b>$this->server</b>.");
 }
 $this->database = $database
 if(!@mysql_select_db($this->database, $this->link)) {//no database
 $this->reportError("Could not open database: <b>$this->database</b>.");
 }
 }

 //run query q
 public function query($q){
 $this->query = $this->string_escape($q);
 $this->currentResult = mysql_query($q);
 if (!$this->currentResult){
 $this->reportError("There was an error with your query: " . mysql_error();
 $this->currentResult = false;
 return false;
 }
 return $this->currentResult;
 }
 //returns row from the result a query returned
 public function fetch_row($assoc = true){
 if (!$this->currentResult){
 $this->reportError("There is no valid result set to return data from.");
 return false;
 }

 if ($assoc)
 return mysql_fetch_assoc($this->currentResult);
 else
 return mysql_fetch_array($this->currentResult);

 }

 public function string_escape($s){
 return mysql_real_escape_string($s);
 }

 public function fetch_all($assoc = true){
 if (!$this->currentResult)
 $this->reportError("There is no valid result set to return data from.");
 return false;
 }

 $array = [];
 if ($assoc)
 while ($row = mysql_fetch_assoc($this->currentResult)){
 $array[] = $row;
 }
 }
 else {
 while ($row = mysql_fetch_array($this->currentResult)){
 $array[] = $row;
 }
 }

 return $array;
 }
}

//usage
$db = new DB_Manager('username', 'password', 'server (usually localhost');
$db->connect("databse_name");

$db->query("SELECT * FROM sometable");

$rows = $db->fetch_all();

foreach($rows as $r){
 print_r($r);
}

&nbsp;

&nbsp;

?>

If you have any questions, leave a comment!

As requested by a user who left a comment on one of my previous posts, I have zipped up my asset folder (which includes all scripts, models (even the couple horrible models I created!), scenes, etc. in Lerpz 2). Because of size restraints, I had to leave off the extra music folder (which had random songs by a band called Muse that I was planning on using in various places in the game). Because of this, the final scene (the game end scene), and the first scene (the game menu scene)  may cause the game to crash or otherwise not work because I used songs from that folder. You will have use your own songs, and drag the corresponding songs to their correct places in the menu.

I have never actually tried to share a Unity scene(s) before, so I may have done this completely wrong. If this is incorrect, please let me know in the comments so I can fix the download.

As always, if you have any questions on my methodology, or general questions on how I completed the tutorial, leave them in the comments!

Use the following link to download: http://mediafire.com/?25z5efm0i80f679

As a tutor and coding help forum poster, I notice many instances of people using OOP, but using it incorrectly. Now, i don’t necessarily mean that they have errors in their code, or that it isn’t logically correct, but rather that the programmer in question has problems with their concepts of OOP. In this post I’ll be discussing the very basic and common problems I see, and ways to think about OOP such that these mistakes can be avoided. I’ll only be going over two of the simplest OOP concepts, encapsulation and inheritance.

Object Oriented Programming: The Why?

Many people simply use Object Oriented Programming because its the “latest and greatest” paradigm in the computer science field. The problem is that they learn the syntax and semantics of OOP, but never truely learn what OOP is. Let me start by giving a basic explanation of what OOP brings to the table as far as programming is concerned.

First, the basic concept of OOP is instead of programming procedurally, or functionally, you program in such a way that your entire program consists of discrete, separate objects that interact with each other in certain ways. This concept is fairly easy to understand, but doesn’t quite explain how to implement such a program that takes advantage of all OOP has to offer. However, lets take a simple example to further illustrate this concept. Lets say we are writing a program to model driving a car. Each car is a separate object of course, but these objects are instances of the same class (in the case, a car), but have different properties. Some are fast, some are strong, and some have great gas mileage. Each car, consequently, is composed of many other discrete objects. Like the rear view mirror, or the engine (which in turn could be composed of other objects) and the tires (and of course these each have their own attributes). Then there is the driver of the car which is another object that interacts directly with the car. The Driver tells the car to drive, and the car in turn tells the engine to turn on, and tells the wheels to spin. The Driver doesn’t ever interact with the individual components of a car, but rather the car itself. The car interacts with each individual components. In (very PHP-like) pseudo code, this interaction might look something like

$Honda_Accord =  new Car();
$Honda_Accord->addEngine(new Engine());
//add rest of components
$bob = new Driver();
$bob->Drive($Honda_Accord);

//inside the drive method,
$Honda_Accord->start_engine();
$Honda_Accord->spin_wheels();
//etc..

Encapsulation

This is probably the most widely known but often misunderstood concepts that OOP brings to the table. The basic concept is that of data hiding. Each discrete object in your program has data inside of it, that it hides from the rest of the program. If we consider the example above, each car would have certain properties (like speed, gas mileage, etc.). These properties would only be changed or acted with by the car. The rest of the program cannot (and should not) have access to any of these properties. For example, the driver tells the car to start, but the car is the one that sends the signals to the tires to move. The driver doesn’t (and can’t) interact with each individual wheel.

Encapsulation is often widely misused though. I see misuse in many forms, but the most common are as follows. The programmer may completely forgo encapsulation (For example, he makes all data members public). The programmer also may take it too far (he makes every single data member private, even those that conceptual shouldn’t be). I also see many people doing a very curious thing. They make all (or most) of the classes data members private, but create mutators and accessors for all of them, essentially making them public, but writing a lot more code to do so. For example

class A {
private $some_int;
private $some_string;

public function get_some_int(){ return $this->some_int; }

public function set_some_int($i){ $this->some_int = $i; }

public function get_some_string(){ return $this->some_string; }

public function set_some_string($s){ $this-> some_string = $s; }

}

Now, trying to explain how to correctly use encapsulation is almost impossible, since it can be applied in so many ways. However, I often try to tell my students the following, which has mixed, but predominantly positives results: When deciding what data members to make public, which to make private, and which to make accessors or mutators for, consider the following. If we consider a data member, say int x, how is it going to be used? Is it only ever going to be accessed and modified inside the class. If so make it private. If it will be accessed outside of the class, but you only want to be able to change it inside, then make it a private variable with an accessor (like GetX()). If you are going to be accessing and changing it outside of the class without any restrictions (IE a programmer using this class can set the value of x to any reasonable value) Then make it public. If you want to make it so that the data member can be set and retrieved outside the class, but setting the variable has restrictions (Like x cannot be over 10 or below 0) then make the variable private, and use an accessor and mutator.

Lets take an example. Lets say we are creating a Person class. The name of the person would obviously be private (since no one can change someone’s name but the person) but with an accessor (people can still ask for their name). The amount of cash someone has would again be private, but would have an accessor (someone can ask how much money they have) and a restricted mutator (someone can’t just set the amount of money they have, but a store keeper can ask for a certain amount, or give a certain amount back as change.) The class could look something like:

class Person {
private $name;
private $cash;

public function getName(){ return $this->name; }

public function getCash(){ return $this->cash; }

public function giveChange($c){ $this->cash += $c; }//function to return change back to user

public function pay($price) { $this->cash -= $price; }//function to pay for something

}
<h3>Inheritance</h3>
Inheritance is one of the most commonly misused concepts I see. Sometimes even more than encapsulation (since its a bit easier to understand the implications of it in a conceptual sense, so its much easier to correct past mistakes). However, inheritance is slightly more complex than encapsulation. The basic concept is rather easy to understand. Inheritance in OOP models inheritance in real life fairly closely. You have a Base or Parent object, and you have a Derived or Child object that inherits from it. The child has all the properties that a parent has, and more.

The main problem I see many students and novice programmers trip up on is having children inherit from parents for no apparent reason. For example (and this is a real example) one of my students had a lab recitation to model a car (much like the example above, but much simpler). Cars were composed of Engines, and Wheels and had some basic attributes (like model name and number). This student decided to have the engines and wheels inherit from the car because they were part of the class, and he took this to mean that they had to inherit from cars. This shows two things. One, laziness, and two, a complete misunderstanding of the concept of inheritance.

When deciding on using inheritance, take the following into consideration:

Say we have a system where we have a few different classes. Lets say that these classes all have some sort of similarities. If they do, then I would take these similarities (generally in the form of the same attributes, or the same methods) , move them into a base class, and have my other classes derive from them. Inheritance can be used to avoid having to repeat code. However, inheritance is unnecessary or irrelevant if we have two classes that are quite different from each other, even if they seem to have some similarities. For example, if we are creating a GUI system, we may have a bunch of different shapes. Each shape would have some similar methods and attributes (Like the name of the shape, and a method for drawing the shape). Each shape should derive from some Base shape class. Another example would be a system where we have musicians and a music store. Each musician and each store would have a store of instruments (for example, a musician may have a guitar and drums, and a store may have a whole selection of guitars, basses, drums, etc.) Musicians and stores would also each have names, and other things. However, it really wouldn't make sense for either musicians to inherit from stores, or stores from musicians since each has unique data members that the other doesn't have.

Taking the shapes example, the code may look something like



class Shape { //base shape class
protected $name= "abstract shape";//protected so derived class can access of course

public function draw(){ ... }

}

class Triangle extends Shape {//triangle class that inherits from shape class

private $height;
private $base;

function _construct(){ $this->name = "triangle"; } //constructor to set name of this class to triangle

}

 

If you have any questions, comments or feedback, please let me know in the comments!

public function draw() { ... draw the triangle ... }

As a frequent forum poster in a few programming help boards, I have noticed a lot of well meaning people simply don’t know how to ask a question right, and this leads to incomplete, or inadequate answers, or simply getting told off. The poster will ask follow up questions usually, in a strained struggle to get their question/homework/project completed, and usually these end up annoying those who do want to help (as they are of the same bad format as the original question) or get shuffled off to some distant tutorial on the other side of the internet.

The problem is that they simply don’t know how to ask their question correctly, or more commonly are so fed up with the problem that they can’t be bothered to do any research and formulate an intelligent question that will get an intelligent answer. For example, I often see posts like this.

Hi I have a problem. I want my code to print my birthday from the database, but it won’t. Help

Code here Code here

This may seem like a perfectly reasonable question to a novice because they simply don’t realize how vague of a question this is. The reason that the above code may not work could be one of multitudes of different things, from simple syntax errors to very complex server problems. No forum poster wants to have to prod the user for more information to fix the problem (unless its super obvious) so questions like these can go unanswered, or answered in the form of a question requesting more information.

 

So How do I ask?

Well, this depends entirely on the question. But a general formula for asking good questions, and seeming like you actually care about the Why of the answer, rather than just the answer is as follows:

  • First research the problem. For very simple problems, this can save a lot of time debugging, since someone else is bound to have run into the same problem. Generally, if I have some sort of error I will start by Googling the actual error text. Remember, Google is your friend, and should always be the first resort!
  • Try to debug yourself. Debugging is a practice learned through experience, but some helpful tips are as follows (Note these are rather specific to PHP, but the concept can be applied to anything):
  1. Output all the variables in question. Do they have values you think they have? If not trace where these values are set.
  2. If its a MySQL problem, make sure you are checking if there was a MySQL error. If there was, make sure you note it in any posts you make.
  3. Turn error reporting on. Generally, when people have simple syntax errors and don’t see them, its because error reporting is turned off.
  4. Comment out everything in your script until  you pinpoint the problem line.
  • Once you have tried debugging without success, you can make your post. Make sure you list all the steps you took to debug, and post the relevant code. DO NOT POST ALL THE CODE. You don’t know how many posts I skip over because someone just posted their whole page, HTML and all on the page. Not only does this make it seem like you simply don’t care about the other posters, but it is incredibly irritating to see a whole HTML page slathered on a forum post. Posting the relevant code makes it seem like you actually care not only about the problem, but about the posters who want to help you. It is also a good way to test yourself. Its easy to post the whole page, but its a little harder to figure out what exactly is relevant to the problem.
  • Make sure that if you are posting code, you post it in code BBCode tags if the forums supports them (and most coding forums do)

 

Why?

Why should you follow the above directions? Well, it’s not just about getting a good answer (which following the above advice will really help). Debugging and figuring out problems is half of the battle in coding. Many times, when people who post questions like my example above get their answers, its generally in the form of code you can copy paste and move on. This may make fixing things quicker and easier, but what happens when you are on your own? Being able to debug is a very important part of programming, and while asking for help is never a bad thing, when you go through the steps of trying to solve the problem yourself, you understand the problem better. After doing a little research, you may not find the answer, but you may find some tid bits of information that you didn’t know before. Above all, learning how to program efficiently is the most important part!

Also, when you put forth the effort to research your problem, it shows on the post. Its obvious when you clearly haven’t even tried to solve this problem, opting instead to just post generic SOS messages on various forums  until someone solves your problem. Its also obvious when you put forth the effort to try to solve the problem, and are generally interested in not only fixing the problem, but not repeating the mistake you made. When someone has clearly put some effort, I will put forth equal effort into not only solving the problem, but also explaining it. I usually end up posting a few paragraphs of explanation along with annotated code (that I may have even tested on my local server!) For those who simply want the answer, and don’t care about the underlying problem, I simply put a few words of explanation and  a code snippet, and I almost never test the code. Think about it. Why should I put forth effort into fixing your problem that you aren’t willing to put effort into fixing.

 

Hopefully this gives the question poster good perspective on what a help poster thinks, and the internet will see better questions!

One of the most awesome things about Unity is the focus on Assets, and the large community you have at your disposal that create assets. Usually, if one wanted to create a game one would have to not only do the tasks they don’t mind (for me thats programming) but the tasks that are difficult and time consuming for them (for me thats graphics/modelling. I can’t model worth a dam.)

Fortunately, the folks at Unity have created a store where you can browse through and purchase different asset packages! These could be simple models, to entire scripts, or prefabs, or any combination! Here is a link to the Unity asset store

 

However, for developers on a very tight budget, there are also free and discount asset packages offered at various places on the web. They range in quality (and of course you get what you pay for so to speak) but there are plenty of great quality free and low price assets available. Following is a list of free, free/paid, and paid sites where you can get Unity Asset packages:

Free

Free/Paid:

Paid Only:

I created and finished my first Unity game today! Its called Lerpz Escapes! and is based on a basic Unity tutorial that teaches you how to build a 3D platformer game. Luckily, the tutorial came with all the Assets I needed, (including most of the scripts) so I wasn’t overwhelmed, and was able to complete the project fairly quickly (only took me about a day!)

The Game

The Controls are as follows:

  • WADS keys to move around
  • Left click to attack
  • Right click to re-focus camera
  • Space bar to jump (while in mid-air if you hold space bar your jetpack will slow your descent)
The objective of the game is to collect 20 fuel canisters, so you can escape Robot world 2. The full description is the following:

Our hero is Lerpz: an alien visiting Robot World Version 2. This replaced Robot World
Version 1, which suffered a particularly brutal segmentation fault and abruptly
crashed into its sun many years ago.
Unfortunately, Lerpz has had some bad luck: his spaceship has been impounded by the
corrupt local police. After looking high and low, Lerpz has found his spaceship, but
Every platform game has its star
character who the player controls.
Our star is Lerpz.how can he get it back from Mr. Big’s nastier, obsessive>compulsive cousin, Mr. Even
Bigger?
Mr. Bigger loves nothing more than artistically arranging fuel canisters on his floating
patio. He particularly admires how they glow when he places them on hover pads.
(And, of course, they’re cheaper than fitting normal garden lights.)
But there’s something Mr. Bigger hasn’t realized! Thanks to his penny-pinching ways,

Lerpz knows that if he collects all the fuel canisters, the power used to keep them
hovering will overload the security system. This will shut down the impound lot’s
fence and free Lerpz’s spaceship. Lerpz can then enter his spaceship, add the fuel from
the cans and fly away to freedom.
All our hero has to do is collect enough fuel canisters and the impound’s force field
will automatically shut down. Lerpz can then get back into his space car and drive it
away. Mr. Bigger’s hired robot guards will try to stop Lerpz, but luckily, they’re not
particularly bright.

The heart shaped power ups give you health, and the glowing blue platforms are respawn points that you can enable by jumping on. The rest of the mechanics are rather straight forward.

 

The game is complete, with a few minor bugs (a few of the laser traps are not positioned correctly.) For the future of this project I plan on adding quite a few more features, like power ups, another level, scores, and who knows what else! The very next feature I plan to add is changing the enemy AI a bit to make them wander about while they are idle (in addition to fixing the minor bugs). If you have any feedback for me, or any features you think would be cool let me know in the comments section! If you wish to download and try out the game yourself, click this link: http://www.mediafire.com/?7u9jae3necxdxrj

A gallery of the screen shots is below

The Unity Platform

From this tutorial, even with the basic experience I have I can tell that Unity is an extremely powerful tool for game developers. It addresses game development in a much different way than is traditional, with a focus on the actual game assets. The object model is also very interesting, as everything in Unity is what is known as a GameObject, which in turn is composed of child GameObjects, and components (like scripts, audio files, models, etc.) After learning the basic UI controls, using Unity was a breeze. It presents all the information about what you are doing precisely and elegantly, and makes organizing your project a breeze! And Unity also has different options for building your game for different platforms, which makes deploying a game on, say, Mac and PC a breeze. You simply select the platform you want and… voila!

For anyone wanting to get into game development, and game developers who want to streamline their development process, Unity might be the answer you are looking for. I can’t wait to continue development on this platform, and see what else it has to offer.

Links: