Shootout – Session 1


imageThis week we will be starting a new game – Shootout. It is essentially a reaction time test, but using a western gunfight theme. Yosemite Sam will draw and fire and the player must shoot him after he draws, but before he fires. If you shoot him before he draws then you will surely hang for killing an innocent man, but if you wait too long…

To tackle this game we will be looking at a really common pattern in computer programming – the finite state machine (or FSM). This is a really useful way of breaking down the computational logic required for many tasks you will encounter.

But before we get onto that, we need to create the usual basic game framework – a loop which cycles updating our game data and drawing the screen. As previously we will break this down into functions that each deal with a specific aspect of the game.

In a new python file, import the libraries we are going to need – pygame, sys and random.

import sys, pygame, random

Now we need to create our function structure.

Init

This function completes all the one-time initialisation of the game. Things that are done once, and only once, when our program is first run – such as creating the game screen window and loading the game assets into memory.

def Init():
global screen, current_keys, current_mouse, \
background_surface, gamestate, \
big_font, little_font


# Initialise pygame - must always be done first
pygame.init()

gamestate =
"Start"


# Set the screen size using background image size
background_surface = pygame.image.load("images/Background.png")
screen_size = background_surface.get_size()
screen = pygame.display.set_mode(screen_size)


# Convert the surfaces according to the screen bitdepths
# This will dramatically speed up blitting later
background_surface = background_surface.convert()


# Load a big and little font
big_font = pygame.font.Font(None, 72)
little_font = pygame.font.Font(
None, 36)


# Initialise our pressed key list
current_keys = pygame.key.get_pressed()
current_mouse = pygame.mouse.get_pressed()

Reset

This function resets all the properties of our game for each go. Having started the game up, we expect the player to have several go’s and so this function will be called lots of times. Since we haven’t started to create our game yet, this function is empty and we can just use the return keyword. As the game develops, we will add more code here.

def Reset():
return

GameLoop

The main process of repeating the update and draw cycle. This function will only complete and return when we ‘quit’ the game – this is triggered by setting the gamestate variable to “Quit”.

def GameLoop():
global gamestate
while gamestate is not "Quit":
for event in pygame.event.get():
if event.type == pygame.QUIT:
gamestate =
"Quit"



Update()
Draw()


# If we get here, we should quit
sys.exit()

Update

This function processes all the changes to the game data in response to time, user input or other events.

def Update():
global current_keys, last_keys, current_mouse, last_mouse
last_keys = current_keys
current_keys = pygame.key.get_pressed()

last_mouse = current_mouse
current_mouse = pygame.mouse.get_pressed()
elapsed_ms = pygame.time.Clock().tick(30)

Draw

This function constructs and draws our screen. As you create more sophisticated game loops, you will find that you will usually call the update and draw functions at different rates so keeping this work logically separate is a good habit to get into.

Call the functions

Finally we need to actually call these functions (remember, they are only defined so far and so won’t actually run), so at the bottom of your file add your calls.

Init()
Reset()
GameLoop()

Now you should be able to F5 and see your window created according to the background image and the loop should run until you close the window. Essentially, this set of code is the basis of any game you may wish to start, so it might be a good idea to keep a copy of it somewhere so you can reuse it easily in the future. Next week we’ll discuss how to structure and begin adding our game logic to this framework.

Quick Skills Builder


After last week’s Python refresher, those of you who would like to consolidate the topics we covered can have a crack at this guided tutorial:

https://www.codecademy.com/courses/python-beginner-en-4XuFm/0/1

We’ll be on hand to discuss the interesting bits and at the end you should have your first fully functional version of a very simple Battleships game – ready for some enhancements and customisation if you finish it with time to spare! More importantly though, you should also have the set of coding concepts we will put to further use with some graphics and pygame next week.

Python Crash Course


Introduction

This page details the absolute essentials that you need to know to get up an running with Python. This short list of concepts is deceptively powerful. If you get these ideas really clear in your mind and spend some time experimenting with IDLE, you will be well on your way to getting your coding chops.

Comments & Indents

Any line that starts with # is called a comment and is ignored by Python. These are where you can document your code


# This is a comment, it will be ignored by python

Python uses space or tab indenting to group code. On the screen you cannot see spaces or tabs but they do have a unique code inside your text file, so they are known as ‘whitespace’ and they really matter in Python!


flag = True

# Logic Test
if flag is True:
    # Indented code is treated as a group or block
    # It 'belongs' to the test above
    # It is run if the test succeeds
    print("Only print this if flag is true!")

# No indenting means this code is NOT part
# of the test and will run regardless of flag
print("Always print this")

EITHER indent using spaces OR tabs. Don’t use a mixture, it will cause an error. Be careful of this problem if you cut and paste someone else’s code into your own – they may have used different indenting.

Strings & Numbers

Python represents the whole number 2 differently from the text symbol for it, which is ‘2’.

Letters and other text symbols are called characters. Groups of characters are called Strings. Characters and strings are always represented inside inverted commas, or quotation marks.


this_is_a_string = Two
so_is_this = 2
and_this_is_a_single_text_character = 2
but_this_is_a_number = 2

Whole numbers are called Integers


this_is_an_integer = 2

Python can only combine or compare like types so you will often need to convert one form to the other.

Integer to String


str(2) # returns '2'

will return the string equivalent of 2, which is ‘2’

String to Integer


int(‘2’) # returns 2

will return the integer equivalent of ‘2’, which is 2

Strings & Integers are just two of the types of data that you can create, store, modify and retrieve. When they are created we give them a name label. Because the data associated with the label can change, we often call these name labels variables. Below are the more of the common types of data you can create and reference using named variables.

Tuples & Lists

It is often useful to keep groups of numbers or strings together under a single variable name if they represent related information. The width and height of your display window, for example are often kept together.

Tuples

If the numbers will not need to be changed during your program - for example, the width and height of your graphics window will be set once when the window is created but not changed while your program runs – then you can use a tuple. Tuples are created using a comma ‘,’ separated list of data between two normal brackets ‘(‘ ‘)’


my_screen_res_tuple = (640, 480)

You can access an individual value within a tuple by specifying the index of the item in the tuple


my_screen_res_tuple[0] # will return 640

All indexes start from 0. The first item in a tuple, list or dictionary is at index 0, the second at index 1 etc.

Lists

List are very like tuples, but you can modify them as your program is running. You create a list using a comma ‘,’ separated list of data between two square braces‘[‘ ‘]’


my_flexible_list = [2, 4, e’, 25, 2’, a string’, 5, 2’]
my_flexible_list[2] # will return ‘e’
my_flexible_list[2] = f # will replace ‘e’ with ‘f’
my_flexible_list[1:3] # will return a new list - [4, ‘e’]
len(my_flexible_list) # returns the length of the list – 8
my_flexible_list.append(42) # adds 42 to the end of the list - [2, 4, ‘e’, 25, ‘2’, ‘a string’, 5, ‘2’, 42]

Strings are a List of characters. You can manipulate strings in the same way as a list.

Dictionaries

Dictionaries are a bit like lists, but with labels for each item. Instead of finding items by their index, you can find an item by its label. You create a dictionary using a comma ‘,’ separated list of labels & data between two curly braces‘{‘ ‘}’. Label and data pairs are separated by a colon ‘:’


my_dictionary = {“Item 1 Label”:101, Second Label”:23}
my_dictionary[“Second Label”] # returns 23
Item 1 Label in my_dictionary # returns True

Logic

Logic allows you to test the state of variables and make your code ‘branch’ in different directions depending on the outcome of the test. The logical test can have several parts to it, but always ends with a colon ':'. The code block to be run if the test succeeds must be indented below it.


if test:
	# Do indented code here, if test is True
elif other_test:
	# Do indented code here, if other_test is True
else:
	# Do indented code here, only if test and other_test are False

You can use the if block on its own without an else (or any elif's).

You can also have as many elif blocks as you need, but there should never be more than one else

Loops

Loops allow you to repeated indented code blocks. You can repeat until a logical test becomes False by using a While loop. The Loop declaration, like logic, ends with a colon ':' and the block of code to be looped must be indented below it.


flag = True

while flag:
	# Indented code here is repeated
	# until flag becomes False	

You can repeat a fixed number of times using a For loop.


for thing in my_list:
	# Indented code here is repeated
	# for each item in my_list
	# You can access the item 
	# using the 'thing' variable 
    # each iteration	
	
for x in range(10):
	# Indented code repeated 10 times
	# x will be 0 through 9
	# as the loop repeats
	print(x)
	
for x in range(5,10):
	# Indented code repeated 5 times
	# x will be 5 through 9
	# as the loop repeats
	print(x)

GCC Restarts This Week (Feb 24 2016)


Lets get the second half of this term underway with a bit of game coding! I’ll be starting a Python Crash Course (or ‘Refresher’, depending on your perspective) for those who are new to the club, preparing for their GCSE project, or would just like to brush up on their skills.

For everyone else, there is still plenty of interesting stuff to do on building your game levels or extending the game engine for YumikosAdventure. I’ve noticed a couple of people have branched the github repository, so I’m interested to see what you have been up to over the half-term break. See you there. E

GCC 2016 is here!


The first session of the New Year will be this Wednesday:

Wednesday 13 January @ 7-8pm

We hope you all had a great Christmas break with plenty of coding and gadgets to tell us about when you get there. We are planning a very cool tiled-map based game this term using the excellent Tiled map editor. If you want to get a bit of a head start, you should take a look at http://www.mapeditor.org/ and there is an tutorial video here: https://www.youtube.com/watch?v=ZwaomOYGuYo

GCC is Back This Wednesday!


Everything is up an running with shiny new versions of Python, pygame and our other game dev tools. Make sure you join us for 7-8pm in L24. We’ll start the term off with a bit of retro-gaming on the RPi’s for a bit of fun and inspiration. Nick is working hard on a brand new game framework for us to work through and we’ll also be making extensive use of Codeacademy this term to hone our python and javascript game coding skills.

Don’t forget to bring along your own laptops and Pi’s if you want, and we’re looking forward to seeing what projects you’ve been up to over the break. See you there! E

Computer Club Cancelled Until Further Notice :(


I’m afraid that the changes to the school computer lab are still precluding us from restarting the computer club. It seems that all of the club’s tools and code samples were removed by the school over the summer and we have been unable to get them reinstated so far – without basic coding tools we obviously cannot teach coding.

We *hope* that we might be allowed to restart in the next half of the term but as I’m sure you can appreciate it is quite a commitment for the helpers (and your parents!) and after four cancellations in a row I think we are better to write-off this half-term now. I am, of course, very sorry.

If you are still coding in your spare time (I hope you are) then do drop me a line at my raspberrypilot.com email address at any time with any computing questions you may have and we can still try and help out with your code and projects.

Hopefully see you after the half-term break.

E

No Games Creators Club again this week :(


There will be no session this week on Wednesday 23 or 30 September due to on-going difficulties with the computer lab & the school open evening. We *hope* that normal service will resume soon, currently we're aiming for:

Wednesday 7 October– 7-8pm.

But watch this space please…

Sorry about the delay in getting back up an running.

Welcome back to Games Creators Computer Club 2015-16!


It’s been all change in the computer lab over the summer, so we can look forward to a big update to the computers we use at the club. We’re still waiting to hear when this work will be complete and our games tools will be ready to roll again, so unfortunately there won’t be a club session this week (no session on Wednesday 16 September). But watch this space and we’ll have things underway as soon as we can. Lots of new, fun  and interesting stuff ahead…