1.5 Snail Bait’s Humble Beginning
Figure 1.16 shows Snail Bait’s initial set of files. Throughout this book we add many more files, but for now all we need is an HTML file to define the structure of the game’s HTML elements, a CSS file to define the visual properties for those elements, a JavaScript file for the game’s logic, and two images, one for the background and another for the runner.
Figure 1.16 Snail Bait’s initial files
Figure 1.17 shows the starting point for the game, which simply draws the background and the runner. To start, the runner is not a sprite; instead, the game draws her directly.
Figure 1.17 Drawing the background and runner
Example 1.3 lists the starting point for the game’s HTML, which is just a distilled version of the HTML in Example 1.2.
Example 1.3 The starting point for Snail Bait’s HTML
<!DOCTYPE
html
>
<html>
<head>
<title>
Snail Bait</title>
<link
rel
=
'stylesheet'
href
=
'snailbait.css'
/>
</head>
<body>
<div
id
=
'snailbait-arena'
>
<canvas
id
=
'snailbait-game-canvas'
width
=
'800'
height
=
'400'
>
Your browser does not support HTML5 Canvas.</canvas>
</div>
<!-- JavaScript................................................--><script
src
=
'snailbait.js'
></script>
</body>
</html>
Initially, the arena contains only the game’s canvas, which is 800 pixels wide by 400 pixels high and has a thin blue border. Example 1.4 shows the starting point for Snail Bait’s CSS.
Example 1.4 The starting point for Snail Bait’s CSS
body{
background:
cornflowerblue;
}
#snailbait-arena
{
margin:
0
auto;
margin-top:
50px;
width:
800px;
height:
400px;
}
#snailbait-game
-canvas
{
border:
1.5px
solid
blue;
}
Example 1.5 shows the starting point for Snail Bait’s JavaScript.
Example 1.5 The starting point for Snail Bait’s JavaScript
var
canvas=
document.
getElementById
(
'snailbait-game-canvas'
),
context=
canvas.
getContext
(
'2d'
),
background=
new
Image
(),
runnerImage=
new
Image
();
function
initializeImages
()
{
background.
src=
'images/background.png'
;
runnerImage.
src=
'images/runner.png'
;
background.
onload=
function
(
e)
{
startGame
();
}
;
}
function
startGame
()
{
draw
();
}
function
draw
()
{
drawBackground
();
drawRunner
();
}
function
drawBackground
()
{
context.
drawImage
(
background,
0
,
0
);
}
function
drawRunner
()
{
context.
drawImage
(
runnerImage,
50
,
280
);
}
// Launch game.........................................................initializeImages
();
The preceding JavaScript accesses the canvas element and subsequently obtains a reference to the canvas’s 2D context. The code then draws the background and runner by using the three-argument variant of drawImage() to draw images at a particular location in the canvas.
The game starts when the background image loads. For now, starting the game entails simply drawing the background and the runner.