Python in SteamOS

Want to learn programming so you could create a new computer game? You might have heard that you can do it with a Steam Machine and it led you to read this.

You do not need a Steam to make a game. Alternatively you could study javascript and html. There are ways to draw 3D models in browsers. Many operating systems have their own ways to code games as well. This tutorial introduces to some of the tools that SteamOS can provide.

Why learn programming to make games?

You have probably heard or thought about this question: Why aren't you using a game engine or game making software? If you had not stumbled to the question before someone would have eventually asked it. The answer is that you still have to learn programming to use those tools at all.

Game making software lets you create animations, paths. It lets you position boxes, models and sounds into a scene. It also lets you attach physics engine to the objects on the scenery so they move and collide to others.

Asset positioning is all cool but all the assets you create do not magically become a living thing that responds to what you do in the game. The scenery jumps into life only when you write a script. You need code to get game controller move the player, or check when the game has been won or lost. The scenery might sit there just for some moment and you need code to trigger switch from one scene to an another.

Word of warning though. I never really arrived to finishing any of games I meant to write. The programming, different kind of productivity tools and tutorial design became so exciting that I sticked to that. Perhaps you arrive there? I'll try to make sure of it.

Terminal Access

You need an environment for programming. It consists of all the tools you need for creating programs and trying them out.

You might have heard the term IDE or Integrated Development Environment. It's an application for programming. It usually comes with several tools that let you write some code, turn it into a computer program and search what's wrong in the code when it doesn't work properly. The problem is that you can't switch between tools different IDEs provide. Either you get all them or you don't get the IDE at all. You end up using the certain tools, were they useful for your work or not.

Instead of jailing yourself inside some single software you can use several small programs that do what you need. This method lets you switch between tools whenever you find a better replacement. You can also repurpose some of those programs to do the things you need. Funny thing is that most of programming is quite similar after all. You're going to use the same tools that are used to program SteamOS itself, and some of your own. You can write new tools easily when you need to do so, and they are on equal footing to the tools you did not write yourself.

You still need some environment for programming. How do you find that from SteamOS? Get into desktop mode and find a program called "Terminal". When you open the terminal, it prints out some text into a big box. The text reads like this:

steam@steamos:~$

You can use the terminal to start up programs and pass files around them. It starts into a working directory ~, which points you a directory where you work. Whenever you type a command and press return, the command evaluates and does something. Here's what happens when you type ls and press return:

steam@steamos:~$ ls
Desktop     Downloads   Pictures   Templates
Documents   Music       Public     Videos
steam@steamos:~$

The command ls lists the working directory contents for you. It might return nothing if your home(~) directory is empty.

When the command finishes, the terminal writes a prompt to ask for new input. You can do some programming with terminal prompt alone, but you easily end up with a script that is really hard to understand. For that we have a python. We can open a python prompt by running the command:

steam@steamos:~$ python
Python 2.7.3  (default, Nov  3 2013, 17:05:49) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

The command doesn't finish, instead it gives it's own prompt >>>. You can exit it by pressing ctrl + d, which kills the program running in the terminal.

You can type your first program into the prompt. It evaluates the program you type into it.

steam@steamos:~$ python
Python 2.7.3  (default, Nov  3 2013, 17:05:49) 
[GCC 4.7.2] on linux2
>>> print("hello world")
hello world
>>>

What's the time now? Is it morning or evening?

>>> from datetime import datetime
>>> if datetime.now().hour <= 12:
...     print("morning")
... else:
...     print("evening")
... 
morning
>>>

As you can see, you can write larger clauses into the prompt and they get evaluated. This way you can try out some simple expressions when you're unsure what they do. It's 6AM when I'm writing this tutorial, how to make it show that?

>>> hour = datetime.now().hour
>>> if hour <= 12:
...     print(str(hour) + "AM")
... else:
...     print(str(hour) + "PM")
... 
6AM
>>>

Uh oh. So what's next? Well lets exit the prompt and write that program into a file. cat can be used to write and read files from the terminal.

steam@steamos:~$ cat > hour.py
hour = datetime.now().hour
if hour <= 12:
    print(str(hour) + "AM")
else:
    print(str(hour) + "PM")

Press ctrl + d to kill the cat. It's not a real kitty so don't feel bad about it. Lets try the program we just wrote.

steam@steamos:~$ python hour.py
Traceback (most recent call last):
  File "hour.py", line 1, in <module>
    hour = datetime.now().hour
NameError: name 'datetime' is not defined
steam@steamos:~$

Whoops we forgot a line! So are we going to fix it with the cat? No. It's too tedious to retype the whole program always when you need to change it.

Text editing in terminal with VIM

Now you probably want to fix that broken program from the last section. We know it's missing a line from the beginning. Type vi into the terminal and it opens a screen that calls to help poor children in Uganda. The editor is empty. We should first help ourselves, so lets type :q for now.

So how do you open the hour.py into VIM? Add the filename into the command:

steam@steamos:~$ vi hour.py

The bottom of the terminal says: "hour.py 5 lines, 102 characters which means you have the file open. Type O and see how the whole body of text jumps downwards. You just inserted a line over you. If you did it wrong and typed o instead, you opened a line under you. Let's fix it later if you did so, now type:

from datetime import datetime

Now press Esc and type :w. The bottom of the terminal says: "hour.py 6 lines, 132 characters written so you know that the file was changed.

If you pressed just o earlier, how do you fix that? You see a block there. It's the cursor. You can move it in the file. Try type j and then k. See? It is moving. If you press h or l, it moves horizontally. What's this sorcery? Well the keyboard hasn't always been like this and VIM is really old software. There used to be arrows in the home row buttons a long time ago. The arrows disappeared but the commands were never removed because it's really convenient this way. There's also other nice movement commands:

0    to beginning of the line
$    to end of the line
gg   to beginning of the file
G    to end of the file
5gg  to fifth line.
5j   five lines down.

Now how do you move a line somewhere else? Move the cursor over the line, type dd, then move to the beginning of the file, type P. If you typed p instead, the line will appear back to the wrong location so it's sort of frustrating at first. You'll get used to it.

What if you have something like datetimen instead of datetime. Move the cursor over the excess n and press x. That'll teach them! If you have more things wrong you can press v to transform your cursor into a big evil visual painting brush. Navigate over the text to paint it. Now you can do several things:

p   replace with something you just killed
d   kill
c   write over

The VIM authors used the term 'kill' instead of 'remove' to make it sound more exciting than it is. Actually it's not even removing the text permanently. Instead the text goes into a hidden file, from where you can 'yank' the text back by pressing p If you press V, you can select whole lines.

Type :wq to finish editing and exit the editor. The file should look like this when you're done:

from datetime import datetime
hour = datetime.now().hour
if hour <= 12:
    print(str(hour) + "AM")
else:
    print(str(hour) + "PM")

Now lets try it out:

steam@steamos:~$ cat hour.py
from datetime import datetime
hour = datetime.now().hour
if hour <= 12:
    print(str(hour) + "AM")
else:
    print(str(hour) + "PM")
steam@steamos:~$ python hour.py
7AM
steam@steamos:~$

It takes time to teach arcane editor commands. Why did I told you something like that anyway? Aren't there easier way to edit files? Well there is the modeless grandma's way to edit files yes. Such editors have been designed for people who do not understand that computer program can wait for more keypresses or that there's an Esc key.

If you are going to do programming then you are supposed to understand computers very well though. You are also supposed to tinker with source code and VIM has been designed for such task. It's also easily accessible from the terminal. Well it's standard software for most terminals. If you know VIM it means you can always edit a text file.

Finally lets remove the file because it's just a tutorial after all. You can return to this page to copy it if you need it for something.

steam@steamos:~$ rm hour.py

Tabs and Spaces

If you input a tab in VIM editor, it produces a special tab character. In python code you're supposed to indent every line with 4 spaces. If you mess this up the python will respond with IndentationError: unexpected indent.

VIM can be configured to do expand indentation into spaces. Also if you press tab it will probably equal to 8 character spacing. Add these lines into the ~/.vimrc.

set expandtab
set tabstop=4

Now your editor doesn't insert tab characters at all.

Python code

If a python program has been written even a little bit wrong it doesn't do what it is supposed to do. Instead it may return that odd Traceback message we saw earlier. It may also do something you didn't want from it.

That's the reason why computers have bugs in them. You don't always get to express yourself clearly. You also tend to forget or not even know about things. What you do not know ends up reflected into the program you write.

You probably noticed already that python scripts evaluate line by line when they do. Let's walk through some grammatic structures we used in this tutorial.

Statements

Statements appear on line, and they might have block of statements after them.

import {module name}
from {module name} import {name}

The import -statement loads a module if it's not been loaded and hands out a name from within it. This is the way to extend the python language. We reached into datetime -module to get datetime -object, which we then used to measure time.

if {expression}:
    {statement block}
else:
    {statement block}

If -statement is used to express logic. We used it to evaluate different blocks depending on whether the computer thinks it's a morning or evening.

{variable} = {expression}

This statement assigns a value to a variable. It was used to remember the number that signified hour of the day so we could print the number after we used it to check whether the hour of the day was less than 12.

Expressions

We combined these two:

{expression}.{name}
{expression}()

Into this:

{expression}.{name}().{name}

datetime.now().hour

This expression evaluated a method now in datetime object to retrieve the current time. We were only interested about the hour of the day, so we took just the hour and dropped everything else.

Infix expressions

We used one comparison operator to determine whether it was morning or evening, from the hour of the day.

{expression} != {expression}    inequal to
{expression} == {expression}    equal to
{expression} >= {expression}    greater or equal to
{expression} <= {expression}    less or equal to
{expression} < {expression}     less than
{expression} > {expression}     greater than

We also used one of these:

{expression} + {expression}    addition or concatenation
{expression} - {expression}    subtraction
{expression} * {expression}    multiplication
{expression} / {expression}    division
{expression} % {expression}    modulus

Normally you do boring mathematics with them. We used them to catenate two strings together!

Onwards!

You've finished the first tutorial, but don't stop!

If you are very eager to learn more about python, you can read the Python documentation. It's not a requirement for understanding future tutorials though. I try to explain things and I might explain them better than the documentation is doing.

If you absolutely want to store your first programs, you can create directory for them and create them into that directory:

steam@steamos:~$ mkdir python-study
steam@steamos:~$ cd python-study/
steam@steamos:~/python-study$ ls
steam@steamos:~/python-study$

You can also move files you already created.

steam@steamos:~/python-study$ mv ../hour.py .

You can remove the directory like this if you don't want to save them after all:

steam@steamos:~$ rm -rf python-study/

If you want to play more, you could try these commands in python:

>>> raw_input()
>>> raw_input('> ')
>>> 5 + 2
>>> 5 * 2 - 3
>>> 5 * (2 - 3)
>>> 2 - 3
>>> 5 * 2
>>> 10 - 3

Press Ctrl + c to interrupt any program.

>>> while True:
...     print "jam"
... 
jam
jam
jam
jam
jam
jam
jam
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyboardInterrupt
>>>

If you can get it to write out "jam 1 jam 2 jam 3" up to 300 and then stop with less than 5 lines, I think you might have learned something here. The thing is, you're supposed to experiment here. Large part of programming is experimentation. You are going to try out things to see whether they work.

You might be wondering is this any better than game making tools? After all you were able to put in assets there and such. Now you're looking at blank screen with text on it. Well it's up to you decide what you need.

In the next tutorial we'll be getting graphical and musical. It's going to be harder to do than this so I'll provide a library to make it little bit easier. Actually this is equivalent to using game making tools. It's just more compatible with everything. Can you imagine? For example, you could reflect real-time weather within your game. How easy is that in the game maker?

Similar posts