Thursday, March 31, 2011

Perls of Wisdom

Playing around some more with Perl I would like to share a few gems that I have discovered. This first comment will only impact any of a small number or users, but if you are programming on a *nix system using Emacs as your text editor you can use a little script to make the shebang appear in all of your perl files. Open up your .emacs file and insert the following code:

(setq auto-insert-directory (expand-file-name "/home/awestove/mytemplates/"\
))
    (setq auto-insert-query nil)
    (define-auto-insert "\\.pl\\'" "autoinsert.pl")
    (add-hook 'find-file-hooks 'auto-insert)

Basically what this is is elisp (emacs lisp) that sets up an auto-insert command. Every time you create a file with the .pl extension in emacs it will automatically insert the contents of autoinsert.pl into the file. Create the directory that you point to in the first line, and in that directory create your autoinsert.pl file. Inside of autoinsert.pl put your shebang ("#! /usr/bin/perl") and anything else you want in every perl file you create.

Sure this only saves a few keystrokes, but most programmers I know are quite lazy. I also created an alias:

alias ep "emacs /home/awestove/perl/\!*.pl"

This short alias means that all I have to type is "ep name" and emacs will open a file name.pl in my perl subdirectory with the shebang on the first line. The joys of automation.

Working some more with Perl I decided the next thing I wanted to focus on was some file I/O and conditional statements. Always good skills to have when learning any programming language, and Perl is no exception. All the better that Perl really simplifies the process of file I/O compared to other programming languages. The command is simply:

open(FILEHANDLE, "fileVariable");

When you want to access the file you use the FILEHANDLE. If you want to open the file for reading place a '<' before the file name, and use '>' for writing. There are a lot of ways you can use this, so I'll just start with the sample program I made to play with some file I/O:

#! C:/Perl/bin/perl
# ask the user to type the file name to read from
print "What file am I reading?";
my $fileIn = <>;
chomp($fileIn);
# and the file name to write to
print "What file should I create to write to?";
my $fileOut = <>;
chomp($fileOut);
# try to open the reading file, $opened is a boolean to signify if the operation was successful
my $opened = open(IN, "<$fileIn");
# unless is sort of an 'if not' statement, unless the file opened, print an error and exit
unless($opened){
     print "I could not open $fileIn";
     exit 1;
}
# if the file did open, try to open the output file
# instead of using an unless, we can just tell it to open 'or die'
# dying prints the given message and exits
open(OUT, ">$fileOut") or die("I could not create $fileOut");
# using the <> command on a specific file handle gets input from that file, instead of the default STDIN
# while loop continues executing as long as something is true, once the last line is read the loop will end
while($line = ){
     # get rid of the new line
     chomp($line);
     # a reg exp, if the line contains the number 1, print it to the screen
     if($line =~ /1/){
          print "$line\n";
     }
}
# the loop left us at the end of the file, we need to reopen to get back to the top
open(IN, "<$fileIn");
# @ means array, this reads the entire file into an array, one line per element
my @lines = ;
# printing to a file handle the sorted array
print OUT sort(@lines);
# closing our file connections
close(OUT);
close(IN);

Note the sort function for arrays, this assumes by default the array is characters, so it sorts based on strings. That is to say if your file was:

1
2
3
10
20
30

It would be sorted to:

1
10
2
20
3
30

All in all the use of file I/O and regular expressions is very simple and powerful with Perl. There is a reason the language is still popular for certain scripting projects.

Monday, March 28, 2011

Learning Perl

Have you ever woken up and said, "Today would be a great day to learn a new programming language?" Today is one of those days and I have decided on learning Perl. Why Perl? Why not! Perl is an older language but still being developed and maintained, and is a dynamic language. Perl supports many different programming paradigms and is particularly powerful for tasks such as text parsing and code generation. For small scripts it is nice to have a basic language that you can just hack out some commands and get the job done, and Perl is an excellent choice for doing that. I am sure Perl has many more uses, but I am just learning it along with you right now, so we will discover those other uses when the time comes.

If you are working on a Macintosh or *nix system, chances are Perl is already installed, but for Windows users you will need to download and install it. I personally recommend ActivePerl which you can download from here. Just download the most recent version for your operating system and follow the instructions. When installing, make sure you check the option to add Perl to the Windows PATH variable.

With Perl installed it is best to follow tradition and start with a Hello World program. Using your text editor of choice create a blank document. The first line in all Perl programs is called shebang and should be something like:

#! usr/bin/perl for *nix
or #! C:/Perl/bin/perl for Windows

Since Perl is interpreted rather than compiled, this shebang points to the Perl interpreter. The rest of the code in the file is sent to the interpreter where it is run. In this program, we are only interested in doing one simple thing, printed a phrase to the screen, also know as standard output. To do this in Perl, like many other languages, the command is simply print followed by the string we want to print, using quotations for literals. So for our hello world program the full code is:

#! C:/Perl/bin/perl
print "Hello World!\n";

Nice and simple. Make sure you note the semicolon at the end of the print command and the lack of the semicolon after the shebang. This is because the shebang is not an actual Perl command, but rather a scripted instruction to the interpreter. Now, this is all well and good, but not overly useful, so let's add a few new things to our program. Some of the most useful things in a programming language are variables and input, so let's add those two features.

Instead of saying hello to the whole world, let's get personal and say hello just to the person running the program. In order to do this, we are going to have to ask there name using standard input. In Perl standard input is signified by <stdin> but by convention can be shortened to <>. To provide a prompt just use the print command. In order to save the answer the user gives us, however, we will need to create a variable, which in Perl is signified by a dollar sign ($). So, to ask the user their name and store it in a variable we would type:

print "What's your name?";
$name = <>;
print "Hello $name!";

Note that their is no need to concatenate the variable into the string literal, the use of the $ tells the interpreter that you want the value of the variable, not a literal $, to be printed to the screen. If you tried actually running this code, you might notice that the formatting seems off, specifically the program prints out a new line after the name before the exclamation point. This is because when the user typed their name, they hit the 'Enter' or 'Return' key, and that new line got saved in the variable as well. To remove this new line we can use chomp:

chomp($name);

Notice that you do not need to do $name = chomp($name); chomp actually modifies the passed in variable directly. With all of this our final program should look like:

#! C:/Perl/bin/perl
print "What's your name?";
$name = <>;
chomp($name);
print "Hello $name!";

And now we have a basic understanding of starting Perl. If you notice that the DOS window closes automatically without letting you see the program, either run the program from the command line, or add an extra <>; as the last line. This will stop the program from completing until you hit enter.

Monday, January 24, 2011

Minesweeper in Java: Part One - GUI

Continuing from yesterdays post about Minesweeper as an introduction to game programming today we are going to start by creating Minesweeper in Java, a traditional starting language. Creating graphical user interfaces is normally more advanced of a topic than a usual starting tutorial, but the basics are quite simple.

For Minesweeper the basic interface for the game is a simple grid with squares. In Java we will do this by creating a JPanel with GridLayout. For simplicity sake we will assume that the grid will always be 10x10. These are set in the constructor.

import java.awt.*;
import javax.swing.*;

public class GameGridGui extends JPanel{

public GameGridGui(){
     this.setSize(400,400);
     this.setLayout(new GridLayout(10,10));
}
}

Once the basic layout is taken care of the next thing that needs to be done is build the squares. There are lots of ways to do this but since we need to click on the squares there is no reason why we shouldn't just use an array of JButtons. Create a method called buildButtons and call it from your constructor.

import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JPanel;

public class GameGridGui extends JPanel{

 private JButton squares[][];
 
public GameGridGui(){
     this.setSize(400,400);
     this.setLayout(new GridLayout(10,10));
     squares = new JButton[10][10];
     buildButtons();
}

private void buildButtons(){
     for(int i=0;i<10;i++){
          for(int j=0;j<10;j++){
               squares[i][j] = new JButton();
               squares[i][j].setSize(400,400);
               this.add(squares[i][j]);
          }
     }
}
}

If you want to test this out to see what it looks like, just create a quick main method with a JFrame.

public static void main(String[] args) {
  GameGridGui g = new GameGridGui();
  JFrame frame = new JFrame("My Minesweeper");
  frame.add(g);
  frame.setSize(400,400);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setVisible(true);
 }

And with that you have a basic Minesweeper GUI in Java.

Sunday, January 23, 2011

A Mine in Many Languages

One of my favorite games is the Windows classic Minesweeper. It is a simple yet addictive game that really engages your mind, and it is an excellent introduction to game programming. A lot of budding programmers are most interested in game programming because it gives you instant gratification, the visible results and interactivity that is missing from a large number of introductory programming assignments. Minesweeper may not have the flashy graphics or multiplayer capabilities of a hit game, but it is that simplicity that makes it an excellent starting program.

With any program, no matter the language or the scale, the first thing that you want to do is determine what exactly you will need. For minesweeper the list is fairly straightforward:

  1. Area to display the grid.
  2. Ability to click on squares in the grid.
  3. Ability to distinguish between unclicked square, square with a mine, square with a number, and square that has been flagged.
  4. On square click, the ability to determine if the square is a mine and if not the ability to count neighboring squares.
  5. Ability to detect when game is finished, either by clicking on a mine or by clicking on all non-mine squares.
  6. (Optional) Timer or move counter
  7. (Optional) Ability to change options; grid size, number of mines, etc.

Your answer to these questions may change depending on the language you choose to write the program in, and the personal desires of the client. It is important to note that creating any list such as this is not meant to be too detailed or all inclusive. Some programmers prefer to just jump right in, others prefer to have absolutely everything planned and outlined in advance.

I will be referring back to this post regularly, with the goal of having a working version of minesweeper in every language that I learn.

Thursday, January 20, 2011

Esoteric is as Esoteric does

There is a whole realm of esoteric programming languages, languages which really serve no purpose other than existing. One example is lolcode, the programming language of lolcats. A quick example program in lolcode looks like:

HAI
CAN HAS STDIO?
VISIBLE "HAI WORLD!"
KTHXBYE

This code is nothing more than hello world, "HAI" and "KTHXBYE" represent the open and close blocks, CAN HAS is the equivalent of an import or include statement, with STDIO being the namespace for standard input and output. Finally VISIBLE is the command to print out to the screen, followed by the string literal "HAI WORLD!", which is what would be printed out to the screen.

Of course, lolcode is not the only esoteric programming language out there. Another esoteric language is the aptly named Brainfuck. Learning this language will fry your mind worse than any night binging on whiskey and vodka. Once again we are going to start out with the simplest program, hello world.

++++++++++
[>+++++++>++++++++++>+++>+<<<<-]
>++.>+.+++++++..+++.>++.
<<+++++++++++++++.
>.+++.------.--------.>+.>.

Right now you are probably saying "What the fu...", but what you should be saying is "What the brainfu..." Brainfuck uses only 8 symbols and runs using a set of counters. In this example there are 5 elements in an array, '<' and '>' iterate through the array, '+' and '-' increment and decrement the values respectively, '[' and ']' denotes a loop and '.' prints to the screen. So to start with the array[1] is set to 10, this is the constraints for the loop. The loop then iterates 10 times (notice the - at the end of the loop when the pointer has returned to the first element) Since this happens 10 times array[2] becomes 70, array[3] becomes 100, array[4] becomes 30 and array[5] becomes 10.

With these values the letters can start to be printed. Array[2] becomes 72 and is printed out, 72 being the ascii value for 'H'. Next 101 is printed ('e'), 108 ('l') is printed twice, and so on, using < > + and - to change the ascii values that are printed.

These are far from being the only esoteric languages out there, but they manage to show a good glimpse at what you can expect from extremely bored programmers.

Wednesday, January 19, 2011

Misadventures in CSS

So I have spent the past two days updating various websites to make sure they looked nice and worked in all the various browsers, specifically Chrome, Firefox, and IE 8. As anybody who has spent any time at all working on CSS can tell you, programming for Firefox and Chrome is simple, Internet Explorer... not so much. There are several nuances that make Internet Explorer difficult, they have gotten better with IE 8 - I remember having to create entirely different CSS files, one for IE and one for other browsers - but as my headaches these past days can attest to, cross compliance is far from reality.
One specific issue I was having was formatting select elements, the drop down boxes with pre-populated values that are so common on HTML forms. Specifically, my client needed added space between three elements, a date field, month field, and year field. Chrome automatically added in some space, but Internet Explorer and Firefox mashed all three fields together. "No problem," I thought to myself, "one quick CSS rule and I'll be on my way."

select{
     margin-right: 0.5em;
} 

A quick refresh and Firefox confirmed that this rule worked as expected, but alas, Internet Explorer did not want to play ball. Now, when updating a website lots of things could be the problem: is the CSS code even being reached? Is there a cached version still being used? Is there an error with the CSS? With the HTML? Using a hard-refresh (control-F5) to clear cache, and using Developer Tools to trace the CSS, I ruled out the first two possibilities, and since the code worked perfectly in Firefox and Chrome, one would think the other two were equally impossible. After a little tweaking I found the silly little bug, Internet Explorer cannot or will not style a select element without also styling the option element, the various dropdown options that appear when you click on the box. With that the working code for all three browsers is:

select{
     margin-right: 0.5em;
} 

option{
     margin-right: 0.5em;
} 

The other issue I had the pleasure of tangling with was getting an entire form to be centered on the page while keeping the elements left aligned with one another. Once again the fix for Firefox and Chrome was quite simple:

form{
     margin: 0 auto;
}

The shorthand for the margin command sets the top and bottom margins with the first value, and the left and right with the second. Since the left and right margins are both set to the same auto-computed value, the content becomes horizontally centered on the page. Of course, Internet Explorer chooses to ignore this command by default. This fix is deceptively simple though, and many programmers will not even notice the issue. The problem comes with Internet Explorer's Quirks mode, if a website does not specify an HTML Doctype, Internet Explorer defaults to an old, HTML 4 compliant version. To force an updated XHTML 1 rendering, place the following line at the VERY top of your webpage, even before the <html> tag.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

A simple fix to solve future headaches.

Tuesday, January 18, 2011

The Start of a Journey

Hello all, I am Anthony Westover from Valparaiso University, and I am a computer programmer. If there is one thing I love about computer programming it is learning and using as many languages as possible. Each language is unique, each has a set of strengths and weaknesses. This is a journey through the universe of programming languages.