Issuu on Google+

17te 2u0pda

The best programming guide money can buy!

Learn how to program the easy and fun way LEARN HOW TO… • Master Scratch and Python • Write your own programs • Create games on a Raspberry Pi

TMS16 2016


DIScOVeR the futuRe Of autO tech IN tODaY’S cONNecteD wORlD

Online • PrinT • TableT

apple watch Pre-condition and open your car

BMw i3 The compact electric vehicle to die for

lIfe’S BetteR wIth t3 t3.com


Learn how to program the easy and fun way


Editorial team Contributors Editor

Neil Mohr Art Editors

Efrain Hernandez-Mendoza Fraser McDermott

Editor-in-chief

Les Pounder, Mayank Sharma, Graham Morrison, Ben Everard, Mike Saunders, Jonni Bidwell, Mihalis Tsoukalos

Graham Barlow Images

ThinkStock, Future Photo Studio

Management Editorial director

Marketing

Circulation

Marketing Manager

NEWSTRADE MANAGER

Kristianne Stanton

Andy Williams

Paul Newman Group art director

Graham Dalzell

Print & production

Licensing

HEAD OF PRODUCTION UK & US

senior Licensing & Syndication manager

Mark Constance

Matt Ellis matt.ellis@futurenet.com Phone +44(0)1225 442244

Production Controller

Vivienne Calvert

Subscriptions UK reader order line & enquiries: 0844 848 2852 Overseas reader order line & enquiries: +44 (0)1604 251045 Online enquiries: www.myfavouritemagazines.co.uk

Printed in the UK by William Gibbons on behalf of Future. Distributed in the UK by Marketforce (UK), 2nd Floor, 5 Churchill Place, Canary Wharf, London, E14 5HU

Future Publishing Limited Quay House, The Ambury, Bath, BA1 1UA, UK www.futureplc.com www.myfavouritemagazines.co.uk Phone +44 ( 0 )1225 442244 Fax +44 ( 0 )1225 732275 All contents copyright © 2016 Future Publishing Limited or published under licence. All  rights reserved. No part of this magazine may be reproduced, stored, transmitted or  used in any way without the prior written permission of the publisher. Future Publishing Limited (company number 2008885) is registered in England and Wales. Registered office: Registered office: Quay House, The Ambury, Bath, BA1 1UA. All information contained in this publication is for information only and is, as far as we are aware, correct at the time of going to press. Future cannot accept any responsibility for errors or inaccuracies in such information. You are advised to contact manufacturers and retailers directly with regard to the price and other details of products or services referred to in this publication. Apps and websites mentioned in this publication are not under our control. We are not responsible for their contents or any changes or updates to them. If you submit unsolicited material to us, you automatically grant Future a licence to publish your submission in whole or in part in all editions of the magazine, including licensed editions worldwide and in any physical or digital format throughout the world. Any material you submit is sent at your risk and, although every care is taken, neither Future nor its employees, agents or subcontractors shall be liable for loss or damage. Future is an award-winning international media group and leading digital business. We reach more than 57 million international consumers a month and create world-class content and advertising solutions for passionate consumers online, on tablet & smartphone and in print. Future plc is a public company quoted on the London Stock Exchange (symbol: FUTR). www.futureplc.com

Chief executive Zillah Byng-Thorne Non-executive chairman Peter Allen Chief financial officer Penny Ladkin-Brand Managing director, Magazines Joe McEvoy Tel +44 (0)1225 442 244

We encourage you to recycle this magazine, either through your usual household recyclable waste collection service or at recycling site. We are committed to using only magazine paper which is derived from well managed, certified forestry and chlorine-free manufacture. Future Publishing and its paper suppliers have been independently certified in accordance with the rules of the FSC (Forest Stewardship Council).


Learning to code will change the way you think about the world. It’s an exciting journey! With the internet driving a new world of information exchange, business start-ups and online gaming, coders have suddenly become the gatekeepers to these new realms. Combine the huge interest in learning how to create and control these worlds with the surge of cool devices, such as the Raspberry Pi, and you’ve got a head of technological steam the world hasn’t seen since the coding craze of the early 1980s. Back then, it was more Code Britannia than Cool Britannia – jump forward to today, and Britain is again firmly at the heart of a web and coding revolution. A Brit invented the web, a Brit designed the Raspberry Pi, and Britain is firmly pushing coding to the fore of education.

Made Simple books are designed to get you up and running quickly with a new piece of hardware or software. We won’t bombard you with jargon or gloss over basic principles, but we will… Explain everything in plain English so you can tackle your new device or software with confidence and really get to know how to use it

So no matter if you’re looking to relive those heady ’80s coding days or are a newbie looking to take your first steps into the coding world, you hold in your hands the ideal guide to start coding. Thanks to a new generation of open free software, we all can access operating systems, development tools, compilers and the programming languages needed to create professional programs, apps and tools. We’ll show you how to get up and running with a Linux system, then access everything you need freely online. Coding is easy, exciting and fun. We’ll explain the basics, move on to more advanced topics, explain how you can use the Raspberry Pi, and provide you with fully updated exciting and easy-to-follow projects. So what are you waiting for? Get coding! Neil Mohr, Editor

Break instructions down into easy-to-follow steps so you won’t be left scratching your head over what to do next Help you discover exciting new things to do and try – exploring new technology should be fun and our guides are designed to make the learning journey as enjoyable as possible for you

Teach you new skills you can take with you through your life and apply at home or even in the workplace Make it easy for you to take our advice everywhere with you by giving you a free digital edition of this book you can download and take with you on your tablet, smartphone or laptop – see page 146 for more details on this offer

How are we doing? Email techbookseditor@futurenet.com and let us know if we’ve lived up to our promises!

Coding Made Simple | 5

Welcome & Manifesto

Welcome!


Contents

Contents

Download the code at

Scratch

http://bit.ly/ codingmadesimple16

Getting started with Scratch Using variables in Scratch Learn about Loops Using lists in Scratch Build a game with Scratch Scratch: Hack it

10 12 14 18 20 24

������������������������������������������������������������������������

����������������������������������������������������������������������������������

�������������������������������������������������������������������������������������������������������������������

���������������������������������������������������������������������������������������������������������� ��������������������������������������������������������������������������������

�������������������������������������������������������������������������������������������������������������������������������

Coding on Pi Welcome to Pi Coding in IDLE Minecraft: Start hacking Minecraft: Image walls Minecraft: Build 2048 Python Turtle: Draw shapes Sonic Pi: Make some noise! Ruby: Compose music Sonic Pi: Use a dance mat Sonic Pi hardware control

28 30 32 34 38 44 46 50 52 54

�������������������������������������������������������������������������������������������������������������������������������������� ������������������������������������������������������������������������������������������������������������������������������������

�����������������������������������������������������������������������������������������

������������������������������������������������������������������������������������������������

��������������������������������������������������������������������������������������������������� ���������������������������������������������������������������������

���������������������������������������������������������������������������

�����������������������������������������������������������������������������������������������

����������������������������������������������������������������������������������

����������������������������������������������������������������������������������

Coding basics Get started with Linux Mint and Python

58 62

���������������������������������������������������������������������������������������������������

����������������������������������������������������������������������������������������������������������������������������

6 | Coding Made Simple


Contents

64 66 70 72 74 76 78 82 84 86 88 90

Get started with IDEs Python lists Functions & objects Conditionals Variables Building proper programs Recursion Sorting algorithms Hidden secrets of numbers Using loops The magic of compilers Common coding mistakes

������������������������������������������������������������������������������������������������������

�������������������������������������������������������������������������������������������������������������������������������������������������

��������������������������������������������������������������������������������������������������������������

�����������������������������������������������������������������������������������������������������������������������������������������������

��������������������������������������������������������������������������������������������������������������������������������������������������������������

�����������������������������������������������������������������������������������

���������������������������������������������������������������������������������������������������������������������������������������������������������

������������������������������������������������������������������������������������������������������������������� ���������������������������������������������������������������������������

��������������������������������������������������������������������������������������������������������������������������������������������������� ��������������������������������������������������������������������������������������������

������������������������������������������������������������������������������

Python Types of Python data More Python data types Reliability by abstraction Files and modules Write a UNIX program Enhance your UNIX program Finish up your UNIX program Neater code with modules Storage and persistence Data organisation

94 96 98 100 102 104 106 110 112 114

������������������������������������������������������������������������������������������������������ ����������������������������������������������������������������������������������������

����������������������������������������������������������������������������������������

��������������������������������������������������������������������������������������������������������������

���������������������������������������������������������������������������������������������� �������������������������������������������������������������� �������������������������������������������������������������

����������������������������������������������������������������������������

�������������������������������������������������������������������������������������

�������������������������������������������������������������������������������������������������������������������

Coding projects Python: Dead man’s switch���������������������������� 118 Object oriented coding ���������������������������������� 120 Practical Python 3 modules�������������������������� 124 Programming wc in Python��������������������������� 130 Copying files in Python ���������������������������������� 134 Functionality of find����������������������������������������� 138 Tkinter: Build a money app���������������������������� 142 Coding Made Simple | 7


erubyracer”, “~> 0.11.4” group :development, :test do gem “rspec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails ate_attributes(params[:task]) format.html { redirect_to @task, notice: ‘...’ } format.json { head :no_content } else format.html { render action: “edit” } format.json { ren xec rails generate migration add_priority_to_tasks priority:integer $ bundle exec rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate _at, ‘is in the past!’) if due_at < Time.zone.now #!/usr/bin/en python import pygame from random import randrange MAX_STARS = 100 pygame.init() screen = py tars = for i in range(MAX_STARS): star = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) for event in pygame. $numstars = 100; use Time::HiRes qw(usleep); use Curses; $screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $s >clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refre ment, :test do gem “rspec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond tml { redirect_to @task, notice: ‘...’ } format.json { head :no_content } else format.html { render action: “edit” } format.json { render json: @task.errors, status: :unpro rity_to_tasks priority:integer $ bundle exec rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_ one.now #!/usr/bin/en python import pygame from random import randrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) c star = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pyg Res qw(usleep); use Curses; $screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] rs ; $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “theru ails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond_to do |format| if @task.update_ .’ } format.json { head :no_content } else format.html { render action: “edit” } format.json { render json: @task.errors, status: :unprocessable_entity } $ bundle exec rails exec rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_in_the_past errors.add(:due_at, ‘is in th ygame from random import randrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() stars = ge(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/bin/perl $nu = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { $screen$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group :dev undler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond_to do |format| if @task.update_attributes(params[:task]) forma ent } else format.html { render action: “edit” } format.json { render json: @task.errors, status: :unprocessable_entity } $ bundle exec rails generate migration add_priori exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_in_the_past errors.add(:due_at, ‘is in the past!’) if due_at < Time.zon andrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() stars = for i in range(MAX_STARS): star = pend(star) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use Time::HiRes qw(us r ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < $numstars ; $i++) creen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group :development, :test do gem “rspec-rails”, “~> 2.13.0 ehash $ rails new todolist --skip-test-unit respond_to do |format| if @task.update_attributes(params[:task]) format.html { redirect_to @task, notice: ‘...’ } format.json { h son { render json: @task.errors, status: :unprocessable_entity } $ bundle exec rails generate migration add_priority_to_tasks priority:integer $ bundle exec rake db:m alidate :due_at_is_in_the_past def due_at_is_in_the_past errors.add(:due_at, ‘is in the past!’) if due_at < Time.zone.now #!/usr/bin/en python import pygame from een = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() stars = for i in range(MAX_STARS): star = [randrange(0, 639), randrange(0, 479), randrang pygame.event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use Time::HiRes qw(usleep); use Curses; $screen = new Curses; noecho; 0); $star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_ >refresh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group :development, :test do gem “rspec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --versi ond_to do |format| if @task.update_attributes(params[:task]) format.html { redirect_to @task, notice: ‘...’ } format.json { head :no_content } else format.html { rende unprocessable_entity } $ bundle exec rails generate migration add_priority_to_tasks priority:integer $ bundle exec rake db:migrate $ bundle exec rake db:migrate $ at_is_in_the_past errors.add(:due_at, ‘is in the past!’) if due_at < Time.zone.now #!/usr/bin/en python import pygame from random import randrange MAX_ST 40, 480)) clock = pygame.time.Clock() stars = for i in range(MAX_STARS): star = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] stars.append(star) while Tru pygame.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use Time::HiRes qw(usleep); use Curses; $screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $nums $i] = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($sta erubyracer”, “~> 0.11.4” group :development, :test do gem “rspec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails ate_attributes(params[:task]) format.html { redirect_to @task, notice: ‘...’ } format.json { head :no_content } else format.html { render action: “edit” } format.json { ren xec rails generate migration add_priority_to_tasks priority:integer $ bundle exec rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate _at, ‘is in the past!’) if due_at < Time.zone.now #!/usr/bin/en python import pygame from random import randrange MAX_STARS = 100 pygame.init() screen = py tars = for i in range(MAX_STARS): star = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) for event in pygame. $numstars = 100; use Time::HiRes qw(usleep); use Curses; $screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $s >clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refre ment, :test do gem “rspec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond tml { redirect_to @task, notice: ‘...’ } format.json { head :no_content } else format.html { render action: “edit” } format.json { render json: @task.errors, status: :unpro rity_to_tasks priority:integer $ bundle exec rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_ one.now #!/usr/bin/en python import pygame from random import randrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) c star = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pyg Res qw(usleep); use Curses; $screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] rs ; $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “theru ails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond_to do |format| if @task.update_ .’ } format.json { head :no_content } else format.html { render action: “edit” } format.json { render json: @task.errors, status: :unprocessable_entity } $ bundle exec rails exec rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_in_the_past errors.add(:due_at, ‘is in th ygame from random import randrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() stars = ge(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/bin/perl $nu = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { $screen$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group :dev undler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond_to do |format| if @task.update_attributes(params[:task]) forma ent } else format.html { render action: “edit” } format.json { render json: @task.errors, status: :unprocessable_entity } $ bundle exec rails generate migration add_priori exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_in_the_past errors.add(:due_at, ‘is in the past!’) if due_at < Time.zon andrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() stars = for i in range(MAX_STARS): star = pend(star) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use Time::HiRes qw(us r ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < $numstars ; $i++) creen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group :development, :test do gem “rspec-rails”, “~> 2.13.0


Scratch Learn the basics of coding with the visual programming language Getting started with Scratch

������������

10

Using variables in Scratch

���������������������

12

14

Learn about Loops

�������������������������������������������������������

Using lists in Scratch

����������������������������������������������

18

Build a game with Scratch

��������������������

20

Scratch: Hack it

�������������������������������������������������������������������

24

Coding Made Simple | 9

Scratch | Contents

s new todolist --skip-test-unit respond_to do |format| if @ nder json: @task.errors, status: :unprocessable_entity } $ :due_at_is_in_the_past def due_at_is_in_the_past errors. ygame.display.set_mode((640, 480)) clock = pygame.time. e.event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/ star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { esh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group d_to do |format| if @task.update_attributes(params[:task]) ocessable_entity } $ bundle exec rails generate migration _in_the_past errors.add(:due_at, ‘is in the past!’) if due_at clock = pygame.time.Clock() stars = for i in range(MAX_ game.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < rubyracer”, “~> 0.11.4” group :development, :test do gem _attributes(params[:task]) format.html { redirect_to @task, s generate migration add_priority_to_tasks priority:integer he past!’) if due_at < Time.zone.now #!/usr/bin/en python for i in range(MAX_STARS): star = [randrange(0, 639), umstars = 100; use Time::HiRes qw(usleep); use Curses; ->clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= velopment, :test do gem “rspec-rails”, “~> 2.13.0” $ gem at.html { redirect_to @task, notice: ‘...’ } format.json { head ity_to_tasks priority:integer $ bundle exec rake db:migrate ne.now #!/usr/bin/en python import pygame from random = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] sleep); use Curses; $screen = new Curses; noecho; curs_ ) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] 0” $ gem install bundler $ gem install rails --version=3.2.12 head :no_content } else format.html { render action: “edit” migrate $ bundle exec rake db:migrate $ bundle exec rails m random import randrange MAX_STARS = 100 pygame. ge(1, 16)] stars.append(star) while True: clock.tick(30) for ; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] _x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } ion=3.2.12 $ rbenv rehash $ rails new todolist --skip-tester action: “edit” } format.json { render json: @task.errors, $ bundle exec rails server validate :due_at_is_in_the_past TARS = 100 pygame.init() screen = pygame.display.set_ ue: clock.tick(30) for event in pygame.event.get(): if event. stars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); ar_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; s new todolist --skip-test-unit respond_to do |format| if @ nder json: @task.errors, status: :unprocessable_entity } $ :due_at_is_in_the_past def due_at_is_in_the_past errors. ygame.display.set_mode((640, 480)) clock = pygame.time. e.event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/ star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { esh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group d_to do |format| if @task.update_attributes(params[:task]) ocessable_entity } $ bundle exec rails generate migration _in_the_past errors.add(:due_at, ‘is in the past!’) if due_at clock = pygame.time.Clock() stars = for i in range(MAX_ game.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < rubyracer”, “~> 0.11.4” group :development, :test do gem _attributes(params[:task]) format.html { redirect_to @task, s generate migration add_priority_to_tasks priority:integer he past!’) if due_at < Time.zone.now #!/usr/bin/en python for i in range(MAX_STARS): star = [randrange(0, 639), umstars = 100; use Time::HiRes qw(usleep); use Curses; ->clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= velopment, :test do gem “rspec-rails”, “~> 2.13.0” $ gem at.html { redirect_to @task, notice: ‘...’ } format.json { head ity_to_tasks priority:integer $ bundle exec rake db:migrate ne.now #!/usr/bin/en python import pygame from random = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] sleep); use Curses; $screen = new Curses; noecho; curs_ ) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] 0” $ gem install bundler $ gem install rails --version=3.2.12


Scratch | Getting started

Getting started with Scratch

New to coding? Scratch is the ideal language to begin with, and in this guide we show you how to get started and learn some basic coding principles.

L

earning to code can be tough but thanks to Scratch it is now much easier to build your own games and projects. Scratch was created by MIT in 2002 and later released to the public in 2005. It has since become the first coding language many children around the world learn. In the UK Scratch was made popular via Code Clubs, after school clubs for children lead by volunteers in the tech community. It soon entered the school curriculum and children as young as six are taught how to construct simple sequences of code by using metaphors such as making a sandwich or programming a simple robot toy known as a Bee Bot. This practical knowledge is then put into practice using Scratch as a foundation. Children learn the basics of computer science by building their own games, applications and animations using this simple language made of blocks. Scratch uses a block interface to build sequences of code for objects, known as sprites, that can be controlled in many different ways using these blocks of code. These sprites are visible upon a ‘Stage’ where interactions with the user happen. A sprite can be moved, rotated, made to change colour, or resized. Sprites are actors that we can tell what to do on the stage and they do it all using simple blocks of code. Coding with Scratch is really simple. Blocks are dragged from the palette and are placed into a large coding area on the right of the screen. There are many different types of blocks. For example there are hat blocks, commonly used for events such as starting the programme or reacting to input

The Scratch interface is designed for children to just get going with their creations.

10 | Coding Made Simple

such as a key press. Hat blocks will only accept blocks underneath them, as an event typically triggers a sequence of code. Other blocks are C blocks, used for loops and conditional tests, such as “If..Else”. C blocks enable the coder to place blocks inside them, and these blocks will run based upon the type of C block used. So, any code contained in a forever loop will run forever, while any code in a conditional test will run if the condition is true. Other types of blocks include the hexagonal Sensing blocks which are used to give sprites basic collision detection and respond to sensor inputs such as cameras and microphones. All of these give us the basic building blocks of computer science, such as sequence, iteration and selection, and we can build quite complex projects using them. Thanks to Scratch’s easy to use interface and the ability to deconstruct larger problems into small, easy to manage, portions we have a tool perfect for children who want to just “get on” with making something fun, rather than explicitly learn how to code. In this first tutorial we shall get to grips with creating a simple project that enables us to learn how to work with the Scratch interface and understand how some of the common blocks work to produce a project that greets the player based on their name which can be used in future games to identify the players in a multi player game. So to begin open a web browser to http://scratch.mit.edu and click on Try it Out to begin a new Scratch session.


1

Learning the layout

Scratch has three main sections. First we see the Stage, which is where our projects will come to life. In the screenshot above we can see the default Cat sprite. Under the Stage we see a list of sprites, which are the objects that we can programme. Next to here we can see our palettes of blocks that make up the language. These can be dragged to the large grey coding area.

3

Building our first programme.

Letâ&#x20AC;&#x2122;s get used to Scratch by creating a simple project that asks for our name and then reacts according to the name of the person. Our first block is found in Events and is called When Green Flag Clicked. This is a hat block and only allows blocks to attach underneath it. Our next block is in Control and is called forever. This is a C block, otherwise known as a loop.

5

Conditionals

To check that the name of the person is known, we need to use the _=_ block from Operators. This checks the name entered against a known name. Next we go to the Looks palette and select the Say hello for 2 secs block and place it inside the If condition. We then use join from Operators to greet the user by name.

2

Building the code

Our code is based upon coloured blocks that are organised into a series of sections, based upon their function. To write a programme we select the correct block and drag it into the large grey coding area. We can then build a sequence of code by attaching the blocks together. This sequence is commonly referred to as an algorithm and is being taught to children as young as 7.

4

Inside the loop

Our forever loop runs the code contained within it until the end of time (or you stop the program). Our next block is in Sensing and is called ask ______ and wait. Drag this inside the loop and type the question. Next, grab an If block from Control. This block checks a condition, in this case the name stored in a variable called answer, which is a block in the Sensing palette.

6

More Conditions

To add more names to our project we need to add more conditions to test. Here we use an If..Else block from Control to check for another name. We use the Else condition to respond to any unknown names. Once you have completed the code, click on the Green flag, in the top right of the Stage, to launch the code.â&#x2013; 

Coding Made Simple | 11

Scratch | Getting started

Building our project


Scratch | Using variables

Using variables in Scratch Learning about variables and data storage is easy in Scratch, and it can help you build a simple number guessing game.

O

Comparing variables, one generated by a user, the other by a computer is a great way to demonstrate how they can be used in games and their logic

ver the course of computer history, data storage has seen many forms, from the humble tape, to magnetic disks, to CD/ DVD discs. But data storage doesn’t just mean hard disks, flash drives or The Cloud. Rather data storage means storing different data types in many different ways. When it comes to coding, data types are primarily organised into three groups: strings, integers and floats. A string is a line of text, which can also contain numbers, which cannot be used for any mathematical operations. In Scratch we use strings to communicate with the user, for example we use say to ask the user a question. Integers are numbers that have no decimal place and Floats are numbers with a decimal place. But in relation to variables why are these important? Well, variables are used to store these data types, as they are boxes in to which we can place objects (such as our data). We then name the box so that every time we say the name of the box, its contents are revealed. In this tutorial we use one data type, integers, with two variables. Firstly we create a variable called Rand_ Number which is used to store a randomly generated integer between 1 and 100. We then use the ask block to ask the user to try and guess the number. Each guess is stored as a variable called answer which is part of the Sensing palette blocks. Then, using a conditional test we check the value of the two variables against one another. If the answer given is higher than the Rand_Number then the user is told that their guess is too high. If their answer is lower than the Rand_

12 | Coding Made Simple

Scratch code can get a little complicated, but remember that you can take your code apart and examine each block

Number then they are told it is too low. Variables are a key skill to learn in computer science as they have far reaching applications. We see variables all around us: timers, scores, player names in video games, timer durations for digital cameras and user names when logging into websites. Variables can be used to replace hard values in projects. For example, rather than change the values of 10 or more lines that repeat the same information, we can just refer to a variable that we change once, and that change is reflected across all 10 (or more) lines of code. Scratch introduces variables using the Data palette, and here we can create variables for individual sprites. For example, individual scores for each team in a football game. Or we can create a variable for all sprites such as a simple timer for a game. We can alter the contents of a variable using the set and change blocks. Set is used to change a value to a specific value, such as going from 1 to 9. Change is used to increase or decrease a variable by a numerical value, such as changing the value of a variable from 9 to 8 by subtracting 1 from the variable. So let’s start our project by opening http://scratch.mit. edu in a browser and clicking on ‘Try It Out’ to start a new Scratch window. Remember if you get anything wrong, pull the code apart and try again.



Tech Made Simple Bookazine 16 (Sampler)