Wednesday, 24 September 2014

The Game of Life Solution Walkthrough

Dear blog, it has been an awfully long time since my last post, I hope you are in a forgiving mood.  During the past two months, I have actually been blogging elsewhere, but you will always be my first and most important blog site.  The reason for the absence is that in mid-July I started my one-year sabbatical from my finance job in order to do my Computer Science Masters (see my Back To School post from March) and I used the summer to go travelling in Singapore, Australia and New Zealand.  I used this blog as a photo diary of my adventures so that my parents could check that I was still alive.
Maybe I should have done a career change to become a beach bum instead....
While on my travels, I really lived life on the edge - I went on helicopters, mountain and glacier hikes, caving, white water rafting, scuba diving, bungy jumping and sky diving, but throughout my trip my laptop and university pre-course reading were never far away.  The textbook I have been working through is called Problem Solving with C++ by Walter Savitch...many people I met on my trip thought it was weird that I had brought work with me, but I had some looooong coach journeys to sit through and so far I have enjoyed working through the "homework" problems at the end of each chapter.

This blog post is a walkthrough of my solution to one of these problem sets, and what better way to resurrect my blog than with an article about the Game of Life.  Before we get into the meat of the solution, I just want to spend a bit of time comparing and contrasting C++ with Python (the programming language I had previously had most experience with).  When people who have some programming knowledge ask me what language my Masters course will use, they generally make the following face, when I tell them it will be taught in C++:


People then go on to say things like "If you can do it in C++, you can do it in any language".  I'm not sure how C++ acquired this formidable reputation, but so far, I have to say that Python was definitely easier to learn and seems to be more flexible.  As you will see with my C++ solution to the Game of Life, at the top of the code, there are some header statements  - when you are a newb you just have to accept this as given and not get too bogged down with the details of why they are there.  Also, with C++, when you use variables in your program, you have to define the variable's type in advance (e.g. whether it will be an integer, or a character etc), whereas Python sort of allows variable types to be defined as and when they are created.  Similarly, when you want to run programs you have written in C++, they must be compiled first (compiling just means the computer checks through the code you have written in your editor and converts into code that your machine can understand), but again, Python cobbles it all together while the program is being run.  The compilation stage is often useful as it brings up any errors before your program is being executed, and you do get a super satisfying feeling whenever your program compiles correctly the first time!

Ok, I've used this meme before - forgive me, I'm a Futurama fanatic


Most of the time, it doesn't compile and for me, more often than not, it's because of these darn semicolons you have to put at the end of every statement in C++!  After being used to coding in Python, it takes a while to get used to them...  My final gripe with C++ is Microsoft Visual Studio Express - ok, so it's not really related to the language itself, but this is possibly one of the least intuitive and most beginner-unfriendly development environments EVER!  Thankfully a new Macbook Pro is on its way to me and I will hopefully never have to deal with Visual Studio again!

Another way to illustrate the differences between Python and C++ is the different philosophies behind the two languages.  The bullet points below are taken from Wikipedia, and I think the way they are written gives you a real feel of the conceptual differences between them as well as an idea of what it is like to code with them.

Python:
  • Beautiful is better than ugly
  • Explicit is better than implicit
  • Simple is better than complex
  • Complex is better than complicated
  • Readability counts
C++:
  • It must be driven by actual problems and its features should be useful immediately in real world programs.
  • Every feature should be implementable (with a reasonably obvious way to do so).
  • Programmers should be free to pick their own programming style, and that style should be fully supported by C++.
  • Allowing a useful feature is more important than preventing every possible misuse of C++.
  • It should provide facilities for organising programs into well-defined separate parts, and provide facilities for combining separately developed parts.
  • No implicit violations of the type system (but allow explicit violations that have been explicitly asked for by the programmer).
  • Make user created types have equal support and performance to built in types.
  • Any features that you do not use you do not pay for (e.g. in performance).
  • There should be no language beneath C++ (except assembly language).
  • C++ should work alongside other pre-existing programming languages, rather than being part of its own separate and incompatible programming environment.
  • If what the programmer wants to do is unknown, allow the programmer to specify (provide manual control).
This all sounds like a big rant against C++, but as with all new things, I've learnt to adapt and get used to it, so there really is no bad feeling between me and C++.  Also, I'm sure it has many advantages over other languages that I'm yet to understand, but hope to discover during my Masters course!

Phew! That was a long detour, but now we've gotten that out of the way, let's get onto the meat of the Game of Life solution! The following description is taken from Chapter 7,  Programming Project 13 of the Savitch textbook and you can also read a more detailed and very interesting Wikipedia article (complete with cool gif animations!):

The mathematician John Horton Conway invented the "Game of Life". Though not a "game" in any traditional sense, it provides interesting behaviour that is specified with only a few rules.  This Project asks you to write a program that allows you to specify and initial configuration.  The program follows the rules of LIFE to show the continuing behaviour of the configuration.

LIFE is an organism that lives in a discrete, two-dimensional world...This world is an array with each cell capable of holding one LIFE cell.  Generations mark the passing of time.  Each generation brings births and deaths to the LIFE community:

  • We define each cell to have 8 neighbour cells...(directly above, below, to the right, to the left, diagonally above to the right and left, and diagonally below to the right and left).
  • If an occupied cell has 0 or 1 neighours, it dies of loneliness (awwww....). If an occupied cell has more than three neighbours, it dies of overcrowding (anyone who has been on the Central Line will sympathise with this).
  • If an empty cell has exactly 3 occupied neighbour cells, there is a birth of a new cell to replace the empty cell (hmm, talk about a love triangle..?! this Conway dude can't have been much of a biologist)
  • Births and deaths are instantaneous and occur at the changes of generation.  A cell dying for whatever reason may help cause birth, but a newborn cell cannot resurrect a cell that is dying, nor will a cell's death prevent the death of another, say, by reducing the local population.

So given these rules and a starting pattern of live cells on a two dimensional grid, with every generation the pattern of the live cells evolves.

I have put my code on my github page: https://github.com/ttz21/Game-of-Life

Using the framework for problem solving I outlined in my TicTacToe Solution walkthrough, I'm going to start off with the all-important Step 0: Don't Panic.  So after taking deep breath, let's consider the following....

1. What are the inputs?

That's simple - the initial configuration of live cells on a board.  In my solution I have used a 20 x 20 array, because it roughly suits the default size of the screen that pops up when the code is run.  Of course, we could have also written the program to let the user specify the size of the board.  We can declare the size of this board as a constant right at the beginning, so in future we can easily alter it's size without having to go through the entire code:

const int WIDTH = 20, HEIGHT = 20;  (it's customary to give constants names in uppercase, the const means the program can't alter these variables, and the int declares them as integer variables)

I have used an array of integers to track live (1) versus dead (0) cells, though this could also be accomplished using an array of booleans (true/false).  For this solution, the initial configuration has to be input manually (no, I didn't sit and write out all the curly brackets and "0," x400, I wrote a program that did it for me!) - I have put in a little star pulsar pattern that repeats itself every third generation, to give us something pretty to look at when the program is complete!  The code below declares a two-dimensional array of integers named "board", with HEIGHT+2 rows and WIDTH+2 columns (the reason for the +2 will become clear later...)

int board[HEIGHT + 2][WIDTH + 2] = {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};

2. What are the outputs?

We want to display the board to the screen in response to a user prompt (e.g. pressing the Enter key to bring up the next generation).  Rather than showing 1s and 0s, it would be more visually appealing to show asterisks for live cells and just a blank for dead ones.  The function display_board below uses board as an input and uses a nested loop (i.e. loop within a loop) to go through all the rows and columns to print "*" to a screen when the ith row and jth column of the board has an entry of 1.

In C++, when functions are defined, you must declare whether the function returns a value or variable.  The display_board does not return anything, as it simply prints stuff to the user's screen so we declare it as a "void" function.  The "for" loops can be interpreted as: starting with an integer, i at 1, increment i by 1 each time (i++) while i is smaller than HEIGHT+1.  "cout <<" means output the statements that follow to the screen and "endl" simply puts the cursor onto a new line.

void display_board(int board[HEIGHT+2][WIDTH+2])
{
for (int i = 1; i < HEIGHT+1; i++)
{
for (int j = 1; j < WIDTH+1; j++)
{
if (board[i][j] == 1)
cout << "*";
else
cout << " ";
}
cout << endl;
}
}

3. Solve the problem!

To work out what the pattern of the new generation of cells looks like, we need to look at the neighbouring cells of every cell in the current generation.  The problem brief specifies that every cell has 8 neighbours - however, this is not strictly true, because the cells at the very edges of our board will have fewer than 8 neighbours.  In order to get around this, we actually use a 22x22 size board to help us calculate each generation's births and deaths (i.e. giving our 20x20 board a border with the width of 1 cell), but when we are choosing what to display to the user, we only iterate over the inner 20x20 board, and reset the "shell" to dead cells every period (because they technically don't exist and are not part of the game).

We need to know what the previous generation's board looks like in order to calculate the new generation, but after this has been done, we can discard the old board. This means we need to have two boards to work with at one time, as well as a function to copy the board that we use for our calculations onto the board used by the display_board function to show the latest generation.

The new_generation function below takes our board as an input and creates a temporary board of the same size.  This temporary board is then filled with 1s and 0s according to the rules of the Game of Life using the configuration of our input board.  When this has been done, our board with the initial configuration is overwritten with the temporary board using the copy_board function.


void new_generation(int board[HEIGHT + 2][WIDTH + 2])
{
int temp_board[HEIGHT+2][WIDTH+2];
int neighbours;

for (int i = 0; i < HEIGHT+2; i++)
{
for (int j = 0; j < WIDTH + 2; j++)
{
if (i == 0 || j == 0 || i == HEIGHT + 2 || j == WIDTH + 2)
temp_board[i][j] = 0;
else
{
//counting alive neighbouring cells
neighbours = board[i - 1][j - 1] + board[i - 1][j] + board[i - 1][j + 1]
                                   + board[i][j - 1] + board[i][j + 1]
                        + board[i + 1][j - 1] + board[i + 1][j] + board[i + 1][j + 1];
 
if (board[i][j] == 1)
{
if (neighbours < 2 || neighbours > 3)
temp_board[i][j] = 0; //cell dies due to loneliness or overcrowding
else
temp_board[i][j] = 1;  //don't strictly need to write this line, but I have added it for extra clarity
}

else
{
if (neighbours == 3)
temp_board[i][j] = 1; //birth of a new cell
else
temp_board[i][j] = 0;
}
}
}
}

copy_board(temp_board, board);


}

void copy_board(int board1[HEIGHT + 2][WIDTH + 2], int board2[HEIGHT + 2][WIDTH + 2])
{
for (int i = 0; i < HEIGHT + 2; i++)
{
for (int j = 0; j < WIDTH + 2; j++)
{
board2[i][j] = board1[i][j];
}
}
}

Once we have the display_board, new_generation and copy_board functions, all we need to do is implement them in the main function of the program!  The code below has a "while" loop that keeps repeats as long as the user hits the Enter key. The program displays the board, then reads the user's input using the command cin.get(repeat) and then calculates the next generation of LIFE.  cin is like the opposite of cout - it reads in a user's input from the keyboard and we are asking it to "get" one character (which I have called repeat).  '\n' is the way we represent the "Enter" character in C++.

int main()
{
char repeat;

do
{
display_board(board);
cin.get(repeat);
new_generation(board);

}while (repeat == '\n');

return 0;
}

For the initial configuration I entered, the displayed output should look a little something like an asterisk version of this:
Ta da!

I don't want the solution to get too complicated in this blog post, but from the subsequent chapters I have read in my textbook, I could have implemented LIFE as a class and represented the board as a dynamic array.  There are also interesting extensions to this problem to find static displays or cool evolving patterns, but I'll leave that to the mathematicians out there...

Wednesday, 2 July 2014

Udacity Web Development course

Like many other Londoners, on my daily commute I plug in my earphones and listen to a variety of podcasts in an attempt to block out the what-I-like-to-call "post-apocalyptic nightmare" that is travelling on the London Underground during rush hour (when your transport infrastructure is more than 100 years old, it's always rush hour).  One of my favourite podcasts is TEDTalks, which is a series of short videos of "Ideas worth spreading" and I like it because they cover such a vast range of topics, some are serious, some more entertaining, they do vary in quality, but I always learn something new from watching a TED video (the acronym stands for Technology, Entertainment and Design).

One I watched recently was about what makes a new word officially a word, and one of the examples was "adorkable" (A guy that is a nerd, but in a very cute/adorable way), and this word actually made it into the Collins English Dictionary very recently.  For me, the embodiment of adorkable is Steve Huffman, co-founder of reddit, who is the instructor for a great Web Development course I took this year with Udacity.com.

What is printed in the dictionary, under the definition of "adorkable"

This course requires basic knowledge of Python and is a good follow-on to Udacity's Intro to Computer Science 101 course that I did a few months ago.  The course is focused on building a basic blog website as a web application from the ground up, using Google App Engine to develop and host the site.  You start off by learning some basic HTML, but the majority of the course is not focused on the appearance of the website (i.e. "the front-end"), rather you learn the programming associated with creating and storing new blog posts, displaying these posts, as well as creating user accounts and how cookies work (i.e. "back-end" development).  As a side-project that compliments the main blog-building part of the course, you also learn how to build a website that allows users to submit ASCII art.  You can see my code for both the blog assignment and the ascii art website on my GitHub account.

For your enjoyment, here's a pretty awesome retro-cool example of a simple ASCII art piece:
             
             |\_|\
             | a_a\
             | | "]
         ____| '-\___
        /.----.___.-'\
       //        _    \
      //   .-. (~v~) /|
     |'|  /\:  .--  / \
    // |-/  \_/____/\/~|
   |/  \ |  []_|_|_] \ |
   | \  | \ |___   _\ ]_}
   | |  '-' /   '.'  |
   | |     /    /|:  |
   | |     |   / |:  /\
   | |     /  /  |  /  \
   | |    |  /  /  |    \
   \ |    |/\/  |/|/\    \
    \|\ |\|  |  | / /\/\__\
     \ \| | /   | |__
   snd    / |   |____)
          |_/


I found the course very engaging (not just because of Steve Huffman - he actually wasn't the best lecturer!). Although the set-up was obviously a lot simpler than what is used by "real" websites, understanding how to create user accounts with passwords, logging users in and out, storing and retrieving the blog posts using a database, caching pages etc was really interesting and gives you a basic understanding of how web applications work.  It was also encouraging and inspiring to know that when Steve Huffman co-founded reddit, his experience in web development was about the same as the pre-requisite level of knowledge for this course!

Although overall this is a course that I would thoroughly recommend, and given that it's a totally free resource, I feel bad about complaining, but there were some aspects that I found lacking.  First of all, it was a downright pain installing and running Google App Engine on my Windows laptop - if it wasn't for the advice that was posted on the Udacity forums by other users and answers I found via in-depth googling, I would not have been able to get it to work.  Google App Engine is a platform that you use to write the back-end code for your web application and get it functioning on a real life website. However, Google have now come up with something called Cloud Playground, which looks like it would give you all the functionality of App Engine without having to install anything! This brings me onto my main gripe about this course - it was created a few years ago and the world of web development is evolving so fast that some of the course content is already not as relevant as it could be.

You might be wondering by now why I'm not using the content of the course to host this blog.  As I mentioned earlier, the course focuses almost entirely on the back-end, which means the appearance of the blog that you build with the course leaves a lot to be desired.  To help improve the front end, I went along to a few Codebar sessions to get some expert input.  Codebar is a fantastic (and free!) initiative set up to give free one-on-one coding advice and tutorials to people who are under-represented in the tech industry (i.e. women, ethnic minorities and LGBT).  These sessions take place on a weekly basis around the Silicon Roundabout, where students are paired up with coaches, who are all full-time professional web developers, plus there's free pizza!

FREE PIZZA!!!!!!!!!!
On a serious note, the Codebar organisers and coaches are actually *amazing* and I feel so lucky and grateful I live near to such an incredible and generous resource, that I haven't done anything to deserve!!!
When I rocked up with my  blog web application, no one had heard of  Google App Engine or the template language (Jinja) that was used in the course to build the basic framework of the individual blog pages.  It was also very difficult and frustrating to get the back-end stuff that I had written to work with some of the commonly used "industry standard" templates.  After a while, I also began to realise that I was basically re-inventing the wheel and while I was learning a lot along the way, it would be productive to get to grips with a more widely used set up and learn how to customise that rather than committing to a project where I had built the back end....this is still a work in progress, so, watch this space!

Wednesday, 11 June 2014

Tic Tac Toe Solution Walkthrough

A couple of blog posts ago, I interviewed my friend Stuart about his new job as an app developer. As part of his interview, he was given a week to program a simple 2-player tic-tac-toe game using a programming language of his choice.  This seems to be a common homework problem for computer programming students and I thought it would be good practice to see if I could write my own version in Python. Here is an example of a tic-tac-toe programming assignment I found from a google search:

You are to implement the two player game of Tic Tac Toe. The program should display the board and prompt each user a move. The program should validate each move and handle any incorrect input. The entire user interaction should be command line based. Upon winning or a draw of the game, an appropriate message should be displayed acknowledging such condition.


Not a valid win.
Through the Computer Science 101 course I did with Udacity.com, there was a very good segment on "How to solve problems" that I've found useful as a framework to tackle programming projects.  At the risk of stating the obvious, the heart of the framework is just pure good old-fashioned common sense, but it's often sooooo tempting to just jump straight into the problem.  By breaking down the solution into steps, you can (hopefully) get to a more efficient and elegant solution, which should save time and frustration later on.

So the most important thing is to start off by heeding the zero-th rule! (this is computer programming after all, and everything begins from 0 rather than 1).  The all important zero-th rule is....

0. DON'T PANIC!  Take a deep breath and keep calm... 

It's actually really funny how many times the instructor reminds us to not panic during the Udacity video lesson on Problem Solving.  Computer Science students must be an anxious bunch.
So after our chill pill, the next thing to do is to make sure we understand the problem - what are the possible inputs and what are the desired outputs.  The solution is getting to a procedure that takes those inputs and maps these to the outputs defined by the job spec.

1. What are the inputs? 

  • Which player (X or O) is playing
  • The position that the player wants to play 
We need to consider how the inputs are represented -I chose to go with inputs passed in as numerical coordinates (e.g. the user enters the number of the row and column they wish to place their move).  Whenever a program uses user input, we also need to program "defensively", i.e. take into account invalid inputs by the user such as inputting letters instead of numbers or coordinates on the board that don't exist or are already occupied.  

2. What are the outputs?  

  • Print out the board after each move
  • Return when a game is complete; who won or if there was a stalemate.

3. Solve the problem!  


Working out the relationship between the inputs and outputs is clearly the hardest part (at various points, you may need to remind yourself of step 0). Some good advice is to start off by working out some examples and test cases by hand, consider what could a win looks like? What does a stalemate look like?Everyone has played tic tac toe so I won't bother going through the mechanics of the game here. Once you think systematically about how a human would play the game, we can come up with some "pseudocode" for our solution (i.e. an algorithm that describes the processes you want your code to run).  The aim of this is to get down a draft of an idea for the solution and see if it makes sense.

Pseudocode:
  • Decide which player is going first
  • Ask for that player's first move and check if it's legal (e.g. that it's on a 3x3 board, and in an empty space)
  • Has a win or a stalemate occurred?
  • If not, it's the next player's go
  • Keep going til we get to a win or stalemate


Once you get to a process of a sensible-looking solution that you're happy with, the next part is to decide which part of the code to write first.  In general, the advice is to write the simple cases first and worry about special cases at a later date - don't optimise too early.  Write small bits of code, test them and understand fully what they do before adding to it.  Obviously it depends on the problem in hand, but it's good to make a start and make your code flexible to incorporate potential changes.  I like writing a little welcome message to really get me in the mood!

print "Welcome to Tic Tac Toe, in order to play please enter your row and column numbers between 1 and 3"  

Here is my full code on Github (it is written for a 2player as well as a 1player game where the computer chooses its moves randomly among the available spaces): https://github.com/ttz21/TicTacToe/blob/master/TicTacToe.py

I probably should have commented it a bit better, but below is a little bit more of a step-by-step walkthrough of how I went about solving it (Disclaimer: it's clearly not the only solution and hopefully in future, with a bit more experience I'll have time to revisit this problem and improve it).

So I started out by deciding that I would have the tic tac toe board as an array in the program, and wrote the code that would go through each entry in the array and “print” out the board on the screen:

board = [[" "," "," "],[" "," "," "],[" "," "," "]]

def print_board(board):
    for i in range(0,3):
        print " "+board[i][0]+" : "+board[i][1]+" : "+board[i][2]
        if i<=1:
            print "..........."

Next, I thought about how moves would be recorded to the board array using the raw_input() function, and how to account for invalid inputs from the user (i.e. if something other than a 1,2 or 3 was entered as a co-ordinate value).  The function get_player_input() below asks for either the row or the column coordinate and returns the player’s entry –e.g. get_player_input( “X”, “row”) will ask player X for the row coordinate on their move.  During gameplay, this “helper” function is then used to alternately between player X and O to get their moves and store them in the board array.

def get_player_input(player_name, coordinate):
    correct_input=False
    while(not correct_input):
        value = raw_input("Player "+player_name+", it is your go, enter your desired "+coordinate+": ")

        try:
            value=int(value)
        except ValueError:
            print "That is not a valid input!"
             
        if value>3 or value<1:
            print "Co-ordinate must be a number between 1 and 3"
        else:
            correct_input=True
    return value


Besides inputting invalid numbers as co-ordinates, a player could also enter a co-ordinate that is already filled, so we also need another helper function that checks whether a particular cell is empty and returns either True or False (otherwise known as a boolean).

def valid_cell(board, row_value, col_value):
    if(board[row_value-1][col_value-1]==" "):
        return True
    else:
        return False

This can then be combined with the get_player_input() function in order to write the user’s input to the board and then display the board on the screen:

def check_player_input(player_name):
    valid=False
    while(not valid):
        row_value = get_player_input(player_name,"row")
        col_value = get_player_input(player_name,"col")

        if(valid_cell(board, row_value, col_value)):
            board[row_value-1][col_value-1]=player_name
            print_board(board)
            valid=True
        else:
            print "That cell is already taken!"
                      

After these steps, it was time to write what a win looks like in tic tac toe.  The function below returns a Boolean (True/False) by first checking whether a player has filled the cells diagonally and then loops through the rows and columns to check for horizontal and vertical wins.

def check_for_win(board, player_name):
    if (board[0][0]==board[1][1]==board[2][2]==player_name):
        return True
    if (board[0][2]==board[1][1]==board[2][0]==player_name):
        return True
    for i in range(0,3):
        if(board[i][0]==board[i][1]==board[i][2]==player_name):
            return True
        if(board[0][i]==board[1][i]==board[2][i]==player_name):
            return True
    return False

In addition to a win, the game can also be stopped by a stalemate if the board is full – the function below loops through the entries in the board searching for empty cells.

def board_full(board):
    for i in range(0,3):
        for j in range(0,3):
            if board[i][j]==" ":
                return False

    return True

Finally, we just need to alternate between the players until there is a win or the board is full.  I also added some extra functions to allow players to choose whether X or O would go first, and later on, I put in a computer player that would make moves at random – you can see the code for this on the github link above, but I won’t go into it in detail in this post.

def determine_play_mode():
    mode = raw_input("Would you like a 1 or 2 player game? ")
    return mode

def determine_first_go():
    go= raw_input("Who would like to go first? (X, O, or flip a coin?)")
    if(go.upper()=="X"):
        return["X", "O"]

    elif(go.upper()=="O"):
        return ["O", "X"]

    else:
        if(random.randint(0,1)==0):
            return ["O", "X"]
        else:
            return ["X", "O"]

gameplay = True
num_gos = 0

play_order = determine_first_go()
play_mode = determine_play_mode()

while gameplay:

    if(num_gos%2==0):
        check_player_input(play_order[0])

    else:
        if(play_mode == 2):
            check_player_input(play_order[1])
        else:
            print "Computer thinking..."
            get_AI_input(play_order[1])

    if(check_for_win(board,"X")):
        print "Congratulations Player X, you have won!"
        gameplay=False

    elif(check_for_win(board,"O")):
        print "Congratulations Player O, you have won!"
        gameplay=False

    elif(board_full(board)):
        print "This round was a draw..."
        gameplay=False

    if(not gameplay):
        again = raw_input("Would you like to play again? Enter Y to play again, or any other entry to quit: ")
        if (again.upper()=="Y"):
             gameplay = True
             board = [[" "," "," "],[" "," "," "],[" "," "," "]]
             play_order = determine_first_go()
             play_mode = determine_play_mode()
             num_gos=-1
              


    num_gos=num_gos+1



Saturday, 17 May 2014

Keep Calm and Git over it!




Many programming languages have funky names and (semi) interesting stories behind why those names were chosen.  Python was so-named due to the creator’s love of Monty Python comedy.   Java pays homage to the dependency of programmers on one of the most widely used addictive (yet legal!) drugs on the planet.  Groovy, I’m guessing, was written by some fun-loving dudes who wish they were still living in the psychedelic-seventies.   There is also a very bemusing Wikipedia article on a whole host of “joke” programming languages – my favourites are LOLCODE (designed to imitate lolcats memes) and Chef (where the programming instructions resemble cooking recipes!)

When I first heard of Git, one of the world’s most popular version control systems ,  I immediately wondered why someone would choose to use such a name.  I suppose any word in the English language could stand for something rude or nonsensical in another, but this seemed to be a very weird choice of name for anything – this is what urban dictionary has tosay about the word!   It turns out that Git was invented by Linus Torvalds, who also came up with the Linux operating system.  Apparently Torvalds once said “ I'm an egotistical b*stard, and I name all my projects after myself. First 'Linux', now 'git'”!

In my previous blog post, where I interviewed a friend who had recently become an app developer, I received some advice to get a GitHub account ASAP.  It seemed pretty sound guidance, as GitHub provides a free online way to track changes being made to files and projects.  Up until now, I thought the only program that had a “Track Changes” feature was Microsoft Word and for the Udacity homeworks and mini-programs I had written myself, I had just been saving multiple versions on my computer whenever I added new code.  Little did I know that, although the first steps of creating a GitHub account and installing the software were easy as pie, the path ahead was one rocky road.

Unlike the many tutorials out there for Python or HTML/CSS,  it took A LOT of digging to find a tutorial that started from the very beginning.  I was surprised at how many assumed some familiarity with the basic git-related terminology from page 1, while I was still asking what “commit” even meant (no, this is not related to being a commitment-phobe in real life!)

“Repository”, “Commit”, “Fetch”, “Push”….you what???

The best (free) tutorials for complete Git – newbs I found were the following:


After reading these multiple times and following the steps one-by-one, plus A LOT of trial and error from playing around with different commands from the official Git documentation (and often failing), I finally think I understand some of the basics.  As usual with a lot of programming related problems, while you are experimenting around it can sometimes feel like you are hitting your head against a brick wall, when you do get a breakthrough, there’s a real sense of achievement.

I started off with uploading a web application that functions as a basic blog that I built as part of Udacity’s Web Development course (review to hopefully come in a later blog post).  Then later, through a tech-related mailing list I’m on, I found out about an open-source project that I could easily contribute to.  I have mentioned previously that I live in London near an area that is called the Silicon Roundabout due to the fact that there are many tech startups in close proximity to Old Street roundabout.  There is an organisation called TechHub that has been set up to help support these growing businesses and they have set up a website that acts as a guide to where to eat, drink, sleep and workout near the Silicon Roundabout.

The web address is simply http://techhub.london and they have put the html and relevant css and javascript files into their GitHub account (TechHubLondon.github.io) so that others can clone this project onto their own computers, make edits and then send a request for these edits to be merged with their master file (and of course, eventually appear on the website).  I used this article to find out about how to contribute to other people’s GitHub project.

One of my favourite things to do is put on my geeky spectacles and an assortment of brightly coloured clothes from American Apparel, go out in Shoreditch and eat way too  much food.  So when I saw this project, I knew I could contribute in some way and using basic HTML knowledge, I could understand how to add my recommendations of places to eat and drink with friends or entertain investors.

You can find my GitHub account at https://github.com/ttz21 and you can see the simple edits I made, as well as my other mini-projects, which I will hopefully be expanding upon in this blog at some point in future!