MaKE yOUR OWN aPP: PaRt ONE

January 18, 2015
LEARN
to code
IN
STNMAST2008
1
day
MAKE YOUR
OWN APP:
part one
CREATE AN APP IN A DAY
If you can’t code,
you’ll be left in the
past — so snap to it
Coding is no longer a geeks’ hobby: it’s everywhere. Now is the time for
families to hone their HTML, crack CSS and jump into JavaScript together, and
our hi-tech snap app is a brilliant way to get started, writes Kathryn Parsons
W
hether you are 60 or six years
old, understanding the technology behind
the screen is becoming increasingly valuable.
In today’s world digital literacy and
programming skills are in high demand and
short supply across every industry and sector.
By taking your first steps behind the screen,
you may unearth a latent talent and love of
programming or at the very least begin to
understand the machines influencing our
lives. An exciting journey lies before you.
Only a tiny percentage of the world is
code-literate, but coding is one of the most
creative skills that anyone could have — and
this is what we’ve set out to prove in our
Learn to Code guide over the next two weeks.
More than 12,000 of you took your first steps
into the world of programming in September
last year, coding your very own quiz game
app. This week and next we bring you another
tutorial in our Learn to Code series, using the
Playto online code education platform
designed by the team at Decoded.
We’ll be teaching you to code your own web
app called Snap That! (well, that’s what we’ve
called ours — you can give yours any name
you like). It’s a game of snap that you can
code, customise and then play with friends or
family on your smartphone or tablet.
Snap That! will introduce you to algorithms
— using logical reasoning to design computer
programs that make decisions — while guiding
you through the creating and debugging
process. Not only is this valuable and fun for
adults; we’ve also taken care to ensure the
tutorials cover the key aspects of the new
computing curriculum for key stages 1 and 2
— so you and your kids can learn together.
Apply your problem-solving skills,
creativity, persistence and imagination to the
task at hand. You are about to go further
behind the screen than a vast proportion of
the web-consuming population has ever been.
You are about to become a creator of
something that could be as simple and fun as a
game or could inspire a business idea or help
formulate new ideas in your job — the
possibilities of code are truly endless.
The future is being written in lines of code.
Become part of that future.
Everyone loves the card game
snap. We’re going to build a
touchscreen version
1
THE BRIEF
1
The Playto Editor
Introduction to our editor environment
Wireframing
If you fail to plan, plan to fail
3
Coding our content
First bits of content using HTML
Kathryn Parsons, chief executive of Decoded
Since the start of this school year coding has been part of the
national curriculum, so there’s never been a better time for
families to get coding together. Don’t worry if this tutorial
challenges you: it’s the equivalent of finishing key stage 2
!
2
“You are about to go further
behind the screen than most of
the population has been. The
future is being written in lines of
code. Be part of that future”
STNMAST2008
4
Valid HTML
Following the rules of html to make our
content ‘valid’
5
Meta and Structural HTML
Giving our app shape and description
6
Intro to CSS
Connecting our stylesheet to do some design
7
Designing our User Interface
Getting creative with CSS
8
choosing images
Finding pictures for the game to use
9
programming overview
The three key ideas behind computer languages
10
intro to javascript
We will start by
“wireframing”, or
planning, the app.
We’ll then work on
defining the content
and setting up our
page. With our basic
content in place, we can focus on the design of our app.
Once it looks right, we can begin to make it work.
The Playto Editor
On any computer, start by going to:
thesundaytimes.co.uk/learntocode.
Sign in to the Playto Editor (you’ll need to sign up first if you
haven’t before), and then start following the instructions
below. As you create your app, the editor will automatically
save your work and update a preview to give you feedback as
you progress. But first we need to do some planning.
2
Wireframing
12
Random Image
Selecting a random image
absolutely vital to building an
app. If you sit down and start
sketching, it’s possible to
explore multiple options for
what your app could do and
how it could look.
the Google Docs Draw app, with a template of app
wireframes — go to tinyurl.com/nun28lr. We want to include
the title of our app, a button to start the game, space for two
images to display and a space to show the player scores.
Carrier
12:00
Snap That
PLAY
Player 1:0
Player 2:0
Carrier
This is looking
a little busy. We
could hide the
player scores
until play begins.
This gives us
space to put the
images stacked
on top of each
other ...
12:00
Snap That
PLAY
Better. But we could
make things even
neater by combining
the title with the play
button, and move it
between the images to
balance the layout ...
We now know
what we need to
build and how
it’s going to look.
So let’s dive into
the HTML!
in the frame
Wireframes are basic
designs that are incredibly
useful for planning the
user feel of a digital
experience, before a single
line of code is written.
Originally, wireframes
tended to be long lists of
specifications and page
elements but today they
are often very visual
representations of the
app or website that is
going to be built.
If you're thinking of
commissioning an
application, or working
with a developer, often
bringing wireframes
(however sketchy!) can be
a useful starting point for
discussion and design.
2There
TOOLS
is a ton of tools out there
3We’ll
GOOGLE
DOCS
start with some rough sketching. We’re going to use
Random Numbers
Generating a random number
1ThePLANNING
planning process is
for making basic prototypes. You can get a very long way
with tools such as fluidui.com and proto.io. But actually
nothing beats a pencil and paper. The key thing is to get the
idea out of your head and into a medium where you can play
around with it. A huge part of the development process is
Googling, reading, thinking, sketching. Let’s get to it.
Using Javascript to make our app come alive
11
Our snap game app for
smartphone or tablet
will use our own
images. Although it is
a touchscreen game, it
is a web app, running
on a web browser
such as Chrome or
Safari.
3
coding our
content
Carrier
12:00
PLAY SNAP THAT!
Every web page and many of
the apps you know and love
use HTML. It allows us to tell
the browser what everything
is: our logos, paragraphs, any
images, videos and so on.
HTML is a universal language
— it is understood by every
browser, and all smartphones
can run apps built in HTML.
We want our app to be accessible
to everyone. HTML is the only language that everyone’s
device can understand.
1Create
NEWaPLAYTO
PROJECT
new project in the Playto Editor.
2Replace
APP NAME
“Hello, universe!” with the name of your app.
3PutHEADING
1
the app name text inside an <h1> element.
MOBILE FIRST
Web design used to
be mainly for desktop
computers, but as more
and more people now use
mobile devices to access
the web it is best practice
to design "mobile first".
This means thinking about
a mobile user's experience
first, and then extending
your design to desktop.
<h1>PLAY SNAP THAT!</h1>
4Under
PARAGRAPH
your h1 add text for your two players in paragraph
elements.
<p>PLAYER 1</p>
<p>PLAYER 2</p>
5AddCANVAS
a new canvas element above and below your code. A
canvas allows the browser to draw — or create images — in
an area on the page. In our case, we’ll be using the canvas to
display the snap images.
<canvas>Canvas not supported</canvas>
<h1>PLAY SNAP THAT!</h1>
<p>PLAYER 1</p>
<p>PLAYER 2</p>
<canvas>Canvas not supported</canvas>
Turn to page 4 Â
{HTML}
HTML — THE
LANGUAGE OF
CONTENT
HTML, which stands
for HyperText Markup
Language, was developed
by the inventor of the web,
Sir Tim Berners-Lee
in 1989.
The original idea behind
HTML was to write an open
set of rules so that any
browser could interpret
a piece of content and
know where there were
paragraphs, headings,
lists and so on. BernersLee's idea was to allow the
transfer of information
between different
computers, and so HTML
is purely a language
of content.
The fact that HTML is
a "markup language"
means that rather
than writing rules
and instructions for a
computer, we are simply
"marking up" content
with tags.
AN EVOLVING
STANDARD FIRST
HTML is constantly
evolving and developing
as new features come
out. If you use a browser
like Chrome, updates will
happen in the background,
meaning that you'll always
have the latest version.
Aa
THE IMPORTANCE
OF CASES You may have seen
that whether you type
in upper or lower case
matters sometimes when
you’re coding, but not
all the time. It’s usually
best practice to keep
everything lower case
when you are coding, to
make sure that you can
always references files
and elements.
CREATE AN APP IN A DAY
ERROR! Don't panic
Inevitably it won't always work. If you get an error message, go back through and check
every line and punctuation mark carefully. Then check the detail of your error message
for clues. If that doesn't work, help is on hand at our forum — forum.playto.io. Key in
your question and everything will be OK. We’ve also printed a complete rundown of how
your HTML, CSS and JavaScript files should look on the back cover
4
Valid HTML
When Sir Tim Berners-Lee
created the language of HTML,
he set rules for how a page
should be laid out. We need to
add a few more HTML elements
in our page before the content
can be considered “valid”, or as
adhering to the rules of HTML.
HTML is the language we use
for telling the browser what
things are. If you check out your
app in the browser (by clicking
“View Your App” in the Editor) you will notice that there’s no
title in the tab at the top. We need to give the app its own
name, which means adding in a bit more structure.
All HTML pages are made up of two sections: the head for
information about the page, and the body for content the user
sees. The content we’ve written will therefore go in the body.
We can also indent our code. This is purely to show us, as
coders, what’s where. The browser ignores white space.
<html>
<section>
<canvas>Canvas not supported</canvas>
When HTML was
created there were other
competing markup
languages. One of the
reasons HTML has become
so widely used is that
Berners-Lee decided to
make it completely open.
This means that if you
right click on any page on
the web and select "View
page source" you will be
able to see the raw HTML
that makes up the page.
<body>
!DOCTYPE
<html>
<head>
</head>
<body>
<canvas>Canvas not supported</canvas>
</section>
2 GIVE YOUR APP A TITLE
This “title” is not part of the body content. It gives the page a
name, which displays on the tab in your browser and is what
a search engine will use.
<head>
<title>Snap That!</title>
</head>
Doctype tells the browser
what version of HTML
we’re going to be using.
Since HTML is now an
evolving standard (which
means there will never
be an HTML6), it means
that this tag is slightly
less important. However,
for older browsers in
particular, we need to
make sure it is the first
line of our HTML page.
content="width=device-width,
initial-scale=1.0, user-scalable=no">
</head>
<p>PLAYER 2</p>
</>
2 COMMENTS
Let’s add in a comment at the very top of the page to label
who created this page (using your name, of course).
<!-- This app was made by Harriet -->
5
Meta and
Structural HTML
Now we have the important
elements in HTML in our code,
we can add a few more meta
and structural elements to help
give our page a name, ensure it
is mobile-ready and add a little
more structure.
1 CREATE A SECTION ELEMENT
AROUND YOUR CONTENT
The “section” element tells
the browser that this area
is a piece of generic content.
keeping up
STANDARDS
HTML is often described
as quite a "forgiving"
language to code in. If you
miss some tags out, like
the head or the body for
example, your website
will probably still display.
However, there are web
standards that every
developer should try to
stick to. By keeping to
these standards you can
be sure that your web
page will look the same on
every device and browser.
CSS (cascading style sheets) is
the way you give your HTML
project a design. It works by
targeting HTML elements and
giving them a list of style
instructions. Look out, though,
because they are spelt the
American way — color, center
and so on.
6
Intro to CSS
<canvas>Canvas not supported</canvas>
scale=1.0, user-scalable=no">
<link href="style.css"
rel="stylesheet">
</head>
3 CREATE A BODY SELECTOR IN CSS
To create an instruction in CSS we first tell it what element to
target, and then we list the changes between curly brackets.
Start your style.css file with:
body { }
4 ALIGN YOUR TEXT AND CHANGE THE FONT FAMILY
Each instruction starts with a property to change, for example
“text-align”. This is followed by a colon and then the value it
should be changed to, for example “center”. Finally we add a
semicolon to tell the browser that we’ve finished.
CSS, THE LANGUAGE
OF DESIGN
CSS stands for cascading
style sheets. It was
developed by Hakon Wium
Lie and Bert Bos in the
early 1990s.
Fundamentally, CSS
gives developers the
ability to breathe life into
HTML – colours, borders,
backgrounds and more.
We’ll be showing you a
variety of CSS commands,
but to see an entire list
of them have a look at
the W3.
font-family:Helvetica;
If you think about it, any
particular part of a design could
be described by how it looks.
You say things like: I want my h1 to be big, bold, red and
centred.
Lots of HTML tags are not
very descriptive. Div, for
example, just stands for
‘division’ and could be
anywhere on a page. With
HTML5 came a number
of new more ‘semantic’
(descriptive) tags – things
like section, footer and
header. These semantic
tags make it easier for
a computer to read and
understand an HTML
page, which is especially
useful for things like
accessibility (so that text
can be enlarged for people
with visual impairments,
for example).
h1 {
font-weight: bold;
text-align: center;
1 CREATE A NEW STYLESHEET
Click the plus sign in the file panel to the left of the Playto
Editor. We can call this new stylesheet anything; style.css is a
sensible name, as it’s short and clear.
2 CONNECT YOUR STYLESHEET TO YOUR HTML
We connect a stylesheet with a link tag. This is like the meta
element — it doesn’t require a closing tag. So, back in the
HTML file:
There are many “word colours”
that have already been defined by
developers. If you want to truly customise your design, you’ll
need to create your own (see “In the pink” panel, far right).
1 BACKGROUND COLOUR
body {
text-align:center;
3 MARGIN AND PADDING
Our h1 will start the game, so we want it to look like a button.
We can give it a bright background colour and then add
padding and margin instructions to give our heading text a
little space to breathe. Padding is a property that adds space
inside an element. Margin adds space around it. These border
instructions give our h1 a solid black border 2 pixels wide.
h1 {
background:yellow;
padding:2%;
margin:2%;
SEPARATION
OF CONCERNS
In computing we often
talk about the idea of the
"separation of concerns",
and in web development
this means having
separate languages and
files for content, design
and interactivity.
This separation is
important because it
makes our code easier
to change. For example,
multiple content files can
reference the same design
file. This means that a
change only needs to be
made in that one style
page and it will affect all
the content pages.
ONLINE
RESOURCES
There are a whole host of
online resources related to
CSS styles. Pretty much
anything you can imagine
from a design perspective
is possible with CSS. One
of the best starting points
is to Google what you
want to do (e.g. ‘make the
background red’) and
find the code.
RGB
}
p {
width:40%;
float:left;
padding:2%;
margin:2%;
border:2px solid black;
border-radius:40px;
background:yellow;
}
5 DISPLAY NONE
Finally, we don’t want our player score to show until play
begins. We can insert “display:none;” to hide the paragraphs
until we are ready to show them.
p {
width:40%;
float:left;
background:LightGrey;
padding:2%;
border:2px solid black;
Our next instruction targets the HTML, body and section
element at the same time. We need to set their heights to 100%
so the canvas height of 42% will be rendered properly.
canvas {
width:100%;
height:42%;
background:yellow;
border-radius:15px;
border-radius:40px;
When Berners-Lee
created the language of
HTML, he decided to use
international (American)
English as it is the most
widely used version. This
can sometimes trip up
those of us in the UK when
we are spelling words like
colour (color) and centre
(center). If you find this
frustrating, just remember
how lucky we are it is
written in our language.
in the pink
There is a set number of
"word colours" that have
already been defined by
developers, but if you truly
want to customise your
design, you'll need to
pick your own.
To do this, you can go
to colorpicker.com, and
you'll see that each colour
has an R, G and B value
(standing for red, green,
blue). Just select a colour
you like, and then copy the
RGB colours to your CSS.
For example, you might
change your heading to a
lovely shade of pink:
h1 {
color: rgb(222, 38, 210);
}
If you'd like to have a bit
of transparency in your
colour, you can also give it
an "alpha" value between
0 and 1, with 0 being
completely transparent
and 1 being opaque.
h1 {
color: rgba(222, 38, 210,
0.8);
}
margin:2%;
divided by the
same language
Once you understand
the principle of CSS, you
can add as many rules
for each bit of the page
as you like. What's great
too is that they're all
interchangeable, so if
you know how to change
the size of a heading, you
can change the size of a
paragraph (or anything
else you like).
border-radius:40px;
font-family:Helvetica;
Our canvas elements will display the snap images. Right now
they are not showing on the page as they don’t have a size.
First we create a new set of instructions for the canvas
elements; then we create changes for the width, height, and
background colour. The last instruction rounds the corners,
adding a curve with a radius of 15 pixels.
BE AS CREATIVE
AS YOU LIKE
border:2px solid black;
2 SIZE AND COLOUR
color: red;
But hold on — that code needs to go in a CSS file, so let’s set
one up.
Designing our
User Interface
Let’s start by giving our apps a
little more colour and structure.
Add a new design instruction to
our body in our stylesheet for
“background”. Note the
international spelling of “color”.
}
}
font-size: 48px;
}
7
height:100%;
Our player paragraphs will eventually display our player
scores. We can style them the same as our h1. However, we
want them to sit next to each other. To do this we need to add
a “float” value so that they sit side by side.
text-align:center;
SEMANTIC
ELEMENTS
html, body, section {
4 FLOAT
body {
Now we’ve got everything set
up, we can start to design our
user interface.
STNMAST2008
}
CSS
}
<meta name="viewport"
<p>PLAYER 1</p>
</html>
INITIAL SCALE
When the iPhone was
launched in 2007,
one of the reasons it
revolutionised the mobile
computing landscape was
because it pretended to
every web page that it had
a much greater width than
the screen size.
This meant an iPhone
could display a site as it
had been designed, and
the user could double-tap
to zoom in and see more.
As we’re designing
specifically for mobiles, we
must get mobile devices to
tell us their true width, and
to automatically have a
zoom level of 1 that makes
up the page.
content="width=device-width, initial-
<title>Snap That!</title>
<h1>PLAY SNAP THAT!</h1>
</body>
3
<meta name="viewport"
<head>
<!-- content goes in the body -->
<!DOCTYPE html>
<canvas>Canvas not supported</canvas>
This line probably looks a bit intimidating, but essentially it’s
a “meta” description — a piece of information about our file
that gives the browser information about how to display it.
The initial-scale and user-scalable parts ensure our games
will look correct on a mobile device. This element is selfclosing — it doesn’t need a closing tag.
</head>
Why do we need to add !DOCTYPE? See panel, right.
<p>PLAYER 2</p>
3 TELL THE BROWSER THIS APP IS MOBILE-READY
head -->
1 HTML, BODY AND HEAD
<p>PLAYER 1</p>
A RADICALLY
OPEN LANGUAGE
<!-- meta information goes in the
</html>
<title>Snap That!</title>
<h1>PLAY SNAP THAT!</h1>
<head>
</body>
<head>
background:yellow;
display:none;
}
8
Storing Images
Now that we’ve got our page
looking at bit better, let’s take a
look at how we can add images
to our project. You can use any
images that are hosted online
— all you need are the URLs.
1. CHOOSE SOME IMAGES
You could get images of your
family from your Facebook, use
some holiday snaps from
Turn to page 6 Â
AA
AA
custom-built
Why not customise your
app? "Google Fonts" is a
great tool that allows you
to import a font direct into
your page.
CREATE AN APP IN A DAY
Instagram or just find some pictures of cats on a search engine
(Snap Cat!).
If you use Google, we recommend you filter your search by size
(click “Search tools”, then select “Medium” from the “Size”
filter), and also filter “Usage rights” to “Labelled for reuse” to
ensure they are copyright-free.
In our tutorial we are just going to use 5 images. However, you
can use as many as you want. Be as creative as you like!
2 TEST YOUR IMAGE URLS
Let’s check our images are working properly. We can add some
CSS to our canvas instructions to define the “backgroundimage” URL. When you add this code, your image should
appear as the background of both canvas elements.
!
NATIVE
FUNCTION
A "native" function is
a one that is already
understood by a
programming language.
For example, all
programming languages
understand the rules of
mathematics. JavaScript
has various native
functions, for example
an "alert", which
produces a pop-up.
There are many native
functions in JavaScript.
Here are some examples:
alert (message),
if (condition),
prompt (question),
Math.round (number), etc.
Make sure you test all your image URLs. They should have a
similar structure to our example in the code above. The code
below won’t actually work — you need to get your own
images. Don’t worry if your URL is really long, but it should
end in “.jpg”, “.jpeg”, “.png” or similar. These are all types of
image file.
canvas {
width:100%;
All programming languages are made of the same three ideas:
Variables fl Data
Functions fl Actions
Logic fl Decisions
Variables are the bits of information the program is concerned
with.
Functions are predefined sections of code that do a certain
thing.
Logic is the decisions the code needs to make at any given
time.
It’s always helpful to break down your desired outcome into
the variables, functions and bits of logic we’ll need to write.
Let’s do this together.
Variables
height:42%;
background-color:yellow;
border-radius:15px;
background-image:url("http://image-url/
image1.jpg");
We’ll need to know where the images we’re using are stored,
and we’ll also need a way to make the images random. For the
players, we need to define which part of the screen detects a
tap for each player and their scores. Finally, to stop them both
gaining a point, we will need a variable to define if a snap has
been correctly made.
appear. See “Native function” panel for more information
about the alert function.
alert("Hello World!");
THE
CONSOLE
The console displays
diagnostic information
about the web page
being displayed.
It has two purposes:
2) It is an interface in
your browser where you
can execute JavaScript
commands directly in your
browser. This lets you test
out JavaScript commands
before adding them
to a script.
You might find that your images aren’t filling the space in the
way you would like. There are two properties for background
that we can add — “size” and “position” — which will help to
place the images so they fill the canvas element without
distorting the aspect ratio and are positioned in the centre.
canvas {
width:100%;
height:42%;
background-color:yellow;
border-radius:15px;
background-image:url("http://imageurl/image1.jpg");
background-size:cover;
background-position:center;
}
9
Programming
Overview
It’s all well and good having a
beautifully designed page —
we’re certain some of your apps
will be more beautiful than
others ;-). But if it doesn’t do
anything, it’s a bit ... pointless.
This is where JavaScript comes
in. JavaScript is a programming
language. It enables us to tell the
app to respond to certain events,
compute certain calculations,
and essentially do the things we
want it to do. In our case we want to display a random cycle of
images and allow our users to gain points when they match.
But you can do anything you can imagine using a
programming language. The only limit is the speed of your
hardware and your own imagination!
Let’s do a quick intro to programming.
Run a looping function which randomly changes the images
Detect if a user has tapped the screen
Check if the images match
Change the scores if there was a winner.
LOGIC
What logical decisions might we make?
If a user taps the screen when the images match, increment
their score and prevent further “snaps”. If the user taps the
screen when the images do not match, reduce their score.
Note how logic makes use of our functions and variables. Logic
is the glue that holds a program together.
Let’s get cracking.
10
Intro to
JavaScript
// alert("Hello World!");
Random
Numbers
At the moment our canvas
elements are displaying the
same image. This won’t work
for our snap game! We can put
our images in an “array” and
use a random number to select
an image randomly.
1 DELETE THE BACKGROUND IMAGE
LINE IN THE CSS
Before we start making our
image randomly cycle, we need to
delete the line in our CSS that adds it as the background image
— background-image:url(“http://image-url/image1.jpg”);.
We are going to change the image dynamically using
JavaScript.
canvas {
We will need to:
3 BACKGROUND IMAGE SIZE AND POSITION
// Test if script.js is working
The CSS file should now look like this.
FUNCTIONS
}
Before moving on, add a comment above your alert to remind
yourself what the line was for (see “Comments” panel). We do
this by adding // at the start of the line. Now we are sure the
file is working, we can comment out the alert.
11
In line with our “separation of
concerns” idea, rather than
typing our JavaScript directly
into our content HTML we can
instead create a new JavaScript
file and link this to our HTML.
1 CREATE A NEW JAVASCRIPT FILE
Click the plus sign in the file
panel to the left of the Playto
Editor. We can call this new
Javascript file anything: “script.js”
is a sensible name, as it’s short and clear. But first:
2 CONNECT YOUR JAVASCRIPT TO YOUR HTML
</section>
<script src="script.js"></script>
</body>
</html>­
3 TEST THAT SCRIPT.JS IS CONNECTED PROPERLY
Now that our .js file is connected, let’s do a little test to see if
it’s working. Add this native “alert” function code in your .js
file. Then click “View Your App” and a pop-up box should
Now we put a random number in each variable. This is done
with a native JavaScript “Math” function.
// Randomly change number
4 COMMENTING IN JAVASCRIPT
1) It is a place to output
diagnostic information
like JavaScript and CSS
errors and any information
passed to the console.
width:100%;
height:42%;
num1 = Math.floor( Math.random() *
imgArray.length);
num2 = Math.floor( Math.random() *
imgArray.length);
5 TEST RANDOM NUMBERS
We should test if our random number generator is working
OK. We could use an alert function again; however, there is a
more sophisticated way of testing our code. Every browser
has a “Developer console” that shows the live activity of any
JavaScript running on a website.
Click “View Your App” to see your app preview. If you’re
using the Chrome browser from the toolbar select View >
Developer > JavaScript Console.
This will open a panel at the bottom of your screen where
you should see the random results of your Math function. If
you refresh the page, you should see a new pair of random
numbers.
See “The Console” panel for more information about this.
// Test random numbers
console.log("First random number is "
+num1);
console.log("Second random number is
"+num2);
background-color:yellow;
comments
These are essential for
any web project. One
reason you should always
try to put comments
in your work is in case
another developer picks
up the project and wants
to continue with it. In the
open-source community,
where hundreds or
thousands of people will
be working on a project,
comments allow people to
express how they decided
to structure the code.
Even if you’re the only one
who will ever be coding
your project, if you write
some code and then come
back to it a year later you
may have forgotten what
you wrote. Comments are
really useful for jogging
the memory.
border-radius:15px;
background-size:cover;
background-position:center;
}
2 CREATE AN ARRAY
Create an array in script.js to define which images to use in
your game. Use the URLs of your images surrounded by quote
marks. (The code below won’t link to any real images. You
need to use the images you found in section 8!)
// Test if script.js is working
// alert("Hello World!");
// Define images to use
var imgArray = ["http://image-url/image1.
jpg","http://image-url/image2.jpg",
"http://image-url/image3.jpg", "http://
image-url/image4.jpg", "http://image-url/
image5.jpg"]
3 CREATE NUMBER VARIABLES
We want our game to randomly cycle through the images. To
do this we need to create a random number for each.
Create two new variables in script.js to store the random
number. We could use any names here, but “num1” and
“num2” are short and clear.
// Create variables for random numbers
var num1;
var num2;
STNMAST2008
4 RANDOM NUMBER SELECTION
12
Random
Image
Now we are generating two
random numbers, we can use
these to change the images
displayed in our canvas
elements.
1 CREATE IMAGE VARIABLES
Create two new variables to
store the random images. We
could use any names here, but
“img1” and “img2” are short
and clear.
// Create image variables
var img1 = imgArray[ num1 ];
var img2 = imgArray[ num2 ];
2 CREATE URL VARIABLES
Next we create two new variables to store the location of our
images. We combine the “img” variables with the required
CSS syntax — url(“”); — to produce the final URL needed to
locate the image. As the images are changing randomly we
need to use dynamic information.
A plus sign in JavaScript combines two things. We’re using it
here to mix a variable [eg, img1] with the opening CSS code
[url(“] and the closing CSS code [“);], but if these were
numbers it would add them together.
// Create css value for background image
var url1 = "url("+ img1 +")";
var url2 = "url("+ img2 +")";
That’s it for this week.
Turn over to see how your complete code should look.
NEXT
WEEK:
Don’t miss part two
of Learn to Code in
The Sunday Times
next week.
In it you will find the
final eight steps
to bring your Snap
That! app to full
functionality.
On top of that we’ll
show you how to
share your game
with millions of
others by launching
it on social media.
Don’t worry if you
have found this
difficult — just
think how much
you have learnt
and congratulate
yourself on having
joined the 1% of
humanity who have
learnt the skill set of
the future.
Quick check: if you have followed the
instructions in the previous pages correctly,
the code you have written should look as it does
in the boxes below — if you have any problems
there is a forum waiting to help you at
forum.playto.io.
Key in your question and it will be answered
index .html
<!-- This app was made by Harriet
-->
body {
font-family:Helvetica;
<!DOCTYPE html>
<title>Snap That!</title>
<meta name="viewport"
content="width=device-width,
background:LightGrey;
}
<link href="style.css"
<h1>PLAY SNAP THAT!</h1>
<p>PLAYER 1</p>
<p>PLAYER 2</p>
<canvas>Canvas not
supported</canvas>
</section>
width:100%;
image3.jpg", "http://image-url/
height:42%;
image4.jpg", "http://image-url/
background-color:yellow;
image5.jpg"];
background-image:url("http://
image-url/image1.jpg");
<section>
supported</canvas>
image2.jpg", "http://image-url/
border-radius:15px;
rel="stylesheet">
<canvas>Canvas not
// Define images to use
var imgArray = ["http://image-url/
canvas {
scalable=no">
<body>
// alert("Hello World!");
image1.jpg", "http://image-url/
initial-scale=1.0, user-
</head>
// Test if script.js is working
text-align:center;
<html>
<head>
Script.js
STYLE.CSS
// Create variables for which card
to pick randomly
background-size:cover;
var num1;
background-position:center;
var num2;
}
// Randomly change number
html, body, section {
height:100%;
}
num1 = Math.floor( Math.random() *
imgArray.length );
num2 = Math.floor( Math.random() *
imgArray.length );
h1 {
<script src="script.js"></
script>
</body>
</html>
background:yellow;
// Test random numbers
padding:2%;
console.log("First random number is
margin:2%;
" +num1);
border:2px solid black;
console.log("Second random number is
border-radius:40px;
"+num2);
}
// Create image variables
to get
started go to
THEsundaytimes.
co.uk/learntocode
p {
width:40%;
var img1 = imgArray[ num1 ];
var img2 = imgArray[ num2 ];
float:left;
padding:2%;
// Create css value for background
margin:2%;
image
border:2px solid black;
var url1 = "url("+ img1 +")";
border-radius:40px;
var url2 = "url("+ img2 +")";
background:yellow;
display:none;
}