<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Game Code SchoolGame Code School -  &#187; Kotlin</title>
	<atom:link href="https://gamecodeschool.com/category/kotlin/feed/" rel="self" type="application/rss+xml" />
	<link>https://gamecodeschool.com</link>
	<description>Game Coding for Beginners</description>
	<lastBuildDate>Wed, 29 Jan 2025 11:28:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.2.38</generator>
	<item>
		<title>Coding a Space Invaders Game in Kotlin</title>
		<link>https://gamecodeschool.com/kotlin/coding-a-space-invaders-game-in-kotlin/</link>
		<comments>https://gamecodeschool.com/kotlin/coding-a-space-invaders-game-in-kotlin/#comments</comments>
		<pubDate>Mon, 04 Mar 2019 14:24:46 +0000</pubDate>
		<dc:creator><![CDATA[John Horton]]></dc:creator>
				<category><![CDATA[Kotlin]]></category>

		<guid isPermaLink="false">http://gamecodeschool.com/?p=16045</guid>
		<description><![CDATA[This Kotlin beginner tutorial is an attempt to introduce readers with just a basic knowledge of Kotlin to game programming. Space Invaders is an all-time classic and my first experience with a video game outside of the home. When my dad would take me to the pub as a kid I wasn&#8217;t thinking about the [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>This Kotlin beginner tutorial is an attempt to introduce readers with just a basic knowledge of Kotlin to game programming. Space Invaders is an all-time classic and my first experience with a video game outside of the home. When my dad would take me to the pub as a kid I wasn&#8217;t thinking about the coke or the crisps I might get but whether or not I would be granted 10p to have a game of Space Invaders.</p>
<p><a href="https://www.patreon.com/Gamecodeschool"><img class="alignleft size-full wp-image-16509" src="https://gamecodeschool.com/wp-content/uploads/2015/01/patreon1.jpg" alt="patreon" width="125" height="38" /></a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>I remember the thrill the first time I cleared a wave. I had been struggling to do it for a long time until I saw someone else do it and copied their technique. Rather than take out all the lowest invaders, the better tactic is to pick off a column at a time from either the left or the right. This way you can delay the invaders going lower and it is also easier to stay targeted on one column than it is to accurately move from one column to the next. The other trick was to blast a hole through the middle of a shelter and pick them off from relative safety.</p>
<p>While this tutorial will not have all the features or quite the same aesthetic as the original; it will enable the player to shoot through the shelters and the same column attack pattern is viable too. I hope you enjoy building this game. I will also be doing a video version of this tutorial so why not visit <a href="https://www.youtube.com/channel/UCY6pRQAXnwviO3dpmV258Ig/videos">my YouTube channel</a>.</p>
<h2>Who this tutorial is for</h2>
<p>The tutorial assumes you already know basic Kotlin like what a property is and how to create a class but I do give fairly in-depth explanations of most of the code. You should be able to follow along provided you have just basic knowledge of any object-oriented programming language, perhaps gained from the Java tutorials on this site.</p>
<h2>The structure of the code</h2>
<p>The project consists of six classes which are <a href="https://github.com/EliteIntegrity/Kotlin-Invaders">available on GitHub</a> :</p>
<ul>
<li><pre class="crayon-plain-tag">KotlinInvadersActivity</pre>: This class is the entry point to the game and will initialize an instance of the class that does all the work as well as starts and stops the game loop/thread when the player starts and stops the app.</li>
<li><pre class="crayon-plain-tag">KotlinInvadersView</pre>: This class is the class that does all the work. In fact, it probably does too much work and we can discuss that a bit at the end of the tutorial. It will hold instances of all the other classes and control their updating, interaction, and drawing to the screen. It will also handle the player&#8217;s screen touches.</li>
<li><pre class="crayon-plain-tag">PlayerShip</pre>: This class will respond to the player&#8217;s touches and represent the ship that the player uses.</li>
<li><pre class="crayon-plain-tag">Invader</pre>: We will instantiate dozens of these to build a whole army of arm-flapping, bullet-shooting Space Invaders. They will move from left to right drop down then go back again and repeat; until destroyed or landed on the Earth.</li>
<li><pre class="crayon-plain-tag">DefenceBrick</pre>: Dozens of instances of this class will be instantiated in order to build destructible shelters that the player can hide behind and shoot a gap in to take cover while dealing damage.</li>
<li><pre class="crayon-plain-tag">Bullet</pre>: We will use this class for both the player&#8217;s single reusable bullet and the invaders will have a reusable <pre class="crayon-plain-tag">ArrayList</pre> full of bullets.</li>
<li><pre class="crayon-plain-tag">SoundPlayer</pre>: A very simple class that uses the <pre class="crayon-plain-tag">SoundPool</pre> API to play the various beeps and explosions we need.</li>
</ul>
<h2>Starting the Kotlin Space Invaders tutorial</h2>
<p>Create a new project in Android Studio, I called mine <pre class="crayon-plain-tag">Kotlin Invaders</pre> and be sure to check the box to Include Kotlin Support. I named the Activity; <pre class="crayon-plain-tag">KotlinInvadersActivity</pre> and used the Empty Activity template without backward compatibility and without generating a layout file.</p>
<p>For Kotlin Invaders, we will use some bitmaps from external graphics files for the invaders and player ship and use the <pre class="crayon-plain-tag">Canvas</pre> class <pre class="crayon-plain-tag">drawRect</pre> function to represent the bullets and the bomb shelters.</p>
<p>Before we get coding we want to add the player ship graphic and two different graphics for the two frames of animation for our invader to our project files so we can use them in our code. The graphics are white so they are displayed below on a blue background. Here they are.</p>
<div class="fusion-table table-2">
<table width="100%">
<thead>
<tr>
<th>
<p><div id="attachment_11992" style="width: 100px" class="wp-caption aligncenter"><a href="http://gamecodeschool.com/wp-content/uploads/2015/05/playership.png"><img class="size-full wp-image-11992" src="http://gamecodeschool.com/wp-content/uploads/2015/05/playership.png" alt="The Space Invaders player ship graphic" width="90" height="55" /></a><p class="wp-caption-text">The Space Invaders player ship graphic</p></div></th>
<th>
<p><div id="attachment_12010" style="width: 101px" class="wp-caption aligncenter"><a href="http://gamecodeschool.com/wp-content/uploads/2015/05/invader1.png"><img class="size-full wp-image-12010" src="http://gamecodeschool.com/wp-content/uploads/2015/05/invader1.png" alt="The first frame of animation for the invader" width="91" height="66" /></a><p class="wp-caption-text">The first frame of animation for the invader</p></div></th>
<th>
<p><div id="attachment_12011" style="width: 101px" class="wp-caption aligncenter"><a href="http://gamecodeschool.com/wp-content/uploads/2015/05/invader2.png"><img class="size-full wp-image-12011" src="http://gamecodeschool.com/wp-content/uploads/2015/05/invader2.png" alt="The second frame of animation for the invader" width="91" height="66" /></a><p class="wp-caption-text">The second frame of animation for the invader</p></div></th>
</tr>
</thead>
</table>
</div>
<p>You can download them by right-clicking on the images and then selecting the <span style="color: #008000;">Save image as&#8230;</span> option. Just make sure the file names are kept the same. They are named <span style="color: #008000;">playership.png</span>, <span style="color: #008000;">invader1.png,</span> and <span style="color: #008000;">invader2.png</span>. Add the graphics to the <span style="color: #008000;">res/drawable</span> folder via the project explorer window.</p>
<h3>The sound</h3>
<p>We will have a menacing two-tone sound to represent the invader&#8217;s movement. This sound will speed up as the invaders speed up. I have called these two sounds &#8220;uh&#8221; and &#8220;oh&#8221; because if we were attacked by invaders we might say, &#8220;uh oh&#8221;. We also need sounds for shooting a bullet, the player being hit, an invader being hit and a bomb shelter being hit.</p>
<p>Of course, we need to add the sound files to our project. You can create your own or download mine by right-clicking on the files listed below. Just make sure you use exactly the same file names. You can also listen to each of the sounds by using the media controls below each of the links.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/05/uh.ogg">uh.ogg</a></p>
<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
<audio class="wp-audio-shortcode" id="audio-16045-1" preload="none" style="width: 100%; visibility: hidden;" controls="controls"><source type="audio/ogg" src="http://gamecodeschool.com/wp-content/uploads/2015/05/uh.ogg?_=1" /><a href="http://gamecodeschool.com/wp-content/uploads/2015/05/uh.ogg">http://gamecodeschool.com/wp-content/uploads/2015/05/uh.ogg</a></audio>
<p>&nbsp;</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/05/shoot.ogg">shoot.ogg</a></p>
<audio class="wp-audio-shortcode" id="audio-16045-2" preload="none" style="width: 100%; visibility: hidden;" controls="controls"><source type="audio/ogg" src="http://gamecodeschool.com/wp-content/uploads/2015/05/shoot.ogg?_=2" /><a href="http://gamecodeschool.com/wp-content/uploads/2015/05/shoot.ogg">http://gamecodeschool.com/wp-content/uploads/2015/05/shoot.ogg</a></audio>
<p>&nbsp;</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/05/playerexplode.ogg">playerexplode.ogg</a></p>
<audio class="wp-audio-shortcode" id="audio-16045-3" preload="none" style="width: 100%; visibility: hidden;" controls="controls"><source type="audio/ogg" src="http://gamecodeschool.com/wp-content/uploads/2015/05/playerexplode.ogg?_=3" /><a href="http://gamecodeschool.com/wp-content/uploads/2015/05/playerexplode.ogg">http://gamecodeschool.com/wp-content/uploads/2015/05/playerexplode.ogg</a></audio>
<p>&nbsp;</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/05/oh.ogg">oh.ogg</a></p>
<audio class="wp-audio-shortcode" id="audio-16045-4" preload="none" style="width: 100%; visibility: hidden;" controls="controls"><source type="audio/ogg" src="http://gamecodeschool.com/wp-content/uploads/2015/05/oh.ogg?_=4" /><a href="http://gamecodeschool.com/wp-content/uploads/2015/05/oh.ogg">http://gamecodeschool.com/wp-content/uploads/2015/05/oh.ogg</a></audio>
<p>&nbsp;</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/05/invaderexplode.ogg">invaderexplode.ogg</a></p>
<audio class="wp-audio-shortcode" id="audio-16045-5" preload="none" style="width: 100%; visibility: hidden;" controls="controls"><source type="audio/ogg" src="http://gamecodeschool.com/wp-content/uploads/2015/05/invaderexplode.ogg?_=5" /><a href="http://gamecodeschool.com/wp-content/uploads/2015/05/invaderexplode.ogg">http://gamecodeschool.com/wp-content/uploads/2015/05/invaderexplode.ogg</a></audio>
<p>&nbsp;</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/05/damageshelter.ogg">damageshelter.ogg</a></p>
<audio class="wp-audio-shortcode" id="audio-16045-6" preload="none" style="width: 100%; visibility: hidden;" controls="controls"><source type="audio/ogg" src="http://gamecodeschool.com/wp-content/uploads/2015/05/damageshelter.ogg?_=6" /><a href="http://gamecodeschool.com/wp-content/uploads/2015/05/damageshelter.ogg">http://gamecodeschool.com/wp-content/uploads/2015/05/damageshelter.ogg</a></audio>
<p>Next, using your preferred file browser, go to the <span style="color: #008000;">app/src/main</span> directory in your project and add a folder called <span style="color: #008000;">assets</span>. Now add the sound files to the <span style="color: #008000;">assets</span> folder.</p>
<h2>Coding the Activity class</h2>
<p>The first class we will code is the <pre class="crayon-plain-tag">KotlinInvadersActivity</pre> class. Edit your code to match the following and then we can talk about it.</p>
<p><script src="https://gist.github.com/EliteIntegrity/f46842997e4867b2cd342e8ec20be43e.js"></script>There will be multiple errors in the preceding code because we are instantiating a class (<pre class="crayon-plain-tag">KotlinInvadersView</pre>) that doesn&#8217;t exist yet. We will fix that shortly. The <pre class="crayon-plain-tag">KotlinInvadersActivity</pre> class is the entry point for the game.</p>
<p>When the player taps to run the app, the onCreate function will execute. In the <pre class="crayon-plain-tag">onCreate</pre> function, we use a <pre class="crayon-plain-tag">Display</pre> instance and a <pre class="crayon-plain-tag">Point</pre> instance to capture the resolution of the screen. This is necessary because the range of screens our game could be played on is so varied that we need to adjust our game objects to accommodate.</p>
<p>In the next line of code, we instantiate (or attempt to) our soon-to-be-written class. The thing to notice is what we pass into the constructor. We pass a reference to the <pre class="crayon-plain-tag">Activity</pre> as well as the <pre class="crayon-plain-tag">size</pre> object which contains our screen resolution.</p>
<p>The final line of code in the <pre class="crayon-plain-tag">onCreate</pre> function calls <pre class="crayon-plain-tag">setContentView</pre> to tell Android what to use as the view for this app. We will be using our <pre class="crayon-plain-tag">KotlinInvadersView</pre> instance that we will code soon. The next two functions are <pre class="crayon-plain-tag">onResume</pre> and <pre class="crayon-plain-tag">onPause</pre>. The first is called by the operating system when our app is resuming from a pause; the second is when it has been quit by the user.</p>
<p>Note that <pre class="crayon-plain-tag">onResume</pre> is also called after <pre class="crayon-plain-tag">onCreate</pre> so will execute when the app is started by the user as well as when it resumes from a pause, perhaps when the user got a phone call. The functions simply call <pre class="crayon-plain-tag">resume</pre> and pause on our <pre class="crayon-plain-tag">KotlinInvadersView</pre> instance. </p>
<h2>Coding the Kotlin game engine</h2>
<p>Next, we can code the outline of the <pre class="crayon-plain-tag">KotlinIvadersView</pre> class that we instantiated, passed to <pre class="crayon-plain-tag">setContenView</pre> and called the pause and resume functions from. We will then have an error-free code base and will be able to run the game. <pre class="crayon-plain-tag">KotlinInvadersView</pre> is the main class of the app and we will be returning to it throughout the project. To get it started, create a new class called <pre class="crayon-plain-tag">KotlinInvadersView</pre> and code it as shown next.</p>
<p><script src="https://gist.github.com/EliteIntegrity/145921b2c6b1fced0d213ff97ce58422.js"></script></p>
<p>In the class declaration, we can see that we receive the <pre class="crayon-plain-tag">Context</pre> and the <pre class="crayon-plain-tag">Point</pre> from the <pre class="crayon-plain-tag">Activity</pre> class just as we should expect. Also, notice that we inherit from <pre class="crayon-plain-tag">SurfaceView</pre>. The <pre class="crayon-plain-tag">SurfaceView</pre> class inherits from <pre class="crayon-plain-tag">View</pre> and is therefore suitable to pass to <pre class="crayon-plain-tag">setContentView</pre> which we did back in the <pre class="crayon-plain-tag">KotinInvadersActivity</pre> class. Also, notice we are implementing the <pre class="crayon-plain-tag">Runnable</pre> interface. We will be running all our game logic and drawing code in a separate thread to the main user interface interaction. This way our game will run at around 60 frames of updates and animations per second while still listening and then responding to the player&#8217;s interactions. The rest of the preceding code sets up this game loop.</p>
<p>The properties include a <pre class="crayon-plain-tag">Thread</pre> instance called <pre class="crayon-plain-tag">gameThread</pre>. When we pass the <pre class="crayon-plain-tag">KotlinInvadersView</pre> instance to the <pre class="crayon-plain-tag">Thread</pre> constructor the OS will be able to call the overridden <pre class="crayon-plain-tag">run</pre> function. The <pre class="crayon-plain-tag">run</pre> function must be overridden because we implemented the <pre class="crayon-plain-tag">Runnable</pre> interface. The <pre class="crayon-plain-tag">run</pre> function is the basis of the game loop.</p>
<p>There are two <pre class="crayon-plain-tag">Boolean</pre> properties called <pre class="crayon-plain-tag">playing</pre> and <pre class="crayon-plain-tag">paused</pre> and they will be used to control when we execute certain parts of the game loop.</p>
<p>Next, we have a <pre class="crayon-plain-tag">Canvas</pre> and a <pre class="crayon-plain-tag">Paint</pre> instance which together are used to draw bitmaps(like the invader graphics) and primitives(like the bullets and bomb shelters).</p>
<p>The <pre class="crayon-plain-tag">score</pre>, <pre class="crayon-plain-tag">waves</pre>, <pre class="crayon-plain-tag">lives</pre>, and <pre class="crayon-plain-tag">highScore</pre> properties do as their names imply and keep track of the player&#8217;s progress including saving their best-ever performance.</p>
<p>The <pre class="crayon-plain-tag">menaceInterval</pre> property is the amount of time in milliseconds that we want to wait in between each flap of the invader&#8217;s arms and each playing of the uh or oh sound. The reason it is a <pre class="crayon-plain-tag">Long</pre> is that we will do calculations using other variables that are also type <pre class="crayon-plain-tag">Long</pre>. The <pre class="crayon-plain-tag">uhOrOh</pre> <pre class="crayon-plain-tag">Boolean</pre> tracks whether the next sound will be uh or oh and <pre class="crayon-plain-tag">lastMenaceTime</pre> tracks the time we last menaced the player. This property is initialized by calling <pre class="crayon-plain-tag">System.currentTimeMillis</pre> which returns the number of milliseconds since the start of January 1970. This number is obviously going to be quite big (understatement) and is why we use the <pre class="crayon-plain-tag">Long</pre> type. If you want to find out why we use this measurement you can find out more here.</p>
<p><a href="https://www.epochconverter.com/">The Unix epoch</a>.</p>
<p>The <pre class="crayon-plain-tag">prepareLevel</pre> function is currently empty but we will be calling it every time we need to set up a wave of invaders. As we code the various game objects we will return to this function to initialize many of them.</p>
<p>The <pre class="crayon-plain-tag">run</pre> function is the brain of the operation. It is called by the operating system when it is our thread&#8217;s turn to execute. You can see inside the <pre class="crayon-plain-tag">run</pre> function that all the code is wrapped in a <pre class="crayon-plain-tag">while</pre> loop that executes when <pre class="crayon-plain-tag">playing</pre> is true and inside that <pre class="crayon-plain-tag">while</pre> loop we only call the <pre class="crayon-plain-tag">update</pre> function when <pre class="crayon-plain-tag">paused</pre> is false. Potentially, in fact, most of the time, we will call <pre class="crayon-plain-tag">update</pre> and then <pre class="crayon-plain-tag">draw</pre> on most executions of the thread. We have two variables <pre class="crayon-plain-tag">fps</pre> and <pre class="crayon-plain-tag">startFrameTime</pre> and they are used to calculate how long it took for the current pass through the <pre class="crayon-plain-tag">run</pre> function. The value stored in <pre class="crayon-plain-tag">fps</pre> at the end of each pass through the loop is how many frames per second would be achieved if every frame took the same amount of time as this one. We will see soon how we pass this value to each of our game objects so they can use it and work out how far to move each frame of animation. The code at the end of the <pre class="crayon-plain-tag">run</pre> function which performs this calculation is wrapped in an <pre class="crayon-plain-tag">if</pre> statement because if <pre class="crayon-plain-tag">timeThisFrame</pre> is ever zero the division calculation would crash the game. It is worth studying the <pre class="crayon-plain-tag">run</pre> function because it is key to understanding how everything else works.</p>
<p>The <pre class="crayon-plain-tag">update</pre> function (that is called from the <pre class="crayon-plain-tag">run</pre> function) is empty for now but notice its one parameter is <pre class="crayon-plain-tag">fps</pre> so that when it updates all the game objects it can also be passed this vital information.</p>
<p>The <pre class="crayon-plain-tag">draw</pre> function (that is also called from the <pre class="crayon-plain-tag">run</pre> function) unsurprisingly is where we will do all the drawing. The code that was added within sets up the basics ready to draw the game objects. First, the entire code of the function is wrapped in an <pre class="crayon-plain-tag">if</pre> statement that determines whether <pre class="crayon-plain-tag">holder.surface.isValid</pre> is true. If it is it means that we are able to draw to the area of memory that holds the graphics. The next step is to call <pre class="crayon-plain-tag">canvas = holder.lockCanvas</pre> that guarantees that some other process, perhaps the OS cannot also draw to this surface at the same time. We can now proceed to do some drawing.</p>
<p>The <pre class="crayon-plain-tag">canvas.drawColor</pre> call draws a color to the entire screen. The color drawn is determined by the ARGB value. In this case, we pass in <pre class="crayon-plain-tag">255, 0, 0, 0</pre>. This is full opacity black as seen in the image of the game at the start of this tutorial. If you want to know more about how the ARGB color system works then take a look at this article.</p>
<p><a href="https://en.wikipedia.org/wiki/RGBA_color_space">ARGB/RGBA color space</a>.</p>
<p>Next, the code calls <pre class="crayon-plain-tag">paint.color</pre> setter and this sets the color that will be used in any subsequent function calls using the <pre class="crayon-plain-tag">canvas</pre> and <pre class="crayon-plain-tag">paint</pre> objects. The code passes in <pre class="crayon-plain-tag">255, 0, 255, 0</pre> which is full opacity green which is the color of the bomb shelters. You can see from the comment that follows that this is where we will draw all the game objects.</p>
<p>The next line of code calls <pre class="crayon-plain-tag">paint.color</pre> again and sets the color back to white so we can draw the text for the player&#8217;s HUD. The <pre class="crayon-plain-tag">textSIze</pre> property of paint is set to <pre class="crayon-plain-tag">70f</pre> which is a size that looks good on my current emulator. Obviously, adjust this if you are not happy with the results. Next, we draw some text to the screen using the <pre class="crayon-plain-tag">canvas.drawText</pre> function and passing in a String template that prints the score, remaining lives, and the high score to the top-left of the screen.</p>
<p>The final line of code in the function is <pre class="crayon-plain-tag">holder.unlockCanvasAndPost</pre> which passes all our drawings to be written to the screen. At this point other processes can access the graphics memory- but not for long because we will lock it again in about a sixtieth of a second.</p>
<p>The <pre class="crayon-plain-tag">pause</pre> function is the function that we called from the <pre class="crayon-plain-tag">onPause</pre> function of the <pre class="crayon-plain-tag">Activity</pre> class. This means that every time the player leaves our game, either temporarily or permanently, this function gets called. For now, the only code in it sets <pre class="crayon-plain-tag">playing</pre> to false so that <pre class="crayon-plain-tag">update</pre> isn&#8217;t called anymore and stops the thread so that <pre class="crayon-plain-tag">run</pre> isn&#8217;t called anymore. The code <pre class="crayon-plain-tag">gameThread.join</pre> is the line that does the work and it is wrapped in a <pre class="crayon-plain-tag">try</pre>-<pre class="crayon-plain-tag">catch</pre> block as required. Near the end of this tutorial, we will save the high score to the device storage in this function too.</p>
<p>The <pre class="crayon-plain-tag">resume</pre> function is called by the <pre class="crayon-plain-tag">onResume</pre> function in our <pre class="crayon-plain-tag">Activity</pre> class. This means that every time the player starts our game or resumes it after pausing, this function will be called and the thread will be started, <pre class="crayon-plain-tag">playing</pre> set to true so the <pre class="crayon-plain-tag">while</pre> loop executes and we also call the <pre class="crayon-plain-tag">prepareLevel</pre> function which currently does nothing but will soon set up a wave of invaders, shelters and bullets.</p>
<p>At this stage, we can run the game for the first time. If you run it you will see that the score, lives, and hi-score text are drawn to the top left of the screen.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2019/03/kotlin_space_invaders_1.png"><img class="aligncenter size-full wp-image-16069" src="http://gamecodeschool.com/wp-content/uploads/2019/03/kotlin_space_invaders_1.png" alt="kotlin_space_invaders_1" width="605" height="300" /></a></p>
<h2>Coding the player&#8217;s spaceship</h2>
<p>Let&#8217;s move on to the <pre class="crayon-plain-tag">PlayerShip</pre> class. We will code the class in its entirety but will not make use of all the code until later because we need to write a class to represent the bullets it will fire. Create a new class called <pre class="crayon-plain-tag">PlayerShip</pre> and add the following code to it and then we will review the new code.</p>
<p><script src="https://gist.github.com/EliteIntegrity/d8f1958fe72db5f9647d5f2685f9fb8c.js"></script></p>
<p>The preceding code starts with the class declaration and the constructor receives three properties. The first is a <pre class="crayon-plain-tag">Context</pre> object which is used to create and scale bitmaps. The second and third are <pre class="crayon-plain-tag">Int</pre> values that will contain the horizontal and vertical resolution of the screen. We will use these values to scale and position the ship.</p>
<p>Next, we initialize an instance called <pre class="crayon-plain-tag">bitmap</pre> with a call to <pre class="crayon-plain-tag">BitmapFactory.decodeResource</pre>. The function takes the <pre class="crayon-plain-tag">Context</pre> and the resource ID that represents the image we are using for the player&#8217;s ship. This property is declared as <pre class="crayon-plain-tag">var</pre> because we need to reassign it shortly in the <pre class="crayon-plain-tag">init</pre> block.</p>
<p>We have a property for each of the width and height of the ship. They are initialized arbitrarily but effectively by using the screen resolution divided by <pre class="crayon-plain-tag">20</pre>.  We declare and initialize a <pre class="crayon-plain-tag">RectF</pre> object which holds four <pre class="crayon-plain-tag">Float</pre> values that represent a rectangle. This rectangle can be used for keeping track of and manipulating the position of the ship as well as quickly positioning the bitmap for drawing. The arguments sent to the constructor are derived from the screen&#8217;s resolution and the recently calculated width and height. The preceding logic will position the ship in the center bottom of the screen.</p>
<p>Following on we have a property called <pre class="crayon-plain-tag">speed</pre> which is speed in pixels per second that we want the ship to move at. Shortly we will see how we combine this value with the frames-per-second passed from the <pre class="crayon-plain-tag">update</pre> function in <pre class="crayon-plain-tag">KotlinInvadersView</pre> to achieve a smooth animation when the player moves the ship. The code that comes next sets up a companion object. This means that they are already instantiated and not part of a specific instance- hence why it is called <pre class="crayon-plain-tag">object</pre>. This means that these values will be accessible using the class name as opposed to an instance and will be useful for referring to the constant values assigned to represent moving left, moving right, and stopped. We then initialize the <pre class="crayon-plain-tag">moving</pre> property with the constant value contained in <pre class="crayon-plain-tag">stopped</pre>. The player&#8217;s ship will begin the game stopped, as you might expect.</p>
<p>In the <pre class="crayon-plain-tag">init</pre> block which runs after the constructor and property initializations, the code calls <pre class="crayon-plain-tag">Bitmap.createScaledBitmap</pre> passing in the bitmap instance and the size to scale it to. The result is reassigned to <pre class="crayon-plain-tag">bitmap</pre> itself. Now the bitmap is ready to be drawn with the correct graphic that represents the ship and also the correct scale.</p>
<p>The <pre class="crayon-plain-tag">update</pre> function does most of the work for this class. The code is structured into an <pre class="crayon-plain-tag">if</pre>-<pre class="crayon-plain-tag">else</pre>-<pre class="crayon-plain-tag">if</pre> shape. The first <pre class="crayon-plain-tag">if</pre> executes when <pre class="crayon-plain-tag">moving</pre> is set to <pre class="crayon-plain-tag">left</pre> and the player&#8217;s ship position (obtained from <pre class="crayon-plain-tag">position</pre>) is further right than the horizontal coordinate zero. This means that the code to keep moving left will only execute when the ship is not about to disappear to the far left (like the Democratic party) side of the screen. The code inside the <pre class="crayon-plain-tag">if</pre> statement subtracts from <pre class="crayon-plain-tag">position.left</pre> based on the speed we want the ship to go and the current frames-per-second as supplied to the function. Remember this happens up to sixty times per second. The values will be manipulated very steadily yet very frequently, creating a fast and smooth animation.</p>
<p>The <pre class="crayon-plain-tag">else if</pre> statement executes when the player is moving right but is not so far right (insert far-right joke for political balance) that it will begin to disappear off of the screen. Outside of the <pre class="crayon-plain-tag">if</pre> blocks the <pre class="crayon-plain-tag">right</pre> property of <pre class="crayon-plain-tag">position</pre> is set using the just-updated <pre class="crayon-plain-tag">left</pre> property and the width of the ship. The <pre class="crayon-plain-tag">position RectF</pre> is now ready to be interacted with for collision detection and for drawing.</p>
<p>Now we can put the <pre class="crayon-plain-tag">PlayerShip</pre> class into action inside the <pre class="crayon-plain-tag">KotlinInvadersView</pre> class. First, add and initialize a new property to the class as shown next.</p>
<p><script src="https://gist.github.com/EliteIntegrity/49a884cfcb7353ed7e658cd5ccd9caa3.js"></script></p>
<p>Next, we will call the <pre class="crayon-plain-tag">update</pre> function of <pre class="crayon-plain-tag">PlayerShip</pre> from the <pre class="crayon-plain-tag">update</pre> function of <pre class="crayon-plain-tag">KotlinInvadersView</pre>.</p>
<p><script src="https://gist.github.com/EliteIntegrity/1aae305ccea9d0a5dd9e78a07eb45def.js"></script></p>
<p>We can now draw the player&#8217;s ship inside the <pre class="crayon-plain-tag">draw</pre> function. Remember that <pre class="crayon-plain-tag">update</pre> and <pre class="crayon-plain-tag">draw</pre> get called up to 60 times per second. So if the code in <pre class="crayon-plain-tag">update</pre> changes the position of the ship it will animate smoothly. Add this code to the <pre class="crayon-plain-tag">draw</pre> function.</p>
<p><script src="https://gist.github.com/EliteIntegrity/1e0951f2e1366fbcab714e4c3ef1dd2e.js"></script></p>
<p>The <pre class="crayon-plain-tag">canvas.drawBitmap</pre> function uses the <pre class="crayon-plain-tag">bitmap</pre> and <pre class="crayon-plain-tag">position</pre> properties from the <pre class="crayon-plain-tag">PlayerShip</pre> class as well as the <pre class="crayon-plain-tag">paint</pre> property to get the bitmap drawing done.</p>
<h2>Coding the space invaders</h2>
<p>Let&#8217;s code the <pre class="crayon-plain-tag">Invader</pre> class. Create a new class called <pre class="crayon-plain-tag">Invader</pre> and add the following code to it.</p>
<p><script src="https://gist.github.com/EliteIntegrity/718dcc96beb892a3c87a180da902ab63.js"></script></p>
<p>The constructor receives a <pre class="crayon-plain-tag">Context</pre> instance which like the <pre class="crayon-plain-tag">PlayerShip</pre> class is used for preparing bitmaps. It also receives four more values. A row and column number along with the horizontal and vertical screen resolution. The last four values will be used to work out the size and starting position of each instance of the class. All we will need to do is decided the whereabouts in our grid of invaders each Invader instance should go and the <pre class="crayon-plain-tag">Invader</pre> class will take care of the rest.</p>
<p>The properties include a <pre class="crayon-plain-tag">width</pre> and <pre class="crayon-plain-tag">height</pre> which are calculated by dividing the resolution by <pre class="crayon-plain-tag">35</pre>. This is arbitrary and you could adjust this for a size that suits you. A better way to do this would be to create a formula based on the physical size in inches, the resolution, and the ratio of width to height of the screen, but this way we get the game done a bit quicker. There is also a <pre class="crayon-plain-tag">padding</pre> property which is used to determine the space in between each invader.</p>
<p>The next property is a <pre class="crayon-plain-tag">RectF</pre> named <pre class="crayon-plain-tag">position</pre>. This is where most of the properties are put to work. The <pre class="crayon-plain-tag">column</pre>, <pre class="crayon-plain-tag">width</pre>, <pre class="crayon-plain-tag">padding</pre>, <pre class="crayon-plain-tag">row</pre>, and <pre class="crayon-plain-tag">height</pre> are all used to determine the left, top, right, and bottom coordinates of the rectangle. As with the <pre class="crayon-plain-tag">PlayerShip</pre> class, the <pre class="crayon-plain-tag">position</pre> property will be used for collision detection, movement, and drawing.</p>
<p>Next, we have some more properties that will probably sound familiar to the <pre class="crayon-plain-tag">PlayerShip</pre> class. The <pre class="crayon-plain-tag">speed</pre>, <pre class="crayon-plain-tag">left</pre>, <pre class="crayon-plain-tag">right</pre> and <pre class="crayon-plain-tag">shipMoving</pre> values will keep track of which direction and how fast the ship is moving. The <pre class="crayon-plain-tag">isVisible Boolean</pre> will keep track of whether we need to bother updating, drawing and doing collision detection on this particular instance.</p>
<p>Following on, in the class there is a <pre class="crayon-plain-tag">companion object</pre> with two <pre class="crayon-plain-tag">Bitmap</pre> instances initialized to <pre class="crayon-plain-tag">null</pre> so that all the instances can share the same bitmaps. One for arms up and one for arms down. There is also a <pre class="crayon-plain-tag">numInvaders</pre> value that will track how many instances are visible and will be quite useful in a few places throughout the codebase.</p>
<p>Proceeding on, in the <pre class="crayon-plain-tag">init</pre> block which follows, both of the <pre class="crayon-plain-tag">bitmap1</pre> and <pre class="crayon-plain-tag">bitmap2</pre> two are initialized using the appropriate graphics and then scaled to fit our previously decided scale. Then <pre class="crayon-plain-tag">numInvaders</pre> value is incremented. Remember <pre class="crayon-plain-tag">numInvaders</pre> is in the companion object and is not a property for each instance and, therefore, will eventually hold the number of instances that are instantiated.</p>
<p>The <pre class="crayon-plain-tag">update</pre> function is nearly identical to the one with the same name in the <pre class="crayon-plain-tag">PlayerShip</pre> class. Depending on whether the invader is heading left or right the <pre class="crayon-plain-tag">position</pre> property is manipulated left or right.</p>
<p>The <pre class="crayon-plain-tag">dropDownAndReverseFunction</pre> will be called from <pre class="crayon-plain-tag">KotlinInvadersView</pre> when an invader touches either the left or right of the screen. The code moves the invader down by a distance equal to its <pre class="crayon-plain-tag">height + padding</pre>. Then the invader is made more dangerous by increasing its speed by 10% + the current wave number divided by 10. This is a quick and dirty formula to make the invaders get faster as they get lower as well as get progressively faster as the player clears more waves. Notice that the wave number is passed in as a parameter.</p>
<p>The <pre class="crayon-plain-tag">takeAim</pre> function is the most complicated function of the class but isn&#8217;t really very technical. The function receives the player&#8217;s horizontal position, length in pixels, and wave number. The function then uses these values to determine how likely it is to take a shot at the player. If the odds look quite low then remember that this will happen for every invader about sixty times every second which adds up fast.</p>
<p>The first <pre class="crayon-plain-tag">if</pre> block determines whether the invader is within a ship&#8217;s width on either side of the player. If it is then the formula is 100 * the number of invaders remaining divided by the wave number. If the outcome of this random number generation is zero then a shot is taken. This means that the fewer invaders remaining, the more vicious they will be, and in addition, the higher the wave number, the more vicious as well.</p>
<p>The second <pre class="crayon-plain-tag">if</pre> block uses a simpler formula to take a shot that has almost no chance of hitting the player but will begin to wear down the bomb shelters and reduce the cover the player has. It is now possible to use the <pre class="crayon-plain-tag">Invader</pre> class. Obviously, we will want a whole bunch of menacing Invader instances. Add these two properties to represent the invaders and control their numbers.</p>
<p><script src="https://gist.github.com/EliteIntegrity/0ec115a983f3be0ed85c5abcd7c4687b.js"></script></p>
<p>Add this code in the <pre class="crayon-plain-tag">prepareLevel</pre> function that will be called each time we need a new wave of invaders including when the thread is first started.</p>
<p><script src="https://gist.github.com/EliteIntegrity/51588208d37d4f65e180fc963d06b62d.js"></script></p>
<p>Next, we can add the following code to the <pre class="crayon-plain-tag">update</pre> function.</p>
<p><script src="https://gist.github.com/EliteIntegrity/223e350263343d864a28707793b63cff.js"></script></p>
<p>In the preceding code, we added a new variable called <pre class="crayon-plain-tag">bumped</pre> and one called <pre class="crayon-plain-tag">lost</pre>. Then the code updated all the Invaders including checking if we need to lower them and reverse their direction. After the updating is completed the value of <pre class="crayon-plain-tag">bumped</pre> is checked and if it is true then the invaders are all moved down one row at the same time as checking if the invaders have reached the bottom of the screen. If they have then the <pre class="crayon-plain-tag">lost</pre> variable is set to true. The <pre class="crayon-plain-tag">lost</pre> variable gets checked and responded to later in the tutorial.</p>
<p>Finally, for the invaders (for now) we will draw them in their updated positions, each frame, in the <pre class="crayon-plain-tag">draw</pre> function.</p>
<p><script src="https://gist.github.com/EliteIntegrity/d5ac681122a5a08dc33c6b3996cdd4a1.js"></script></p>
<p>In the preceding code, we check the value of <pre class="crayon-plain-tag">uhOrOh</pre> to decide which bitmap is used to draw the invaders in the current frame of animation. Currently, this doesn&#8217;t change so the same bitmap will be drawn over and over but we will fix this soon.</p>
<p>Let&#8217;s run the game and see where we are up to.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2019/03/kotlin_space_invaders_2.png"><img class="aligncenter size-medium wp-image-16070" src="http://gamecodeschool.com/wp-content/uploads/2019/03/kotlin_space_invaders_2-300x214.png" alt="kotlin_space_invaders_2" width="300" height="214" /></a></p>
<p>In the image above, if you look closely, there is something missing. Where is the player&#8217;s ship? What has happened is that the screen dimensions that we captured in <pre class="crayon-plain-tag">KotlinInvadersActivity</pre> and then passed to <pre class="crayon-plain-tag">KotlinInvadersView</pre> and subsequently used to position the player&#8217;s ship calculates the resolution of the entire screen and doesn&#8217;t make allowance for the app title which is displayed at the top of the screen. Therefore the player&#8217;s ship is drawn just out of sight at the bottom of the screen. If we make the game use the full screen and hide the title then the ship will become visible. Open the <pre class="crayon-plain-tag">AndroidManifest.xml</pre> file inside the <pre class="crayon-plain-tag">manifests</pre> folder. You need to add two lines of code as shown next.</p>
<p><script src="https://gist.github.com/EliteIntegrity/0892f821242aca5efc7d926dd5d877cf.js"></script></p>
<h2>Making Kotlin Invaders full screen</h2>
<p>Next, I will show you the AndroidManifest.xml file in its entirety so you can identify where the preceding XML code goes.</p>
<p><script src="https://gist.github.com/EliteIntegrity/ecac97d4b435543704449eb54943ce63.js"></script></p>
<p>If you run the game now you should see the player&#8217;s ship parked neatly in the bottom center of the screen.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2019/03/kotlin_space_invaders_3.png"><img class="aligncenter size-medium wp-image-16071" src="http://gamecodeschool.com/wp-content/uploads/2019/03/kotlin_space_invaders_3-300x56.png" alt="kotlin_space_invaders_3" width="300" height="56" /></a></p>
<h2>Coding the Space Invader shelters</h2>
<p>Let&#8217;s move on to the <pre class="crayon-plain-tag">DefenceBrick</pre> class. We will use dozens of instances of this class to construct destructible barriers for the player to hide behind when things get tough. Create a new class called <pre class="crayon-plain-tag">DefenceBrick</pre> and add the following code.</p>
<p><script src="https://gist.github.com/EliteIntegrity/4f5d10cd80fd58d8e65f6fe31f2e35d0.js"></script></p>
<p>In the preceding code, we have a fairly busy constructor which passes in a column and row number as well as a shelter number and the screen resolution.</p>
<p>The properties keep track of whether the instance is visible and a crude but effective calculation is used to decide how wide and high each brick will be. We then use all the constructor parameters and the width and height to initialize a <pre class="crayon-plain-tag">RectF</pre> that will represent the position of the current shelter. Let&#8217;s put the shelters to work in the <pre class="crayon-plain-tag">KotlinInvadersView</pre> class.</p>
<p>Add these properties for the <pre class="crayon-plain-tag">DefenceBrick</pre> instances.</p>
<p><script src="https://gist.github.com/EliteIntegrity/a1e18d28b01e6a93013b998774e0c9e3.js"></script></p>
<p>Next, add this code to initialize the <pre class="crayon-plain-tag">DefenceBrick</pre> instances inside the <pre class="crayon-plain-tag">prepareLevel</pre> function just after the code which initializes the invaders.</p>
<p><script src="https://gist.github.com/EliteIntegrity/7a404b96351c94a4b98c71dd65bacd96.js"></script></p>
<p>We don&#8217;t need to update the bricks because they don&#8217;t move but we will add some code to detect when they get shot in a minute. Add this code to draw the bricks just after the code which draws the invaders.</p>
<p><script src="https://gist.github.com/EliteIntegrity/4b5f317b8b4899f5f3368139cb6cfa2d.js"></script></p>
<p>This is what the game looks like if you run it at this stage.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2019/03/kotlin_space_invaders_4.png"><img class="aligncenter size-medium wp-image-16072" src="http://gamecodeschool.com/wp-content/uploads/2019/03/kotlin_space_invaders_4-300x206.png" alt="kotlin_space_invaders_4" width="300" height="206" /></a></p>
<h2>Coding the Space Invader bullets</h2>
<p>Now we will code the <pre class="crayon-plain-tag">Bullet</pre> class. We will have a single <pre class="crayon-plain-tag">Bullet</pre> instance for the player to shoot and reuse and we will have a whole <pre class="crayon-plain-tag">ArrayList</pre> of instances for the invaders to use. Add a new class called <pre class="crayon-plain-tag">Bullet</pre> and code it as follows.</p>
<p><script src="https://gist.github.com/EliteIntegrity/0fc357fee5d105516d411b78db8d3be3.js"></script></p>
<p>In the preceding code, we track the bullets in the usual way using a <pre class="crayon-plain-tag">RectF</pre> instance and update them in the usual way by moving it. Obviously, the bullets go up and down rather than left to right. We added a <pre class="crayon-plain-tag">shoot</pre> function that will test whether a bullet is available (just a single bullet for the player like the original) but the invaders will have more.</p>
<p>Now we need to declare some properties for the player&#8217;s bullet and the invader&#8217;s bullets.</p>
<p><script src="https://gist.github.com/EliteIntegrity/034eea11518f5c0b0db4484d6a120bc6.js"></script></p>
<p>We can spawn the bullets in the <pre class="crayon-plain-tag">prepareLevel</pre> function as we have come to expect. Do so after we initialized the shelters.</p>
<p><script src="https://gist.github.com/EliteIntegrity/71ed4f643a22524132073b82ff0f5ad6.js"></script></p>
<p>We can update all the bullets in the <pre class="crayon-plain-tag">update</pre> function as usual.</p>
<p><script src="https://gist.github.com/EliteIntegrity/2ba491b8c3707265f09d7436fdbb87b7.js"></script></p>
<p>In the preceding code, we check if the bullet is active and if it is we update it.</p>
<p>And we can draw all the bullets in the <pre class="crayon-plain-tag">draw</pre> function. Add the code after the code that draws the bricks.</p>
<p><script src="https://gist.github.com/EliteIntegrity/824274b79fffd288c7545b4277605cd8.js"></script></p>
<p>If you run the game then no bullets will be drawn. This is because we need to trigger them to spawn. Furthermore, we need to unpause the game loop. We will allow the player to unpause the game loop by tapping the screen. This is a good time to code the <pre class="crayon-plain-tag">onTouchEvent</pre> function to control the player ship, un-pause the game loop, and fire some bullets. We will then add some code that triggers the invaders to fire at the player.</p>
<h2>Playing the sound effects</h2>
<p>Quickly before we do let&#8217;s add a class that will play all the sound effects. Add a new class called <pre class="crayon-plain-tag">SoundPlayer</pre> and code it as follows.</p>
<p><script src="https://gist.github.com/EliteIntegrity/a8333bbf538b007c039b99cf6d5a53e4.js"></script></p>
<p>In the preceding code, we declare an instance of <pre class="crayon-plain-tag">SoundPool</pre> which does all the work. We also have a <pre class="crayon-plain-tag">companion object</pre> with a bunch of integers which will represent all the different sounds that the <pre class="crayon-plain-tag">SoundPlayer</pre> knows how to play. In the <pre class="crayon-plain-tag">init</pre> block all the sounds are loaded from the <pre class="crayon-plain-tag">assets</pre> folder into memory. Notice how each sound is associated with one of the integers from the companion object.</p>
<p>The one and only function is <pre class="crayon-plain-tag">playSound</pre> that takes an <pre class="crayon-plain-tag">Int</pre> argument to represent which sound we want to be played. The <pre class="crayon-plain-tag">SoundPool</pre> class is used to play that sound using the <pre class="crayon-plain-tag">play</pre> function.</p>
<h2>Handling the player interaction</h2>
<p>Code the <pre class="crayon-plain-tag">onTouchEvent</pre> function as shown next.</p>
<p><script src="https://gist.github.com/EliteIntegrity/f4323afe65098f877640e2bd4d8486e4.js"></script></p>
<p>In the preceding code, we use a <pre class="crayon-plain-tag">when</pre> expression which has two possible outcomes. The first handles what happens if any of the player&#8217;s fingers have touched or is touching the screen. And the second handles what happens when any of them leave the screen. This is quite unsophisticated but its quick and it works. If you want to you can respond individually to different pointers and to move and touch events. This is beyond the scope of this tutorial.</p>
<p>The first <pre class="crayon-plain-tag">if</pre> statement inside the first <pre class="crayon-plain-tag">when</pre> outcome checks whether the player&#8217;s finger is below the bottom eighth of the screen and if it proceeds to detect whether it is in the left half or the right half. It then proceeds to set the <pre class="crayon-plain-tag">moving</pre> property of the <pre class="crayon-plain-tag">PlayerShip</pre> instance accordingly. Next time <pre class="crayon-plain-tag">update</pre> is called on the player&#8217;s ship it will move as the player wants it to.</p>
<p>The second <pre class="crayon-plain-tag">if</pre> in the first <pre class="crayon-plain-tag">when</pre> outcome checks if the player has touched above the bottom eighth. If he has it attempts to fire a bullet by calling the <pre class="crayon-plain-tag">shoot</pre> function. Whether or not this attempt is successful is decided inside the <pre class="crayon-plain-tag">Bullet</pre> class. If it is successful a sound is played using our new <pre class="crayon-plain-tag">SoundPlayer</pre> class.</p>
<p>The second <pre class="crayon-plain-tag">when</pre> outcome simply stops the ship which is exactly what we want to happen when they remove their finger from the screen.</p>
<p>There will be an error in the preceding code until we declare the instance of <pre class="crayon-plain-tag">SoundPlayer</pre> called <pre class="crayon-plain-tag">soundPlayer</pre> as shown next.</p>
<p><script src="https://gist.github.com/EliteIntegrity/4b30be9f489e20308f24344ddce400bc.js"></script></p>
<p>Now you can run the game and fire off a single bullet with a satisfying peeowww sound &#8211; but only one.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2019/03/kotlin_space_invaders_6.png"><img class="aligncenter size-medium wp-image-16074" src="http://gamecodeschool.com/wp-content/uploads/2019/03/kotlin_space_invaders_6-300x189.png" alt="kotlin_space_invaders_6" width="300" height="189" /></a></p>
<p>The invaders will dutifully move left and right while getting lower for each pass of the screen. But the invaders do not flap their arms, make a noise, shoot back at the player and the player&#8217;s one and only bullet passes harmlessly through them. Let&#8217;s fix all those problems.</p>
<h2>Shooting back and collision detection</h2>
<p>Now we will code the invaders firing at the player. Add this code after the call to <pre class="crayon-plain-tag">invader.update</pre> and before the <pre class="crayon-plain-tag">if</pre> statement which checks if the invader has bumped the edge of the screen.</p>
<p><script src="https://gist.github.com/EliteIntegrity/17d9eafaaa3fdc0bdbfad9d0a55ed5ed.js"></script></p>
<p>In the preceding code, we loop through each invader that is active and call the <pre class="crayon-plain-tag">takeAim</pre> function. The <pre class="crayon-plain-tag">Invader</pre> class uses the logic inside the function to decide whether to take a shot. If it returns true the next bullet in the array of bullets has its <pre class="crayon-plain-tag">shoot</pre> function called. If that function returns true as well then a new bullet is fired, a sound is played and the <pre class="crayon-plain-tag">nextBullet</pre> value is incremented. If the <pre class="crayon-plain-tag">nextBullet</pre> value gets as high as <pre class="crayon-plain-tag">maxInvaderBullets</pre> then <pre class="crayon-plain-tag">nextBullet</pre> is set to zero and the invader bullets <pre class="crayon-plain-tag">ArrayList</pre> gets reused.</p>
<p>We are nearly done. The big job that is remaining is collision detection.</p>
<p>It will use the <pre class="crayon-plain-tag">RectF.intersects</pre> function to check the following combinations of collision.</p>
<ul>
<li>Player bullets with an invader</li>
<li>Alien bullet with a brick from a shelter</li>
<li>Player bullet with a brick from a shelter</li>
<li>Invader bullet with the player ship</li>
</ul>
<p>Study the code that follows and note the actions that are taken when each of the different collisions occurs. Lives are removed, the score is increased, sound effects are played, objects are set to inactive/invisible. Add the code to the end of the <pre class="crayon-plain-tag">update</pre> function.</p>
<p><script src="https://gist.github.com/EliteIntegrity/f2e822e805e4194cb58c0a0ea0ad276f.js"></script></p>
<p>If you run the game now you can move, shoot, destroy invaders, build up your score, and be shot at by the enemy as well.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2019/03/kotlin_space_invaders_6.png"><img class="aligncenter size-medium wp-image-16074" src="http://gamecodeschool.com/wp-content/uploads/2019/03/kotlin_space_invaders_6-300x189.png" alt="kotlin_space_invaders_6" width="300" height="189" /></a></p>
<h2>Finishing the game</h2>
<p>What we need to do to finish off is write and call a new function that handles the menace level and plays a sound and then save the high score so the player can come back another day and try and beat his best score.</p>
<p>Add the <pre class="crayon-plain-tag">menacePlayer</pre> function to the <pre class="crayon-plain-tag">KotlinInvadersView</pre> class as shown next.</p>
<p><script src="https://gist.github.com/EliteIntegrity/b351cc9bf61300f64835e688740546dc.js"></script></p>
<p>Now we will call this function selectively from the <pre class="crayon-plain-tag">run</pre> function. Add the following code near the end of the <pre class="crayon-plain-tag">run</pre> function but inside the while loop.</p>
<p><script src="https://gist.github.com/EliteIntegrity/1d0eb2533399ae5f001bdd93fd6e3e78.js"></script></p>
<p>Now the invaders will flap their arms while making a menacing sound; that gets more menacing each time they cross the screen and drop down a little. Furthermore, this menace level as well as the speed, and the invader frequency of shooting will increase as the player clears more waves of invaders.</p>
<h2>Saving the player&#8217;s high score</h2>
<p>Let&#8217;s save the player&#8217;s high score. Add the following property before the declaration of the <pre class="crayon-plain-tag">highScore</pre> property and change the initialization of <pre class="crayon-plain-tag">highScore</pre> to load a value from the device storage.</p>
<p><script src="https://gist.github.com/EliteIntegrity/90725a7eebcef739ccb224b4b7bdd5c6.js"></script></p>
<p>And add this code to the end of the <pre class="crayon-plain-tag">pause</pre> function so that every time the player quits the game the code checks if a new high score was achieved in the current play session and if it was, save it to the device storage.</p>
<p><script src="https://gist.github.com/EliteIntegrity/15c0b6aa5e5bb498cc868cfa7e117e1a.js"></script></p>
<p>The initialization of the <pre class="crayon-plain-tag">SharedPrefferences</pre> instance created a label &#8220;Kotlin Invaders&#8221; that could be referred to access and store data. In the line of code that initialized the <pre class="crayon-plain-tag">highScore</pre> property, the <pre class="crayon-plain-tag">getInt</pre> function accessed this storage. The reason there are two parameters for <pre class="crayon-plain-tag">getInt</pre> is the second parameter is a default value in case there is nothing in the storage; which there won&#8217;t be the first time the game is executed.</p>
<p>In the <pre class="crayon-plain-tag">pause</pre> function, the value is retrieved again and compared to the <pre class="crayon-plain-tag">highScore</pre> property. If the <pre class="crayon-plain-tag">highScore</pre> property holds a higher value than the device storage then a new high score is saved into the device storage using a <pre class="crayon-plain-tag">SharedPreferences.Editor</pre> instance.</p>
<h2>Improving the Space Invaders code</h2>
<p>The biggest problem with the code in this tutorial is its structure. We have achieved only a simple retro shooter and yet the main class is around 500 lines long! You can imagine that if we were to add some more invader types and a few extra features then the code would quickly become unmanageable. The solution isn&#8217;t especially complicated but it does amount to quite a big tutorial to demonstrate. Hopefully, a quick overview instead will be helpful.</p>
<p>We could put all the game objects into an inheritance hierarchy and store them all in a single <pre class="crayon-plain-tag">ArrayList</pre>. Furthermore, we could get all the objects to draw themselves; they could each have a <pre class="crayon-plain-tag">draw</pre> function. We could then shrink down the <pre class="crayon-plain-tag">update</pre> and draw functions in <pre class="crayon-plain-tag">KotlinInvadersView</pre> to just a <pre class="crayon-plain-tag">for</pre> loop each. We could also pass the <pre class="crayon-plain-tag">onTouchEvent</pre> function data straight to the player game object and it could decide how to handle it.</p>
<p>This then leaves the problem of how we distinguish between the different types of objects for collision detection. One way to solve this is to give every game object a label/tag. All we would need to do then is decide on some special cases (as we did in this tutorial) and loop through the objects looking for the cases we care about.</p>
<p>Another pattern that is useful as our games get bigger is the entity component pattern. This involves having a single hierarchy for every game object; let&#8217;s call it <pre class="crayon-plain-tag">GameObject</pre> and then every instance has an <pre class="crayon-plain-tag">ArrayList</pre> of components; let&#8217;s call them <pre class="crayon-plain-tag">Components</pre>. You could then design components that draw, components that think, components that chase the player, components that avoid the player, etc. This would mean you could have wildly different game objects from a dumb brick with just a drawing component through to an intelligent enemy with multiple update components and a draw component. Hopefully, I will have time to show some examples of this in the near future.</p>
<h2>Congratulations</h2>
<p>Congratulations on reaching the end of the tutorial! What is next then? I will keep adding tutorials to this site as well as to YouTube. I intend to add more advanced tutorials than this as well as some simpler tutorials to help newcomers build up to this one. They do take quite a long time to write though so I won&#8217;t promise any particular schedule.</p>
<p><a href="https://www.patreon.com/Gamecodeschool"><img class="alignleft size-full wp-image-16509" src="https://gamecodeschool.com/wp-content/uploads/2015/01/patreon1.jpg" alt="patreon" width="125" height="38" /></a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>https://gamecodeschool.com/kotlin/coding-a-space-invaders-game-in-kotlin/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
<enclosure url="http://gamecodeschool.com/wp-content/uploads/2015/05/uh.ogg" length="15334" type="audio/ogg" />
<enclosure url="http://gamecodeschool.com/wp-content/uploads/2015/05/shoot.ogg" length="44642" type="audio/ogg" />
<enclosure url="http://gamecodeschool.com/wp-content/uploads/2015/05/playerexplode.ogg" length="167054" type="audio/ogg" />
<enclosure url="http://gamecodeschool.com/wp-content/uploads/2015/05/oh.ogg" length="10518" type="audio/ogg" />
<enclosure url="http://gamecodeschool.com/wp-content/uploads/2015/05/invaderexplode.ogg" length="56582" type="audio/ogg" />
<enclosure url="http://gamecodeschool.com/wp-content/uploads/2015/05/damageshelter.ogg" length="16646" type="audio/ogg" />
		</item>
	</channel>
</rss>
