100% found this document useful (11 votes)
26 views

Full Download (Ebook) Introducing JavaScript Game Development : Build a 2D Game from the Ground Up by Graeme Stuart ISBN 9781484232514, 9781484232521, 1484232518, 1484232526 PDF DOCX

The document is a promotional material for the ebook 'Introducing JavaScript Game Development: Build a 2D Game from the Ground Up' by Graeme Stuart, which provides guidance on creating a 2D game using JavaScript. It includes details such as ISBN numbers, links for download, and a brief overview of the content covered in the book, including chapters on drawing, animation, and game building. Additionally, it mentions other related ebooks available on the same platform.

Uploaded by

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

Full Download (Ebook) Introducing JavaScript Game Development : Build a 2D Game from the Ground Up by Graeme Stuart ISBN 9781484232514, 9781484232521, 1484232518, 1484232526 PDF DOCX

The document is a promotional material for the ebook 'Introducing JavaScript Game Development: Build a 2D Game from the Ground Up' by Graeme Stuart, which provides guidance on creating a 2D game using JavaScript. It includes details such as ISBN numbers, links for download, and a brief overview of the content covered in the book, including chapters on drawing, animation, and game building. Additionally, it mentions other related ebooks available on the same platform.

Uploaded by

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

Download Full Version ebook - Visit ebooknice.

com

(Ebook) Introducing JavaScript Game Development :


Build a 2D Game from the Ground Up by Graeme
Stuart ISBN 9781484232514, 9781484232521,
1484232518, 1484232526
https://ebooknice.com/product/introducing-javascript-game-
development-build-a-2d-game-from-the-ground-up-6840584

Click the button below to download

DOWLOAD EBOOK

Discover More Ebook - Explore Now at ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Introducing JavaScript Game Development: Build a


2D Game from the Ground Up by Graeme Stuart ISBN
9781484232514, 9781484232521, 1484232518, 1484232526
https://ebooknice.com/product/introducing-javascript-game-development-
build-a-2d-game-from-the-ground-up-24685560

ebooknice.com

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason;


Viles, James ISBN 9781459699816, 9781743365571,
9781925268492, 1459699815, 1743365578, 1925268497
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com

(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena


Alfredsson, Hans Heikne, Sanna Bodemyr ISBN 9789127456600,
9127456609
https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312

ebooknice.com

(Ebook) Game Development with MonoGame: Build a 2D Game


Using Your Own Reusable and Performant Game Engine by
Louis Salin, Rami Morrar ISBN 9781484277706, 1484277708
https://ebooknice.com/product/game-development-with-monogame-
build-a-2d-game-using-your-own-reusable-and-performant-game-
engine-35650828
ebooknice.com
(Ebook) 2D Game Development: From Zero To Hero: A
compendium of the community knowledge on game design and
development by Daniele Penazzo
https://ebooknice.com/product/2d-game-development-from-zero-to-hero-a-
compendium-of-the-community-knowledge-on-game-design-and-
development-48968506
ebooknice.com

(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT


II Success) by Peterson's ISBN 9780768906677, 0768906679

https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018

ebooknice.com

(Ebook) Godot 4 Game Development Projects: Build five


cross-platform 2D and 3D games using one of the most
powerful open source game engines by --
https://ebooknice.com/product/godot-4-game-development-projects-build-
five-cross-platform-2d-and-3d-games-using-one-of-the-most-powerful-
open-source-game-engines-56267534
ebooknice.com

(Ebook) Master SAT II Math 1c and 2c 4th ed (Arco Master


the SAT Subject Test: Math Levels 1 & 2) by Arco ISBN
9780768923049, 0768923042
https://ebooknice.com/product/master-sat-ii-math-1c-and-2c-4th-ed-
arco-master-the-sat-subject-test-math-levels-1-2-2326094

ebooknice.com

(Ebook) Cambridge IGCSE and O Level History Workbook 2C -


Depth Study: the United States, 1919-41 2nd Edition by
Benjamin Harrison ISBN 9781398375147, 9781398375048,
1398375144, 1398375047
https://ebooknice.com/product/cambridge-igcse-and-o-level-history-
workbook-2c-depth-study-the-united-states-1919-41-2nd-edition-53538044

ebooknice.com
Introducing
JavaScript Game
Development
Build a 2D Game from the Ground Up

Graeme Stuart
Introducing
JavaScript Game
Development
Build a 2D Game from
the Ground Up

Graeme Stuart
Introducing JavaScript Game Development
Graeme Stuart
Market Harborough, Leicestershire, United Kingdom

ISBN-13 (pbk): 978-1-4842-3251-4 ISBN-13 (electronic): 978-1-4842-3252-1


https://doi.org/10.1007/978-1-4842-3252-1
Library of Congress Control Number: 2017962296
Copyright © 2017 by Graeme Stuart
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or
part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software,
or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Cover image designed by Freepik
Managing Director: Welmoed Spahr
Editorial Director: Todd Green
Acquisitions Editor: Louise Corrigan
Development Editor: James Markham
Technical Reviewer: Aditya Shankar
Coordinating Editor: Nancy Chen
Copy Editor: Corbin Collins
Compositor: SPi Global
Indexer: SPi Global
Artist: SPi Global
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505,
e-mail [email protected], or visit www.springeronline.com. Apress Media, LLC is a
California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc
(SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected], or visit www.apress.com/
rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is
available to readers on GitHub via the book's product page, located at www.apress.com/
9781484232514. For more detailed information, please visit www.apress.com/source-code.
Printed on acid-free paper
Table of Contents
About the Author��������������������������������������������������������������������������������vii
About the Technical Reviewer�������������������������������������������������������������ix
Introduction�����������������������������������������������������������������������������������������xi

Part I: Drawing����������������������������������������������������������������������������������1
Chapter 1: HTML5 and the Canvas Element������������������������������������������3
HTML Primer���������������������������������������������������������������������������������������������������������3
Drawing to the Canvas������������������������������������������������������������������������������������������5
Style the Page to Highlight the Canvas�����������������������������������������������������������������7
Experiment with fillStyle���������������������������������������������������������������������������������������9
Rendering Text����������������������������������������������������������������������������������������������������10
More Shapes and Lines���������������������������������������������������������������������������������������13
Summary������������������������������������������������������������������������������������������������������������16

Chapter 2: Understanding Paths���������������������������������������������������������17


Organizing Your Files������������������������������������������������������������������������������������������17
The Canvas Grid System�������������������������������������������������������������������������������������19
Refactor Early, Refactor Often�����������������������������������������������������������������������������23
Working with Paths���������������������������������������������������������������������������������������������26
Adding Curves to a Path��������������������������������������������������������������������������������������33
Summary������������������������������������������������������������������������������������������������������������37

iii
Table of Contents

Chapter 3: Drawing to a Design����������������������������������������������������������39


Pac-Man��������������������������������������������������������������������������������������������������������������40
Create a Function������������������������������������������������������������������������������������������������43
Randomization����������������������������������������������������������������������������������������������������44
Summary������������������������������������������������������������������������������������������������������������46

Chapter 4: Drawing a Spaceship��������������������������������������������������������47


Basic Trigonometry���������������������������������������������������������������������������������������������47
A Basic Ship��������������������������������������������������������������������������������������������������������48
Using Object Literals�������������������������������������������������������������������������������������������52
Transforming the Canvas Context�����������������������������������������������������������������������54
Adding Some Curves�������������������������������������������������������������������������������������������60
Summary������������������������������������������������������������������������������������������������������������69

Chapter 5: Drawing an Asteroid���������������������������������������������������������71


Drawing Basic Shapes����������������������������������������������������������������������������������������71
Storing Shape Data���������������������������������������������������������������������������������������������76
Summary������������������������������������������������������������������������������������������������������������80

Part II: Animation���������������������������������������������������������������81


Chapter 6: Basic Animation����������������������������������������������������������������83
Start Simple��������������������������������������������������������������������������������������������������������83
A More Complicated Example�����������������������������������������������������������������������������86
Summary������������������������������������������������������������������������������������������������������������92

Chapter 7: Animating Asteroids����������������������������������������������������������93


A Solid Game Loop����������������������������������������������������������������������������������������������93
Refactoring into Simple Objects�������������������������������������������������������������������������99
Using Object Constructors��������������������������������������������������������������������������������101

iv
Table of Contents

Extending the Asteroid Prototype����������������������������������������������������������������������102


Working with Multiple Asteroids�����������������������������������������������������������������������105
Summary����������������������������������������������������������������������������������������������������������107

Chapter 8: Practicing Objects�����������������������������������������������������������109


Why Objects?����������������������������������������������������������������������������������������������������109
Pac-Man Chased by Ghosts������������������������������������������������������������������������������110
The PacMan object�������������������������������������������������������������������������������������������112
The Ghost Object�����������������������������������������������������������������������������������������������117
Summary����������������������������������������������������������������������������������������������������������123

Chapter 9: Inheritance����������������������������������������������������������������������125
Set Up a Template���������������������������������������������������������������������������������������������125
Newton’s Laws of Motion����������������������������������������������������������������������������������127
A General-Purpose Mass Class�������������������������������������������������������������������������128
A Simple Approach to Inheritance���������������������������������������������������������������������133
Asteroids�����������������������������������������������������������������������������������������������������������134
The Ship������������������������������������������������������������������������������������������������������������137
Summary����������������������������������������������������������������������������������������������������������140

Part III: Building the Game������������������������������������������������141


Chapter 10: Simple Keyboard Interaction�����������������������������������������143
Controlling Pac-Man�����������������������������������������������������������������������������������������143
Summary����������������������������������������������������������������������������������������������������������149

Chapter 11: Controlling the Ship������������������������������������������������������151


Thruster Control������������������������������������������������������������������������������������������������151
Steering������������������������������������������������������������������������������������������������������������156
Shooting������������������������������������������������������������������������������������������������������������158
Summary����������������������������������������������������������������������������������������������������������168

v
Table of Contents

Chapter 12: Collision Detection��������������������������������������������������������169


A Quick Refactor�����������������������������������������������������������������������������������������������169
Ship vs. Asteroids���������������������������������������������������������������������������������������������178
Taking Damage�������������������������������������������������������������������������������������������������182
Asteroid vs. Projectile���������������������������������������������������������������������������������������185
Summary����������������������������������������������������������������������������������������������������������193

Chapter 13: Death or Glory���������������������������������������������������������������195


Game Over��������������������������������������������������������������������������������������������������������195
Restarting the Game�����������������������������������������������������������������������������������������199
Implementing Levels�����������������������������������������������������������������������������������������201
Summary����������������������������������������������������������������������������������������������������������203
Conclusions�������������������������������������������������������������������������������������������������������204

Index�������������������������������������������������������������������������������������������������207

vi
About the Author
Graeme Stuart is a self-taught developer
with 15 years of experience building data
analysis tools and web-based applications
using JavaScript, Ruby, and Python. He has a
PhD in energy management, and much of his
programming skill was originally developed
to that end. He taught JavaScript games
programming to first-year undergraduates for
a while, and this book is the result. He now
mostly uses complexity science to encourage
a deep understanding of agile approaches
to software engineering and to justify his
outlandish research ambitions.

vii
About the Technical Reviewer
Aditya Shankar started programming in 1993
when he was first introduced to the world of
computers. With no access to the Internet or
online tutorials at the time, he wrote his first
game in GW-BASIC by painstakingly retyping
code from a book he found at the local library.
After graduating from the Indian Institute
of Technology Madras in 2001, he spent nearly
a decade working as a software consultant,
developing trading and analytics systems
for investment banks and large Fortune 100
companies, before eventually leaving his corporate life behind so he could
focus on doing what he loved.
A self-confessed technology geek, he has spent his time since then
working on his own projects and experimenting with every new language
and technology that he could, including HTML5. During this time, he
became well known for singlehandedly re-creating the famous RTS game
Command and Conquer, as well as Commandos: Behind Enemy Lines,
entirely in HTML5.
Apart from programming, Aditya is passionate about billiards, salsa
dancing, fitness, and personal development. He maintains a personal
website where he writes articles on game programming, personal
development, and billiards, and shares his popular game demos.
When he’s not busy writing or working on his own projects, Aditya
does consulting work with companies to help them launch new software
products and games.

ix
Introduction
This book provides a full set of exercises in which we will build a fully
functional HTML canvas game. Though not a direct clone, the game is
inspired by the 1979 Atari classic, Asteroids. The code is provided for you
and is introduced piece by piece over the various chapters of the book.
If you’d like to try Asteroids, or if you’ve never played it, the the modern
Atari version can be played at https://atari.com/arcade#!/arcade/
asteroids/play. I’ve made a few different gameplay decisions for the
game we create in this book, and I encourage you to attempt to adapt the
game in any direction you like as we go along, if you feel confident in doing
so. It’s all good practice!
Typically, each chapter introduces an area of game design in a generic
way, develops the ideas towards implementing an aspect of the Asteroids
game, and urges you to think about alternative approaches. Towards the
end of the book, the game will be complete, and you should have all the
skills necessary to build a quality game of your own.
During most of the exercises, you’re encouraged to be creative. Go
through the material provided, consider the challenges presented, and
explore the impact of modifying the provided code. There’s no “correct”
way to design a game like this—it involves making many decisions, and the
provided code is only one of thousands of possible ways to do it. So, please,
try it your way if you feel confident enough. That’s a great way to learn
something.

xi
PART I

Drawing
The HTML canvas element, true to its name, provides a blank canvas on
which we can draw our game. Drawing is a fundamental aspect of working
with the HTML canvas element, so in these first few chapters we will
explore how drawing works and learn the fundamentals necessary to draw
our own designs with simple lines and fills. We will also develop some of
the game elements necessary for our Asteroids game clone.
CHAPTER 1

HTML5 and the


Canvas Element
This chapter introduces some of the basics of HTML, CSS, and JavaScript.
These are the core web technologies, and we’ll use them for developing
our game throughout this book. In order to follow along, you’ll need a text
editor to generate text files and a web browser to view the results with.
You won’t be learning everything there is to know about these
technologies. We’ll focus on just enough to draw some stuff on an HTML
canvas element. We’ll work with the HTML canvas element throughout
this book, so pay attention.

H
 TML Primer
HTML (HyperText Markup Language) documents describe content on
the web. When you access a web page, you’re typically downloading and
viewing an HTML document. HTML is a way to organize and add semantic
meaning to multimedia content (text, images, videos, and more) and to
link between documents in a “web” of information.
HTML5 is the current version of the HTML standard. The standard
was originally developed in the early 1990s and has evolved a little since
then. The modern standard allows for the extremely rich experience of
the modern World Wide Web. We’ll be working with the HTML canvas

3
© Graeme Stuart 2017
G. Stuart, Introducing JavaScript Game Development,
https://doi.org/10.1007/978-1-4842-3252-1_1
Chapter 1 HTML5 and the Canvas Element

element, so let’s create our first HTML document and add a canvas
element to it.
Create a file called exercise1.html and type in the basic HTML template
shown in Listing 1-1.

Listing 1-1. A Basic HTML Template

<!doctype html>
<html>
  <head>
    <title>This is an HTML canvas</title>
  </head>
  <body>
    <h1>This is an HTML canvas</h1>
    <canvas id="asteroids" width="400" height="400"></canvas>
  </body>
</html>

Listing 1-1 begins with a <!doctype html> declaration. The doctype


declaration is always the first thing in an HTML document. It’s an
instruction to the web browser about what version of HTML the page is
written in. In the past, using doctype was complex because there were
many versions of HTML to choose from. With HTML5, the declaration is
reduced to simply specifying that we’re using HTML.
After the doctype, the main <html> element is opened. Note that it’s
closed at the end of the file with an </html> closing tag. Everything in
between the opening and closing html tags is said to be within the html
element. There should be nothing more in an HTML file than a doctype
and an html element with content.
Within the html element there are two nested elements: <head>
and <body>. The <head> element is used to describe details about the
document, such as the <title> to be displayed in a browser tab. It often
also contains links to stylesheets or JavaScript files that specifies how the

4
Chapter 1 HTML5 and the Canvas Element

contents are to be rendered and how they behave. The <body> element
contains the content of the document and in this case includes a level one
header <h1> and a <canvas> element.
The <canvas> element provides a JavaScript API (application
programmable interface) for drawing simple shapes and lines. It’s this API
that we will use to render our game.

D
 rawing to the Canvas
<script> elements contain JavaScript code that’s executed by the browser.
Add the <script> shown in Listing 1-2 into your document <body> after
the <canvas> element.

Listing 1-2. A Simple Script

<script>
  var canvas = document.getElementById("asteroids");
  var context = canvas.getContext("2d");
  context.strokeStyle = 'dimgrey';
  context.lineWidth = 5;
  context.rect(75, 75, 250, 250);
  context.stroke();
  // this is a comment, it has no effect!!!
</script>

You’ll need to reload the page in order for the script to run. The
script runs line by line once the page is loaded. The first line calls the
getElementById method on the global document object. The document
object is defined automatically and provides a programmable interface into
the entire HTML document. The document is loaded into memory as a
tree-like structure often referred to as the DOM (Document Object Model).
In this case we’re using getElementById to get a reference to the <canvas>
element within the DOM using the id value we specified in the HTML.

5
Chapter 1 HTML5 and the Canvas Element

The second line in the script generates a reference to a canvas context.


Canvas contexts provide an API for drawing. In this case, we’re accessing
the "2d" canvas context. It has a variety of methods for drawing lines
and shapes on the canvas and for transforming the canvas. Other canvas
contexts are available but are outside of the scope of this book.
The third and fourth lines of the script set some properties of the
context. Setting context.strokeStyle affects the color of the line, here
we set it to the built in 'dimgrey' color. Setting context.lineWidth affects
the thickness of the line, and here we set it to five pixels wide. When we
set properties of the canvas context, they remain in force until we change
them. All future lines we draw will be five pixels wide and 'dimgrey' until
we tell the canvas context otherwise.
The fifth line specifies a rectangle using the context.rect method. The
(x, y) pixel coordinates of the origin of the rectangle is specified in the first
two arguments (75 and 75). The pixel width and height of the rectangle are
specified in the last two arguments (250 and 250). Most canvas operations
involving lengths are specified in pixels (and angles are in radians). Note
that this line specifies the rectangle but doesn’t draw it. The rectangle
specification is stored in memory as a structure known as a path. We’ll talk
more about paths later.
The final active line tells the context to draw the stored path using the
current values of the context properties (lineWidth and strokeStyle).
Open the file in your browser and you’ll see the rectangle has been drawn
on the canvas, as shown in Figure 1-1.

6
Chapter 1 HTML5 and the Canvas Element

Figure 1-1. A rectangle (actually, a square)

The final line of the script is actually a comment. Comments begin


with double forward slashes (//) and are ignored by the browser when
running the code. Comments are useful for annotating your code but also
for quickly removing lines of code while keeping the ability to uncomment
them again later by removing the slashes.

Style the Page to Highlight the Canvas


Great so far, but we can’t see the edges of the canvas on the page because
the page and canvas are both white. Insert the <style> element from
Listing 1-3 into the <header> element after the <title> element and
reload the page.

Listing 1-3. Styling the Canvas

<style media="screen">
  body {
    text-align: center;
    font-family: sans-serif;
  }

7
Chapter 1 HTML5 and the Canvas Element

  canvas {
    background-color: black;
  }
</style>

Styles allow us to control how the content of the document looks when
it’s rendered by the browser. In this case, we’re specifying that we want the
<body> element to be centrally aligned with a sans-serif font (this applies
to all child elements of the body element, as font-family is inherited by
default). We’re also specifying that <canvas> elements should be drawn
with a black background color. After reloading the page, you should see
something similar to Figure 1-2.

Figure 1-2. A 250 × 250 “rectangle” in a 400 × 400 canvas.


The top-­left corner is at point (75, 75).

This allows us to see exactly where the canvas edges are and
understand that the rectangle is positioned as specified within the canvas.
I won’t cover styles much more in this book, but they’re a very powerful
technology providing exquisite control over how to render HTML content.

8
Chapter 1 HTML5 and the Canvas Element

Experiment with fillStyle


Setting the context.fillStyle determines the color to use when filling
drawn shapes (including fonts). Try setting the fill style to a light grey (for
example, context.fillStyle = 'lightgrey'). Reloading the page does
nothing. That’s because we haven’t asked the context to fill the path.
To fill the path it’s necessary to call the context.fill method. Go
ahead and add the call at the end of the script, just like the call to context.
stroke. Also, swap the values of fillStyle and strokeStyle to create a
dark square with a light border for more contrast. Your page should look
like Figure 1-3.

Figure 1-3. A dark square with a light border

Now let’s change the shape of the rectangle so we can create a


motivational poster. Replace the rectangle coordinates with those shown
in Listing 1-4. Notice that we can access the canvas.width and canvas.
height attributes and use them to calculate the size of our rectangle.

9
Chapter 1 HTML5 and the Canvas Element

Listing 1-4. Changing the Rectangle Color, Shape, and Position

<script>
  var canvas = document.getElementById("asteroids");
  var context = canvas.getContext("2d");
  context.strokeStyle = 'lightgrey';
  context.fillStyle = 'dimgrey';
  context.lineWidth = 5;
  context.rect(75, 50, canvas.width - 150, canvas.height - 100);
  context.stroke();
  context.fill();
</script>

R
 endering Text
The canvas treats text a lot like a collection of shapes. The outline can be
drawn with the context.strokeText method, or text can be filled with
the context.fillText method. Both methods must be passed a text
string and the (x, y) coordinates (in pixels) at which to render the text.
Before rendering text it’s useful to change the font from the default using
context.font.
Add the two lines in Listing 1-5 to your script.

Listing 1-5. Write Some Text

context.font = "34px Arial";


context.fillText("2D Drawing", 110, 100);

It seems like nothing has happened, but actually, the text has been
drawn. The problem is that the fillStyle is still set to the same color as
the filled rectangle. The text color and the background color are the same,
so nothing visibly changes.

10
Chapter 1 HTML5 and the Canvas Element

Edit your script to add a second call to context.fillStyle. Set it to a


contrasting (light) color (for example, 'lightgrey'). Make sure your new
line is positioned after the previous call to context.fill and before your
call to context.fillText. Refresh the page and admire the fruits of your
hard work—you should have something similar to Figure 1-4.

Figure 1-4. Use fillText to render text

Try using context.strokeText instead—it has exactly the same API


(it takes the same arguments in the same order) as context.fillText.
Notice that the text is rendered as an outline but that the line width is
still set to 5 pixels. Add another call to context.lineWidth and choose a
suitable thickness. Note that you can use non-integer values such as 0.5.
Update your code to match Listing 1-6.

Listing 1-6. Some Fancy Text

<script>
  var canvas = document.getElementById("asteroids");
  var context = canvas.getContext("2d");
  context.strokeStyle = 'lightgrey';
  context.fillStyle = 'dimgrey';
  context.lineWidth = 5;

11
Chapter 1 HTML5 and the Canvas Element

  context.rect(75, 50, canvas.width - 150, canvas.height - 100);


  context.stroke();
  context.fill();
  context.font = "34px Arial";
  context.strokeStyle = '#FF2222';
  context.fillStyle = '#FFAAAA';
  context.lineWidth = 0.75;
  context.textAlign="center";
  let msg = "2D Drawing"
  context.fillText(msg, canvas.width / 2, 100);
  context.strokeText(msg, canvas.width / 2, 100);
</script>

The changes are all in the second half of the script. We set the familiar
context properties to some sensible values (note the use of hexadecimal
color codes). We then set a new property context.textAlign to the value
"center". This tells the context to use the central point in the text as the
“anchor.” So, when we actually render the text, the central point in the
text is positioned at the x-coordinate we provide rather than the default
leftmost point. The final few lines set a message variable and draw the text.
First we fill it and then we draw an outline (experiment with swapping the
order of these method calls). This is just the same as before except this
time we’re calculating the x-coordinate rather than specifying a literal
value (such as 110, as before). In this case, we’re aligning the text centrally
on the horizontal axis so we divide the width by 2. See Figure 1-5.

12
Chapter 1 HTML5 and the Canvas Element

Figure 1-5. Fancy, centred text

More Shapes and Lines


Drawing to the canvas is pretty simple. The tricky part is deciding what to
draw and designing it. Listing 1-7 includes some code for a simple stick
figure waving. Paste it in at the end of your script.

Listing 1-7. A Stick Figure

context.strokeStyle = '#FFFFFF';
context.lineWidth = 2;
context.beginPath();
context.arc(200, 140, 20, 0, Math.PI * 2);
context.moveTo(200, 160);
context.lineTo(200, 220);
context.moveTo(180, 300);
context.lineTo(185, 260);
context.lineTo(200, 220);
context.lineTo(215, 260);
context.lineTo(220, 300);
context.moveTo(240, 130);
context.lineTo(225, 170);

13
Chapter 1 HTML5 and the Canvas Element

context.lineTo(200, 170);
context.lineTo(175, 180);
context.lineTo(170, 220);
context.stroke();

The script starts by setting the stroke color to white and the line width
to 2 pixels. Then we see two new methods of the context object. The
context.beginPath method begins a new path or resets the current path.
We need to call this because we already had an active path left over from
when we drew the original rectangle. If we don’t call it (try commenting it
out), then we continue the original path, and a line will be drawn from the
rectangle to our first circle. You’ll learn more about paths in Chapter 2.
The circle is drawn using the context.arc method. This method
can be used to draw any circle or portion of a circle. The method takes
five arguments, as follows: the first pair of arguments includes the (x, y)
coordinates (in pixels) of the center of the circle. The third argument is
the radius of the circle, and the fourth and fifth arguments are the starting
angle and finishing angle of the arc (measured in radians). To draw a full
circle, these angles should be 0 and 2π. We access the value of π via the
Math.PI method. We’ll use the built-in JavaScript Math object extensively
in later chapters.
The remaining method calls are all either context.moveTo or context.
lineTo until we finally call context.stroke to draw the path. The context.
moveTo and context.lineTo methods both take two arguments, and in both
cases these are the (x, y) coordinates specifying a location on the canvas in
pixels. They each do exactly what you would expect. To move the “pen” to
a location without drawing a line, call context.moveTo. To draw a line from
the current location to the given location, call context.lineTo.
Follow the code line by line and see how each line of code is necessary
to draw the stick figure shown in Figure 1-6. Try removing or editing some
of the lines to see what happens. Play around until you can predict the
effect of a change.

14
Chapter 1 HTML5 and the Canvas Element

Figure 1-6. Circles and lines

Finally, complete the motivational poster by adding the code in


Listing 1-8 to your script before the recent changes to context.lineWidth
and context.strokeStyle.

Listing 1-8. A Motivational Message

let msg2 = "its quite easy";


context.font = "24px Arial";
context.fillText(msg2, canvas.width / 2, 330);
context.strokeText(msg2, canvas.width / 2, 330);

The final image should appear like Figure 1-7. Note how the position
in the code where you insert the new lines makes a difference. If you place
the new code after the context changes, the text outline will be drawn with
a thicker, white line.

15
Chapter 1 HTML5 and the Canvas Element

Figure 1-7. The finished poster

S
 ummary
In this chapter we’ve had a very quick run-through of the basic
technologies we’ll be using to create our game. We’ve created our first
HTML document and viewed it in the browser, we’ve styled our document,
and we’ve written code to manipulate our canvas element.
We’ve seen that the HTML <canvas> element has a programmable
interface, and we’ve used HTML <script> elements with JavaScript code
to draw to the canvas. We’ve been introduced to some of the methods
available in the canvas context and used them to render a motivational
poster to the canvas. And we’ve seen that the interface gives us tools for
drawing lines and filling shapes and that we can control the thickness of
lines and the color of lines and shapes.
We learned a little about the coordinate system and how paths are
constructed. In Chapter 2, we’ll expand on this and try to get a deeper
understanding of how to master the art of drawing what we want on the
HTML canvas.

16
CHAPTER 2

Understanding Paths
Chapter 1 introduced some of the basic methods for drawing to the canvas.
This chapter presents a follow-up exercise that looks more closely at the
canvas coordinate system and explores how to construct paths. These
concepts are critical to understanding the canvas and designing your own
drawing code.
We’ll also start to add a bit more structure to our code. Complex code
can be difficult to comprehend—adding structure is the main way to keep
the complexity under control. Structuring code into functions allows
the development of simpler code that uses those functions. This chapter
introduces functions and goes through the process of refactoring, a crucial
skill that’s necessary to manage code of any complexity.

Organizing Your Files


To get started, we are going to organize our HTML document in a more
traditional way. In Chapter 1, we simply included the styling information
in a <style> element. To remove clutter and make the styles reusable,
we’re going to move the styles into a separate file. Create a file called
exercise2.html and start with the basic template shown in Listing 2-1.

17
© Graeme Stuart 2017
G. Stuart, Introducing JavaScript Game Development,
https://doi.org/10.1007/978-1-4842-3252-1_2
Chapter 2 Understanding Paths

Listing 2-1. A Basic Template

<!doctype html>
<html>
  <head>
    <title>More drawing to canvas</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <h1>More drawing to canvas</h1>
    <canvas id="asteroids" width="400" height="400"></canvas>
    <script>
      var canvas = document.getElementById("asteroids");
      var context = canvas.getContext("2d");
      // Grid drawing code goes here
    </script>
  </body>
</html>

We’ve added a <link> element that refers to an external stylesheet


called styles.css. Create the styles.css file and add the rules from Listing 2-2.
Both files should be saved in the same folder. It’s usually a good idea to
have a folder exclusively for these two files.

Listing 2-2. A Standard Stylesheet

body {
  text-align: center;
  font-family: sans-serif;
}
  canvas {
  background-color: black;
}

18
Chapter 2 Understanding Paths

Load exercise2.html into your browser. We have a blank canvas, so let’s


put something on it.

The Canvas Grid System


We saw in Chapter 1 that the canvas has a coordinates system. The origin (0, 0)
is in the top-left corner. The canvas is canvas.width pixels wide and canvas.
height pixels high. Let’s make these coordinates visible by drawing a grid.
Start by setting the stroke color and line width. Add the following lines
into your <script> tag after the comment "Grid drawing code goes here":

context.strokeStyle = "#00FF00";
context.lineWidth = 0.25;

Now we use a for loop to increment the x-coordinate from 0 to the


canvas width in 10-pixel steps, drawing the vertical grid lines in each
iteration. Within the loop we move the current path position to the top of
the canvas at our x-coordinate and draw a line all the way to the bottom of
the canvas. Keeping the x-coordinate unchanged between the context.
moveTo and context.lineTo calls ensures we get a vertical line each time:

for(var x = 0; x < canvas.width; x += 10) {


  context.moveTo(x, 0);
  context.lineTo(x, canvas.height);
}

If you refresh the page, nothing is drawn. That’s because we’re still only
building a path and haven’t yet asked for it to be drawn. Repeat the same
pattern with the horizontal grid lines:

for(var y = 0; y < canvas.height; y += 10) {


  context.moveTo(0, y);
  context.lineTo(canvas.width, y);
}

19
Chapter 2 Understanding Paths

Again, we’re drawing each horizontal line in turn from the left of the
canvas (x = 0) to the right (x = canvas.width). The y-coordinate starts at
0 and increases by 10 pixels each iteration until it reaches canvas.height.
Nothing is actually drawn to the canvas until we call context.stroke():

context.stroke();

This then draws the path onto the canvas, as shown in Figure 2-1.

Figure 2-1. A basic grid pattern

We’d like to have a major/minor grid system so we can easily pick


out coordinates. To do this we need every fifth line to be thicker. But as
we currently do it, we have no control over the line width. The context.
stroke method we call at the end of the code applies the current stroke
style and line width to the entire current path. This means all the lines will
have the same width. If we want to give them different widths, we need to
split the drawing into multiple paths, one for each line. To do that, we need
to call both context.beginPath and context.stroke within our loops.

20
Exploring the Variety of Random
Documents with Different Content
ole hoivan tarpeessa, vaan päinvastoin odottaa hoivatakseen
tuotakin, joka tuolta tulee, ja joka jo totisesti alkaa olla hommissaan
retuperällä, tolkkua vailla aivan.

Räntää tuiskuaa taivaan täydeltä. Pilvet näyttävät riippuvan


katonharjojen varassa, ja katu on kuin ahdas holvikäytävä.
Yksinäisen kulkijan silmille ryöppyää räntää, joka sulaa vaatteilla
vesivirroiksi. Katukäytävän hyhmäinen velli roiskuu kävelijän
töksähtelevien askelien alla. Hän mutisee itsekseen:

— Ei tämä vetele enään. Tästä häätyy tehdä loppu. Tuota ovea en


tämän jälkeen aukaise. — Ei ole meillä enään nuoruuden
kaikkivaltiasta viattomuutta, joka pyhittää senkin mitä homehtunut
"yleinen moraali" nimittää vääräksi. Me olemme kerran jo
sivuuttaneet sen ajan, jolloin olisimme voineet kuulua toisillemme.
Hulluja olimme molemmat, kun yritimme kaivaa entisyyttä esille
haudastaan. Me löysimme vain luurankoja ja ruumismyrkkyä. —
Vainajia voi palvella, jos haluttaa, ja viedä kukkia heidän haudoilleen,
mutta koskea heihin ei pidä. Entisyyttä ei pidä vetää esille
nykypäivään; ei pidä sekottaa entisyyttä ja nykyisyyttä. Niistä sikiää
kuolema ja rikos. Rikosta tämä on ollut, koska se on raakaa ja
inhottavaa. Hän jo kynsi minua, ja vaati minun eroamaan Lahjasta.
Ei neitiseni, sitä en tee koskaan. Lahjan kanssa me elämme alituista
nykypäivää, piittaamatta vuosista, jotka ovat ohitsemme kulkeneet.
Me olemme vanhenneet. Meistä on tullut mies ja vaimo. Meillä on jo
lapsikin. Olin mieletön kun hetkeksikkään antausin heidän piiristään
pois. Vain heidän luonaan olen olemassa, vain heidän luonaan voin
elää ja ponnistaa eteenpäin. Rauha vainajille — kaikille. Eteenpäin!
Olen jo kyllin kauvan tässä luisunut takaperin.
Pekka astelee päättävästi, niinkuin tämä räntäpyryn läpi
painauminen hyvinkin olisi menoa eteenpäin. Lienee kai se sitäkin,
sillä onhan jo kohta ristinväli erottamassa kävelijää siitä ovesta,
jonka hän äsken sulki. Ja välimatka pitenee joka askeleelta.

Katu ei olekkaan vielä typötyhjä. Tulee toinen yökulkija Pekkaa


vastaan, samallatavoin kaulus pystyssä ja kourat taskuihin
työnnettyinä. Tulija kävelee hitaasti, kumarassa. Pekan edessä se
pysähtyy, katsoen silmiin. Se on Liuski.

Siinä seisovat nyt vastakkain appiukko ja vävypoika. Pekka on


perinjuurin ällistynyt, eikä tahdo päästä tolkulleen mitä tämä kohtaus
oikein merkitsee. Sillä siitä ei pääse yli eikä ympäri että Liuski on
edessä, ehkäpä vartavasten tähän tulleena ja odottaneena. Ukon
päällystakki ja lakki näyttävät märjiltä, niinkuin hän jo tovin aikaa olisi
viipyillyt ulkosalla. Kovin vanhentunut on ukko. Vartalo on kutistunut,
parta niin valkea ettei voi erottaa lumihiutaleita, jotka siihen
putoilevat ja sulatessaan kastelevat sen märäksi. Parta alkaa
tärähdellä:

"Mahtanetkohan sinä arvata, Pekka, mitävarten minä olen tässä?"

Jos nyt tuo Pekka tuossa olisi oikea mies, niin älyäisi toki hävetä
vanhuksen edessä, jonka äänessä ei ole mitään uhkaavaa — surua
vain. Pitäisi tunnustaa olleensa tyhmä ja avuton leikkipallo tässä
kohtalossa, joka miestä näin on paiskellut. Mutta Pekka tunnustaisi
mieluummin olevansa vaikka roisto kuin leikkipallo. Pekka ei osaa
vielä nöyrtyä. Sitäpaitsi häntä tietysti harmittaa näinikään joutua
kolttosestaan kiinni kuin koulupoika. Siksi hän epäluuloisena
murisee:

"Mistäs minä teidän olemisenne tietäisin."


"Kyllä tämä hävettää minua", jatkaa ukko, puistaen päätään. "Sen
toki arvannet että olen sinua odottanut?"

"Onpas sekin vanhan miehen työtä! Olisitte mennyt meille kotia


odottamaan, jos teillä lienee jotain asiaa."

"Hyvän tunnin minä jo siellä vartoilin, mutta pistäysin sitte tälle


suunnalle. Minä tiedän nykyisin sinun asioistasi enemmän kuin sinä
itse. Eivätkä ne ole iloisia asioita, sanon minä."

"Minä hoitelen itse asiani."

"Kunpa ne hoitaisitkin!" kivahtaa ukko jo tulisemmin, ja hänen


silmänsä välähtävät. "Sanoppas minulle nyt missä vaimosi on, ja
lapsesi?"

"Onko Lahja? — eikö hän ole — —?"

"On ja ei ole. Tänään iltajunalla hän meni, eikä kukaan tiedä mihin.
— Muuta ei minulla olekkaan asiaa. Nyt vain tahtoisin tietää
kummalle meistä tämä asia tästälähtien kuuluu."

Siihen kysymykseen ei Pekka kykene vastaamaan, sillä tuntuupa


kuin ei mikään enään kuuluisi hänelle. Hänen pikkuhumalansa on
tuokiossa haihtunut, ja samalla tuntuu haihtuneen kaikki
elämänmerkit hänen rinnastaan. Siellä on kammottava seisaustila,
josta ei tiedä onko se lopullinen loppu vai hetkinen tyventä rajuilman
edellä. — Hän on näkevinään miten jo saavuttamattomissa kiitää
pois se, johon hän oli järkkymättä luottanut ja joka oli häneen
luottanut. Jos Lahja olisi pettänyt, ei voisi tuntua näin autiolta. Silloin
olisi edes kivun ja katkeruuden lohdutus.
Mutta mennä ilman muuta pois, sanaa sanomatta! Se on tietoinen
teko, ja merkitsee että jotain korvaamatonta on luhistunut. —
Yhtäkkiä katkaistu monien vuosien yhdessäolo repäisee miehen
näennäiseen vapauteen, keskelle maailmaa, mutta hän tuntee
olevansa yksin — tyhjyydessä. Hänen sisäisen katseensa edessä on
auttamattomasti tyhjiö. Onko se todellinen aistimus vai ainoastaan
äkkiä heräävän syyllisyydentunnon ensimmäinen raivaustyö, sitä ei
Pekka kykene ratkaisemaan. Ei hän kykene ajattelemaan ei
puhumaan ei liikkumaan. Hän on kankea. Hänen ruumiinsa ja
sielunsa ovat jäykistyneet. Hänen silmänsä vain ovat revähtäneet
suuriksi, ja ne näkevät edessään yhä tuon vanhuksen, joka
katkaisee äänettömyyden lausumalla katkerasti:

"Niinpä niin. Kauniita huhuja sinusta jo käy, ja ne näyttävät olevan


totta."

"Vaari", sanoo Pekka nöyrästi, "minä halusin vain hiukkasen elää".

"Siksipä sietäisikin katsoa eteensä, ettei elä nurin itseään — ja


muita."

Sen sanottuaan vanhus kääntyy ympäri, lähtien astelemaan pois.


Menee hiljalleen, töpöttelee kankein ukon askelin, pää kumarassa,
eikä edes kertaakaan katso taakseen, vaikka Pekka sitä melkein
toivoisi. Mitävarten? Sitävarten vain että saisi jotain tehdä tai sanoa
— ettei tukehtuisi. On kamala olla, kun ei ukko syytä mistään, sanoo
vain; kysyy vain, ja menee pois. Mutta ei Pekankaan itsetunto salli
huutaa menijää takaisin. Hän tuijottaa ukon perään, kiristellen
hampaitaan. Vasta sitte kun toinen on jo kadonnut nurkan taakse,
alkaa Pekka herätä. Hän karjasee mielettömästi, alkaen sitte
nyrkeillään piestä talojen seiniä, kunnes veri tihkuu rystysistä. Pekan
on niin paha olla että tämä typerä riehunta virkistää häntä — torjuu
pois tyhjyydentuntoa ja vaimentaa lähestyvän itsesyytöksen askelia.

Kesken kaiken näkyy, räntäsateen ohetessa, kadun päässä


miehen hahmo, joka lähenee. Se ei voi olla mikään muu kuin poliisi.
Pekka, joka on kylliksi sekaisin päästään, saa silloin jalat alleen.
Vaistomainen poikavuosilta periytynyt poliisikammo, ja omituinen
uusi rikollisuuden aavistus, jouduttavat hänet sukkelasti lähimmästä
portista sisälle ja sieltä edelleen aidan yli, seuraavalle pihamaalle. Ei
kuulu ketään jälessä tulevaksi. Pekka istahtaa kärryn aisalle,
pyöritellen neuvottomana päätään. Sitte alkaa hän pyyhkiä verta
käsistään, huomaa samalla pitkän kaulahuivinsa, ja maiskauttaa
suutaan kuin olisi se makeaakin syötävää. Mitäs tekee hän? Ei
muuta kuin tempaisee kaulahuivinsa, solmiaa sen päät yhteen, tekee
siitä silmukan, ja sovittelee sen kaulaansa. Katselee sitte
ympärilleen. Vesirännissä näkyy mukava koukku. Siihen Pekka
kiinnittää huivin toisen pään, ja rupeaa riipuksiin. Sylkäisee vielä
kerran. Oikaisee sitte koipensa eteenpäin.

Tulee kai paha olla, sillä pian alkavat jalat uudelleen haparoida
maata. Kädet tarraavat vesiränniin. Pekka nousee riipuksista
sukkelasti jaloilleen, repäisee huivin kaulastaan, ja hengittää syvään.

— Hyi hitto, kun olin tukehtua, mutisee hän itsekseen, vieläpä


haparoi seinäviereltä kouraansa lumisohjua, jolla hieroo ohimoltaan
ja kaulaansa. — Ei minusta näy olevan mihinkään, ei edes tähän.
Täytyy keksiä joku parempi konsti.

Mutta toisellaisiakin ääniä alkaa kuulua Pekan mielessä. Siellä ei


suinkaan ole tyyntä tyhjyyttä, vaan siellä pauhaa ja poreilee. Siellä
syyttää! Ja sepä ääni olikin ensimmäinen, jonka hänen järkkynyt
mielensä äsken tajusi. Siitä johtui tuo hillitön halu ottaa itsensä
hengiltä, heti, siekailematta. — Nyt sanoo jo toinen ääni: raukka,
sinä yrität paeta. Kolmas sanoo: syyllinen ei tarvitse paljoa
uskallusta kuollakseen, mutta kyllä elääkseen. Niin kuuluu monta
ääntä, ristiriitaisia keskenään, enimmät syyttäviä, toiset
lohduttaviakin. Ja Pekka tulee iloiseksi, voimasta iloiseksi, sillä kaikki
näivettynyt itsetarkastelu ja entisyyteen tuijotus on poissa hänen
sielustaan. Siellä poreilee ja liikkuu. Sieltä välähtää aivoihin kirkas
ajatusyhdistelmä, niin kirkas että se hohtaa kuin otsaan kirjoitettuna:

Narri on se, joka luulee että kuolema on meitä varten. Se ei ole


meitä, vaan me sitä varten. Elämä on meitä varten. Uskalla elää,
uskalla kärsiä, uskalla kantaa tekojesi seuraukset, uskalla nöyrtyä,
uskalla rakastaa! — eikä rakastella.

Pekka on taasen istahtanut kärrynaisalle. Hänen rinnassaan


liikahtelee ja kihelmöi oudosti. Se on itkua, joka vastustamattomasti
pisaroi esille. Pilvet ovat jo lakanneet satamasta, mutta Pekka istuu
aisalla, katsellen miten kyyneleet tipahtelevat lumisohjuun. Ei niitä
monta tule, eivätkä ne sokaise näköä; joku vain silloin tällöin
kierähtää esille ja noruu nenänpäähän, josta Pekka niitä sitte
puhaltelee maahan. — Mitkään eläimet eivät osaa itkeä, ihminen
vain; ja Pekasta on lohdullista olla yksi heistä, ei huonompi jos ei
parempikaan, yksi vain tällainen.

Kun ne puolikymmentä pisaraa ovat heruneet, mitä tuleman piti,


eikä nenänpäästä, vaikka siihen kuin puhaltelisi, erkane enään
yhtään pisaraa, herpoutuu Pekka ihmettelemään tämän itkun syytä.
Ei sitä voi ymmärtää. Mutta Pekka tuntee taasen olevansa Pekka, ei
tosin entinen, koskei enään haluakkaan olla entinen, ei uusi, koskei
kukaan voi olla uusi; onpahan vain kuin itsensä löytänyt. On iloinen
siitä että tässä istuu ja hengittää, että on tehnyt tyhmyyksiä ja että
niitä tulevaisuudessakin tietysti tekee. On tyytyväinen siitä että on
ollut vastuksia, ja tulee vastakin olemaan. On onnellinen siitä että on
rakastanut, ja yhä — niin, varmasti — siinä on jotain uutta:
syvemmin kuin ennen.

Pekka päättää hetikohta lähteä etsimään Lahjaa.

— Omituista, ajattelee Pekka kadulle tullessaan, miten passiivista


on ollut minun suhteeni Lahjaan. Olen melkein itsetiedottomasti
luisunut hänelle, ensin erään daamin sylistä, sitte kuoleman. Ja nyt
olisi ilman Lahjan pakoa tapahtunut kaiketi taasen samallatapaa.
Muut ovat valloituksia, hän on kohtalo, joka vastustamattomasti
vetää puoleensa. Hän on ainoa, joka ei kysy mitään, luottaa vain ja
uhrautuu. — Olisikohan tämä pakokin hänen puoleltaan minulle
annettu uhri-lahja? Sellaista tekoa ei keneltäkään muulta voisi
odottaa, häneltä ehkä. Se olisi yliluonnollista, eli, sanotaan suoraan;
luonnotonta. Luonnosta viis! se ei kuulu minulle, mutta tämä kuuluu.
Minä otan sen vastaan, minä tahdon sen, ja syleilen sitä Lahjana. En
päästä häntä mihinkään, en edes kuolemaan, jos nimittäin niin
hullusti on että hänellä olisi sellainen halu. En päästä. Jos ennen
olen hänelle vain luisunut, niin nyt otan hänet.
XVIII

Pekka: Näet että tulen sittenkin. Et pääse minua pakoon. Minä


tahdon sinut.

Lahja: Ei, ei. Mene pois.

Pekka: Tuomitsetko minua?

Lahja: En.

Pekka: Pitäisikö minun tuomita itseäni?

Lahja: Ei.

Pekka: Olenko tehnyt jotain pahaa?

Lahja: En tiedä.

Pekka: En minäkään tiedä. — Miksi siis tämä pako?

Lahja: Sinä olet ollut minun epäjumalani.

Pekka: Ja nyt se luhistui?

Lahja: Niin.
Pekka: Siinä ainakaan ei ole mitään pahaa. Päinvastoin siinä
vasta lienee kylvetty meidän onnemme itu. — Sinä luhistuit minun
silmissäni jo aikoja sitte, muutamana juhannusyönä. Mutta minä
iloitsin siitä. Sinä tulit silloin ihmiseksi. Etkö nyt iloitse siitä että
minäkin olen vain ihminen — parempi siis kuin epäjumala?

Lahja: En tiedä. — On toinenkin syy, mutta sitä en voi sanoa.

Pekka: Tahdoit antaa minulle vapauteni takaisin, tahdoit uhrautua?


Niinkö?

Lahja: Niin.

Pekka: Rakas, sillä olisit saattanut musertaa minut, ja niin olikin


vähällä käydä. — Mihin sinä olisit mennyt?

Lahja: Pois.

Pekka: Etkö arvannut että minä olisin tullut mukanasi, vaikka


mullan rakoon asti?

Lahja: Olisihan sinulle jäänyt Taimi. Minä aijoin sittenkin jättää


hänet sinulle.

Pekka: Taimi ei merkitse minulle niin paljon kuin sinulle. Minä en


välitä lapsista ja kapaloista. Rakastaja minä lopultakin olen
enemmän kuin isä.

Lahja: Eikö Taimi ole sinulle rakas?

Pekka: On kyllä, sentakia että sinä olet sen äiti. Siten te olette
minulle samantapainen asia kuin kristityille Uusi Testamentti.
Lahja: Olemmeko me sinulle asioita, eli asia? Mikä sen asian nimi
sinun kielelläsi on?

Pekka: Kutsu sitä vaikka lahjaksi, mutta nyt vain pienellä


kirjaimella, sillä silloin se minusta merkitsee enimmän.

Lahja: Nyt en minä ymmärrä sinua.

Pekka; Ei se ole tarpeenkaan. Eivät ketkään ihmiset ymmärrä


toisiaan, mutta voivat silti rakastaa. — Muistathan että kerran sanoin
tarvitsevani vielä paljon oppia tässä asiassa. Mutta minusta tuntuu
nyt ettei siinä oppia tarvitakkaan, vain uskoa. — Vieläkö sinä uskot
minuun, tarkotan minuun ihmisenä, ei epäjumalana?

Lahja: Kyllä.

Pekka: Rajattomasti?

Lahja: Niin.

Pekka: Luulenpa että voimme heti palata kotia. Pue päällesi; minä
puen
Taimin. Juna lähtee tuossa tuokiossa.

Lahja: Mitähän tästä tulee? Tuntuu niin oudolta kuin olisi edessä
uusi elämä.

Pekka: Ei ole mitään vanhaa ja uutta elämää, mutta kyllä


vaillinainen ja täysi elämä. Puhuimme kerran kesästä, meidän
kesästämme. Se oli kovin lyhytnäköistä. Nyt minä juhlin sinussa
koko elämääni. Sinussa näen minä kaikkeuden. Eikö totta?
kaikkeuden voi nähdä missä tahansa. Minä näen sen sinussa. —
Sinussa on siis minulle annettu kaikki.
Lahja: Nyt sinä liiottelet.

Pekka: En liiottele. Minulla on kaikki, sellaistakin, jota en muinoin


luullut koskaan voivani omistaa. — Kun olen saattanut teidät kotia,
arvaappas mitä senjälkeen ensiksi teen?

Lahja: Rupeat pohtimaan sitä iänikuista höyrykattilaasi,

Pekka: Kas veitikkaa! — Ei, ei niin. Mutta kaikkein ensiksi, vaikka


nyt onkin kelirikon aika, pistäyn Jyrkänkoskella — viemässä kukkia
äitini haudalle. Ja sitte minä otan sinut, ymmärrätkös? Ja sitte tulkoot
vasta työt.
XIX

Pekka makaa hangella, valkoisella hangella, jolle aurinko paistaa.


Hänellä on valkea hiihtopusero päällään, mutta se on veressä.
Hänen suksensa ovat eri tahoilla, toinen pitkänään toinen pystyssä.
Toinen sompasauva riippuu aidalla, toista ei näy. Aidan takana
kohoaa sylenkorkuinen kallioseinä. Sieltä onnellinen Pekka on
laskenut mäkeä, ja pudonnut aidanseipääseen, joka on puhkaissut
hänen vatsansa.

Heloittavalla keväthangella hän makaa. — Lumi voi olla haurasta


kiteinä, mutta haukena se on väkevää ja juhlallista, etenkin silloin
kun se auringossa säihkyy, valontäyteisen taivaankuvun sitä
vartioidessa. Hanki patjana ja taivaankansi peittona on Pekalla. Pari
mäntyä värähtelee sivumpana heikossa tuulen hengessä. Aidan
vierellä yksinäinen riippakoivu heiluttelee alastomia ritvojaan,
odottaen kesää. Hangen alla kaikki niityn ruohot nukkuvat, odottaen
nekin kesää.

Hangella nukkuja ei liiku, eikä nuku sellaista unta, josta herätään.


Ei hän kysy enään koskaan: miksi? Eikä hän enään odotakkaan
mitään. Mutta hänen vierellään seisoo valkea olento, joka näyttää
odottavan.
Pekka: Kuka sinä olet, joka vielä tulet minun luokseni? Minä
pelkäsin että tähän voisi tulla surullisia ihmisiä ja minut voitaisi viedä
kuulemaan voivotuksia. Mutta sinun vaatteesi ovat valkeat, ja sinun
kasvosi näyttävät iloisilta. Kuka olet sinä?

Valkea: Etkö tunne minua?

Pekka: En tunne. Mutta sinä olet niinkuin se pouta, joka kerran


nauroi minulle kun minä luulin olevani minä. Ja samalla sinä olet
kuitenkin niinkuin Lahja, ja sinun hymysi on niinkuin minun lapseni,
joka jäi aamulla nukkumaan. Sinussa on kaikkea sitä, mitä minä olen
rakastanut. Signeäkin sinussa on, ja Elinaa. Vaaditko sinä minua
tilille?

Valkea: Näytänkö minä tuomarilta?

Pekka: Et näytä. Mutta minusta tuntuu että koko minun elämäni on


sinussa.

Valkea: Minä olen sinun elämäsi.

Pekka: Noin valkea! Mihin ovat tahrat jääneet?

Valkea: Ne olet sinä itse pessyt pois.

Pekka: Sehän on mahdotonta. Miten minä siihen olisin kyennyt?

Valkea: Näytpä kuitenkin kyenneen. — Nyt me lähdemme. Tule!

Pekka: Mihin minut viet?

Valkea: Elämään.

Pekka: Tuonnekko, josta vastikään pääsin pois?


Valkea: Sinne juuri, vaikka se, mitä sinä tarkotat, oli vain pieni
hiihtoretki. Minä vien sinut sinne, missä sinä et omista mitään, mutta
jossa kaikkeus omistaa sinut. Vien sinut vapauteen. — Katso, minä
puhallan sinut tomuksi.
*** END OF THE PROJECT GUTENBERG EBOOK SULJETTUJEN
OVIEN TAKANA ***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying copyright
royalties. Special rules, set forth in the General Terms of Use part of
this license, apply to copying and distributing Project Gutenberg™
electronic works to protect the PROJECT GUTENBERG™ concept
and trademark. Project Gutenberg is a registered trademark, and
may not be used if you charge for an eBook, except by following the
terms of the trademark license, including paying royalties for use of
the Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is very
easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund from
the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law in
the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name
associated with the work. You can easily comply with the terms of
this agreement by keeping this work in the same format with its
attached full Project Gutenberg™ License when you share it without
charge with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the terms
of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears, or
with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning of
this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1 with
active links or immediate access to the full terms of the Project
Gutenberg™ License.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or expense
to the user, provide a copy, a means of exporting a copy, or a means
of obtaining a copy upon request, of the work in its original “Plain
Vanilla ASCII” or other form. Any alternate format must include the
full Project Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt that
s/he does not agree to the terms of the full Project Gutenberg™
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like