100% found this document useful (8 votes)
750 views

Coding Club Level 3 Python Building Big Apps Roffey C. 2024 Scribd Download

Building

Uploaded by

cristcigelj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (8 votes)
750 views

Coding Club Level 3 Python Building Big Apps Roffey C. 2024 Scribd Download

Building

Uploaded by

cristcigelj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

Download the full version of the ebook now at ebookultra.

com

Coding Club Level 3 Python Building Big Apps


Roffey C.

https://ebookultra.com/download/coding-club-
level-3-python-building-big-apps-roffey-c/

Explore and download more ebook at https://ebookultra.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Coding Club Level 1 Python Basics Roffey C.

https://ebookultra.com/download/coding-club-level-1-python-basics-
roffey-c/

ebookultra.com

Building iphone apps with html css and javascript Making


App Store Apps Without Objective C or Cocoa 1st Edition
Stark
https://ebookultra.com/download/building-iphone-apps-with-html-css-
and-javascript-making-app-store-apps-without-objective-c-or-cocoa-1st-
edition-stark/
ebookultra.com

Building Fluency Grade 3 Compilation

https://ebookultra.com/download/building-fluency-grade-3-compilation/

ebookultra.com

Dead Simple Python Idiomatic Python for the Impatient


Programmer Jason C. Mcdonald

https://ebookultra.com/download/dead-simple-python-idiomatic-python-
for-the-impatient-programmer-jason-c-mcdonald/

ebookultra.com
Python 3 for Absolute Beginners 1st Edition Tim Hall

https://ebookultra.com/download/python-3-for-absolute-beginners-1st-
edition-tim-hall/

ebookultra.com

C Python Tricks And Tips 4th Edition

https://ebookultra.com/download/c-python-tricks-and-tips-4th-edition/

ebookultra.com

Laravel a Framework for Building Modern PHP Apps 2nd ed


Edition Stauffer

https://ebookultra.com/download/laravel-a-framework-for-building-
modern-php-apps-2nd-ed-edition-stauffer/

ebookultra.com

Numerical Methods in Engineering with Python 3 3rd Edition


Jaan Kiusalaas

https://ebookultra.com/download/numerical-methods-in-engineering-with-
python-3-3rd-edition-jaan-kiusalaas/

ebookultra.com

Battle for Big Tree Country Page Turners Level 11 1st


Edition Gregory Strong

https://ebookultra.com/download/battle-for-big-tree-country-page-
turners-level-11-1st-edition-gregory-strong/

ebookultra.com
Coding Club Level 3 Python Building Big Apps Roffey C.
Digital Instant Download
Author(s): Roffey C.
ISBN(s): 9781107666870, 1107666872
Edition: Spi ed.
File Details: PDF, 3.69 MB
Year: 2013
Language: english
Cod
i
Clu ng
Python b
Building
BIG Apps level 3
Chris Roffey
Cod
i
Clu ng
Python b
Building
BIG Apps level 3
Chris Roffey
cambridge university press
Cambridge, New York, Melbourne, Madrid, Cape Town,
Singapore, São Paulo, Delhi, Mexico City

Cambridge University Press


The Edinburgh Building, Cambridge CB2 8RU, UK

www.cambridge.org
Information on this title: www.cambridge.org/9781107666870

© Cambridge University Press 2013

This publication is in copyright. Subject to statutory exception


and to the provisions of relevant collective licensing agreements,
no reproduction of any part may take place without the written
permission of Cambridge University Press.

First published 2013

Printed in Poland by Opolgraf

A catalogue record for this publication is available from the British Library

ISBN 978-1-107-66687-0 Paperback

Cambridge University Press has no responsibility for the persistence or


accuracy of URLs for external or third-party internet websites referred to in
this publication, and does not guarantee that any content on such websites is,
or will remain, accurate or appropriate.
Contents
Introduction 4

Chapter 1: Can you guess my password? 7

Chapter 2: Objects, classes and factories 17

The MyPong Project 32

Chapter 3: Creating the Table 34

Chapter 4: Making the Ball 51

Chapter 5: Building the Bats 69

Chapter 6: The rules and scoring 91

Bonus Chapter: Two more games 106

Taking things further 120

Appendix: Some key bits of information 123

Glossary and index 126

Quick Quiz answers 131

Acknowledgements 132
Contents 3
Introduction
Who is this book for?
This book is the Level 3 core book in the Coding Club series. Before reading this, you should
have either read Coding Club, Python: Next Steps or have become familiar with Python 3 and
learned about variables, while loops, lists and tuples. This book is aimed at coders with a
little bit of previous programming experience.

Why should you choose this book?


Building larger programs and applications can seem daunting. As well as sorting out the
normal details and algorithms, the big picture has to be maintained. This book helps you to
see your way through the big picture – it shows you how to break your applications up into
manageable chunks that are logical, and even better, reusable. To do this you are given an
introduction to a style of programming called object oriented programming (OOP). This is
a great way to program but might seem a little more complicated at first than the way you
have learned to code in the level 1 and 2 books.

Introduction 4
At this stage in your coding it is important that you are introduced to classes and objects.
This is because you will certainly want to use other people’s classes, and to do this effectively
a little understanding goes a long way. What is special about this book is how the
explanations are rooted in the real world and use analogies that you will understand. The
code is also built so that it mirrors real objects whenever possible. This is so that when you
go on to write your own applications you will be able to imagine how to convert real objects
into coded objects.

What you will need


Any type of computer can run Python 3. If yours does not already have it installed, there is a
section on the companion website (www.codingclub.co.uk) that guides you through installing
IDLE and Python 3. This only takes about 5 minutes, and is all you require to get started.

So that you do not have to do too much typing and do not get lost in the bigger projects,
there are start files and, if you need them, finished files for all the projects in the book in one
easily downloadable zip file. The website also has answers to the puzzles and challenges to
help you if you get stuck.

How to use this book


The ideal way to use this book is to read everything carefully and build all the main projects
in order. At the end of each chapter there are further ideas, and challenges that you can
think of as ‘mini quests’. Some readers will want to work through them all so that they
understand everything all the time. Some of you will probably prefer to rush through and get
to the end. Which approach is best? The one you are most comfortable with. However, if you
are being guided by a teacher, you should trust their judgement so that they can help you in
the best possible way.
Introduction 5
There are four ways in which this book tries to help you to learn:

1 Typing out the code – this is important as it encourages you to work through the code a
line at a time (like computers do) and will help you to remember the details in the future.
2 Finding and fixing errors – error messages in Python give you some clues as to what
has gone wrong. Solving these problems yourself will help you to become a better
programmer. To avoid feeling bored and frustrated though, the code can be downloaded
from the companion website www.codingclub.co.uk
3 Experimenting – feel free to experiment with the code you write. See what else you can
make it do. If you try all of the challenges, puzzles and ideas, and generally play with the
code, this will help you learn how to write code like a pro.
4 Finally, this book will not only provide the code to build some pretty cool, short
projects – it will also teach you how the programs were designed. You can then use the
same methods to design your own applications.

A word of warning
You may be tempted to simply get the code off the website instead of typing it yourself. If you
do, you will probably find that you cannot remember how to write code so easily later. In
this book you will only be asked to type small chunks of code at a time – remember that this
will help you understand every detail of each of your programs.

Introduction 6
Chapter 1
Can you guess my password?
This book assumes that you have read Coding Club: Python Basics. If you have not, you
should at least understand what variables and functions are and know how to use IDLE in
both interactive mode and script mode. In this first chapter you will recall some of this by
making a very simple application called ‘Guess My Password’. You will then have revised:

• variables

• if, elif and else

• functions

• while loops

• modules

• using IDLE’s script mode.

Chapter 1: Can you guess my password? 7


Guess My Password
The game is going to start by asking the player to guess my password. The app then waits for
the player’s input, which is stored in a variable. Finally, the player’s input will be compared
with the computer’s own secret password. If the guess is correct the player is congratulated, if
not, a random message is supplied and then the player is asked to try again.

As in the previous Coding Club books, you will use IDLE, an example of an IDE. You can start by
opening IDLE and then choosing New Window from the File menu. This gets you into IDLE’s script
mode. It is a good idea to now re-arrange the windows so that the interactive mode console and
new window are next to each other and both can be seen at the same time (Figure 1.1).

Python 3.1.3 (r313:86834, Nov 28 2010, 10:01:07) # GuessMyPassword.py is a quick revision application.
[GCC 4.4.5] on linux2
Type "copyright", "credits" or "license()" for more information. import random
==== No Subprocess ====
>>> # Initialise variables:
Hello. response1 = "I am afraid not. Please try again."
response2 = "That is a good password but not my password. Keep guessing."
See if you can guess my password? Abracadabra response3 = "That is not my password. It really is easy to guess my password."
I am afraid not. Please try again. response4 = "Well done! You must work for MI6. Give my regards to James Bond."
MY_PASSWORD = "my password"
What is your next guess?
# Function to find out if the user has guessed correctly:
def is_correct(guess, password):
if guess == password:
guess_correct = True
else:

interactive mode script mode


Figure 1.1 A simple IDLE arrangement.
Chapter 1: Can you guess my password? 8
Copy the code from Code Box 1.1 and save the file to your Python Code folder as
GuessMyPassword.py. You may not have a Python Code folder so you might need to create
one first. Choose a sensible place to save this, such as your Documents folder.

Code Box 1.1


# GuessMyPassword.py is a quick revision application.

import random

# Initialise variables:
response1 = "I am afraid not. Please try again."
response2 = "
That is a good password but not my password. Keep guessing."
response3 = "
That is not my password. It really is easy to guess my password."
response4 = "
Well done! You must work for MI6. Give my regards to James Bond."
MY_PASSWORD = "my password"

Analysis of Code Box 1.1


Comments

Comments appear in red in IDLE; these are aimed at humans only and begin with the
hash symbol #.

Chapter 1: Can you guess my password? 9


Modules

A module is a collection of useful functions and data in one place. Sometimes we will want
to write our own. Modules have to be imported before they can be used. In this app the
random module is imported so that it can be used later in the program. Variable value
(a string)
n
Variables

i
ase t r y a ga
These are labels we make to allow us to access data. We create a variable by giving it a
name and then assign data to it using the equals operator. Good programmers begin
their variable names with lowercase letters and make them descriptive. The name for
a constant is all in capitals.

Ple
You have just created five string type variables and labeled them response1,
response2, response3, response4 and MY_PASSWORD. response1
MY_PASSWORD is a constant – it does not change.

Functions
Variable name
Figure 1.2 A variable called response1
storing a string.
A function is a piece of code that can be used again and again. You can already
use any of the many functions that are built into Python. You can also make your own.
Functions are created with the def keyword. Here is the code for a function that finds out if
the guess is the correct password.

Chapter 1: Can you guess my password? 10


Code Box 1.2 Have you saved yet?
# Function to find out if the user has guessed correctly: You should try and
remember to do so after
def is_correct(guess, password):
entering each Code Box.
if guess == password:
guess_correct = True
else:
guess_correct = False
return guess_correct

Add the code from Code Box 1.2 to your GuessMyPassword.py file. The is_correct()
function has to be passed an argument called guess and another argument called
password. The function then compares the two strings. If they are the same, the function
sets the guess_correct variable to True, if not it sets it to False. Finally the function
will return True or False – depending on the state the guess_correct variable is in.
A variable that only stores the values True or False is called a boolean variable.

User input
To get user input from the keyboard we use Python’s input() function which waits for the
user to type some text and press the enter key. If we want to be able to access the input later
we need to assign it to a variable like this:

user_input = input()

Chapter 1: Can you guess my password? 11


The function can also take an argument, usually a string, which can act as an output
message. This appears on the screen and then the program waits for the user’s input:

user_input = input("Please type some input: ")

Now we are able to access the input, for example, in a print function:

print(user_input)
This program contains
one of those jokes that
We use the input() function three times in this program, in two different ways. are far more fun to tell
Now it is time to finish the program by adding the code from Code Box 1.3 to your than to hear.

GuessMyPassword.py file. As you type, think carefully about what each line does.

Code Box 1.3


# Start the game:
print("Hello.\n")
users_guess = input("See if you can guess my password? ")

# Use our function:


true_or_false = is_correct(users_guess,MY_PASSWORD)

# Run the game until the user is correct:


while true_or_false == False:
computer_response = random.randint(1, 3)

Chapter 1: Can you guess my password? 12


if computer_response == 1:
print(response1)
elif computer_response == 2:
print(response2)
else:
print(response3)

# Collect the user's next guess:


users_guess = input("\nWhat is your next guess? ")

# Use our function again:


true_or_false = is_correct(users_guess, MY_PASSWORD)

# End the game:


print(response4)
input("\n\n\nPress RETURN to exit.")

Analysis of Code Box 1.3


Hopefully you can remember how a while loop works, as described in Coding Club: Python Basics.
If not, do not worry as it is fairly obvious what is going on. The code that is indented after

while true_or_false == False:

forms a block of code. This code keeps running until the true_or_false variable is True.

Chapter 1: Can you guess my password? 13


random.randint(1, 3) generates a random number between one and three. The
randint() function is from the random library so it is necessary to use the dot operator to
tell our application where to find it.

Many computer languages use the structure:

if: [do something]


elseif: [do something else]
else: [do something different again]

elif is Python’s version of elseif. You can have as many elif clauses as you wish but
they must be preceded by an if clause and must end with an else clause.

Delving Deeper
Writing less code
Coders love finding ways of performing the same task with less code. Hopefully you have found the function
in Code Box 1.2 easy to understand and follow. It is logical. There is, however, a lot of unnecessary code in it
because we can simply use comparative operators to compare two variables and return True if they are the
same and False if not. Hence the whole function in Code Box 1.2 can be replaced with this:
def is_correct(guess, password):
return guess == password
Try it out yourself and see that it still works.

Chapter 1: Can you guess my password? 14


Chapter summary
In this chapter you have revised:

• variables
• if, elif and else clauses
• functions
• while loops
• modules and used the Python’s random module
• how to use IDLE’s script mode to write and keep your own programs.

As this is a revision chapter, you can now just play with this application if you want. If you
feel you need some practice, try the ideas below.

Idea 1
Change all the variables so they are a little more helpful and give a clue. (Hint: “Read the
question carefully” would be a good clue.)

Chapter 1: Can you guess my password? 15


Idea 2
Make the app a little more useful by enabling the player to respond “yes” to, “Do you give
up?” This will need a separate message (response5 perhaps?) that is triggered after the
player has guessed three times. (Hint: set a counter variable in the while loop.) Finally, if
the player gives up, tell them the password.

An answer and all the source code for this book can be downloaded from the companion I know the password.
website www.codingclub.co.uk. One answer (there are many different ways to solve these
problems) is in the Chapter 1 folder in the Answers file and is called Ch1-Idea2.py.

Chapter 1: Can you guess my password? 16


Chapter 2
Objects, classes and factories
By the end of this chapter you will have the essential knowledge to start our big project –
writing the MyPong application. This chapter is important for another reason – you will
be introduced to a particular way of programming called object-oriented programming
(OOP). This is one way of coping with the complexity of writing big programs. You are not
going to learn everything there is to know about OOP but you will gain a foundation and
understand how classes and methods can be built.

There is far more in this chapter about how to design programs than about actually writing
them. After you have finished working your way through this book, you will hopefully be
starting to think about how to design your own programs rather than just writing the ones
that are suggested. The bonus chapter illustrates how well-designed code can quickly be
adapted to make new applications.

In this chapter you are going to:

• learn how to design classes

• learn how to make objects from classes

• start to build your own module

• learn how to design larger programs one bit at a time.


Chapter 2: Objects, classes and factories 17
Big programs
If we sat down and wanted to build ourselves a car (a real one, as in Figure 2.1) we might
not even know where to start. How about starting with the engine? An engine manufacturer
does not need to know anything about wheels or windscreen wipers or how to make seats –
the engine manufacturer makes engines. A car manufacturer does not need to know how an
engine is made; they just need to know how to attach a car to it. A car builder can also get a
wheel from one company and a tyre from another company – as long as they fit.

Figure 2.1 McLaren 12C – a very pretty car!

A complex computer program, such as an email application or a video game, can also be
very difficult to build because it is also made of many parts. However, just like the car, large
applications do not have to be built all at once. The latest video games are often made up
of millions of lines of code. If they were built as one program, can you imagine how hard it
would be to find a typing mistake? And believe me, everyone makes typing mistakes. The
way this problem is avoided is by building little bits at a time.

There are several ways to do this. One of these is to use OOP, which builds programs out
of coded objects! The great thing about this is that if you build the objects in the correct
Chapter 2: Objects, classes and factories 18
way, you can make libraries of these objects. These objects can be re-used again in other
applications. You can of course do a lot of this with functions but learning about objects and
classes will help you better understand other people’s code. The popular PyGame library and
tkinter both use classes.

Classes
Our first task is to look at a problem and work out how it can be separated into smaller tasks
and objects. You have just learned that we build libraries of objects. This is not entirely true.
We build libraries of classes. A class is better than an object, because it can act as a factory
for making objects.

Instead of explaining with a complex situation, let’s take something very simple – a cat.

There are many ways to build a Cat class. Here is one:

Code Box 2.1


class Cat:
def speak(self):
print("Meow!")

def drink(self):
print("The cat drinks its milk.")
print("The cat takes a nap.")

Chapter 2: Objects, classes and factories 19


Open a new window in IDLE and type in the code from Code Box 2.1. Save this as cat.py in
your Python folder.

Analysis of Code Box 2.1


The first thing to note is that we use the class keyword and that the class name, Cat, starts
with a capital. The indented code after the colon belongs to the class. Inside the class we
have provided two methods. Methods are very similar to functions except that they belong to
a class.

Remember, this is like a factory. Now, you will learn how to send it orders to build some
objects – in this case, some cats!

Delving Deeper
What is the difference between a method and a function?
A method is just a special function that we make in a class.
Computer scientists might get upset with us calling classes ‘factories’ as this word has another meaning in
advanced OOP. They would prefer us to describe classes as templates or blueprints. You will find it a lot easier to
think of classes as factories though.
If you think of classes as factories, you can understand that by requiring a method to have self as an
argument, you tell the computer that the method will be available to each of the objects made by the factory.

Chapter 2: Objects, classes and factories 20


Modules
By storing class files such as cat.py in one folder they become a module! Any other Python
files in the same folder can use them with a simple import statement:

import cat

There are other special modules in the Python library that can be used. You have already
done this once.
Wow, we have made our
very own module.
OK, so it only has one class
Quick Quiz 2.1 in it – but it’s a start.
Can you remember which module we used before?

main.py
So far we cannot do anything with the Cat class. Have you tried to run it? Not a lot happens
does it?

Open a new window in IDLE and type in the code from Code Box 2.2. Then save this new
file as main.py. Notice cat.py is imported at the beginning of the code which gives our
program access to the Cat class. The file that you have just created is where you will start to
run the program, which is why it is called main.py.

Chapter 2: Objects, classes and factories 21


Code Box 2.2
import cat

# create an instance of a cat, named Romeo


romeo = cat.Cat()

# play with Romeo


romeo.speak()
romeo.drink()

Analysis of Code Box 2.2


romeo = cat.Cat()

This is where we order an object from our cat factory. Computer scientists say: “We have made
an instance of the Cat class.” They might even say that we have instantiated a cat object.
Romeo is the object and it is created by the Cat class (hence the capital letter). The Cat class is in
cat.py so we tell main.py where to look with the dot operator. The dot is used to link the class
with its location. In non-coding language, this line of code translates as:

‘Create an object called Romeo using the cat factory found in the cat.py file.’

Thus we have a cat! And he is called Romeo! All done with one line of code.

Chapter 2: Objects, classes and factories 22


Romeo has all the methods that were built by its factory, the Cat class, available to him.
To access them we call them using the dot operator again:

romeo.speak() # calls romeo’s speak method


romeo.drink() # calls romeo’s drink method

If you have not played with Romeo yet, you can do so now! To play with Romeo you simply
save and run main.py. It must be in the same folder as cat.py.

Improving the Cat class


Warning: There are a lot of selfs in this section!

When calling a function we send it arguments in the brackets like this:

times_tables(12, 12)

This function is from Python Basics and calling it would print out the 12 times table up to
12 × 12 = 144. Objects can do this too. We could supply a name for example:

romeo = cat.Cat("Romeo")

Our Cat class will now need to be re-written though. This is not done in quite the same way
as it is in a function. It is done in a special method called a constructor.

Chapter 2: Objects, classes and factories 23


Constructors have a special bit of code that you will see quite often from now on. It looks a
little bit frightening at first but it is always the same – you will get used to it:

def __init__(self, name):

It always has the self argument to make sure that everyone understands that this
method is going to be available to each object built by this class. Next we must list the
other arguments that we want to pass to the constructor. In the above example the other
argument needed is name. We have nearly finished the new
theory. After this section it is only
Now let’s pause. You may not have been confused by the init surrounded by two a few more examples and then
you have learned the basics for
underscores on each side of it; you may have noticed that this is actually a method because
starting your project.
it has def at the beginning and a colon at the end; you may be a very clever coder! Most
students need a little encouragement at this stage – listen to Mr Campbell.

Now back to work! In this special method called a constructor we have to create a
self.name variable from name (yes that’s right, so that it is available to the object created
by this class). We then will use this new variable, self.name, in our methods.

We are adding self. to the front of all the variable names that are going to be available to
our objects and not simply to the class. This is why we end up with a lot of selfs!

Delving Deeper
When we build classes, we write methods that will be available to the objects we build (create instances of).
In a game of snooker, there may be several balls with different locations. Each one has a find_location()

Chapter 2: Objects, classes and factories 24


method that refers only to itself, even though it has been built from the same class. This is why the methods in
our class have self passed to them as an argument. It is even cleverer than this though.
Programmatically the objects do, in actual fact, refer back to the class code for the method but each object
keeps track of its own data. It is as if each object has been built with its own methods that are specific to it
alone. It is as if the methods act independently of the other objects built by the same factory. This is just what
we would wish for when we build objects, and it is all done with one argument – self.

Open a new window in IDLE and copy the code from Code Box 2.3. Save it as cat2.py.
Compare this with cat.py (Code Box 2.1) to see how we use the new variable self.name
created in the constructor. Yes, that is all this constructor code has done: it has given you a
new variable that you can use! As before, this class does not run anything. It is just a factory,
but you are about to see how useful factories are.

Code Box 2.3


class Cat:
# constructor:
def __init__(self, name):
self.name = name

def speak(self):
print(self.name, " says Meow")

def drink(self):
print(self.name, " drinks some milk.")
print(self.name, " takes a nap.")

Chapter 2: Objects, classes and factories 25


Improving main.py
This is where all that hard work pays off. You are going to order two cats very quickly and
play with both. You will probably find the code makes sense without any help this time.
Open a new window in IDLE and copy the code from Code Box 2.4. Save it as main2.py.

O Romeo, Romeo!
Wherefore art thou
Code Box 2.4 Romeo?

import cat2

# create two instances of a cat


romeo = cat2.Cat("Romeo")
juliet = cat2.Cat("Juliet")

# play with Romeo


romeo.speak()
romeo.drink()

# play with Juliet


juliet.speak()
juliet.drink()

Run this file and then feel free to play and adjust the code. Have fun!
Chapter 2: Objects, classes and factories 26
Designing classes
This section introduces another simple example where you will get to practise what you have
learned and you will start to learn how to design a class. You are going to build a lift and a
lift operator.

Below is one way to make a class for a lift. There are many properties a lift can have, but in
terms of a program there are very few essentials.

The only essential feature of a lift is which floor it is on. Instead of ‘essential feature’ we
could call this a property or characteristic. In programming we call these characteristics
attributes (or sometimes parameters) and we initialise them in the constructor. We call lifts elevators
in the USA.

Class Name
Lift

Attributes
current floor

Methods
get floor
move to floor

Class design sheet 2.1 A lift class.


Chapter 2: Objects, classes and factories 27
We might also want to know how many passengers it can hold, or its velocity – but this lift
is going to be very simple. To plan a lift class we can use a class design sheet. You will find a
blank one in the Appendix at the end of this book and also on the companion website – so
you can print out your own should you wish. The design work goes into the class design
sheet. From this we can build our class.

Two methods are essential: one that finds out what floor the lift is on and another to move
the lift to a new floor. Now let’s see how this gets turned into code:

Class Name
Code Box 2.5
Lift # lift.py provides a Lift Class

class Lift:
Class Name
Attributes # constructor:
def __init__(self, current_floor=0):
current floor Constructor
self.current_floor = current_floor

def get_floor(self):
Methods
return self.current_floor
get floor Method

move to floor def move_to_floor(self, floor_number):


self.current_floor = floor_number

Chapter 2: Objects, classes and factories 28


Analysis of Code Box 2.5
There is a default value set for the current_floor attribute, 0. This can be seen in the
constructor method. Now, if we do not pass a current_floor argument to this class when it
builds a new lift object, the new lift will start on floor 0.

The return key word is used in the first method. This means that if we call this method in
our lift operator program it will return (give back) the value stored in the
self.current_floor variable.

The lift operator


lift_operator.py has some easy code that plays with the lift. Instead of typing it up
you can simply open and run it from the Chapter 2 folder in the source code files you have
downloaded from the companion website. The code can be seen on the next page in Code
Box 2.6.

Chapter 2: Objects, classes and factories 29


Code Box 2.6
# lift_operator.py

import lift

# create a lift object


my_lift = lift.Lift()

# Find out what floor the lift is on


floor = my_lift.get_floor()
print("The lift is on floor", floor)

# move the lift to a new floor


my_lift.move_to_floor(5)

# Find out what floor the lift is on now


floor = my_lift.get_floor()
print("The lift has now moved to floor", floor)

Experiment
When creating my_lift we did not include a current_floor variable so the lift
started on floor 0. Try altering this line of code to my_lift = lift.Lift(3) and
running again. Interesting, huh?

Chapter 2: Objects, classes and factories 30


Chapter summary
In this chapter you have learned:

• about classes, objects and how to design them


• how to build your own module
• a little about object-oriented programming – OOP A relaxing challenge!
That’s a new one.
• what a nuisance self can be!

This has been quite an intense chapter. If you are feeling overwhelmed, do not worry as the
MyPong project is going to reinforce many of these ideas and you will get the hang of them soon.

If you want some practise, try this easy and relaxing challenge. (Easy and relaxing if you
have the code for cat2.py and main2.py in front of you while you complete the challenge!)

Good luck.

Easy and relaxing challenge


Make a Pet class and save it in a file called pet.py.
Make an application called pet_owner.py to build and control some pets.
You can choose any pets you like such as hamsters or chinchillas. Alternatively you might
prefer tarantulas or piranhas. You will find that you have to be careful with what your
pets can do. Piranhas cannot speak or go for walk!

Chapter 2: Objects, classes and factories 31


The
MyPong
Project
There have been many versions of Pong made, written in many
programming languages. The great thing about Pong is that
everyone knows how to play it straight away and it is a great
little competitive two-player game. However, building the game
is simply a means to an end. The real aim of this project and
the book as a whole is to think about how to design bigger
applications and how to design the code in a way that it can be
re-used in other projects.
Chapter 3
Creating the Table
It’s time to start our project. By the end of this chapter you will have written the code for the
first class in our MyPong module. You can download this chapter’s files from the companion
website. There are two folders: pong-table-start and pong-table-final. The first folder
has Python start files with a skeleton made of comments. The second folder contains the
finished files for this chapter in case you cannot get yours to work.

Future chapters follow this pattern. The start files always contain the work you have already
done from the previous chapter with additional commenting. This is so that it is never a
disaster if you get confused. Another reason for providing all of these backup files is to
encourage you to experiment with your code at the end of each chapter without the fear
of losing your way. Please though, do try typing rather than just reading the files. You will
then be justified in calling MyPong your own when it is complete. You will also have a much
better chance of understanding how the code all works.

There is more in this chapter about how to design classes. This theme also continues in the
rest of the book.

Chapter 3: Creating the Table 34


In this chapter you are going to:
CHECKLIST
• design a Table class
Create a table
• learn a bit more about the tkinter module Add a ball
Add two bats
• build a simple graphical app.
Add the goals system
Add the scoring sysem
The big plan
Figure 3.1 shows how the final project will look. You will build a group of classes to
accomplish this. There will be a Ball class and a Bat class for example. The classes will be
built in a way that they could be used in other games. Indeed in the bonus chapter, they will
be. There are many games that have balls and bats in them!

Figure 3.1 The finished MyPong game.


Chapter 3: Creating the Table 35
The game is made up of:

• two bats
• a table with a net and a score board
• a ball
• two players.

We now have to decide how to separate this idea into classes by thinking of the objects we
require. There are several ways of doing this. Never think there is only one correct answer!

Obviously, we are going to create a Ball class and a Bat class. We will also need a file
called main.py which will control most things. There has to be a Table class otherwise this
chapter’s title would make no sense! But what should we do about the net, the rules and the
scoring system?

The obvious place for the rules will be in main.py. The net is very simple and though we
could build a Net class, it seems a lot of effort when all we need to do is draw a dashed line:
it can become part of the table. We do not have to program everything at once though. We
can wait and see how we feel later. This is the beauty of object-oriented programming in
action!

That is enough of a strategy to be able to start designing the first version of our Table class.

Chapter 3: Creating the Table 36


The Table class planning page
Here is a planning sketch and a table class design sheet.
width (perhaps 600 pixels)
Class Name
Table

Attributes
height window
(perhaps width=600
400
height=400
pixels)
colour=black
Ah yes, boolean variables: these
net_colour=green
allow us to clearly see what is True
colour (perhaps black) vertical_net (T/F) and what is False in the world.
horizontal_net
a net (its green, its vertical) (T/F)
needs to go in a window
Methods
Notes

It will be helpful to supply lots of default values such as 600 pixels for width.

The attributes are going to go in a lengthy constructor.

By having some boolean variables for the net position, it will be easy to use this class
to build a variety of tables with a net that is either vertical, horizontal or non-existent!

At the moment the table requires no methods.

Chapter 3: Creating the Table 37


The tkinter toolkit
An additional group of modules is installed along with Python 3, which provide us with This disadvantage of importing
some GUI widgets. These were explored in Python: Next Steps. modules like this is we must now
avoid using any tkinter method
names in our own code.
As we are going to use a lot of the methods from tkinter classes, we can choose to use
this line of code:

from tkinter import *

This means that we can refer to any of tkinter’s methods in the rest of our code. We no longer
need to precede every method with the name of the module where it can be found: we no
longer need to put tkinter. at the front of every tkinter method call.

The Table class constructor


Our constructor needs to be passed an argument for each of the attributes that we
want to be selectable when ordering a new object. Then we will assign them to all
the self.variables, as we have done before.

Open table.py from the pong-table-start folder. This file can be found in the Chapter 3
folder. Open this with IDLE and add the missing code from Code Box 3.1. Add your code to
the file shown in the header bar of the Code Box.

Can you see how this matches the first part of our plan?

Chapter 3: Creating the Table 38


Code Box 3.1 table.py
I never realised that the
# This class defines a Table that is a 2D rectangle that is a play area. British spelt color with
a ‘u’.

from tkinter import *

class Table:
#### constructor
def __init__(self, window, colour="black", net_colour="green",
width=600, height=400,
vertical_net=False, horizontal_net=False):
self.width = width
self.height = height
self.colour = colour

Classes built like this are very much like factories. In main.py we will be able to quickly
manufacture a table with code such as this:

my_table = table.Table(window)

Because of all the default values we have supplied in the constructor’s __init__ line, the
only argument required will be window. The class will make a table object that is just like
the one we want, with one exception.

Chapter 3: Creating the Table 39


Quick Quiz 3.1
Look back at the __init__ line in Code Box 3.1 and the diagram of the required table on the
Table class planning page. What will the difference be between the table we get and the one
we want?

Building classes in this way means we can build a variety of tables in the future using one
line of code. The Table class becomes a very useful little factory (Figure 3.2). Do you want a
red table with a horizontal net that is 300 pixels by 300 pixels? Just ask:

my_table = table.Table(window, horizontal_net=True, width=300, height=300, colour="red")

Figure 3.2 Some table objects.

Chapter 3: Creating the Table 40


Quick Quiz 3.2
What would the code be to make a blue table object with a vertical red net, which is
600 pixels wide by 400 pixels tall?

More tkinter tools


The constructor method is not quite finished as we have not told it to actually build the table
or the net yet. We will leave the drawing of the window for main.py (which will be written
very soon). To build our table we have to use some tkinter code which we might have to find
by looking up the instructions on the tkinter website. This is quite a large library and you do
not need to worry about doing this yourself as it has been done for you. Feel free to look if
you are interested. At the time of writing, instructions could be found here:

http://docs.python.org/py3k/library/tk.html

First we are required to make the canvas, which is coded like this:

self.canvas = Canvas(window, bg=self.colour, height=self.height, width=self.width)

The Canvas class is a tkinter factory that requires the arguments for a window, background
colour, height and width – all of which we have variables for in the first part of our
constructor.

Chapter 3: Creating the Table 41


Delving Deeper
When to use self and when it is unnecessary
When we build a class such as a Table class, we need to pass it any attributes it is going to require to build its
table objects. For example, the table is going to go in a window object – so we need to pass the window to it as
an argument.
If on the other hand we are going to pass the Table class an attribute, such as width, which we might want
other classes or files to query (e.g. Table, how wide are you?) then we need to declare it in the constructor as
an object variable with self. Then, the classes or files could ask the table object how wide it is.

The next thing we have to do is call canvas’ pack() method. It does not require any
arguments:

self.canvas.pack()

The pack() method is required to make our table visible while performing other tasks. Next
we can use canvas’ create_line() method to draw a net. This takes the following form:

self.canvas.create_line(
[top x-coord], [top y-coord], [bottom x-coord],
[bottom y-coord], width=2, fill=net_colour, dash=(15, 23))

The width is in pixels so we want a line that is two pixels thick.

The fill is the colour of the line – we have a variable ready for that.

The dash attribute takes two numbers – the length of the dash and the spacing, also in pixels.
Chapter 3: Creating the Table 42
To understand the coordinates, it helps to know that unlike in maths and science at school,
computers often count pixels from the top left corner of the screen or window. This is the case
in Python. Look at Figure 3.3 to see how this works.

x-axis
(0, 0) (300, 0)

y-axis

(300, 400) (600, 400)


Figure 3.3 Coordinates.

So the call to implement the create_line() method, could be written as:

self.canvas.create_line(300, 0, 300, 400, width=2, fill=net_colour, dash=(15, 23))

Chapter 3: Creating the Table 43


Other documents randomly have
different content
XXV
J OHN DARE was sitting all alone by the fire one evening in the
parlour of The Red House. The boys were at Mrs MacLean’s that
night, and Honor and Vic were assisting in an entertainment to the
Belgian Refugees at a neighbouring hostel.

Desirous as they all were of being of service to the exiles,


circumstances had not permitted of their taking any of them into
their homes. And so they all subscribed towards one of the many
hostels and assisted in such other ways as their many engagements
allowed time for.
And Mr Dare took no exception to it all. It was an unavoidable
part of the general upsetting, and to tell the truth he was so
depressed and uncompanionable these days, that he felt himself
better company for himself than for any of the younger folk.
Honor had got for him from the library the two big volumes of
Scott’s Last Journey to the Pole, and with these and a pipe he was
doing his best to forget for a time business troubles and German
delinquencies.
With a tap at the door, the maid announced, “A gentleman to
see you, sir.”
“Who is it, Bertha?” he asked, with a touch of annoyance at the
disturbance of his peace.
“I don’t know, sir. He said you would not know his name, but it’s
important.”
“Oh well, show him in here,” and he closed his book and stood
up to meet the intruder.
“You won’t know me, Mr Dare,” said the newcomer, when the
door closed on Bertha. “I am Inspector Gretton from Scotland Yard.
I’ve come to consult you on a certain matter and I want all the
information you can give me.”
“At your service, Inspector. Won’t you sit down? Have a cigar,”—
and he got out a box from the cupboard under the bookcase. “Now
what’s it all about?”
“It’s this, Mr Dare. For some time past the wireless stations at
Newstead and Crowston have complained of jamming. In other
words, unauthorised messages are passing, and by a process of
elimination and deduction we are satisfied they emanate from
somewhere in this neighbourhood. As an old resident and a Justice
of the Peace——”
“A very nominal J.P. of late, I’m afraid,—thanks to the war.”
The Inspector nodded. “We felt sure, however, that any
assistance in your power you would render us.”
“Assuredly. Anything I can do. But I don’t at the moment see
what.”
“From the nature of the messages that have been intercepted,—
they are in code of course, but our people have managed to get an
inkling of their meaning,—it is evident that someone is sending out
information of moment to some enemy station, probably nearer the
coast. And we’ve got to get to the bottom of it. Very powerful
instruments are being used and probably from a considerable
elevation. Now is there anyone in this neighbourhood, within your
knowledge, likely to be up to anything of the kind?”
“I should not have thought so.... In fact it is hard to believe it of
any of one’s neighbours....”
“Unfortunately, our experience is that the folks who are in this
kind of business are just the ones one would least expect. What
enemy aliens have you round here?”
“Quite a lot,—or we had. And mostly quite nice people. But a
number have left since the war began,—either they thought it safer
to get back home, or you are taking care of them elsewhere.”
“We’ve got quite a lot on our hands, but evidently not all. Would
you tell me, sir, who there are left about here?”
“Well,—let me see. There are the Jacobsens,—they claim to be
Danish, I believe. He’s a produce-importer in quite a big way.”
“What age of a man, and what family?”
“He’ll be somewhere about fifty, I should say. Family,—wife, two
daughters and a boy of seventeen.”
“Where does he live?”
And so they progressed through such a list as Mr Dare could
make out on the spur of the moment. The Inspector making an
occasional note and asking many pointed questions.
And when Mr Dare’s spring of information had apparently dried
up, he asked suddenly,
“Whose is the tall old-fashioned red-brick house up there on top
of the hill,—the one with the double-peaked roof and the tall old-
fashioned chimney-stacks?”
“That? Oh that’s Dr Rhenius’s. But he’s quite above suspicion.
He’s lived here for over twenty years.”
“What is he? German?”
“It’s the one thing he resents—to be called a German,” said Mr
Dare, with a smile. “His father was a Pole from somewhere near
Warsaw. He himself has been naturalised for twenty years at
least——”
“Do you know that?”
“Well,”—with a surprised lift of the brows—“if you put it as a
legal point,—no! I don’t know that anyone has ever questioned it.
You see, he is our medico round here, and is greatly esteemed and
liked. He’s an uncommonly clever doctor and everybody’s very good
friend.”
“I see. Quite above suspicion, you would say, Mr. Dare?”
“Oh quite. He hates Prussian Junkerdom as every Pole must.”
The Inspector nodded acquiescingly, and they chatted on about
the war and things in general till his cigar was finished and he got up
to go.
“I will ask you to keep all this absolutely to yourself, Mr Dare,” he
said. “Not a word to anyone, if you please, sir.”
“Certainly, Inspector. I’m afraid I’ve not been of much use to
you. If you think of anything else——”
“I’ll let you know, sir,” and Mr Dare saw him out of the front
door, and returned to Scott and the South Pole.
As for Inspector Gretton, he wandered off to have a closer look
at the old-fashioned red-brick house on top of the hill.
Just a week later he called again on Mr Dare, late one night,
and, as before, found him all alone.
The Colonel had suddenly, when apparently getting on well,
developed pneumonia in the other lung and was in a very critical
condition. Mrs Dare spent all her time at Oakdene in unremitting
attendance on him, with every help that Lois and Auntie Mitt and
Honor and Vic could render. The boys were sleeping in town that
night as they had to be on early fatigue next morning.
“Well, Inspector? Any success?” asked Mr Dare, as Gretton was
shown in.
“I’ve come to end the matter, Mr Dare. I thought perhaps you’d
like to see the last act.”
“Really? Got him. Who on earth is it?”
“If you care to come with me I’ll show you, sir,” and Mr Dare got
into his hat and coat in record time and went out with him.
At the gate they were met and followed by half-a-dozen
stalwarts in flat caps and overcoats, who in some subtle fashion
conveyed the impression of law and order, armed not only with right
but with other weapons of a more practically coercive nature.
The roads were almost in darkness in accordance with recent
orders, lest undue illumination should offer mark or direction for
lurking menace up above. They turned into the road up the hill and
came to the gate of Dr Rhenius’s old-fashioned red-brick house.
“You don’t mean to say——” jerked Mr Dare in vast amazement.
“Sh-h-h!” whispered the Inspector, pressing his arm. “See that
tree!”—a huge elm towering a hundred feet high just inside the gate.
“I’ve been up there every night since I called on you, with a pair of
the strongest glasses made—Zeisses,” he said with a chuckle. “Your
friend has visitors of a night and later on he gets busy.”
Mr Dare was dumb. He could not take it all in. There was some
grotesque mistake somewhere.
“We’re a bit early yet,” said the Inspector. Then, adjusting his
field-glasses and peering up at the house, “No, it’s all right. He’s at
work in good time to-night.”
He handed the glasses to Mr. Dare, and whispered, “Look at that
chimney-stack. Get it against the Milky Way. See anything?”
“I see the chimney.... Yes, and something like a flag-pole
projecting above it....”
“Exactly,—a wireless pole. We’ll catch them at it.”
He said a word to his men. They had had their instructions. They
all went noiselessly up to the house, some to the back and sides, the
Inspector, Mr Dare and two others to the front door.
“Keep out of sight till I go in,” said the Inspector, as he rang, and
in the distance inside they heard the thrill of the bell. But no one
came. He rang again.
“Good thing no one’s dying in a hurry,” he growled.
It was not till after the third appeal that they heard steps inside
and all braced up for the event. As the door opened Inspector
Gretton quietly inserted his foot.
“Is the Doctor in?” he asked.
“He is oudt,” said a voice, which Mr Dare recognised as Old
Jacob’s, the Doctor’s factotum.
“Then I’ll come in and wait for him. I want him at once,” and the
Inspector pushed his way in.
As he did so Old Jacob dropped his hand against a spot in the
wall, and far away upstairs a tiny bell tinkled briefly.
“Quite so!” said Gretton, and as his men followed him in, with Mr
Dare behind them in no small discomfort of mind,—“Secure the old
boy, Swift,” and to his still greater discomfort Mr Dare heard the click
of handcuffs.
“Now quick,—upstairs!” and they followed him at speed.
He seemed to go by instinct. Up two flights and they came on a
door which evidently led to a higher storey still. A curious door—of
stout oak, without a handle, and for keyhole only the polished disc
and tiny slit of a Yale lock.
The Inspector wasted not a moment. He was up to every trick of
his profession.
“Barnes,” he said quietly, and indicated the lock, and in a trice
Barnes inserted a thin stick of something into the slit, and as the
Inspector waved them all back there came an explosion and the
stout oak about the lock was riven into splinters. Gretton swung
open the door and ran up the narrow stairs.
In the top passage they came on a short ladder leading to a
skylight through which the night air blew chilly. The others climbed
quickly up. Mr Dare stayed below. He regretted having come. He did
not quite know why he had come. He had not of course known
where he was going when he accepted Inspector Gretton’s
invitation. Then the matter had developed too rapidly to permit of
him backing out.
Exclamations came down to him through the skylight—the sound
of a brief struggle, and presently Gretton came down again
obviously well-pleased with himself.
“Got him,—red-handed!” he said.
“Not Dr Rhenius?”
“If that’s his proper name. The man you’ve known by that name
anyway. And all his tackle. Two minutes more and his poles would
have been out of sight. He lowers them down the chimneys.”
He kicked open a door in the passage, but the room inside was
empty and unfurnished. Two other rooms yielded the same result.
Then the Inspector, searching about, discovered a trap-door,
such as might lead to cisterns, high up in one corner of the passage,
and shifting the ladder, he ran up, pushed the trap open, and said,
“Right—o!”
“Come up and see for yourself, Mr Dare,” he said, as he crawled
out of sight; and Mr Dare followed him.
It was a long tent-shaped apartment formed by the pitch of the
roof, well-lit by electric lights and littered with electric apparatus—a
number of powerful accumulators, spark coils, condensers,
inductances, a heavily built morse key, and so on,—everything
necessary for sending long-distance wireless messages.
Mr Dare gazed about him in amazement.
“There is no doubt about it then?” he jerked uncomfortably.
“Not a doubt. How many lives all this may have cost us, God
only knows. However, he’s scotched now, and it’s one to me.”
“Rhenius!” jerked Mr Dare again. “I can hardly credit it even yet.
Such a good fellow he always seemed, and we all liked him so! It’s
amazing—and damnable.”
“Damnable it is, sir. And there’s too damned much of it going on.
We’re infants in these matters and altogether too soft and lenient.
However, this one won’t send out any more news.”
“What is the penalty?”
“If it’s as bad as I believe, he’ll be shot. We shall know better
when all these papers and things have been gone into. He’s been a
centre for spy-news, unless I’m very much mistaken, but this ought
to end him, as far as this world’s concerned anyway.”
They went down the ladder again and Gretton replaced it below
the skylight and hailed his men, “Bring him along there.”
And presently, preceded by one stalwart and followed by the
other the prisoner was brought down.
The actual sight of this man who had been on such friendly
terms with him, had been admitted to every house in the
neighbourhood on the most intimate footing, had doctored them all
in the most skilful way possible, who was even then in attendance
on their good friend the Colonel,—and who all the time was playing
the spy for Germany, gave John Dare a most gruesome shock. He
felt absolutely sick at heart.
“Rhenius!” he gasped. “Is it possible?”
But Dr Rhenius looked at him without a sign of recognition and
spoke no word.
He was hurried away down the stairs. Inspector Gretton left two
of his men in charge of the house, and with the rest and his
prisoners went off in a taxi which he called up by the Doctor’s
telephone.
Mr Dare went back home feeling bruised and sore. Duplicity and
treachery such as this cut at the roots of one’s faith in humanity. If
he had been told this thing he would not have believed it. Nothing
less than what he had seen with his own eyes and heard with his
own ears would have convinced him. But he was convinced and
saddened.
He went across to Oakdene first thing in the morning. His wife
had to be told. The Colonel’s welfare had to be seen to—another
medical attendant provided,—explanations concocted.
“What is it, John?” asked Mrs Dare, as soon as she set eyes on
his face. “Bad news?”
“Yes, Meg,—bad news. But not touching any of ours,”—at which
the anxious strain in her face relaxed somewhat.
“Dr Rhenius is in prison as a spy——”
“John!”—and she sank aghast into the nearest chair.
“It is true, Meg. I was there. His house is just one big wireless
station. They caught him in the act. It is horrible to think of such
treachery. I’ve hardly slept a wink all night.”
“No wonder! But—is it possible? Is there no mistake?... Dr
Rhenius?... I would have trusted him with my life.”
“Yes. It is beyond me. But there is no possible doubt about it.
They have taken him and Old Jacob away, and the police are in
charge of the house. They say he will be shot.”
“How terrible! Not the shooting. If he has done this he deserves
to be shot. But ... our Dr Rhenius! Oh, I cannot take it in yet.”
But in time she had to accept it, and they fell to discussion of
ways and means.
The Colonel was to be told that Rhenius had been suddenly
summoned from home,—which was grimly true, and Mr Dare was to
call at once on Dr Sinclair in the village, give him the same
explanation, and beg his attendance on their patient.
As he expected, Dr Sinclair received him with a certain amount
of professional surprise at the irregularity of his procedure. He
hummed and hawed for a time, and put such very pointed questions
that Mr Dare was inclined to believe that he must have had
suspicions of his own—provoked possibly, he thought, by
professional jealousy and Rhenius’s German-sounding name; all of
which was natural enough.
All he permitted himself was that Dr Rhenius had been suddenly
called away, and his return was so very doubtful that they felt it
necessary to call in another doctor at once. And Dr Sinclair went.
The Colonel was much put out and not easily reconciled to this
transfer in which he had had no voice. It was so unlike Rhenius to
go off like that without so much as a good-bye. He fumed weakly
and fretted over it, and was barely civil to Dr Sinclair, who shook his
head doubtfully when he went downstairs with Mrs Dare.
“He is very weak,” he said. “Keep on as you are and above all
things keep him quiet and free from disturbance of mind.”
“It is not easy.”
“I see that. But it is absolutely essential. The fever has pulled
him down terribly and his heart is in a very ticklish state.”
The following day the papers had the matter with bold head-
lines—“WELL-KNOWN WILLSTEAD DOCTOR ARRESTED AS SPY,
HOUSE FULL OF WIRELESS APPARATUS,” and so on.
They did their best to keep the paper from the Colonel. But the
very attempt aroused his suspicions and sent his temperature up
again.
In despair he was allowed to glance at it—and the mischief was
done. He insisted on Lois reading every word, and all the time he lay
looking at her with a dazed look on his white face.
“Rhenius!” was all he said, in a strange shocked whisper, when
she had finished, and then he lay back among his pillows and turned
his face as far away from them as he could.
And—“Rhenius!”—they heard him murmur more than once
during the day, as though he were groping painfully among his
shadows after some understanding of it all.
About tea-time, when Lois was sitting with him,—just sitting
quietly by his bed-side so that he should not feel lonely, for he had
declined to be read to, he turned quietly to her and feebly extended
his hand.
She took it in her two warm ones throbbing with life and sudden
fear. It felt very thin and cold, and, with a great dread at her heart,
it seemed to her that his face was changed. It was gray, and very
weary.
“I am so glad, dear,—so very glad,” he whispered,—“about you
and Ray.... Good lad! ... he will come back to you ... and Con—good
lad too!... God bless you all!—all!”
Lois had slipped on to her knees beside the bed, and the tears
were running down her face in spite of herself.
“No!” he said. “Don’t cry!... Very tired.... I shall be glad ... to
rest.”
Then he suddenly raised himself in the bed, and looked beyond
her.
“Last Post!” he said, quite clearly. “Thank God, I have done my
duty!” and then he sank back. And Lois released one hand, from the
thin cold hand which had no longer any response in it, and beat
upon the floor with it to call the others.
XXVI
A LMOST inevitable as it had more than once seemed, in the crises
of his illness, the Colonel’s death was a great shock to them all.

At the sound of Lois’s hasty tattoo on the floor, the others had
hastened up to her. They found her still clasping the one thin cold
hand with one of hers and still beating the floor with the other.
They thought at first that it might be a fainting fit—which in
itself, in the circumstances, would have been ominous enough. But
briefest examination showed them that their old friend had
answered The Call and was gone.
They were down again in the small sitting-room, discussing it
quietly and sadly, when Auntie Mitt, after staring fixedly at Lois for a
full minute, as though she had suddenly detected something strange
in her appearance, said suddenly,
“My dear, you are Lady Luard now.”
And Lois stared back at them both with a startled look, and
gasped, “I never thought of that. Oh, I wish Ray were here!”
They all wished that, but no amount of wishing will bring men
home from the war.
“We must send Alma word at once,” said Mrs Dare. “I will write
out a telegram.”
“It will be a shock to her,” said Auntie Mitt. “Perhaps, my dear, a
letter——”
“Alma was prepared for the worst,” said Mrs Dare. “Last time she
was here she told me it would be a miracle if he got through such an
illness at his age. She would like to know at once, I am sure,” and
she sat down at the writing table to prepare the telegram.
And while they were still in the midst of these agitations, and
Lois was wondering how she would ever be able to reconcile herself
to the inevitable changes, she happened to glance vaguely through
the window and saw Alma coming quickly up the front path.
“Here she is,” she cried, and jumped up and ran to meet her.
At sight of Lois at the door, Alma exultingly waved a paper she
carried in her hand and quickened her pace almost to a run.
“Good news!” she cried. “Word of Con at last.”
“Oh, Al, I am so glad,” and she burst into tears.
“Why, Lo, dear, what’s up? It’s good news——”
“Uncle Tony has just died. Mother was just writing a telegram to
send to you.”
“I am not surprised, dear,” said Alma, putting her arm round her.
“I had very little hope of his pulling through. He was an old man,
you see. I am sure he was not very sorry to go; though he would
have liked to see the end of this war, I know. And I do wish he had
heard about Con. He would have been so glad. However, he knows
more about it all now than any of us, and that will please him
mightily,” and they went in together.
So the good news and the bad—nay, why call the news of a
good man’s promotion bad news?—let us say, the other news tended
to counteract one another in the hearts of those who were left.
Indeed the net result that remained with them all was a sense of
thankfulness,—for the peaceful passing of the fine full life, and for
the young life spared for further work.
Alma’s letter was not from Con himself, which at first sight was
disturbing. But the contents explained. Lieutenant Dare had been
wounded—in the hand, the writer said,—at Landrecies during the
retreat from Mons. He was now a prisoner in Germany—at Torgau,
and was being well looked after. He was making good recovery from
his wounds which had been severe, and they were all hoping that
something might presently be arranged in the way of an exchange
of medical-staff prisoners. The writer signed himself Robert Grant,
R.A.M.C.
“I can’t tell you what a relief it is,” said Alma. “I almost danced
when I got it. It’s worry that kills, and I was beginning to worry
about the boy. What about Ray?”
“It’s ten days since my last letter,” said Lois. “I’m hoping for the
next every minute.... Do you know, Al, just at the very last, when
Uncle Tony knew the end had come, he said, ‘Good lad, Ray! He will
come back to you. And Con—good lad too! God bless you all!—all!’—
that was almost the last thing he said.”
“The dear old man!... We will take it as a good omen.... I think,
you know, that just at the last they often have an outlook—a
forelook—altogether beyond our understanding. They see with other
eyes than ours.”
“Undoubtedly!” agreed Mrs. Dare.
Alma’s stay, even under the circumstances, could not be a long
one. They had had forty-nine wounded officers in, two days before,
many of their nurses had gone to the front, and they were very
short-handed.
Lois walked down to the station with her, and they talked in
quiet sisterly fashion of the past, present, and future.
“It is very curious how things seem to work together at times,”
said Lois.
“Always, maybe, if we knew more about it all, dear.”
“Yes, I suppose so. Here have I been so taken up with nursing
Uncle Tony that I really have never had time to get anxious about
Ray.”
“Ray will be all right, you’ll see. I pin my faith to Uncle Tony’s
vision.”
“And yet, when one allows oneself to think about it all, after
reading the terrible accounts of the fighting—and he would have me
read them all to him—it seems almost impossible that any of them
can come back alive.”
“We had forty-nine of them the other day, and it’s amazing how
well they stand it. They’re as cheerful as can be, laughing and
chaffing and joking. And yet some of them are pretty bad. It’s just
as well for all of us to take the cheerful view of things.”
“And then, just when Uncle Tony goes, and we were feeling it so
badly, you come in with your good news of Con. I can’t tell you how
glad I am, Al.”
“I know, dear. And I’ll be just as glad for you one of these days.
Pin your faith to Uncle Tony.”
And through the many dark days when no news came—and in
those days no news did not as a rule mean good news—the thought
of Uncle Tony’s last words held mighty comfort for them all.
They would have liked to bury him quietly, with no great
outward show of the esteem and love in which they held him. Their
feelings were too deep for any outward expression and the times
hardly seemed suitable for making parade of death. There was
sorrow enough abroad without emphasising it.
But Colonel Sir Anthony Luard, V.C., C.B., was a person of
consequence. He had died for his country as truly as any man killed
at the front. The higher powers decreed him a military funeral, and
the quieter-thinking ones at home had to give way. And, after all,
they believed it would please him.
So, on a gun-carriage, escorted by a detachment from the
reserve battalion of his old regiment, with muffled drums and
mournful music, and the Last Post and the crackle of guns, he was
laid to rest. And the others picked up the threads of life again and
kept his memory sweet by constantly missing him and remembering
all his sayings and doings.
His lawyer, Mr. Benfleet of Lincoln’s Inn, came out immediately
after the funeral and explained to all concerned—so far as they were
available—the remarkably thoughtful provisions of his will.
It had been made—or remade—immediately after the return of
Ray and Lois from abroad, and it aimed at the comfort and security
of all his little circle, so far as he could provide for these.
There were many wet eyes and brimming hearts as Mr. Benfleet
went quietly through the details.
To Miss Amelia Mitten—“my very dear and trusted friend”—he
left four hundred pounds a year for life. And Auntie Mitt, with her
little black-bordered handkerchief to her eyes, sobbed gratefully.
To Margaret Dare—wife of John Dare of The Red House,
Willstead,—“in token of my very great love and esteem,”—he left the
sum of £20,000, settled inalienably on herself, with power to will it
at her death to whom she chose.
“To my niece, Victoria Luard—who-might-have-been-
Balaclava,”—it was down there in the will in black and white, and
they came near to smiling at the very characteristic touch,—the sum
of £50,000 on attaining the age of twenty-one.
To Dr Connal Dare—if still alive—the sum of £25,000; and to his
wife Alma, formerly Alma Luard, an equal sum. In case of Dr Connal
Dare’s death the whole £50,000 came at once to Alma.
To Lois Luard, formerly Lois Dare, the sum of £25,000 in her
own right.
To Raglan Luard, the residue,—which, said Mr. Benfleet, would
amount to probably £100,000 or more when the securities, in which
it was all invested, appreciated again after the war.
There were many little minor legacies and gifts to old servants
and so on. And Uncle Tony, if he was present in the spirit at the
reading of his will, must have been well pleased with the effect of
his generous forethought.
XXVII
M RS DARE, wise woman and excellent housekeeper, had for
some time past been doing her best to cut down her
proverbial coat to suit the exigencies of the shrunken war-time cloth
at her disposal.

In other words, she had been curtailing the running expenses of


The Red House so as to bear as lightly as possible on the attenuated
income from St Mary Axe. Income, indeed, in actual fact, St Mary
Axe had none. Mr Dare was, of necessity, living on such remnants of
capital as he had been able to save from the stranded ship.
So Mrs Dare found another place for her housemaid, prevailed
on her cook, who was a treasure and had been with her over five
years, to remain as ‘general,’ with promise of loss of title and
reinstatement of position as soon as times mended, and with
Honor’s assistance and an occasional helping hand from Mrs Skirrow,
managed to get along very well.
Mrs Skirrow had always been a source of amusement at The Red
House. She had a point of view of her own and a sense of humour,
and an almost unfailing cheerfulness amid circumstances which
drove many of her neighbours to drink.
Mrs. Skirrow did not drink. She had too much hard-earned
common-sense, and she could not afford it. With three men more or
less on her hands, and mostly more, it took every half-crown she
could earn at her charing to keep the home together.
But the war had marvellously altered all that. Not only had she
no men to keep but the boot was on the other leg. Her men were
actually helping to keep her. She woke up of a night now and then
and lay blissfully wondering if it was all a dream, or if she had died
and gone to heaven. To be kept by her lazy ones! It seemed
altogether too good to be true. And yet every Friday, when she drew
her money, proved that true it was. No wonder she hoped with all
her heart that it might go on for long enough,—so long, of course,
as none of them went and got themselves killed. But men were as a
rule so contrary that she lived in daily expectation of one or other
doing that same.
For the first two months,—due possibly to some default on her
part in filling up and sending in the necessary but bewildering
papers,—or it might be to the general muddle at Head-Quarters—
she received no money at all. So she kept steadily on with her own
work, and having only herself to keep, got along very nicely,
meanwhile never ceasing to push her claims with all her powers, and
few were better equipped in that way. And Mrs Dare was kept fully
informed of everything with racy comments on all and sundry.
Then at last, to Mrs. Skirrow’s great satisfaction, the matter was
arranged, and by some extraordinary method of calculation,
promoted without doubt by herself and argued with characteristic
vehemence and possibly just a trifle of exaggeration here and there,
her money began to come in.
She received nearly ten pounds of arrears in a lump sum, and
was to get twenty-three shillings a week.
She had never had ten pounds all at once in her life before, nor
an assured income of over a pound a week without needing to lift
her hand. And, strange to say—yet not so very strange, seeing that
she was Mrs Skirrow,—she did not lose her head and go on the ramp
as some she knew had done.
In the first place she bought herself a new dress and coat and
hat, such as she had vainly imagined herself in, any time this ten
years, and fancied herself exceedingly in them.
The choosing and buying of that dress and coat and hat, the
going from shop to shop and from window to window, comparing
styles and prices, with the delicious knowledge that the money was
in her pocket and she was in a position to pick and choose to her
heart’s content, was in itself one of the greatest treats she had ever
known, and she spread it over quite a considerable period.
And when she turned up one night in her new rig-out, to explain
to Mrs Dare that she would not be able to come to her next week as
she was going to the seaside, Mrs Dare did not at first recognise her.
When she did she complimented her on her taste and good
sense in taking a holiday and hoped she would come back all the
better for it.
“I will that. You bet your life, mum! Fust reel holiday I’ve had for
twenty years an’ I’m going to enjoy it. Seaside and decently dressed
—that’s my idee of a reel holiday. It’s not some folk’s though. There’s
me neighbour, Mrs Clemmens, now. She had no money for a while,
same as meself. Then she got twenty pound all in one lump. She’s
got a heap o’ boys at the war. And what did she do with it? She
gathered all her old cronies—an’ a fine hot lot some of ’em are, I can
tell you, mum!—and she took ’em all up to London, and fed ’em, and
drank ’em, and music-halled ’em, till they was all blind and th’ hull
lot of ’em was run in at last, and in the mornin’ she hadn’t enough
left to pay the fines. A fair scandal, I calls it!”
“Disgraceful!” assented Mrs Dare. “I’m rejoiced to know that
your common-sense condemns that kind of thing, and I hope you’ll
have a real good time and come back all the better for it.”
“I will, mum. You bet your boots on that!”
And she did. She journeyed down to Margate in a ‘Ladies Only’
third-class carriage, and bore herself with such dignity that her
fellow-travellers were divided as to whether she kept a stylish public
somewhere in the West End or a Superior Servants’ Registry Office.
She picked out a cheap but adequate lodging, she revelled in all the
joys of Margate, ate many winkles, and went to ‘the pictures’ at least
once each day, and the whole grand excursion, fares included,
totalled up to no more than thirty shillings,—“an’ the best investment
ever I made in me life,” she told Mrs Dare over her scrubbing brush,
the following week, “an’ I’m thinkin’ I’ll run down for th’ week end
now and again, if so be’s this blessed war keeps on a bit.”
Mrs Dare found it really refreshing, amid the abounding troubles
of the times, to come across someone who had not only no fault to
find with them, but was actually, by reason of them, enjoying quite
unexpected prosperity.
For her own heart had been heavy enough in those days, what
with the Colonel’s illness and her husband’s very natural depression
as to the future outlook.
He had come in one night, some time before, in a state of most
justifiable exasperation. And yet the whole thing was so amazingly
impudent that in telling his wife of it he could scarce forbear a grim
smile. At the same time it was an eye-opener as to the truculent
immorality of the firms he had been dealing with for years past in
the most perfect good faith, and he vowed he would never forget it.
Two of his best customers, one at Hamburg and the other at
Frankfort, owing him between them close on £5000 had coolly sent
him word that, as no money could be sent out of the country, they
had invested the amounts due to him in the German War Loan and
would hold the scrip, and the interest as it accrued, in his name.
Both principal and interest would be paid in due course, that is to
say—when victory crowned the German arms.
It took Mrs Dare some time to realise that it was not merely a
distorted German form of practical joke. But her husband assured
her that it was not.
“I had heard of it being done,” he said bitterly. “But I never
expected either Stein or Rheinberg would play so low a game on me.
I’ve turned over hundreds of thousands of pounds with both of
them, and now—this! It’s damnable!”
“Perhaps the Government forced them to it.”
“It’s dirty low business anyway, and it won’t make for German
credit when things settle down again.”
But presently there came to him a bit of good fortune which
made him feel almost himself again.
Business men who travel daily to and from town by train fall
almost inevitably into sets, who occupy always the same
compartment and the same seats in it, and among whom exists a
certain good-fellowship and friendliness.
In John Dare’s set was a certain John Christianssen, of
Norwegian extraction, long established in London in the timber
business, which his father had founded sixty years before.
Christianssen was British born, his father having been
naturalised. He had two sons with him in the business, and both had
got commissions through the Officers’ Training Corps, and were
heart and soul in their work and eager for the front.
More than once he had lamented to Mr Dare his loss in them just
at this juncture. Not that he grudged them to the service of his
adopted country but that their going made him feel, as he said, as if
he had lost his right hand and one of his feet.
Mr Dare sympathised with him but assured him it was better to
have a healthy body even with only one hand and one foot than to
have no body left. And Christianssen, knowing the nature of the
business in St Mary Axe, understood, and thought the matter out.
And so it came to pass, one morning when they got out at
Cannon Street, that he said to Mr Dare, “I will walk your way, if you
don’t mind. I want to talk to you.”
And when they reached the office, where one small office-boy
now represented the busy staff of old, he sat down in the second
chair and lit a cigar, and said, “I know pretty well, from what I have
heard and from what you have told me, Dare, how you are situated
here. I have a proposal. I can’t go on without help. I want to be
across in Norway and I want to be here at the same time. Now that
Jack and Eric are away my hands are tied. There is huge business to
be done with all this hutting going on, and I’m going to miss my
share unless I make proper provision. And that is you! What do you
say?”
“It’s killing to be out of work, which I never have been before for
over thirty years. My business is gone, as you know, and most of my
capital. Some of it’s invested in the German War Loan——”
“No!”
“Yes! The low-scaled rascals, instead of remitting what they owe
me, write to say they have loaned my money to their infernal
government and it will be repaid with interest when the war is over
—meaning, of course, over in the way they would like it.”
“That is low business!”
“Business! I call it simple dirty robbery. But it’s not only the fact
that they’ve done this, but—well, I just feel that I would be glad
never to have any dealings with any German again as long as I live.”
“I do not wonder. But that is all the better for me. We have
known one another now, what is it—ten, fifteen years? Come in with
me. We can arrange satisfactory terms. You see, my lads may come
back, or they may not. My wonder, when I read the papers, is that
any man of them all ever comes out of it alive. But even if they are
not killed I am doubting much if they will find office-stools agreeable
sitting for the rest of their lives. If they do come back it will be the
overseas part they will want. So there it is. What do you say?”
“I can’t tell you what I feel, Christianssen. The very thought of it
makes a new man of me. But—I don’t know the first thing about
timber.”
“If you will relieve me of the office work and financing, it will be
good business all round. Details as to woods, etc., you can pick up
by degrees. I have a good staff here, but the best staff in the world
is the better for being looked after. If I can be free to get across to
Norway and feel quite safe in going, it will mean much to me and to
the business. You will say yes?”
“I’ll say yes with more in my heart than I can put into words,”
and they shook hands on it.
So John Dare took up a new lease of life and hope, and was
himself again and twenty years younger than he had been any time
this last three months.
And presently, for his still greater comfort and relief of mind,
came Uncle Tony’s unexpected legacy to Mrs Dare. It was a veritable
Godsend. For the heaviest part of his burden, during these late
months of no income and vanishing capital, had been the fear of
what might befall his home-folks when the worst came to the worst.
The thought of it had kept him awake of a night and plunged
him into the depths. He had racked his tired brain to find some way
out of his difficulties. But it was like trying to climb a huge black wall
whose top shut out even the sight of heaven. For always the grim
fact remained that his business was utterly gone and he saw no
prospect of its revival.
By the grace of God and Uncle Tony and John Christianssen he
was delivered from torment. The home-folk were safe whatever
happened, and he took up his new duties with all the enthusiastic
energy of a heart retrieved from despair.
XXVIII
U PON none of them did the burden of these weighty times lie so
heavily as on Lois Luard and Alma Dare.

They both received occasional letters indeed, but Ray’s, though


always full of cheery hopefulness, were very irregular and subject to
lack of continuity through one and another occasionally getting lost
on the way. And, great as was Lois’s joy and thankfulness when one
arrived, telling of his safety and good health eight or ten days
before, she could never lose sight of the terrible fact that five
minutes after he had written it the end might have come.
With what agonising anxiety she scanned each long, fateful
casualty list as it came out, only those who have done that same can
know. Sore, sore on wives and mothers, and on all whose men were
at the front, were those days when the desperate German rush on
Calais and the coast was stayed by the still greater and more
desperate valour of our little army, fighting odds as David fought
Goliath of Gath. The mighty deeds done in those days will never be
told in full, for in full by one Eyewitness only were they seen, and He
speaks not.
But doings so Homeric are of necessity costly. Britain and the
world at large were delivered from the Menace, but Sorrow swept
through the land.
Alma continued to receive word of Con, but at irregular intervals
and always by the hand of Robert Grant, R.A.M.C., Con himself being
still unable to put pen to paper.
Mr. Grant, however, wrote with a clerkly hand, and Alma came to
know it well and to like it. The words were Con’s own for the most
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookultra.com

You might also like