0 ratings0% found this document useful (0 votes) 221 views78 pagesCoding Tricks and Tips - Coding and Programming
Everything you need to master essential coding and programming skills
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
IES
ato Codin
Flat
Programming
@ Advanced guides
and tutorials for
coding Linux and
SECRETS & Ae
HACKS KS
@ We share our
awesome coding tips
and projects to push
Everything you need to
master essential coding
and programming skills
your skills further
@ Next level fixes
and secrets help
you get more from
Linux distributionsTech Guides
Available on
Who” (% TRICKS & TIPS
RYE
CBE ky
Bey
ass
etry | is
vA aa ad Vv Cloud
Cz
For a full list of titles available visit:
www.pclpublications.comTRICKS
& TIPS
Coding
eae
Coding and Programming Tricks & Tips is the perfect digital
publication for the user that wants to take their skill set to
the next level. Do you want to enhance your user
experience? Or wish to gain insider knowledge? Do you
want to learn directly from experts in their field? Learn the
numerous short cuts that the professionals use? Over the
pages of this new advanced user guide you will learn
everything you will need to know to become a more
confident, better skilled and experienced
owner. A user that will make the
absolute most of their software
and ultimately their coding
skills themselves. An
achievement you can earn
by simply enabling us to
exclusively help and teach you
the abilities we have gained
over our decades of experience.
Over the page
our journey Continues,
and we will be with you
at every stage to meets
inform and ultimately
inspire you to
90 Further.8 What isa Batch File? 24
10 Getting Started with Batch Files 26
12 _ Getting an Output 28
14 Playing with Variables 30
16 Batch File Programming 32
18 Loops and Repetition 34
20 Creating a Batch File Game 36
38
40
42
46
48
50
54
56
58
seages
bya Reels ako seek)
Why Linux?
The Best Linux Distributions
Equipment You Will Need
Creating a Linux installer on Windows
Installing Linux on a PC
Installing a Virtual Environment
Installing Linux in a Virtual Environment
Getting Ready to Code in Linux
Creating Bash Scripts Part 1
Creating Bash Scripts Part 2
Creating Bash Scripts Part 3
Creating Bash Scripts ~ Part 4
Creating Bash Scripts — Part 5
Command Line Quick Reference
ES
Planning your Code
Finding Resources
Creating a Loading Screen
Planning a Text Adventure
Text Adventure Script
Retro Coding
Text Animations
Common Coding Mistakes
Python Beginner's Mistakes
C+ Beginner's Mistakesrae
~~
| 4
aT
a
tutte) 1k Nejc au) : ee UST p 6s du 5) to
aby fo} ey yiredn) sais cr lye ee
* ass wate ' 9 od 1
i . 4 ' jl iM 7 ' {1
a a Ps Y
: C6 Oo.
- 5Eb) Coding with Windows 10 Batch FilesCoding with
— Windows 10
mee 5 i-|8G an ellos
DR aera ar Cees ear Ti
eae ee eae cea
around since the early days of Windows, and
Meee Cet ewer itsg
Pere curicaiel te mncicice
they are still there and still just as capable as
A SCC
Ce Cee ea)
Ener eee men eRe att}
a bit of time learning how they work, and
SE el he LeoR aR et cs ola)
introduces batch files, and covers user
ered eee cue T rc)
Tete one eet Cuc taeCoding with Windows 10 Batch Files
What is a Batch File?
.-BAT MAN
A Windows batch file is simply a script file that runs a series of commands, one line at a time, much in the same fashion as a
Linux seript. The series of commands are executed by the command line interpreter and stored in a plain text file with the BAT
extension; this signifies to Windows that it’s an executable file, in this case, a script.
Batch fileshave been around since the earliest versions of Mic
DOS. Although not exclusively a Microsoft scripting fle, bat
soft ine in tun, loading programs that would activate the mouse oF
files optical drive into the memory areas assigned by the Contfigys file
‘are mainly associated with Microsoft's operating systems. nthe
early days, when a PC bootedinto a version of DOS (which produced The DOS user of the day could opt to create different Autoexe:
‘ommand prompt when powered up), the batch fle was _bat files depending on what they wanted to do. For example, iF
Used in the form ofa system file called Autoexec.bat. Autoexec they wanted to play a game and have as much memory available
bat was a script that automaticaly executed (hence Autoexec) as possible, they'd create a Config.sys and Autoexec.bat set of i
commands once the operating system had finished dealing with the that loaded the bare minimum of drivers and so on. IF they n
Configssys ile access to the network, an Autoexec.bat ile could be crea
When a user powered
up their DOS based
computer, and once the
BIOS had finished checking
the system memory
‘and s0 09, DOS would
look to the Configsys
file to load any specific
play requirements
and hardware drivers,
allocate ther a lotin the
‘available memory, assign
‘any memory managers
and tell the system where
the Command.com file,
whichis the command ine
interpreter for 008, was
Once it had done that, then
the Autoexec.bat ile took
over and an through each
‘The Autoexecbatfile was
aPC user's first experience
with a batch file. <
wn peubleationscomBatch files are plain text and often created using Notepad.
Batch files were often used as utility programs, to help users with,
complextasks.
load the network card driver and automatically ain access to the
network, Each of these unique setups would be loaded on toa
Floppy disk and booted as and when required by the user
Autoexec.bat was the first such Fle many users came across in
their PC-based computing lives; since many had come from a 16-bit
or even &-bit background; remember, this was the late eighties
1 batch file was the user's primary tool For
‘automating tasks, creating shortcuts and adventure games and
translating complex pracesses into something far simpler
such when the PC boots. You can use a batch file in the same way
as any other scripting language file, in that you can programit to
ask for us splay the results on the screen; or save to
1nd even send it toa locally or network attached printer. You
can create scriptsto back up your Fle to various locations, compare
date stamps and only back up the most recently changed content as
‘well as program the script to do all this automatically. Batch files are
remarkably powerful and despite them not being as commonly ust
‘as they were during the older days of 008, they are still there and
an be utilised even in the latest version of Windows 10; and can be
as complex or simple as you want them to be,
So what do you need to star batch file programming in Windows?
Well, as long as you have Windows 10, or any older version oF
Windows for that matter, you can start batch file programming
Lely. Allyou need is tobe able to open Notepad and get to
the command prompt of Windows. We show you how it all works, so
read on,
What is a Batch File?
BATCH FILE POWER
Just ike any other programming interface that can directly
interrogate and manipulate the system, batch fils require
a certain amount of care when programming. I's hard to
cdamage your system with a batch file, as the more important
elements of the modern Windows system are protected by
the User Account Control (UAC) security; UAC works by only
allowing elevated privileges access to important system files.
Therefore ifyou create a batch file that somehow deletes a
system file, the UAC activates and stop the process.
However, iF you're working in the command prompt with
elevated privileges to begin with, as the Administrator, then
the UAC won't question the batch file and continue regardless
cof what files are being deleted
That said, you're not ikely to create a batch file that
intentionally wipes out your operating system. There are
system controls in place to help prevent that; but it’s worth
‘mentioning as there are batch files available on the Internet
that contain malicious code designed to create problems,
"Much like a virus, @ rogue bateh ile (when executed with
Administrator privileges) can cause much mayhem and system
damage. n short, don't randomly execute any batch fil
downloaded from the Internet as an Administrator, without
First reviewing what it does.
You can learn more about batch filesin the coming pages, so
don't worry too much about destroying your system with one.
All this ust demonstrates how powerful the humble batch file
canbe.
‘You can create complex batch files or simple ones that display
‘ASCIlimages on screen,
won pelpbbeationscomCoding with Windows 10 Batch Files
Getting Started with
Batch Files
A NEW BATCH
‘Throughout this section on batch files we're going to be working with Notepad, the command prompt and within a Folder
called "Batch Files’. To begin with, let’s see how you get to the Windows command prompt.
PEED the windows PEED white at the command prompt win er
command 2 L/W. This ists all the Files and directories From
prompt may looka little fi 0 In thiscase, that's you
tunting to the newcomer y user that lagsin. You
butit’s simply another
interface (or Shell) used to
access the filesystem. You
go anywhere you tke in nen press Return.
the command prompt, as
you would with the graphical
interface. To begin, click on
the Windows Start button and
enter CMO into the search box.
FETTSPD Click on the search resutlabelled Command Prompt [EWA The prompt should change and display
(Desktop App) and anew window pops up. The Dactimentis>? this means you're the Documer
Command Promat window isrt much to look at to begin with but directory. Now, create a new directory cal Batch Files Enter
you can see the Microsoft Windows version number and copyright
information followed by the prompt itself. The prompt detailsthe
rent directory or folder you're in, together with your username. You need the quotations because without them, Windows
two directories: Batch and Files. Now change directory intothe
newly created Batch Files.
‘You won't need the quotes to change directories,
wn peubleationscomFTISEM Now that you have the directory set up, where you
store your batch files, here fs how you can create
‘one. Leave the command prompt window open and click on the
Windows Start button again. This time enter Notepad and clck on
the search result to open the Notepad program. Notepad isa simple
text editor but deal for creating batch scripts with,
To create your first batch file, enter the following
into Notepad:
Becho off
echo ello
World!
By default, a batch fle displays all the commands that ituns|
through, line by ine. What the @echo off command does is turn
that Feature off forthe whole script; with the ‘@' (at sign to apply
that command toitself
FFE D when saving anything in Notepad the default
extension st, to denate a textile. However, you
want the extension to be bat. lick on File > Save As and navigate
to the newly created Batch Files directory in Documents. Click the
‘drop-down menu Save as Type, and select All Files From the menu In
File Name, cal the file Test.bat
( Getting Started with Batch Files
Backat the conmand prompt window, ete
SHS aiLE/W again to list the newly created Test.bat file,
By the way, the fv parcoF cw meen the Fes aestec across
the screen as opposed to straight down, Enter dif you wane
(athough you need more Festoview) but iesconsdered easerto
read wth the fg
To execute the batch file you've just created, simply
enteritsname, Test, inthe command prompt
‘window. You don't need to add the bat part, as Windows recognises
itasan executable fe, and the only one with that particular name in
the current directory. Press return and see how you're greeted with
Hello World! in the command prompt.
Fa iococcomrereoncponcresun
Becho aff
echo Hello World!
echo This is ny fleet batch file
echo.
echo With a
blank Line between!
Remember to save each new change to the batch fle>) Coding with Windows 10 Batch Files
Getting an Output
While it's great having the command prompt window display what you're putting after
the echo command in the batch File, it’s not very useful at the moment, or interactive
for that matter. Let's change up a gear and get some output.
INPUT, OUTPUT
Batch files are capable oft
the equation.
BEER ets keep things simple to begin with, Create anew
batch file cated ‘drview.bat, short for Directory
View. Start with the @echo off command and under that add
dix “c:\users\YOURNAME\Documents\Hatch Files” >
c:\users\YOURNAME\dirview. txt
Substitute YOURNAME with your Windows username,
‘The new line uses the dic command to list the
contents of the directory Batch Files, in your Home
sry
directory, dumping the output toa text Fle called diewiew.txt in
the root of your Home directory. This is done, so thatthe Windows
UAC doesn't require elevated permissions, as everything isin your
‘own Home area, Save and run the batch fle
19 a normal Windows command and executing it, while also ad
1g extra options and Flags in to
ES TERE DD Youhaveno doubt noticed that there isn
Indication that the batch file worked as there's
rio meaningful output on the screen. However, if you now open
Explorer and browse to 6: \User#\ YOURNAME, remembering to
substitute YOURNAME with your Windows username, and double-
click the diirview. txt file, you can see the batch file's output.
IF you want to automate the task af opening the
text ile that contains the output, add the Following
Sr)
line to the bateh file:
notepad.exe €#\users\YOURNAME\Airview.txt
‘Save the file and once again un from the command prompt. This
time, it creates the output and automaticaly opens Notepad with
the output contentsOUTPUT WITH VARIABLES
Variables offer a more interesting way of outputting something to the screen and create a higher level of interaction between
the user and the batch file. Try this example below.
following lines:
Create anew batch file and call it name.bat. Start
with the echo o££ command, then add the
set /p name- What is your name?
echo Hello, Snanet
Note: there's a space after the question mark. This sto makeit look
neater on the screen, Save it and run the batch file
FETTER the set /p name creates avariable called name,
with the /p part indicating that an ‘=prompt string’
is tofollow. The Set command displays, ets or removes system
and environmental variables. For example, while in the command
prompt window enter:
‘Toview the current system variables. Note the name= variable we
just created,
Variables stored with Set can be called with the
S6VARIABLENAME% syntax In the batch file, we
used the newly created Shname% syntax to call upon the contents of
the variable called name. Your username, For example, stored as a
variable. Try tis ina batch file
echo Hello, WISERNAMEY. what are you doing?
echo oft
echo Hello, SUSERNAMES
echo.
.cho Thanks for logging in. Currently the network
perating at 1008% efficiency
echo Your Howe directory is located at
‘echo The computer nane you're logged in
SCOMPUTERNAMES
SHOMEPATHS
Save and execute the batch file changes; you can
‘overwrite and still use name.bat if you want. The
batch file takes the current system variables and reports therm
‘accordingly, depending on the user's login name and the name oF
the computer. Note: the double percent symbol means the percent
sign willbe displayed, and isnot a variable.
Becho off
Altematively, ou can run the batch ile and display
icon the user's desktop as atext fle:
10 Hello, SUSERNANES. > ¢:SHOMEPATH®\user.txt
>> c:SHOMEPATHS\user.txt
echo Thanks for logging in. Currently the network
is operating at 1008% efficiency. >> e:SHOMEPATHS\,
echo. >> ¢:#HOMEPATHE\User. txt
echo Your Hone directory if located at? $HOMEPATHE
>> cr SHOMEPATH\u
echo The computer name you're logged in to is
SCOMPUTERNAMES >> c:SHOMEPATHS \user. txt
>> crSHOMEPATHS\user.txt
eer.tx
‘echo.
notepad ¢#SHOMEPATHS\user.txt
The > outputs to a new file called user.txt, while the >> adds the
lines within the fileCoding with Windows 10 Batch Files
Playing with Variables
USING MORE VARIABLES
Here's a good example of mixing system and environmental variables with some of your own creation, along with @ number of
external Windows commands.
cenconevbacfiealetaiatonsintat RRB now cx ata ett ds hens
SP il with the Becho eff command. Begin by clearing SHEP) of any directory and post it as a text file to the user's
wemrond ersisceerentSaruGNTiarthe covert scteen,the aleuny athe Deter Me
snectreson he computer
1 echo From the list, which folder would you Like t
pel ot /p view= (enter \folder)
och dir “tviews" > view.txt
notepad.exe view.txt
FETTER ove and execute the batch file. within the BSED What's happening here isthe batch ile asks the user
‘command prompt you can see the contents of all to-enter any ofthe directories displayed in the lst it
the files and directories from the root ofthe C:\ drive; and asany _generated, in the Form of ‘¢\directory. Providing the user enters a
user under Windows has permission to see this, there's no UAC valid directory, its contents are displayed asa textile, We created
elevated privileges required, the view variable here along with %SHOMEPATH%, to store the input
and the text file,
wn peubleationscomtext files cluttering up the file system. That being the case, let's
ear up with:
del /9 wiew.txt
del /Q list.txt
echo All files deleted. syatem clean.
the files without any user input or notification. The Final message.
informs the user that the Files are removed
Depending
on how
your systemis configured,
you may not get any
found. txt
notepad.exe found.txt
ela
JPG for example)
echo Please enter the type of file you want to
search for (MP3, DOC, JPG for example)
‘echo.
colar
i del /9 found. txt
BPE the new commandin this instance is color PEP D Arothernew command, where, looks fora spectic
((mericansed spelling). Color, as you already file or directory based on the user's requirements.
‘assume, changes the colour ofthe command prompt dsplay. The _Inthis case, we have created a blank variable called ext that the user
«olor attributes are spectied by two hex digits, the frst corresponds can enter the'file type in, which then searches using Where and
to the background colour of the Command console and the second dumps he resultsina text file called Founditxt. Save and run the
to the Foreground, and can be any ofthe Following values: batch File
0 = Black
Blue
Green
3=Aqua B=Light Aqua
4=Red C= Light Red
Purple D-=Light Purple
6=Yellow E = Light Yellow
7=White —F = Bright WhiteBatch File Programming ea
CHOICE MENUS
Creating a menu of choices is a classic batch file use and a good example to help expand your batch file programming skills.
Here's some code to help you understand how it all works
FERED ther than using a verableto process a user's PREP érvoctevels are essentaly variables ad the /M
‘command in conjunction with an ErrorLevel parameter tommakea _to’be displayed. Extend this menu with something new
menu, Create anew File called menulbat and enter the Following:
Becho oft
Becho off ela
cls echo.
choice / “po you want to continue? Y/N" echo
if errorlevel 2 goto N ‘echo.
Af errorlevel 1 goto ¥ ‘echo Please choose a directory
goto End: echo.
echo Press 1 for e:\Music
; echo.
‘echo Pre:
2 for c#\Docunents
echo.
echo Press 3 for c:\Pictures
fecha,
echo Press 4 for ¢:\videos
echo.
echo
FETTER erring the code produces anerror aswe've called choice /C 1234
‘Goto command without any reference toitinthe if errorlevel 4/qote Videos
file, Goto does exactly that, goes toa specficline inthe batchfile. if errarlevel 3 goto Pictures
Finish the File wit the Following and run it again: Af errorlevel 2 goto Documents
: Af errorlevel 1 goto Music
oe = foo aaa nee
‘echo You chose No. Goodbye. BE TeeED Now add the Goto sections:
‘goto End
w videos
echo. ele
echo You chose Yes. Hello CD SHOMEPATHE\Videos
echo You are now in the Videos directory
— goto End
Pictures
cls
cD SHOMEPATHE\Pictures
‘echo You are now in the Pictures directory
‘goto End
Documents
ele
(CD SHOMEPATH® Documents
FR ic otnitenyox dee caret depen on
whether you pick V or N. The:End part simplysignifies $969 Ent
the end ofthe fle(alsoknown as EOF). Withoutitthe batchfleruns Muse
through each ine and display the V response evenifyouenterN;soit’s cls
important to remember to Follow your Gato commands. cD SHOMEPATH®\Masie
echo you are now in the Music dixectory
= goto End
End
PETES When executed, the batch fle dsplaysa menu and with,
each choice the code changes directoryto the one the
user entered, The %eHOMEPATH® system variable wil enter the currently
logged in user's Musi Pictures and so directories, and not aryone else'sCoding with Windows 10 Batch Files
Loops and Repetition
COUNTERS
Creating code that counts in increasing or decreasing number sets is great for demonstrating loops. With that in mind, let's look
at the IF statement alittle more, alongside more variables, and introduce the Else, Timeout and eof (End of File) commands.
ESSERE Start by creating a new batch file called count bat.
Enter the following, save it an
Becho off
meout /T 1 /nobreak > nul
starts at numb
nts, scrolling
screen, until it reaches 100,
The Timeout command
leaves a one second gap
between numbersand the
Else statement continues
untilthe counter variable
wn peubleationscom
00 (goto re0f) else (¢
PEPTSED The countbatis a rough way
Ty this example instead
for /1s $n in (1,1,99)
Breaking it
down, there's.
For, then the /Lswiteh, which
handles a range of numbers.
Then the: labelled as
%
the statement howto:
asin 1 (start number), 1 steps
totake),99 (the end number)
he next partis do, meaning
whatever command is afte
‘of demonstrating a
coach would be to use afr loop.You can include the pause between the numbers
easily enough within the Far simpler Forloop by
‘adding multiple commands after the Do For loop. The brackets and
‘ampersand (8) separate the different commands. Try this:
Becho of
for /1 88m in (1,1,99) do. (echo
Ynobreak > nul)
S8n & timeou
ya
(One ofthe great time saving uses of batch filesis to
create multiple, numbered files. Assume that you
ty five text files within a directory, all numbered from 1 to
25.A.For loop much like the previous example does the trick:
want tw
Becho of
for /L 88m in (1,1,25) do copy nul ¥en.txt
FETTER) (0 open windows Explorer, and navigate tothe
Batch Files drectary where you're working fram,
you can now see 25 text files all neatly numbered, OF course, you
append the File name with something lke user.txt and soon by
altering the code to
Becho off
for /L ¥¥n in (1,1,25) do copy nul Users¥n.txt
There are different ways of using the For loop. Ia
SHS this example, the code creates 26 directories, one
for each letter of the alphabet, within the directory c\test which the
batch Fle makes using the MD command:
8
o off
OR 8BF IN (a,b, 6,40,
Bytes V/ V2)
1G LF ke Lym 0, 0,7, aye,
Do (md C#\test\ $F)
Loops can be powerful and extremely useful
elementsina batch file, While creating 26
may not sound too helpful, imagine having to create
7,000 users on a network and assign each one their own set of
unique directories, Tis is where a batch file saves an immense
amount of tr
Should you eve get stuckwhen ug the vaous
SED mmands within a batch file, drop into the
command prompt nd enter the command flowed 2 question
toch Fc ec fr 6° Boa as ome a
Getaiig te arena se 0 war ening, eT a et
‘or /? > forhelp. txCoding with Windows 10 Batch Files
Creating a Batch File Game
Based on what you've looked at
Pei com ite nt
Prey) Veco at Reb lee)
simple text adventure or multiple-
choice game. Here's one that we
fers le teu R ei el Me Sint nce
ele Ulu Reels
Make up your own questions but how about also
including an introductory or loading screen? Make your
loading screen in aseparate batch file and saveitas
screens bat (for example). Then, from the main game
batch Fie, you can load atthe beginning ofthe file
‘with the ‘call’ command followed by colour to reset
the game's colours:
echo off
cis
set /a score=o
set /a questions0
cls
set /p nane= What is your name?
wn peubleationscom
echo off
cle
cstart
set /a scoren
set /a question=0
cls
fet /p name What is your name?
echo,
echo, Wetat#nenunannseasannanatannenannannannsnnnannanasen
echo.
echo Press 1 to get started
echo.
fecho Press 2 for instructions
echo.
echo Press @ to quit
echo.
choice /c 120
if errorlevel 2 goto Instructions
Af errorlevel 1 goto Game
“Instructions
echo. Wetstennannainsannannavanensanannanis,
echo.
‘echo The instructions are simple. Answer the
questions correctly.
echo. Wetetennansainsensenavanentanannaniey
pause
cls
goto menu
act /a question=tquestiont+1
cls
Sf tquestion’ ==5 (goto end) ol
question tquestiont)
(echo you are on
echo get ready for the question.
echo.
‘timeout /T 5 /nobreak > nal
(goto end)
Sf tquestiont
(goto *questiont)
a
als
echo.
echo *echo Your current score is tscoret
echo.
ocho eteseeneuntwastnseesewaten
echo,
echo.
echo Question tquestiont.
echo.
‘echo Which of the following version of Windows is the
best?
echo.
echo A. Rindows 10
echo.
fecho B. Windows ME
echo,
echo C. Windows Vista
echo.
choice /c abe
Lf errorlevel 3 goto wrong
Af errorlevel 2 goto wrong
Af errorlevel 1 goto correct
2
als
echo,
ocho. Weteseunsunteasenseesewaten
echo.
echo Your current score is tecoret
echo.
cho wetentnesensenenetentenatnnten
echo.
echo.
echo Question tquestiont.
echo.
fecho Which of the following version of Windows is the
most stable?
echo,
fecho A. Windows 10
echo.
fecho B. Windows 95
echo.
echo C. Windows ME
echo.
choice /¢ abe
Af errorlevel 3 goto wrong
Af errorlevel 2 goto wrong
Af errorlevel 1 goto correct
3
cls
echo,
cho. seveseeeanesneseetavessesnense
echo.
fecho Your current score is tscoret
echo.
ocho. etestensutwasensnesewaten
echo.
echo.
fecho Question tquestiont.
echo.
‘echo Which of the following Windows version is the
latest?
echo.
echo A. Windows 10
echo.
echo B. Windows 98
echo,
echo C. Windows 7
echo.
choice /¢ abe
Af errorlevel 3 goto wrong
Af errorlevel 2 goto wrong
Af errorlevel 1 goto correct
4
els
echo.
SST
echo.
echo Your current score is t2coret
echo.
cho Wtstenteunstaatansnnenaeenten
echo.
echo.
‘echo Question Squestiont.
echo.
echo Which of the following Windows uses DirectX 127
echo.
fecho A. Windows 10
‘echo.
echo B. Windows 3.12
echo.
echo C. Windows x2
‘echo.
choice /¢ abe
Af errorlevel 3 goto wrong
Af errorlevel 2 goto wrong
Af errorlevel 1 goto correct
‘rong
cle
echo sererastevesseseey
echo.
fecho WRONG!!!
‘echo.
Scho. Veeesaneavennetnes,
set /a scorentscoret-1
pause
goto :gane
reorrect
cle
echo verersetevessesesy
echo.
‘echo CORRECT. YIPEEM!
‘echo.
fecho.seresastavenseseey
set /a scorestscoreti
‘echo Sacoret
echo.
echo. Wetatenawsannseneennanaseananen
choice /M “play again? ¥/N"
if errorlevel 2 goto :eof
Af errorlevel 1 goto start
(Creating a Batch File Game EaRR tT
a in |
err]
Th
mB ty tL
a | la Ugeens
a
7 " Tee Nee cect
Peer Cea eet Ceci
Creme aces a Cue
Pure Rae CAUCE eles
SO ae Cute ee
available on Linux, as they are on Windows
Ene eae ek eee tare)
Oe erin
Bash scripting on Linux can be used to create
ERR ee eels
rea ae a an
background based on a pre-defined schedule.
See cece’
ue RA eC Rae eo
Peace a eRca ntact
EO DeLee Pee aa
23> Coding on Linux
Why Linux?
FREE AND OPEN
Linux isa Fantastic Fit For those who want something different; the efficiency of the system, the availability of applications and
its stability, are just afew reasons why.
‘The firs thing we need to address isthat there is no basic operating
system called Linux, Fundamentally, Linux the operating systern
keanel, the core component ofan OS. When talking abovt Linux we
are in Fact, referring to one of the mary distributions ordistros,
that use the Linux kemel. No doubt youve heard of at least one of
the current popular distros: Ubuntu, Linux Mint, Fedora, openSUSE,
Debian, Raspbian... the lit goes on. Each one ofthese distros offers
the user something alittle different. While each has the Linux kernelat
itscore, they offer a different looking desktop environment, different
pre-loaded applications different waysin which to update the system
{and get more apps installed and a slighty ciferent look and Feel
throughout the entre system. However, atthe centre les Linux, which
iswhy we say, Linux.
A Linuxis a great operating system in
which to start coding,
ees
tates
Linux works very afferently to Windows or macOS. Fora start t's
Free to download, free to install on as many computers as you tke,
Free to use for an unlimited amount of time and free to upgrade
‘and extend with equally free programs and applications. This Free to
use element is one ofthe biagest draws for the developer. while a
‘Windows icense can cost up to £100 and a Mac considerably more,
‘a.user, be they a developer, gamer, or someone who wants to put an
‘older computer to use, can quickly download a distro and get to work
in a matter of minutes,
‘Alongside the free to use aspect comes level of freedom to customise
‘and mould the system to your own uses. Each of the distros avalable on
the Internet have acertain'spin, some offer increased secu, a Fancylooking desktop, a gaming speaic spin or something directed toward
students. Ths extensibility makes Linuxa more desirable platform to
Use, 5 you can quickly mould the system into development base,
including many different kinds of IDEs for use with Python, web
development, C+, Java and so on, or evena base for online anonymity,
perhaps asa Minecrafe server, media centre and much more.
‘Another remarkable advantage for those looking to learn how to code
isthat Linux comes with most ofthe popular coding environments
builtin. Both Python and C+ are preinstalled in ahigh percentage of
Linux dlstros, which means you can stat to program almast as soon as
{yu install the system and boot it up forthe First time,
Generally speaking, Linux doesn't take up as many system resources
‘as Windows or macOS, (by system resources, we mean memory,
hard drive space and CPU load), asthe Linux code has been
streamlined and is free from thirc-party ‘bloatware’, which hogs,
those systems resources. A more efficient system, means more
available resources forthe coding and testing environment and the
programs you will eventually create. Less resource use also means
You can use Linuxon older hardware that would normally struggle,
‘or even refuse to run, the latest versions of Windows or macOS,
A There are thousands of free packages
A) avaiable for programmers under Linux.
Why Linux? &jpg
&, @ suse ty
slack
Cetin = "Mandriva
ee
CentOS
A Each distro offers something unique to the
£2 user but all have Linux atthe core.
‘so rather than throwing away an old computer, itcan be reused with
aLinuxdistro.
However t'snot all about C++, Python, or any ofthe other more
popular programming languages. Using the command tne of Linux
{also called the Terminal), you're abl to create Shell scripts which are
programs made up of scripting languages and designed to run from
the commandline. They are used mainly to automate tasks, or offer the
User some form of input and output fora certain operation
There are many more advantages we could lst, For example, there
{are thousands and thousands of free programs nd apps available
that cover practically every aspect oF computing. Known as packages,
there ae (atthe time of writing) over 8,700 speatic programming
‘applications on Linux Mint alone and an incredible 62,000+ overall
packages, catering from Amateur Radio to WWW tools
In conclusion, Linuxisa great resource and enviconmentinwhich
topprograr. t's perfectly suited for developers, while continually
improving and evalvng, I you're serious about getting into ceding, or
Yyoujust want to explore something new, then ive Linux a tyand see
how it works Foryou.
Linux programming environment can be
Jy Seeman.The Best Linux
Distributions
ea et a ee eee ee eet
Re ee ee ee ee ee eee rnc)
popular distro, Ubuntu. although based on Ubuntu’s Long Term suits you and your computer best.
‘Support build, Linux Mint took a different direction to offer the one
Peeters *
Linux Mint has three main desktop versions available with each
new version of the care OSit releases. This may sound confusing
atfirst, but it’s quite simple. Currently, Linux Mint uses the
Cee atten ee eet
Oe eens
Cinnamon isa graphically rch desktop environment, while MATE
uses less Fancy graphics but is more stable on a wider variety oF
desktop systems and finaly Xfce isan extremely streamlined
desktop environment thats built for speed and ultimate stability.
eee eo
Lenten eon ce ccna ae ore
‘The second most popular distro available Ubuntu: an ancient
ee erate eee ety
has luctuated over its Fourteen-year life. At one time, it was
easily the most used, Linux-based operating system inthe
world, sadly, some wrong choices along the way with regards
toits presentation, along with some unfavourable and
ee eet ad
oes Pre eect
toinstallit on an older computer)
De ee
its way back up the Linuxleader board. The latest versions of Ubuntu, for alits Faults, isa good Linux distro to start
Pete St er ee ee eee
Brie eeu ee ens cag tee en es cd ereoe
‘arch is one of the longest running Linux distributions and
ee ree eae ny
Geet ew eee an ey
Pree et one eee tte)
cr ee
eet uC ee!
Ce a eis
Cee eee ts
Eee te eee ns
Cee eae oe eat
CeO eae aces
You start with nothing more than the command tine and from
there: you manually partition your hard drive, set where the
installation files will go, create a user, set the OS locale and
installa desktop environment, along with the apps you want.
The advantage, forall this hard work, sa distro that you've
ee ea ae el eee
Ce eee
fener eu cea ho
eC eae kate)
ee eee cre eae neces
poeta e has
“Meanwhile, openSUSE attempts to cover both bases.
Crete eee es eet ay
bya community, along with SUSE employees. They develop
an enterprise Level operating system: SUSE, which powers the
ec ae es)
eee Sec ee
For instability IFyou Find allthat too sensible, openSUSE
ee eee ed er)
concerns
‘penSUSEisa highly respected Linux distribution and many
ofits core contributors work on the Linux Kernel, LibreOffice,
Cee ai eee eis eae
Peete
Regs
Sede ese
Renee Cae
cnc)
Preece ees
‘There are several aspects to the
Ce a eed
Peer g ear)
Renee)
emer om ey
fully working computer. I's small,
Ce aCe Sereno
et eee terre eee
ees cee at ue eee)
‘operating system that includes an office suite alongside many
Ce eed
Peete
Ceca)
eee tots)
Peeuneeanecras
However, the Raspberry Pi Foundation
eer raed
acts
Cae tal
Pee ere eer
Cee ee et ee eas
Pe ereetc na tc ee esas
Linux experience, then this is definitely one of the top distros
PensSJ) Codingontinux )
Equipment You
Will Need
MINTY INGREDIENTS
Here's what you'll need to install and run Linux Mint as we work through this book. You have several choices available, so take
your time and see which works best For you.
“The minimum system requirements For Linux Mint are as Follows:
cpu TOOMHz
RAM 512MB
Hard Drive Space 9GB (2068 recommended)
Monitor 1024x768 resolution
Obviously the better the system you have, the betterand quicker}
the experience wil be.
You can instal Linux Mint onto your computer via USB or
DVD. Wellllookinto each a ite later on, but if you're already
familar with the process (or you'e thinking of USB and ust
‘gathering the hardware you'll need), then you're going to
eed a minimum 4GB USB Fash drivejstick to contain the
_wvnepeubleationscomDVD installation of Linux Mint simply requires a lank DVD-R
disc. OF course, you'll also need an optical drive (a DVD Writer
drive) before you're able to transfer, or burn the ISO image to
thedisc
Installation to a virtual environment is a favourite method of
testing and using Linux distros. Linux Mint works exceedingly
Well when used ina vital environment, more on that later.
There are many different virtual environment apps available,
however VirtualBox, from Oracle, is one ofthe easiest. You can
getthe latest version From www.virtualbox.org
¥ VirtualBox
Equipment You Will Need
It goes without saying, that an internet connection is vital For
‘making sure that Linux Mint is resourced with the latest
Updates and patches, as well asthe installation of further
software. Although you dont need an internet connection to
Use Linux Mint, you'll miss out on a world of free software
available forthe distro.
Although Linux Mint can be installed onto a Mac, there's a
school of thought that recommends Mac owners use a virtual
environment, such as VirtualBox or Parallels, and why not,
‘macOS is already a splendid operating system. IF you're looking
to breathe newilife into an older Mac, make sure it'san Intel
(CPU model and not the Power-PC models. However, be aware,
Ik'snotas pain free as installing on toa PC.
_wonpelpbleationscomCreating a Linux Installer
on Windows
You need to transfer the downloaded Linux ISO to either a DVD or a USB key before
BVT Ke Mare) Ua co Reo eM RZ OLN Uke UL RANT ELC ole oy
test the OS prior to installation, but First you need to create the bootable media.
DVD BOOTABLE MEDIA
We're using a Windows 10 PC here to transfer the ISO to a DVD. As tong as you're using a version of Windows from 7 onward,
the process is extremely easy.
Firstlocate the ISO image of Linuxyou've already HED Righttick the Linux SO and from the menu select
SHEP downloaded. In Windows 7, 8.1 and 10 computers, SEP Burn Disc Image, Depending on the speed of the PC,
you'l usually Find this in the Downloads Folder unless, when saving it may take afew seconds before anything happens. Don't worry too
it, you've specified a different location much, unlessittakes more than a minute, in which case it might be
‘worth restarting your PC and trying again, With Luc, the Windows
Name Disc image Sumner should launch
He Quick access
liuamint-12.1-canamon- tit
=F Dropbox Team BOM) Mount
Burn disc image
orev
Disc [GZ Scan with Windows Defender...
2 Share
© coine ey Haste 2 sh
Open with
Newer
$B Open with WinkAR
BB Add to archive.
Net sere recordable VD dc nto your EEEgD ie eyircore osc sure dann
SHA computer's optical drive. After a few seconds, while SHES ‘open, click on the Verify disc after burning’ tick
thedclsreaa vindovs wil pay popup message ang you bo, followed by the Bum btn. The process shoul tate afew
what dowith the ney nsertedse anor thsesweregang mines depending onthe pee of your PCs optial ve. Once
tose thebuitin mage bring funn Wscomplte, lun trough he version stage and when
dee, the pial dive shoul autoeetthe ds Fryou
et)Creating a Linux Installer on Windows Ea
USB BOOTABLE MEDIA
USB media is Faster than a DVD and it’s often more convenient as most modern PCs don't have an optical drive installed. The
process of transferring the imagi
yaaa =
uaa Drive Properties
Fistopenupaweb | ee -
browserandgoto | an
hetps://rufus.akeo. “wt IR ag aa ¥ @ | ser
lepsscoldovnthe | tm a
pagealitieandyou! | ME sew
come to a Download —
heading, under which | Fomat Options
youlseethelatest,
version of Rufus = —
Left-clickon the linkto | S™=es#t ~ Saupe |
start the download. iiereemenintne
a
a
ooze Ss
a Pee fs
Drive Propetes
Double-click the owe
dounioaded Rufus | AERIS 4
executable;youcan ‘Saami =] aur
dick Yes tothe ees eS
Windows security i = itn =
question and"Yes_ =< Besitsnrn
to checking for Format options
updates. With Rufus eee
launched it should sass a
have already dented "eb : fo
youirserted USB | ~ Sentient ee
flash drive (Fo, just Status
remove nd reine). =
oorn ee
FRTEGEDD At first olance the Rufus interface can look litle
confusing, don't worry though, i’ really quite
simple. To begin with, click on the SELECT button next to the ‘Disk
‘ISO Image (Please select’ pull-down menu. This will launch 2
Windows Explorer window from where you can locate and select
the Linux SO.
{___
‘easy, but you'll need a third-party app first and a USB Flash drive of 4GB or more.
When you're ready clkon the Start button at
oud the bottom of the Rufus app. This may open up
another daogue box asking yout donrlead an se 3 ne version
oF Stu Sysinoxisa selection of boot loaders used to awa
modem PCto acess andboot rom a USB fash ve Es necessary,
sof asked, cckon ves to continue.
“Thisimage uses Sysinut 603/20151222 but this application only
Includes the installation fies for Sysnue 603/201 1006.
‘As new versions of Ssinuxare not compatible with one anther, adit
‘rouldnt be posible for Ruf to include ther lo ations fer
‘must be downloaded fom the nteme (Idinuxsy and Idi
Select "Verto connect to thelntrnet and download thee fer
* Slet Moto cancel the operation
‘Note:The file wl be donnloaded inthe corer applistion directory
snd wi be reed automatialy # presen,
“The next step asks in which image mode do you
‘want the Linux IO to be written to the USB Rash
rive. Bath methods wark for different situations, but generally, the
recommended ISO Image Mode i the more popular. Make sure this
mode is preselected and click Ok’ to continue, Followed by ‘Ox’
‘again to confirm the action,
‘The mage you haveseeted a 1SOHyriimage Tis means canbe
irate therin Sige ie copy made oO Image (askmage mode
Fos recommen ang 80 mage mose so that You sans Rave fu
‘ccesrtothe ove ser eting|
Henever you encour sues uring bet you any wating this image
Spann 00 Image made
(© ween SO image mode (Recommended)
‘Oiten 0 mage made
pa :
SUPE Drive Properties,
TretnuxSOisnow nee
being transferred to = neal
Ch LS © Ca
pecesswoudittae tomo ae
too long, depending on hae =| a =
the speed of the USB = Seremesiens nets
evceandtre Pe Duing fmat none
eproces journey the | Sareea
Rfteviloucoperthe sar ==
USB drive in Windows: sal = seshen tao =
Explorer, don't worry you~ Serstettewstortons
‘can minimise or close it Sanam
youve Cet onthe =
Gaetano @ oa wo
process is complete. cose ==4 Coding on Linux
Installing Linux on a PC
UEFI BIOS
‘The Unified Extensible Firmware Interface (UEFI) is used to identify hardware and protect a PC during its boot-up process. It
replaces the traditional BIOS, but can cause issues when installing Linux.
inser your DVD or USB Fl vent your Par
SP il iF you haven't already, shutdown Windows. In this
instance we'e ug the USB boot media but the process tually
ident Star the Pc and when promoted ress the approorite
keto enter the 6103 o SETUP hese cou be, for example, 2,
Delorevene42
FETISED There are different versions ofa UEFI BIOS, so
covering them all would be impossible. What you're
looking for is @ section that detallsthe Boot Sequence or Boot
Mode. Here you'll have the option to tum of UEFl and choose
Legacy, or cisable Secure Booting. Most distros work with UEF but
itcan bea tricky process to enable itto boot.
gacy mode, there are now
wth UEI tured to
SUS two ways of booting into the Live Environment. The
festisvia the 10S you aeadyin Locate he Boot Sequence and
change the fist bot device from is argal setting, ly Intra
HDD osm to USB storage Device forte USB eda options or
BVD Driver theov
eek nnn
eee eat
ed
peenrsnesy
treats
poner
poaeree
FTP ternatively use the Boot Option Menu. With this
‘option, you can press F12 (or sornething similar)
todisplay alist of boot media options; from there, you can choose
the appropriate boot media Either way, you can now Save and Exit
the BIOS by navigating to the Save & Exit option and choosing Save
Changes and Exit.
Network boot from AMD fer?9C370A
“Hard Drive
+Renovable Devices
Netuork boot from AMD Aev?9C370A #2
(_ Installing Linux ona PC Eee
INSTALLING LINUX
(Once the Live Environment has booted, you will see the option to install the distro to your computer. Have a look around and
when you're ready, look for the Install option on the desktop.
course, but the processis the sae. Click Continue wien you'reready. Linux Mint, click Continue. IF you need to back up your files remove
the Linux disc/USB, reboot, back up and start again.
FED wiitetheinstaliationprocessis very similaracioss — RAFEB) eventually you willbe asked to set up your Linux
‘most Linux distros, some offer different questions username and password. Enter your Name to begin
ng the installation. Generally, the questions aren'ttoo difficult, or with, then Computer Name which isthe name used to identify
technical, but some such as ‘installing third partysoftware...canbe it on the network. Next, choose a Username, followed by a good
confusing In this case, you can click Continue, but ifyou're unsure, Password. You can tick the Login Automatically option, but leave
have an Internet-connected device available to ask any questions. _the Encrypt Home Folder option for now,
FED when installing anew operating system it's FETTER The installation process can
recommended that you wipe the old OS, replacing It bbe more questions to answer, or it may simply start
with the new. When you reach this stage ofthe installation process, installing Linux based on your previous answers. Either way, you will
ensure the ‘Erase disk and install Linux. options selected, NOTE: end up being asked to Continue Testing the Live Environment, oF
This wll completely wipe Windows 10 from your computer; make Restarting to use the newly installed OS. IF you're ready to use Linux,
sure you have backups of all your personal files and data. then click Restart Now.
wvmwpegubiationscamwh )
Coding on Linux
Installing a Virtual
Environment
GOING VIRTUAL
Using a Virtual Machine (VM) will take resources from your computer: memory, hard drive space, processor usage and so on.
So make sure you've got enough of each before commencing.
PEED Were using vitualBox inthis instance, asit'soneot RIM with the correct packages downloaded, before
the easiest virtual environments to get to grips with. we install anything, we need to make sure that the
Enter www.virtualbox.org and clickon ‘Download VirtualBox’. This computer you're using is able to host a VM. To do this, reboot the
wil take you ta the main download page. Locate the correct hast. computer and enter the BIOS. As the computer starts up, press the
For your system: Windaws or Mac the Host isthe currentinstalled Del, F2, or whichever key is necessary to Enter Setup.
operating system and click the link to begin the download.
‘| Virtua
ualBo)
= : Downk
Wiis
FED Nex. whilestilatthe VitualBoxdownload page, — EPR seach siosislaid out cifferentl, i's very diff
locate the VirtualBox Extension Pack lnk, The to assess where to look in each personal example.
Extension Pack supports USB devices, aswell asnumerous other However, as @ general rule of thumi, you're looking for intel
ras that can help make the VMenviranmenta more accurate _Virtualisation Technology, or simply Virtualisation, usualy within
emulation ofa ‘eal’ computer. the Advanced section ofthe BIOS. When you've located it, Enable it,
save the settings, ext the BIOS and reboot the computer.y
(installing a Virtual Environment ea
with the computer back up and running, locate
the downloaded main VirtualBox application and
double-click to begin the installation process. Click Next to continue,
when you're ready,
HB cxace vt vinualbo 6.1.16 Setup “
Welcome to the Oracle VM
VirtualBox 6.1.16 Setup
Save, and ext
back tothe Terminal. Entering Ls, will reveal the
run, you need to modify its permissions. Do thiswith chmod +x
helloworld. sh. You need to do this with every script you create
fle Eat View Sevech Terminal Help
( Creating Bash Scripts-Part1 Epes
When you enter 1 again, ou can see that the
helloworld.sh script has now turned from being
white to green, meaning that it's now an executable File. To run
the script, in other words make it do the things you've typed into it,
center: hel loworld. sh.
Fle E§t view Search Terminal Help
faery
‘Although it's not terribly exciting, the words Hello
‘World! should now be displayed in the Terminal
‘The echo commands responsible for outputting the words after
it in the Terminal, as we move on you can make the echo command
‘output to other sources.
Fle E6t View Search Toole Documents Help
Doainv~|xonjag
A *relonrsh
#1 /bin/ash
Jecho Hello World! This is my first script im Linux Mi
‘Think of echo as the old BASIC Print command, I
isplays either text, numbers or any variables that
‘are stored inthe system, such asthe current system date, Try this
example:echo Hello World! Today is $ (date +A). The
S{date +A) is calling the system variable that stores the current day
of the week.
wvmwpegubiationscam4b Coding on Linux
Creating Bash Scripts
—Part 2
VARIABLES
Just as in every other programming language a Bash script can store and call certain variables from the system, either generic
or user created.
PRPTIE DD ets start by creating anew script called hello sh;
xed hello.sh. Initenter: #1/bin/bagh, then,
echo tie lo’ $1. Save the file and exit Xed. Back n the Terminal
make the script executable with: chmod x hello.sh,
Fest Vow Seach Temi Hep
fi tk ew Search Too Documents Hp
poai-~|xoojag
PEPER) the cutautnow willbe Hello David. This is because
Bash automaticaly assigns variables for the user,
which are then held and passed to the script. So the variable
‘$1’ now holds David. You can change the variable by entering
something different: ./hello.sh Mint
file Edie View Search Terminal Help
roy
coed
FETTSPD Asthe script is now executable, run itwith ¥/
hel 1o.sh. Now, 35 you probably expected a simple
Hello is displayedin the Terminal, However, if you then issue the
command with a variable it begins to get interesting. For example,
try /netie.sh
Fle Edt View Search Terminal Help
_wvnepeubleationscom
Youcan even rename variables. Mody the hello
SHES sh script with the following: firstname=$1,
surnane=$2, echo Hello sfirstnane.3surnane Pung
tachstatementon anew ine, Save thesrtand ex backinto
the Terminal
Fle €6t View Search Too Docuners Help
poalev|xonjag
1/bin/bash
fecho Hello Sfirstnane $surnaneBETIS When you run the script now you can use two
custom variables: . hello.8h David Hayward.
Naturally change the two variables with your own name; unless
you're also called David Hayward. tthe moment we're just printing
the contents, so lets expand the twowariable use a litle.
( Creating Bash Scripts-Part2 Eps
Let's expand things Further Create anew script
called greetings -sh. Enter the scripting as below
inthe screenshot, save itand make itexecutable with the chinod
‘command. You can see that there are afew new additions to the
scriptnow.
Fle Edt View Search Terminal Help
rT
Hello David Hayward
rote
Patewenea rts
Create anew scriptcaled addition. 8h, using
the same Format as the hello sh script, but
‘changing the variable names. Here we've added firstrumber and
Secondnunber, and used the echo command to output some
simple arithmetic by placing an integer expression, echo The “sum
ccondinumber) ). Save the script, and
ion. eh)
is $((Slirstnunbert$:
makeit executable (chmod +x addi
Fle Edt View Seorch Tools Oocumens Help
aoa xoojag
x sdstoneh
FRPP RD When you now runthe adsltion.sh script we can
enter two numbers: ./addition.sh 1 2.The
result will hopefully be 3, with the Terminal displaying The sum
is 3. Try itwith a few different numbers and see what happens.
See also iF you can alter the script and rename it do multiplication,
‘and subtraction,
St View Search Terminal Help
Fle Edt View Search Took Documents Help
poajn~|xoojag
im eens sh
#1 /bin/bash
We've added a =n to the echo command here
which wil eave the cursor onthe same line as the
‘question instead oF a new line. The read command stores the
users'input as the variables Firstname and surname, to then read
back laterin the last echo tne. And the clear command clears
the screen.
Fle Edt View Search Terminal Help
FSETD 42 Final addition e's include the date variable
‘we usedin the last section. Amend the lat line
ofthe scriptto read: echo Hello Sfirstnane Seurnane,
are you on this fine $(date +8A) 2. The output should
splay the current day of the week, calling it Froma system variable.
Fle Edt View Search Tools Documents Help
ao on ag
Bu peengesh x
cho /dev/nult )
at UL on “soutput™ 1 then
cha outputFETED when executed the script waits For input fromthe
User, n this case the file extension, such as joa,
‘mp4 and so on t's not very Friendly though, Let's make i a tle
friendlier. Add an echo, with: echo =n “Please enter the
of the file * just
SEES:
Here's an interesting, fun kindof script using the
app espeak. Install espeak with sudo apt=aer
install eapeak, then enter the text below into 8 new script called
‘speak. sh. Asyou can see it's a rehash ofthe first greeting script
weran. Only this time, ituses the variables in the espeak output
\We briefly loked at putting some coloursin the
output for our scripts. Whilst its too long to gig @
little deeper into the colour options, here's a script that outputs
what's avaiable. Create a new script called colours. sh and enter
elo) nto i
Creating Bash Scripts—Part 5 (pd
FETED The output from colourssh can, of course, be
mixed together, ringing ifferent effects
jepending on what you want to the output to say. Far example,
white text ina red background Flashing (or blinking). Sadly the
blinking effect doesn’t work on all Terminals, so you may need to
change toa different Terminal.
Re
ae
Paraareaiereany
Pan
Whilst we're on making fancy scripts, how about
Using Zenity to output 3 graphical interface?
what you see below into a new script, menu. sh, Make it
scutable and then runit. You should have a couple of dialog
boxes appear, followed by a final message.
Sr)
5
While gaming in a Bash script isn’t something
that's often touched upon, itis entirely possible
albet,alitle basic. Movement-based games are ciffuct, and
‘sometimes bugay, however a good text adventure, or Fighting
Fantasy type game isa perfect choice For gaming in the Terminal,
aive it ago, and let us know how you get on.
wvmwpegubiationscamCoding on Linux
Command Line
Quick Reference
TOP 10 COMMANDS,
These may not be the most common commands used by everyone but they will
Linux and the command line
‘The ex command is one ofthe commands you
Luse the most atthe command line in Linux. It
allows you to change your working director
seit to move around within the hierar
fle system. You can also use chai
‘of your
ertainly Feature Frequently For many users of
w command moves afileto a different
location or enamesa file. For example mv file
nb renames the orginal file to sub
Desktop moves the file'sub'to your desktop
icectory but does not rename it. You musts
lename to rename aie,
The you the filesin your
current directory, Used with certain options it ets
you see file sizes, when files where created and file
ermissions. For example, 1s = shows you the files
that are in your home directory.
command sho
sown command chan ser and/
‘or group ownership of each given fie. IFonly an
user ID) isi
uner of each given file, and
\anged.
‘owner (a user name or numer
that useris made the
the files’ group isnot
hep command is used to make copies of files
and directories. For example, ep ab makes
an exact copy of the file whose name you entered
and namesthe copy sub but the First ile wil stil
exist with is original name,
‘The pura command prints the Full pathname
he current working directory (pwd stands For
‘print working directory"). Nate that the GNOME
terminal also displays this information in the title
bar of ts window.
he changes the permissions on
the files listed. Permissions are based ona fairly
simple madel. You can set permissions For user
‘group and world and you can set whether each can
varite a te th
able by
removing files increases the amount
‘and marks that space as
other wor
of avalabl
sture writes In
The clear command clears your screen if this
is possible. It looks in the environment for the
terminal type and then inthe terminfo database
to figure out how ta clear the screen, This is
equivalent to typing ControbL when using the
bash shell
rectory’, mkdir is used to
ies ona filesystem, iFthe specified
directory does not already exist. For example,
rk creates a work directory, More than
ry may be specified when calling mkdir.
_wvnepeubleationscomRE Merete)
USEFUL HELP/INFO COMMANDS.
Rn Tureen rena
RoI uC eu g
program you are working with in Linux. You might
not need them every day, but when you do, they
will be invaluable.
The FEES command displays the total amount
pre hee een as
eda ce hei’
ee
os eee oeares
ere ee erm tennant
seed
recess!
Bs ore ee emt
view oF a running system. can display
eu ue ees
ie
The MNES command with the fH option prints
Pema tre
Peete ering
Die = one Ee Se es
eee ee
eee eae
different but all o the same thing,
Borer ee une
eee ee
Renae Ue cL
cee eee
Cee ge eat as
transformations on an input stream: a file orinput
from a pipeline
Ditacduse eee eerie
Be (ii coo: ou ee eey
Perret eens
Bcc ue rer ieee Meare
Sree eee era)
home directory, you need to ade the SES
Promelaied
The EESTERIMY command removes a group from
Ceram are tc srd
primary group of any users.
The TEENEER command brings up the manual
Cm cua nn eaascd
Perego
‘The SERWEDRES command is especially useful.
Derren etna gets
ima e nau
Serie
EaoLes a
rae Pe Ale oe A
ee ai pee nd seat pono
ene ae aL
i Peewee
ae ee [lS
P| os
fe
1
a rt
Pyne eae
Yi anor
C ae
DRoORe 12) et]
fe 5 pe
i ja. pee
at a OL
be 2.0
PERE EA
F bh
bo uu 2o 1
E a eet ih
Ez lay 1
a Pel ite
yt DL jell
ey
Pha T
PM TA oe
cre Pn eet i
Eafe
PS
Code Projects
and Ideas
SOON atom nine Et
coder, we've included some great coding projects
Pacer ee are
Pee eee
code, or improve and send out into the coding
COSA Scour ie
Peete de ets ek oe)
Pee enim ee eee any
this final section.
RO em eS Ones ite i RC
it’s on to learning more languages, creating
SCE een eo ec
Pe Ree eee caer
made, remember the basics, and have Fun!
From here, it’s down to you and your imagination.
So dream it, and code it.
EePlanning Your
Code
Knowing how to code is great, but it’s not going to get you very Far if you don’t know
what itis you're supposed to be coding. Small samples of code don’t need much
planning, but bigger projects do, so here are some tips on planning your code.
You wl find that nearly all the professional developers out there will,
set aside some time to plan out how their code is going tofitinto the
Sere teeter enone ay
ore ene eee tae eee
cr a eee a
pee er eee
developer will set out their code in plan,
omated
SS eee
company for which they/re working, or the project on which they're
er ea a eee ee cae
the end product wil function, with each developer team then working
nttheir element within the project. Lone developers will sometimes
goback to basics, grab paper and a pencil and start getting their ideas
down, The end result is always the same, though, a plan oF action that
enables the developer to plan without worrying about the actual code
Baireeess
PSEUDOCODE
ine | RECEIVE werNane FR
0M (STRING) KEYBOARD
ine? RECEIVE piaNuuber FROM (STRI BOARD
ive 3 IF weiName VALID OR piaNuuber VALID THEN
ine 4 Allow acces to network
ive ELSE
in x Denied” TO SCREE
ine ENDIF
One of the more popular methods of planning to codes using
pseudocode. t's terms used in programming circles that allows the
eres ee ee ees
Siete a ee Eat ears
eee en ee ere teed eet cits
eis
Fee Ra eee ears
check user input For odd or even numbers will probably begin with a
Sees etc
‘A program to allow a user to check ifthe number is odd or even.
econ es
oars
ey
Ue ey
Eee es eee)
Meco
Pree netPlanning Your Code E99
Ce eee eo canny
may en ra eee etd
Be eco ee ge
ieee tects t ec ete
Se er
Pao en re tee
work of entering the code begins.
GRAPH PAPER
IF you're planning to include graphics in your project, such as 3
Pat etn ane
eer eee eet
ore
Super Mario Bros, launched for the Nintendo Entertainment
System in 1985, was nearly exclusively drawn out - both characters
and levels on graph paper before being applied to cade. Entire Once the graphical planning stage is complete, it's then down to
enna meee rtd Pree eee ee eR a
Cee eee ee eed
Se en een ee ee ee ee ee eee te
Ree ee ere ec gee ee oe
blocks; the developer could then visualise the layout of the sprite pseudocode, you could easily plan out what modules you'd use or
using the drawing on the graph paper and apply that tothe code. _ create, the number of variables needed, and the various endgame
‘The end result, of course, isthe character appearing on the screen. states that wil arise when someone plays your game.
GET PLANNING
BU nea cd
ge cen aa et
Pee eer etree trots
peste eeererc Rt ete eo ns
ROS a een nea)
When planning, begin with small steps. Coding a Hangman game, For
example, begins with the plan to get the player's name, then includes
cee Ty
right. questions, and Finishing the game in one of two states ~a win or
Yee ec ee ei
Once you're used to planning itl come naturally, and youl Find
yourself thankful forall those postit notes stuck to a sheet of A3
Eee eens cee
Seca
Pseudocode Actual Python code
Sf score >= 90
‘grade = °A'
on DO Ray
grade = °F
coVa
ADU aethe biggest Internet portal,
OTL UCU rth
RC
cy Cee ae
eS tm ena aoc ee
Unlimited satisfaction one low price
Cheap constant access to piping hot media
Protect your downloadings from Big brother
Safer, than torrent-trackers
18 years of seamless operation and our users' satisfaction
PNET 0-53
Te Tae MAW ha
oleh)
AvaxHome - Your End Place
We have everything for all of your needs. Just open https://avxlive.icuFinding
Resources
Monee Uae AA Ne Ie sore akeele nA oct ue ead
Internet, so Finding extra help here and there isn’t too much of a problem. However,
Finding good Python resources can be, so here are some ideas for you to try.
You wll reach a point. your Python coding experience when you need to rely
Ce ene Se ar eee vere’
See ee nen eer ese any
the Internet, but not all of them are any good. IF you spend any time looking
er nS et ca econo
Seer ets
Se em eed
being twenty-nine years old, and many cifferent versions under the bridge,
there's a significant amount of content out there that’s simaly out of date~o
FT tee ee
ut, can have cifferent outputs for your code froma previous version ~it's
rot always that case, butt can happen. Therefore, you need to find yourself
some trusted Python resources that work, or atleast 90% would work, with the
See ea
OU Sala date e10] |) Ona Ase) |
eee en ee ea es
Features a wealth of code that covers most aspects of the learning experience,
{even for those who are experts at Python. Youll Find content that wil take your
Py ee en ee eee eee
eee eaten e et enc ir tency
Pores
eee eee ed
covering a wide range of concepts. There's everything in here From the original
Ota ee tear cae ee
Aree nee ee estar)
Cena eetees
ees ey
ProgramArcadeGames.com isa ood place tostart Thissite has plenty of code for
the Pygame module, including moving an object around the screen using amouse
CS ea ere eto
Deeper
CeO ae eee ee eno)
toate, and youray Find yourself having to convert Python 2 cade into Python
3. Nevertheless, you do come across some gems from timeto time, especialy if
youlook up the Pygame examples that users have uploaded, We recommend the
Coen eaeSTRONG GOOGLE-FU
There's no trick toinding good Python resources online; mo:
Pee eae
queens
es
Se ence tte t
ee eee
Stee
Ome eure a
acre ry e screen
ee et ene et et
erry
Peete eta
growing list of Python code and resources that you can Freel
eae
een!
Finding Resources >ind Idea
Eb) Code Projects
Creating a Loading Screen
IF you're looking to add a little something extra to your Python code, then consider
including a loading screen. The loading screen is a short introduction, or piece of art,
Tene let=) 9) oC oL OKA ea MUTINY) eLU mM eoLe(
Cee ad
eu eee)
screens were often used to
display the cover of a game
Pee eras
Coren cea
Perey
eae or)
raster bars danced
Potent tg
the screen,
Loading screens were a part of the
package and often thebuy-in far
eee eed
Peri ere Ea tee ac et)
remaining as the game loads, while others even went so far as to
include some kind of playable game. The point being: ldading,
screen is notjust an artistic part of computing history, butan
esr iecrcr ior ait
While these days loading screens may no longer bé with us, in
Ucar em e uDye
Python content. Either just for fun, or to add alittlefetro-themed
poten
SCREENS
Cee aaa ut ob ACT)
several options to hand: you can create a tkinter Window and
display an image, followed by a brief pause, beforelstarting you
main code, or you could opt Fors console-based ASCWart version
Cares ena ea oe ey
ce
een nea Ce teen rato ge
online, or use an image to ASCII Art converter to transform any
images you have to ASCII. When you have your ASCII art, drop it into
Peet or eee
THE CODE
rere re
SS)
fiviain Code Star
es. system( cls’ if os.name == ‘nt’ else
Seren (Taree onde Dezins bere...7)
le ft Fomat Bun Optone window Hsp
The codes qUite simple: import the OS and Time modules and
then create a Python function called loading_ screen with a
coc MUST an)
PC cease eee eee ee Foren Tener
eee eer eae
Breet eer nc
eeeterermureta seme et |
eee
Sg oe
Cea eee Ria renemeT arn uate
Ser Ree ere teeter am eetens
ne eNotes ave | er)
Sener!Save the code as screns py, drop into a Command Prompt or
See eet ete eet ce ees
De cee yeaa eae eee)
acs
LOADING.
‘Another Favourite introduction screen i that of gsimple loading
‘animation, where the word loading is displayed,Followed by
Bee eee Eee ae eu cd
(ines erica eres oe
beinteresting
Greate a New File in Python and enter the folléwing code:
print “Leading.
print(%<" + (
>
(usin Code start
Loading bar (10)
ADVENTURE TIME
Ou eer enced
text images is when coding atext adventure, Once
you've established your story, created the characters,
events and so.on, you could easly incorporate some
eee encase
Imagine coming across dragon, in game, and
Cee eee te
load up the image tines, one-by-one, and continue with
ee
having 2 play around with andit'l definitely add alittle
Peary
=
Se eg ues
Peer cur ea ac wea}
that prints Loading... followed by an animation of sorts, along witha
percentage counter; clearing the screen every second and displaying
Sees ee en centr
COMBINING THE TWO
How about combining the two elements we've looked at? Let's,
begin with a Loading... progress bar, followed by the loading
screen. After that, you can include your own code and continue
Pee ener too
rine (- 7+ ots (percent) + "07)
peine("in")
Sieersieep 2}
es ayes rea
eres=ty
aasoamnaees (SSarssaa Teer)
print (lines, en:
= (seconde
iE os nano == "nt! else
my
tine. sleep (seconds)
Sermo (= neeuntoscalser instore 2)
BRON (Se
PMU ele cee ae
begining Ryfemer ave the ASCGetieinthe same folder
por ih “ea: oe lena ha
perieseit Ataean )
ee ————_____—eeee——
EyIp) Code Projects and Ideas
Planning a Text CG NUoIA 180K)
eo
ee et oe
peat
open cea taneous ¥
na
necessary tomakethe ame both interesting and payable Lacie rore
eerie
INGREDIENTS FOR A
COMPELLING ADVENTURE
See Oe ae
Sern cor
ete areas
Rete
‘wom peubleationscom‘Although not always necessary, puzzles do form an interesting aspect
of atext adventure. These puzzles can test the players abilities
etree ee)
ee ee ee
See ee ental et Lae
eee ees
Sul eee ok a eet ena
beginning ofthe game and get progressively harder as your character
Brent tars
ernear errr nett ame ee erry
ener es
eee net
east
Poeeer
Hints and help along the way canrmske the advengure seem less
Corn ote ee ee eae ay
Ceeeet eicnege Cee emer A
most text adventures do include some form ofa hint. youve
Coo een seg ets
Cen eee en eae ornare
Caco Sennen fe cnet eee
EY eel ese geese oe ces
Pacing isthe Final aspect of the adventurelgame that needs to be
Blanned correctly. Good pacing within the storys vitalto keeping
Seu etc ere eae)
lengaged with what's going on It’s not an easy'egg to cack, however
Veet epee eee Cem ey ee
Pare eee ene
THE CODE
IRsimpossibleto list the code yoU't need for your adventute
Cy ea lice ain ueneest ed
See eras
Pee ee et roe
various elements of the game. These can be descriptions of
See ea Meer)
Cen us ee ets
ee eee ea me eect
lessen depending on what the player has used/dropped/picked up.
Pe eee eo
the player's name, amount of strength, endurance, skill and health,
For example. Youll also need variables to hold the current score.
tee ee ced
Breer ees
De ea eee a)
include an element of combat. Within such examples, a virtual dice
es nears
Pee ee at ea
‘Strings can be used to keep non-moving elements ofthe game,
ete att cet as
Crete ae eae
Eee ene Ti uc manent ots
Funetioys ate the lifebloodoFa text adventure, as they will Form)
Ihe backbone of the locations, interactions, events and anything
Se ae ee
eC eae eee ae ee
Sete ete Cie a eo
Pern east ete te eee ate
with cholges made: do you take the green door or the red door?
ore 4a on old Fake
oorvas to the arth.
Kunkisht chines ta fr
60 0 lads,
2 North (9)
FT utoriols Tuse GET LADDER then the ENTER button to get the Ladder
D
GOOD LUCK, ADVENTURER
Seo cE ee ee eer)
plan outyour story first. Once you've got the basic story, build on
the settings and tocations; then puzzles and other elements. From
there, you can begin to expand the game world and add things like
cas
reo ae eee RSE)
Potent iecrs
ClJY) Code Projects and Ideas
NTS \or vein 00] es .6 5/0
Adventure game uses just the Time module to be
creating pauses between print Functions. There’sahelp FE RMUESD
SOS elisa Se DEint ("D>sSpSop>rAwasoNe AdVONEMTO RN)
BEint(\n” * 3)
‘Eine.sleep@)
[print(”\nA long tine ago, a warrior strode forth from
‘the frozen north.”)
Tie. steep)
[print(Does this warrior have a nane?)
nane=input(> "Y
[print(nane, “the barbarian, sword in Hand and looking
for adventure!)
‘Eime.sleep@)
PSU ae %
7
Eime.sleep@)
[print (A pair of bulbous eyes regards the hero...”)
‘Eine. seep)
DEint(*Will", name, “prevail, and win great fortune...")
[Print ("Or die by the hands of great evil...)
| Eino.sieep{i)
Be eine CVn" =)
Bee Peint(oniy tine will tell...
§} eine.sicepa)
Se Pine.
BW ine. sicepii)
fprine®...7)
‘Eine. sleep{)
co
[eime.sleepti)
Prine.)
| Sime. sleep)
- ea 5200)
‘A ragged looking man, and a pair of dangerous
eels
‘wom peubleationscom(Text Adventure Script [>
Tad
=agged0)
elif ced = 2
‘guards0)
def ragged
BEInE a" ¥ ZOOP
rint(”’You walk up to the ragged Looking man and
‘greet hin.
‘Ho suilos a toothless grin and, with = strange
accent, says,
“Buy me a cup of wine, and YI tell you of
‘great treasure...)
Eine. sieep@)
def guards0)
“Beit (*\n” #200)
‘Brint(”’You walk up to the dangerous locking guarda|
~and grect thon.
‘print(\aEnter your choives as detailed in
‘the game.)
[print(or enter “quit” to leave the game")
zeturn getend(endist)
elif cad =
BEint Ola
‘Eine. sleep)
[print(Sadly you return to your homeland without
Zane or fortune...”)
Eine aleep@)
‘exit
=a
‘The guards ook up from their drinks and
“Sihat do you want, barbarian?” One guard reaches|
for the hilt of his sword...)
Hine.sleep@)
essessss sss eree 000 oO
Adventure Time
‘This, asyou can see, ijt the beginning ofthe adventure and
takes up a fair few lines of code. When you expand, and weave
the story along, youl find that you can repeat certain instances
suchas. chance meeting with an enemy or the ike,
(We've created each ofthe two encounters as adefined set
(oF Functions along with alist of possible choices under the
cdlist list, and cmd variable, of which s also a defined Function.
Expanding on this is quite easy, just map out each encounter and
choice and create a defined Function around it. Providing the user
doesn't enter quit nto the adventure, they can keep playing.
‘There's also room inthe adventure fora set of variables designed
for combat, luck, health, endurance and even an inventory or
‘amount of gold eamed, Each successful combat situation can
reduce the main character's health but increase their combat skis
‘orendurance. Plus, they could loot the body and gain gold or earn,
{gold through quests.
Finally, how about introducing the Random module. This will
tenable you to include an element of chance inthe game. For
‘example, in combat, when you strike an enemy you will doa
random amount of damage as will they. You could even work out
the maths behind improving the chance ofa better hitbased on
your or your opponent's combat sills, current health, strength and
endurance, You could create a game of dice inthe inn, to see IF you
in or lose gold (again, improve the chances of winning by working
‘out your luck Factor into the equation).
"Needless to say, your text adventure can grow exponentially
{and prove to be a work of wonder. Goodluck, and have Fun with
your adventureCode Projects and Idea
Retro Coding
There's a school of thought, that to master the foundations of good coding skills you
need to have some experience of how code was written in the past. In the past is a bit
folie M ole Me LU mares accel Leolel ae MoM eR asm
‘THE-GOLDEN ERA OF CODE
Ne cu ett een er aed
Tee eee eee ee aed
Pete ae cer ene a
Ce etre tg
See ete en
ago, code stil demands strict discipline to work correctly Secondly,
everydaycoding elernents, such as loops, sub routines afd so on, are
a great visual aid to learn older code, especially BASIC. Lastly,
eer
GOING BASIC
The easiest retro language to play around wits, wfthout doubt,
BASIC. Developed backin the mid-sirties, BASIC (Bealgner's All
ee ewer ee fa i
eto er ert aad
eee ete aa
Cee Cura aes El eet
students could get to grips with, quickly and easly. Thitk oF BASICas a
CSc e
Bini) 44:3
The problem with BASICis that there were so many different versions
percocet certo
Pearcy
ontop ofthe core BASIC
Ce ons
was packaged with the
Cts
Strat ecatay
Preurenntas
rau ene es
Peer ttt oe
ee ee
Pred ene et ear are
Coe eee eg oN
ee eects ee eo ud
ee eee ns
eer nt cnet
For different processoc types, suchas the Zilog 280~a CPU presentin
ara rieet een Tey ts
“The BBC Micro was Wesigned and built by Acom Computers=3
compa thats historically responsible forthe creation of the ARM
ree eee mere tc ech
Se Nate Ey ios
eee RS ee cue et)
eee SET ee
mare Tm eu stys Seis
retary cts rt
ere enna eee ee
eee re
eg ei er
cones cme est
20
Dn Nome EeseRe NE ect eT sn er
Rome ren Geese on an
a we eG
Pieerav ieee eas
Se eae ee aU ae to
Per tarts Pd
Fe Ue Cour ot
Seren eer ater eco ete eos
MeN Ae Me rds hoe
me.uk/beebem/indexchtm, and download the BeebEM414.exe
orca ec
Ceres ee cer
eae et tay)
ee ena aE en