Social networking and the demise of friendship

When I grew up, from the point my parents actually bought a Windows computer with a modem (I had previously been using an Amstrad PCW8512…ahhh), THE thing to be seen on was MSN messenger. The little person icon in your Windows 98 tray, bringing you the possibility of talking to your friends without having to call them up on the phone. The possibility of casually talking to the “cool people” from school, who you had added and were overjoyed when they added you back, but who you knew would never have dreamt of conversing with you on the telephone. The infinite hilarity of changing your username to something stupid, or with lots of smileys or strange characters. This then progressed at uni to the “always contactable” – people who would leave MSN running in their study bedroom so that you could contact them at any time you wished – I was “well jel”, my halls didn’t have internet so the only time I was online was when I toddled down to the library. (Not very rock and roll on a Saturday night.)

So, the other day I was bemoaning to no one in particular the fact that no one uses MSN messenger any more, and the fact that Skype – which I thought was its natural replacement – seems equally dead amongst people my age, and then I realised the missing link: Facebook. I used to have a Facebook account several years ago but I got tired of having to mentally censor everything in case in some unexpected way it could be offensive or inappropriate, or worrying about whether someone else might post horrible photos of me, and just decided the easiest way to stop worrying was to not have an account at all. I was also very not keen about Facebook’s extremely dodgy privacy policies and tendency to expose first, ask later – not great for a teacher to have students showing them pictures they thought were hidden. I can’t say I’ve missed it.

However, I do think that the rise of Facebook has led to one very bad thing – people don’t talk to each other any more. Even if my friends used to laugh at me IM-ing away to other Computer Science undergrads, and joke that if we ever had a “Computer Science Ball” it would just be everyone turning up to a room in a suit with their laptop and chatting on MSN – we were still talking. Because of Facebook, I was not invited to a friend’s engagement party and another friend’s PhD graduation party. The reason? They just invited “everybody” on Facebook, because obviously everyone worth knowing has an account. I figured that if I didn’t have Facebook, anyone who actually cared what I was up to would call me, text me, email me or even (shock horror) SEE me – I was badly wrong.

Instead of speaking to people more often since deciding to ditch Facebook, I’ve actually lost touch with them completely because it’s easier to find out what’s going on in other people’s lives by simply looking on a profile page than it is to go through the hassle of talking. People seem transfixed by looking at their friends lives unfold on a website, occasionally pressing a “like” button or writing a shallow public comment – it’s like being in an episode of the Demon Headmaster. (I realise that with my term “people” I am making a very vast generalisation here.) Where is the support network of friends who you used to spend hours on the phone with putting the world to rights? They’re probably out there posting “Lol” on a photo of your dog doing a trick. Where are your msn buddies who you talked to when you were bored? Sitting at home feeling miserable because they just read that you had an awesome day today and all they did was go to work, pay the gas bill and do the laundry. (In actual fact, that’s all you did too – but you had to write an interesting status!) That’s the kind of world that children of today take as baseline or normal, and even relatively young people like me find that very alien.

As I mentioned before, I was reading a book about happiness and Economics last week, which talks about the last country on earth to introduce TV – the kingdom of Bhutan. No sooner was it turned on in June 1999, than all sorts of crimes started being committed, and people became unhappy about how their whole way of life had changed overnight through the introduction of this technology. Maybe we’ll look back on social networking sites in this way in years to come, as something which truly changed the method of interaction of a large chunk of the population – but was this really a change for the better?

In any case, I still do not have Facebook, and whilst I still do not wish to sign over my life to Mark Zuckerberg, I do wish I could have more contact with my friends. So I did the only reasonable thing a girl could do – I got Twitter 😉

Can you force someone to program?

I have to admit, I’ve been finding it hard to conjure up the enthusiasm to write about anything of late. When I thought about why this was, one of the reasons that has dampened my enthusiasm has been the yearly grind of the A-Level coursework. Although teaching is a very rewarding job at times, at other times it can be very hard to have how well YOU do your job judged on how well someone else performs in an exam or in a piece of assessed work. Someone posted this link on Twitter (I forgot who, sorry) which I found really interesting – what if we treated doctors the same way we treat teachers? According to this article’s philosophy, if doctors were treated like teachers, when you chose to eat so much junk food you got heart disease and your doctor could not resolve it, your doctor would be the one judged to be failing! However on the other hand, I suppose you could argue that it is our job to work with our “patients” every day to ensure this does not happen – although we only have a limited amount of hours to make this happen.

Anyhow, nowhere is this judgement more prevalent than with the huge requirements of the A2 coursework – both in Computing and ICT A-levels – the requirement for this piece of work is ridiculously huge if compared to that of other subjects’ A-level coursework. Not only do students have to produce pages and pages of documentation (around 100 pages for some of my A-grade projects), they also have to write a piece of software too. How is it fair to ask people to complete this amount of work when in other subjects they must simply write an essay – albeit a researched and re-drafted one? I also find the mark schemes to be an arcane science, it seems to be that the teacher has to guess what the moderator is looking for (let alone the students trying to guess!), and no amount of poring over the scant mark scheme descriptors, going on exam board courses or closely emulating the example projects can tell you what you are supposed to be presenting to gain the coveted marks.

And all that is even assuming you have a class of enthusiastic, motivated, A-grade students – what on earth does the prospect of this much work do for the lower end of students who take one look at it and immediately think they can’t do it and give up? I read an interesting article the other day which I now can’t find (curses!) about how programming exposes students to regular failure, which in our culture of ensuring success is not something they encounter often at school. Those who give up easily tend not to do as well in other academic areas, whereas those who show resilience and try to solve their own problems will generally do well elsewhere too. This school might indeed have the right idea. (Yet another cross-curricular boost from teaching Computing to tell your SLT about!)

So, I was thinking about how this kind of work could be better examined, and it’s a tough one.

I firstly thought about the coursework set at university in Computer Science – there was a lot of group work which had good and bad points. Good, because it enabled you to work with a mixture of people, to learn from them, and for the project to be more realistic – I think it’s fairly unlikely that in industry you would have to work on a project on your own. Bad because it meant some people didn’t do enough work and it was difficult to assess the individual’s contribution in a fair way.

Then I thought about doing away with coursework altogether – which would be rather silly for Computing to not have a practical element. It would probably result in more AQA style programming exams, which I am again not a fan of. I find that programming in an environment where you are unable to look anything up or use other resources to help you is very artificial – how many programmers remember the argument order of every single pre-written function in a library? Certainly not me.

Then I thought about just submitting source code without all of the analysis and other huge rainforest-killing documentation that has to go with it. Again, not a great idea because this makes for dreadfully badly thought out programs that don’t meet user requirements and are probably way too large in scope to be implemented. (Probably good for anyone who wants a career in programming for the public sector though! Ho ho ho.)

So in other words, like one of my other lecturers used to say, I don’t have the “silver bullet” of how to fairly examine Computing coursework. However, with the huge and really excellent grass roots movement that is sweeping up the new Computing curriculum, I hope this is something that teachers and industry professionals can offer some advice on, and that the exam boards may listen to and improve. For now, we’re stuck trying to encourage our students to produce programs and huge amounts of documentation through all of the usual stick and carrot methods available in school. Some good advice:

@learningdomain – “start early”

@bringbackcs “I say: Have you checked on-line guides? Have you worked through all tutorials? No?!! Let me know when you have.”

… but it still feels like more of an achievement for the teacher having survived with everyone finished, than a test of the student’s software engineering capabilities.

PHP shoutbox task

Bizarrely enough, I recently started teaching topic #1 on the OCR AS ICT F452 module. The specification clearly isn’t design to be taught from beginning to end, and in fact I’ve found I jumped all over the place trying to teach it. We started off by looking at interface design principles using HTML and CSS, given that we have so far only attempted command line Python interfaces, and I have yet to find an interface package for Python that would be suitable for a 17 year old to use – any ideas on this gratefully received? (I have tried Tkinter and wxpython with no joy.) I then thought back to a very old piece of programming my friend @natbat did at university – a shoutbox – and here was the perfect opportunity to teach writing to files too!

In case you are not familiar with PHP, it is a server side language which processes your code and produces a static HTML page as a result. This means you need to run it through a web server, and for development I don’t think you can beat XAMPP – a package with Apache web server, PHP and MySQL (should you want to teach databases) all bundled together in a convenient installer. (Small note: Apache uses port 80, and so does Skype, so if you do install it and it doesn’t work, check you aren’t running Skype before descending into a quivering wreck and asking the universe “why me”.) Please read the manual for better instructions, but the essentials of getting this working are 1) install, 2) start the server with xampp_control.exe, 3) put your files inside the htdocs folder 4) open a web browser and browse to the address http://localhost/yourdirectoryname/whateveryourfileiscalled.php

So we start off with a page containing a simple form, let’s call the page index.php

<form action="page2.php" method="post">
 <textarea name="shout"> </textarea>
 <input type="submit" value="Shout out"/>
</form>

The action attribute of the form specifies the page the data will be sent to when the button is clicked, and the method attribute specifies that the data will be sent via $_POST, i.e. secretly. There is a textarea for people to write things in, and a submit button. No need for PHP tags yet because although this page is saved with the extension .php we are writing only in HTML at the moment.

So on our unimaginatively named page2.php, at the most basic level we need to take the data from the form, which is conveniently provided to us in the array $_POST, and write it to a text file. Obviously you could also accomplish this task by storing the data in a database too, but the aim of this work was to teach writing to files.

So on page2.php we can add some PHP code as below

<?php
$fp = fopen("shouts.txt", "a");    // Open the file shouts.txt
fwrite($fp, $_POST['shout']."\n"); // Write the shout
fclose($fp);                       // Close the file
?>

This code is extremely basic. It opens the file shouts.txt in append mode (the second argument “a”). This means we are setting the file pointer to the end of whatever contents are in the file already, and writing there. There are other access modes – in fact this would be a good opportunity to teach them and to start getting students to look up functions on php.net for themselves. Line 2 writes the shout plus a newline character (\n) to the file, and then line 3 closes the file. Incidentally, the index in the array $_POST[‘shout’] is the same as the name of the textarea in your form. Essentially, whatever you names you give your form elements will be the index of their data in the $_POST array.

Clever students will hopefully realise that there is a lot they could do to improve this code. Improvements they could make could include:

  • A presence check to see whether text was actually entered into the form (at present this will write an empty line)
  • A length check if they do not want shouts to be over a certain length
  • An input sanitising check to remove things like HTML – functions like htmlspecialchars could help – get them to look it up
  • They could add the date/time of the shout – date function
  • You could add another input for the person’s name
  • They could pre-format the shout with HTML tags e.g. putting the person’s name bold
  • I’m sure there are other improvements I haven’t thought of…

Now, we go back to index.php which is where we want to display a list of the shouts, below our form. There are several ways of doing this, here is one:

<?php 
$shouts = file('shouts.txt');
$shouts = array_reverse($shouts);
$shouts = array_slice ($shouts, 0, 50);
foreach ($shouts as $item)
{				
    print $item."<br/>";
}
?>

This code reads the file shouts.txt into an array. Each line of the file is a new element of the array, and since each shout is on a different line this should mean we have an array of shouts. I  then reverse the array to mean the most recent shouts are first, and then take a slice of the array so that only the top 50 most recent shouts are viewable. A foreach loop goes through this resulting array, printing the shouts (plus a line break) one by one. Again there are changes you could add to this code, for instance formatting the shouts in a prettier way. You could also have used the file_get_contents() function to read the entire file in as a string, and then explode() -ed the string on the newline character to get your array, although not sure why you’d want to from an efficiency point of view.

So, all in all a task which is excellent for teaching numerous things (writing to files, access modes, using a programming language manual, concatenation, array manipulation, interface design) and which is also very decent for differentiation – most people will be able to get a working shoutbox but more advanced students can make it very good indeed. Of course, you could upload finished products to a live webserver if you wished…but beware of inappropriate usage!

Computer Science – no one knows what it is

A short conversation with a Year 10 girl this week made me realise something sad – most students have no idea what Computer Science actually is. The girl referred to a colleague from my department who does not have a PhD as “Dr _X_”. (Well not literally Dr X, that makes him sound like a Bond villain or something – just that I have omitted his real name.) When I informed her that Mr X would be very pleased to know he now had a PhD, she said something along the lines of “oh yes how silly, how could you have a PhD in Computers”.

I started to think about this comment a bit more carefully and I realised that the majority of students basically have no idea how their perception of “using a computer at school” translates to “a degree/PhD/useful qualification in Computer Science”. They have no idea of all the mathematics behind the subject, all of the logic, computation, design, systems analysis, everything good that comprises studying Computer Science at university – which makes me very sad. I remember turning up to my first university logic lecture (which regular readers will remember, was not trivial) thinking “eh, this isn’t what I signed up for”. That’s right, I admit it – I signed up for a Computer Science degree with absolutely no idea of what I was signing up for, other than the fact I liked computers and needed to do a degree. I remember wondering why I had to do Maths when that wasn’t what I’d signed up for and bitterly regretted not taking Maths A-Level. (Still do.) Happily though, I loved every minute of Computer Science!

Clearly what we are offering at the moment at school in KS3/4 is not getting this message across, and even though Michael Gove’s comment about ICT being “harmful” has been totally unhelpful and very skewed by the media, it may be the case if we are putting students off before they even find out about how exciting CS can be. One group of Year 9’s who questioned the value of what they were learning after watching some of the coverage during the BETT week were completely baffled when I pointed out that to create a video game you need Maths and Physics, as well as artists and designers – they just couldn’t see how the subjects were remotely related.

However, it’s not just students that need to know what Computer Science is really all about – it’s all the other people who have an influence on their life and their choices. Parents, careers advisors, form tutors – some of those people probably think studying Computer Science is the equivalent of (to borrow a quote from Bridget Jones’ Diary) “swanning in in your short skirt and fannying around with the press releases”. I don’t blame them for this, it’s just that most people either a) have no experience of what a Computing lesson is like because they never had them at school or b) have a negative experience from being taught ICT at school. Every adult knows what happens in a maths lesson, we’ve all had them, but very few know what happens in a Computing lesson – so how can we be expecting them to recommend the subject?

Thinking task #3: Guess my number

Well, we’ve only been back at school for a very short time and it feels like I have never been away. The pile of marking is mounting, the websites I should really have implemented during the holidays are now politely tapping on my shoulder and demanding to be finished, the Mac Mini I was going to investigate is still sitting in its box on my study floor. So instead of taking care of all that, I’m going to write a blog post. (Well, I already ate the chocolate pudding so I didn’t have much left on my procrastination list…)

This week I have been covering recursion with the Lower 6th and also as revision with the Upper 6th. I quite like recursion because it makes me feel smart. Smart in the sense that I didn’t understand it at university and I do now…so maybe I would now understand all of those things our logic lecturer always said were “trivial”, were I to venture back to start my degree again. Maybe. Anyhow, the students wrote both iterative and recursive methods for finding the Fibonacci numbers and also computing factorials, and they were intrigued by the fact that the recursive function fell over when higher arguments were put in whereas the iterative version was able to cope with a lot larger arguments without throwing in the towel.

This led to a conversation about efficiency (happily on the syllabus!) and I thought of a sneaky way of getting them to implement a very basic number search algorithm – now we have a competition next week!

The task

1. You think of a number between 1 and 100.

2. The computer must use any means possible to guess the number. It may ask any question (except “what is your number?” or similar) in order to find out. Each “guess” of a number costs 1 point. Each “answer” that a user must give also costs 1 point. If an error occurs at any point, a 10 point penalty is awarded and that test is ended.

3. On the day of the competition, I will tell you the 5 items of test data. You will use this data to test your program, and the program which scores the least points across all 5 test items added together is the winner.

I like this idea, and so did they – I could tell because they were silent and their tongues were sticking out as they coded! I think it’s a good opportunity for:
1) independent algorithm design
2) discussion after the competition about why certain algorithms may be more efficient
3) doing some testing of a real program
4) thinking about interesting things such as whether some methods are more efficient at finding certain ranges of numbers, and other such discussions

Thinking Task #2: Mastermind – you need to be!

I thought I’d go with my own recommendation from my first post, and write a piece of code for my A2 students who are currently revising for their programming AS module in January to analyse. A Lower 6th student had suggested that a task could be to implement the “Mastermind” game which I had played as a child. I think this is a fairly standard programming task, but it did actually cause me a little bit of aggro!

Required knowledge: Functions, Selection, Iteration, Lists (arrays), String functions e.g. upper(), Random

The basic premise of the game is that the problem setter picks a combination of four coloured pegs (usually from a choice of white, black, red, yellow, green, blue) and hides them. The guesser then has to guess the exact sequence. They give a series of guesses, to which the setter replies with how many are the right colour in the right place (denoted by a black peg), and how many are the right colour in the wrong place (a white peg). By a process of deduction the guesser can eventually figure out what the combination is.

So far, so easy. By FAR the hardest part was figuring out how to return the correct result for the white peg. Black peg was a piece of cake, but I kept being caught out with multiple counting of correct colours in the wrong places, and tying myself in knots trying to debug things. I *think* this solution works, and even if it does I am sure there is probably a way more elegant solution that someone who is more mathematical than me could come up with.

Some things students could do with this code

(there are of course many more!)

1. Add comments to this code to explain what is happening at each stage of the program. There is no need to comment every line.
2. Why is it necessary to use the line tempGuess = list(guess) instead of tempGuess = guess?
3. Why do we need to make a copy of the lists anyway?
4. Why do we keep a track of which letters we have checked using the list lettersChecked?
5. What is the purpose of validation and why is it important?
6. Which naming convention has been used in this code? Why are naming conventions important?
7. Why do we bother to initialise our variables?
8. At the moment, what happens when the player exceeds the number of guesses allowed? Can you add some code to let the user know when they have lost?
9. Draw up a test plan for 5 black box tests on this code, each test being from a different group of test data.
10. Supposing you wished to add the colour Blue as a valid colour, could you alter the code to include this whilst keeping input simple for the user?
11. The line while True: near the beginning of the validateInput() function is an infinite loop. Why doesn’t this result in the program running forever?

I’m not going to ask them to do this, but this code would be an excellent introduction to programs with a GUI – you could write the algorithm with a text based output and then once they have learnt how to display things on a GUI, ask them to revisit it and make it graphical.

Another obvious extension that I think is rather more university level, although there appear to be various algorithms documented, would be to add an option for the user to be the setter and the computer to be the solver. However, a useful discussion about efficiency could come about if you asked students to consider what the computer’s guessing strategy should be, and then compared their answers to the algorithms.

Of course, if you are not using Python as your language of choice, you could easily translate this code to most other languages.

If you have any other suggestions of possible questions or improvements I could set for my upper 6th, do share them.

Here is the (deliberately uncommented) Python code:

import random

def validateInput():
    inputGuess = raw_input("Enter your guess as 4 letters e.g. XXXX:")

    while True:
        if len(inputGuess) != 4:
           inputGuess = raw_input("Enter your guess as 4 letters e.g. XXXX:")
        else:
            wordList = list( inputGuess.upper() )

            invalidLetters = False
            for letter in wordList:
                if letter not in ['R','G','Y','B','W']:
                    invalidLetters = True 

            if invalidLetters == True:
                print "Possible colours are R G Y B W"
                inputGuess = raw_input("Enter your guess as 4 letters e.g. XXXX:") 

            else:
                return wordList

guessesRemaining = 12
code = []
guess = []
correctPosition = 0
correctColour = 0

for i in range(4):
    code.append(random.choice(['R','G','Y','B','W']))

print "Guess my sequence of four colours, in the correct order."
print "\nPossible colours are R G Y B W"

while guessesRemaining > 0:

    correctPosition = 0
    correctColour = 0
    lettersChecked = []

    guess = validateInput()
    guessesRemaining -= 1 # Deduct one guess

    tempGuess = list(guess)
    tempCode = list(code)

    for i in range(4):
        if guess[i] == code[i]:
            correctPosition += 1
            tempGuess[i] = "X"
            tempCode[i] = "X"

    for j in range(4):

        if tempGuess[j] in tempCode and tempGuess[j] != "X" and tempGuess[j] not in lettersChecked:

            if tempCode.count(guess[j]) > tempGuess.count(tempGuess[j]):
                correctColour += tempGuess.count(tempGuess[j])

            else:
                correctColour += tempCode.count(tempGuess[j])

            lettersChecked.append(tempGuess[j])

    if correctPosition > 0:
        print "You had",correctPosition,"correct colours in the correct place"
    if correctColour > 0:
        print "You had",correctColour,"correct colours in the wrong place"

    if correctPosition == 0 and correctColour == 0:
        print "No correct colours"

    if correctPosition == 4:
        print "You won in",12-guessesRemaining,"guesses, congratulations!"
        guessesRemaining = 0

print "Thanks for playing"

Coding, “the crappy way”

I was talking to my friend Tristan the other day, via the MUD which he has created and programmed himself. If you don’t know what a MUD (Multi User Dungeon) is, it’s a sort of a text based adventure world where you can interact with other people, and move between various rooms and locations, and interact with various objects. If you are about my age you probably remember those books in which you read a paragraph and then at the bottom it gives you a choice of “go to page 46” or “go to page 32” – at which point you secretly keep your finger in the original page just in case your choice of page 46 leads to you being eaten horribly by some kind of dragon. It’s a bit like World of Warcraft with no graphics, or an IRC client with dragons – take your pick.

I digress.

Near the start of this year, I had suggested that students have a go at creating their own text based adventure game as an early task in Python. I gave them this code as a template, and asked them to continue:

# Python adventure game

# Define the direction variable
direction1 = ''

# Print out a statement setting the scene for the user
print """As you step into the cave you can smell musty cobwebs and the
dank odour of dripping water. At the back of the cave the path forks
and you can see two directions to travel, left and right."""

# Keep doing this until they have entered either left or right
while direction1 not in ["left","right"]:

    # Ask the user where they want to go
    direction1 = raw_input("Do you want to go left or right?: ")

    # Decide what happens 
    if direction1 == "left":
        print "\nYou have entered the bear's lair!"
        print "Sadly all that is left of you is a pile of bones."
    elif direction1 == "right":
        print "\nThe back of this passage seems to lead somewhere..."
    else:
        print "That is not a direction"

I’m not afraid to admit, this was not one of my finer tasks because it doesn’t take a genius to figure out (but perhaps this did not occur to a sleep deprived teacher) that very quickly you are going to get in a huge muddle of where you are, which direction you can go in and which you can’t – let alone add in usable items and an inventory! Still, it was a nice practice of lots and lots of nested if statements…

I thought I’d ask Tristan how he would go about solving this problem – and his first response was that he’d use classes. Spanner in the works then, because I told him that we don’t seem to cover any Object Oriented programming at all at AS Level. His second idea was to use the dictionary construct in Python, which is different to the list construct which I usually use to teach arrays, because it allows you to use string keys. (Of course, if PHP were a supported language of the exam board, we wouldn’t have to bother with either we’d just use arrays *grumble* :D) This seemed like a pretty good idea, and we discussed how we would go about it, with the discussion coming to a close on his comment of

“well you do know this is the crappy way of doing it?”

This got me thinking…a lot of the time when we are teaching programming, we are actually teaching “the crappy way” of doing something – and not the way that a real life programmer would approach it. Sometimes this is because the crappy way of doing it is actually more understandable to the learner…a prime example of this which comes to mind is in PHP when you extract all items from an array (most commonly a query result) into variables with the key names. e.g.

$fruit = array("orange" => 1, "apple" => 2, "pear" => 1);
extract($fruit);
print $orange;
// Output will be 1

I suspect that most experienced programmers would not use this much (and especially not on form data!) but often it’s easier to just suggest doing it to avoid the hassle of explaining how to use array keys and then getting a blank look. Even though you’ve covered arrays for approximately 4 weeks and done 10 past papers on it. I exaggerate.

So is this a bad thing? I remember being rather miffed in Science lessons when I was in school that we would be taught something in Year 7, and then the next year they would say “well that’s not completely true, it’s actually like this”…and so on. As much as I cringe a little bit inside every time I have to do it, I don’t think that teaching some things “the crappy way” is necessarily bad. I’m not saying that we should forget good habits like variable names, indentation, and algorithm efficiency – far from it – but as long as they are aware that there are other ways of achieving the same result, you are still teaching a method which works. It’s not the most efficient way, but it gives the students a starting point to work from rather than totally confusing them and making them feel like they’ll never be any good and might as well pack up now. That’s why we are teachers, that’s why we are here – to teach the foundations of the subject and to ignite an interest in programming, not to make a legion of perfect programmers. If they are interested enough to go and look up how things could be done more efficiently and properly, and tell you off for your terrible code – GREAT! Our work here is done. If not, at least their program worked. 🙂 At present I have one of my Lower 6th classes picking me up on EVERY piece of bad coding, poor variable naming, or general mistakes they possibly can, and I LOVE IT!!!

Oh and in case you’re wondering, here’s the foundations of the text adventure game, using the dictionary constructs in Python

# Python adventure game using dictionaries

# Validate their input direction

def input_direction():
    direction = raw_input("Which direction do you want to go? ")
    while direction not in ["north", "south", "east", "west", "exit"]:
        direction = raw_input("Which direction do you want to go ")

    return direction

# ---------------------------------------------
# Set up the rooms

compass = dict({ "north" : {0: 1, 1:2, 2:-1},
                 "south": {0: -1, 1:0, 2:1}
                })

descr = dict({0: "You are in a small lobby type room.",
              1: "You are in a grand hall way",
              2: "You are in a huge palace"})

currentRoom = 0
newDir = ""

# Game loop
while( currentRoom != -1 ):

    # Describe the current room
    print descr[currentRoom]

    # Ask what they want to do
    newDir = input_direction()

    # If they wish to exit
    if newDir == "exit":
        print "See ya later, alligator!"
        currentRoom = -1
    else:

        # Otherwise look up whether there is a path that way
        if compass[newDir][currentRoom] != -1:
            currentRoom = compass[newDir][currentRoom]
        else:
            print "There is no path in that direction"

In case you are interested, a link to Tristan’s MUD

Appy new year!

I am very lucky that my school is doing an iPad trial to see whether this pretty desirable piece of kit is actually any good inside the classroom, instead of the (not usually very) trusty teachers laptop. After bowing and scraping and making lots of coffee in the techies office, I managed to get my hands on one to try out last term.

My preciousss…

*ahem* The first thing I noticed is that the iPad is somewhat shiny, and the second thing I noticed was that it would not continue to be quite as shiny if it were to be subjected on a daily basis to the unceremonious dumping in handbag/book bag on the mad stampede to ensure that the chocolate biscuits are not all taken when you get to break. If they really made these things for teachers they would probably need to look a bit more like a Fisher Price plastic coated contraption than the executive cool that is the iPad (2, 16GB with 3G in case you’re wondering. Not that I have a SIM card). So I ventured on to the internet and spent lots of my own hard earned cash on some covers to ensure that the precious would stay as shiny as possible.

Apps

I have had an iPhone for ages but to be perfectly honest, apart from a few fairly futile Hiragana learning apps (which seem to shout out the answer at the same time as testing you….ehh?) most of the apps I have are not particularly educational. I decided to pick the brains of a few other people who recommended some apps for me to try out.

Splashtop Whiteboard – £6.99

(This is not the same as Splashtop Remote Desktop, so don’t get all excited that the price has gone down to £2.99 and buy the wrong app by mistake.)
This is probably the best app I have in terms of teaching, and it certainly impresses the students. First you must download a small program onto your desktop PC – which I know sounds like a very simple feat but I have also worked in schools where installing any piece of software on a computer results in a lot of umming, ahhing and sucking in of air through the teeth from the techies as if you’d asked them to pole vault over Everest. Luckily our techies are rather nice and allow me to fiddle with most things on our desktops – thank you techies! The app then allows you to connect to your Windows PC via remote desktop – OMG, Windows on an ipad – gets people every time. Well, so what. You have a glorified Powerpoint presentation screen, and not a lot else, right? Admittedly it is extremely useful when presenting, and I am looking forward to using it with the L3 Extended Project presentations this summer, as in another disguise I am a supervisor for Perspectives on Science.

However the best bit of this app and the reason you pay the extra 4 quid for it, is that it has the kind of tools you get with Promethean and SMART boards, built in! You can annotate on the screen, you can add icons, type in text…and even better, you can hand the ipad around in the classroom and have THEM do it! Admittedly there is a little bit of lag which can have hilarious results if the kid is looking on the whiteboard and not on the ipad, but it made for a much more entertaining “spot the mistakes” type intro with Year 9. I did try to use it for a revision class with Year 13 where I asked them to write some code but due to the fact that most of the frequently occurring code symbols (brackets, colons and the like) are on the 3rd page of the on screen keyboard, this did not go so well.

Evernote – Free

Someone recommended I get this because it allows you to take notes and keep pictures in the same place. I thought I would try it out by keeping notes on the progress of my A2 coursework and EP supervisees. To be honest I didn’t last long with using this and it wasn’t through the fault of the app itself which is actually very well made. One of my other colleagues on the trial pointed out that the iPad is extremely good for consuming but not very good for creating, and I agree with this statement. I can touch type and I suspect many ICT/Computing teachers can too. If you can touch type you will find the on screen keyboard SO UNBELIEVABLY FRUSTRATING, especially if you have long nails. If you are someone who cannot touch type but has learnt to type fast with two fingers however, you will probably love it. I haven’t used Evernote very much because of this reason, I find it takes me 3 times as long to write things up on the ipad than it would to log on to the PC and do it. However, it is neat to have things in one place, and the app is thoughtfully made, so you may love it.

Dropbox – Free

This app is so awesome, and the PC version is almost even better (although it does eat a bit of a chunk of my Vista CPU usage, grrah). It is essentially FREE storage on the internet, and you can drag and drop files from your PC and view them on your ipad. Don’t bother printing out the minutes of a meeting, bring your ipad and have it there in front of you (and other much more rock ‘n roll uses, no doubt!) Sadly, I suspect many schools will have blocked Dropbox so you may find you are unable to use the website. Another potential issue is that you shouldn’t use it to store confidential files or information about students – but this is just common sense to me. I use it to save those worksheets I created at home and need to use the next day in school, and it does me proud. And if you’re too stingy to pay for the extra storage, just keep putting stuff up and deleting stuff as and when necessary. It’s like having your own free USB stick that also works on your iPad. Awesome.

Do you know of any apps which would be good for teaching? Have you done something cool with an iPad in your lesson? Let me know on here or via Twitter @codeboom

Sell Computing A-Level in 3 minutes

One year, I rocked up at school on the 1st September and a huge (but not too huge) set of amazing A-Level pupils walked in the door eager to learn about recursion, black box testing and the intricacies of 8 bit binary. Then I woke up and realised that was all a dream and I had to devise a way of selling Computing A-Level to the whole of Year 11, in three minutes, during an assembly in January. Wowzers.

“You should definitely do Computing – the department has all the latest technology”

I think when I first became a teacher I grossly underestimated how much selling and persuading is necessary to encourage students to do your subject. When first confronted with this task three years ago, my shoulder demon protested “but I’m a techy person, I didn’t sign up to be a saleswoman!”, although this is perhaps a rather feeble excuse given that a) I chose to be a teacher and therefore pretty much “on show”, and b) other techy people (Steve Jobs?) seem to make a damn good job of selling things. So eventually I stopped whining to myself and got on with the task of creating the obligatory Powerpoint presentation to go with my “Computing is not the same as IT” talk.

The first year we decided to go with the serious version and just explain what the subject was and why it was different to what had gone before. We were rather spectacularly upstaged by the presentation for Italian AS which contained equal measures of humour and pictures of hot Italians. Damn.

Last year, we decided to go down the entertaining route too, which actually proved rather profitable. Students who did not even choose the subject still remember and ask me about the first slide – the oh-so-hilarious “There are 10 types of people in the world, those who understand binary and those who don’t” joke – mostly because they DIDN’T GET THE JOKE AND WERE CURIOUS!! Yes! This is exactly the kind of interest I wanted to generate, a curiosity to find out more. I will always remember a particular lecture from university which was a module on the programming language Lisp where the lecturer implemented something to do with traffic lights. (I bet you are probably thinking “you can’t remember it that well” – /rasp to you.) Well, what I do remember is that after it had been explained it all seemed so simple and obvious, and yet so clean and, dare I say it without sound like a maths geek, beautiful. I wanted to know more. It’s a bit of a tall order to impart such a revelation in three minutes, but I’m going to try.

One thing which scares me a little bit is that no matter how good my 3 minute pitch is (and happily we also have some “taster lessons” this year too), I will not be pitching to parents. I know that the perception of Computing is hopelessly muddled in with that of ICT as a “doss subject” and a “subject Universities don’t like”, and our challenge can be ably summed up by the Computing at School website. A friend who is an Economics teacher told me that in the first week of the new term, he asked everyone in his Economics class to tell him why they had chosen that subject. He was very surprised at the answer from a lot of pupils, particularly girls, which was “because my Dad thought it was a good idea”. I really hope that Dads out there like Computing as much as they like Economics.

Anyhow, I thought I would ask – since there are probably a lot of us in the same boat – how would you sell A-Level Computing in 3 minutes? Leave a comment or tweet me @codeboom so I can shamelessly pilfer your ideas 🙂

Thinking Tasks #1 – Boxes function

Quite often after covering a big chunk of theory, I will try to get students to think about how to actually put it into practice. This task was very successful and resulted in one student going away and spending hours trying to figure out how to make the boxes work perfectly. After a bit more theory, it is nicely reusable too in the Noughts and Crosses game (with a little bit of a tweak to print the contents of a 2D array inside the boxes.)

Knowledge needed: Loops, Conditional statements, Print statements

 

1. Create some code which will print a box that looks like this:

+ -- +
|    |
+ -- +

This is a useful learning exercise in itself as students will realise they must print on three separate line to make the box. It also introduced the pipe character which might be useful when they encounter it as the “or” operator in some other languages.

 

2. Now make some code that will use a loop to print a row of boxes.

Here is a good opportunity to use a for loop, e.g. for i in range(5) should print 5 boxes

+ -- + -- + -- + -- + -- +
|    |    |    |    |    |
+ -- + -- + -- + -- + -- +

Fairly predictably, the first thing you will get will be some code that looks a little bit like this and results in a huge mess.

for i in range(5):
    print "+ -- +"

for i in range(5):
    print "|    |"

for i in range(5):    
    print "+ -- +"

Why does this code not work? The print statement moves on to the next line before we are ready. I would then offer this hint: If you don’t want to move on to the next line after printing something, put a comma e.g. print “+”,  This will probably result in them simply inserting a comma at the end of the print statement, which means everything is on the same line (albeit wrapped by the display.)
When do we want to move on to the next line then? Hopefully, some clever person will realise that we need to move to the next line after each loop is done, which is a fabulous place to ask “well how can we do something outside of the loop” and hammer home the beautiful elegance of proper indentation. I suppose you could move on to the next line by printing an empty string with a comma, but this is also a great opportunity to point out that if you did it like that, you would end up with this:

+ -- ++ -- +
|    ||    | 
+ -- ++ -- +

..which is not desirable. As my University logic lecturer used to say, the solution to this is trivial. I used to loathe this expression because I usually had no idea what he had been talking about for the previous 40 minutes, so the solution is below. Please don’t hate me! 🙂

for i in range(5):
    print "+ --",

print "+"

for i in range(5):
    print "|   ",

print "|"

for i in range(5):    
    print "+ --",

print "+"

 

3. Now see if you can use a nested loop to create a square of boxes.

This is useful to reinforce the concept of “nesting”. I usually find students think nesting is the same as indentation. We could just whack a for loop around all three of these other loops and call it a day. However this would have the same problem of duplicate tops and bottoms of boxes that we just solved in part 2 for the sides. The solution is of course to only print the top row once (use an if statement to determine whether this is the first iteration of the outer loop), and then print all of the other rows as U shapes:

|    |
+ -- +

Again, try to have them come up with this – if there are enough people in your class (there never seem to be in mine) they could be working on this problem in pairs or groups. Quite often I find myself going too quickly over things which are really obvious to me – I have to stop myself and not panic about taking 10 minutes over something I think is easy, if it’s a really valuable thinking experience for the class.

 

4. Put your code into a procedure boxes(rows,cols)

Not too tricky you might think, but often tough to reconcile their understanding that the number of times the loop executes is the number of rows or columns in the box.

def boxes(rows, cols):
   # Define rows loop
   for i in range(rows):

      # Put previous column loops here

 

5. Extensions – other stuff you can reasonably ask them to do

It’s always useful to have something else up your sleeve to challenge the really adventurous ones. These are things I have asked people to do, with decent results:

  • Validate the arguments to the procedure to check they are actually integers
  • You may also wish to validate that the arguments are within a given range as if you call the procedure with very large arguments a runtime error will occur due to lack of memory
  • Print column numbers (i.e. each row has 1, 2, 3, 4…etc. in the boxes)
  • Print ascending numbers in the boxes (e.g. for a 3 by 3 box, you would get 1 2 3 in the top row, 4 5 6 in the second row and 7 8 9 in the bottom row)

(Note: both of these are not too hard, but for two or three digit numbers will utterly mess up the pretty linear fashion of the boxes! They will also annoy the students because of the loop counter starting at 0 thing…something good to get used to!)

  • Print the ascending numbers in the boxes as above, without the boxes breaking and looking like a dog’s brekkie. Bow wow.
+ -- + -- + -- +
|  1 |  2 |  3 |
+ -- + -- + -- +
|  4 |  5 |  6 |
+ -- + -- + -- +
|  7 |  8 |  9 |
+ -- + -- + -- +

 

Worksheet and the solutions

Here is the Thinking_Tasks_Boxes worksheet I give out with this lesson. It’s not the prettiest worksheet ever, but it works. I have full solutions to all of the problems including the extensions, but to avoid enterprising students (including my own!) using them you’ll need to tweet me @codeboom 🙂

Also two other things. Is it possible to get a syntax highlighter for WordPress? And also check out the “Sweet resources” section (Dude!) for my full student book for OCR AS Computing F452.