Category: Ebook

C++ Asteroids is progressing

C++ Asteroids is progressing

C++ AsteroidsThis is a screenshot of it as it stands and yes those asteroids are moving! It looks identical to the C version; the only difference is the code, not the appearance.

What makes it interesting is the structure. The Player and Asteroids classes both inherit from a Common base class that has all the position and move data.

It took a bit of time to get the overall architecture right. There’s a Game class which manages everything; the Player, Asteroid and Lib classes.  But Asteroids and Player classes also use the Lib class so  it took a bit of faffing around to make them all play happily together.

This is the biggest difference between C++ and C; the classes and how they all fit together. My biggest source of frustration has been arm wrestling with the C++ compiler; it sometimes seems as if never get easier! Sometimes a wrongly placed semicolon can generate hundreds of compile errors…

It took half a day to get it right and bullets should fit in much easier. Mind you I’ve had to incorporate two static variables in the Common class. One is a copy of the SDL renderer; this is needed to draw things on screen. The other is a pointer to the Game class so that I can access the DebugFlag state.  This is used to show debug information but I may be able to move the flag itself into the Common base class and change it through a call on a Player method. So long as it is static then changing it for the Player also changes it for the Asteroids and Bullets.

 

I’ve started on the C++ Windows eBook

I’ve started on the C++ Windows eBook

C++ Code listing photoI made the mistake of starting by trying to convert the final version of Asteroid; all 2,200 lines of C into C++.

It got very messy because I was trying to have all the moving objects (Player ship, asteroids, bullets, aliens ship) all based on a common ancestor class but then was trying to manipulate those instances of the ancestor class and downcast back from the ancestor instances and I don’t think you can in C++. Compiler errors galore!

It was the wrong approach and I wasn’t using virtual functions. So instead I’m doing it step by step, adding on new features. Much like the original C development in 13 different steps.

Here’s the slightly shorter asteroids.cpp:

// Asteroids C++ 2020 Chapter 27
#include "game.h"

int main(int argc,char * args[])
{
	Game g;
	g.InitSetup();
	g.GameLoop();
	g.FinishOff();
    return 0;
} 

There are other classes used from Game. I haven’t put everything in one “God” class!

How I write my ebooks

How I write my ebooks

Screenshot of JutohMy secret: is I use a piece of software called Jutoh from a Scottish software house. It costs £35 and if you are writing a book or e-book I highly recommend it.

Note I have no connection with them except as a very satisfied customer.  

It’s all the little things, inserting pictures, tables, handling source code that make it particularly good for non-fiction books.

It also includes formatting for various programming languages and is cross-platform with versions for Linux, Mac and Windows.

The current version of the Linux e-book has 55144 words, (307407 characters). It takes about 10 seconds to compile that into a .mobi (Amazon) or .epub file with all sorts of warnings.

Originally I started writing the first e-book in a text editor then imported it to MS-Word. But Word is not exactly great software for publishing non-fiction as it’s not desktop publishing. Actually you don’t need desktop publishing per se because Kindle reflows the text, but having pictures, source code and tables makes it more complicated.

I looked about, found Jutoh and consider myself very fortunate; it makes life much easier. I’ve also had excellent support from Jutoh’s creator Dr. Julian Smart who is also well known as a creator of wxWidgets.

Writing an e-book is a multi-pass project that takes me roughly 3-4 months part-time.

  • Pass 1. Develop the software and e-book structure i.e. chapters.
  • Pass 2. Write the chapters.
  • Pass 3. Look for typos. For now this is just me, but eventually I hope to be able to afford a technical editor.
  • Pass 4. Tidy up the layout. This is probably the slowest phase. Because of the images, tables and shortish code listings, it might look neat and tidy at one size, but if you change the viewing font size, it looks er not quite so neat! I can’t see any way round that.

A friend drew the original book cover but I’ve decided to pay for the cover for the Linux version.

Made it to the end of the Linux EBook

Made it to the end of the Linux EBook

Tux with books
Image by OpenClipart-Vectors from Pixabay

That is, I have completed every one of the 13 stages in the game’s development and each is up and running on Ubuntu. It turned out easier than I thought though I still need to fix one or two things.

Because Clang doesn’t support the MSVC fopen_s, I did a quick fix and removed the error checking and when it first ran, it did another segmentation fault because the high score table file didn’t exist. D’oh!

That’s fixed now. Crashing because a file is missing is a very bad practice! Also for some reason last night, Windows and Ubuntu fell out and copy/paste between them wasn’t working. It is working today. I’ve noticed this can be a little bit sensitive at times and I think it was the Windows side that fell over.

However I’ve also been playing with Ubuntu 19.10 and Copy/Paste appears to be disabled on that. That kind of thing I find extremely irritating. I have Guest services ticked, so why does nothing I do enable it? 18.04 LTS apart from last night’s glitch is perfectly happy. And 20.04 Focal Fossa (I know!) is due out on April 23rd.  It’s not quite ready but you can try it an early version if you like. I will be upgrading.

 

Just a picture post!

Just a picture post!

Lots of collisions here with explosions turned offIn the chapter 42 of both e-books when the first collision detection is introduced, I added a SHOWOVERLAP #define. If this is uncommented, instead of things blowing up, it shows every pixel where two objects pixel’s overlap in bright green.

In the picture above you can see the player ship in the centre and all those green bits where things overlap. You don’t normally see this and it is so intensive that it drops the frame rate from the usual 60 fps to about 3 or 4. But I think it’s quite cool!

 

SSSnakes – a game for the next Ebook

SSSnakes – a game for the next Ebook

Screenshot of snake gameI’ve done a snake game in the past for About. That’s the picture and today I’ve uploaded it complete with source to Github. The thing with snake is, everyone knows it, its old hat and not particularly exciting.

Back in the early 80s the same was true about Breakout games. It was a common trope for game programming, bouncing a ball off a bat to break through a wall.

But then in 1987 along came the Arkanoid game which could be best described as Breakout re-imagined.  More balls, special bricks when when hit gave different features. It made Breakout games cool again for a few years.

So Ssnakes, is my name for a re-imagined snake game.  We’ll throw away losing your life when the snake hits a wall or itself. Only if your snake runs out of space is it dead, or if it is killed by an enemy. And as it travels around it picks up food which gives it energy. You can burn this energy is making it longer, moving faster or .. spawn off a new snake! Also you can attack enemy snakes – spitting venom directly ahead or sinking fangs into an enemy body if  your snake’s head is next to it.

Having 2, 3 or 4 snakes on the go will make it a bit more stressful to control. You only lose a life when you only have one snake left in play and you lose it.

Plus instead of a plain empty arena there will be a few static objects in it.

 

Linux E-book Progress

Linux E-book Progress

Screenshot of the chapter 28 executableMy Linux rewrite continues with progress as far as chapter 38.

This is the first Linux version of asteroids on the left and is a demo of the text writing routines and also loading images from files.

It;s drawing all digits from 0 to 99 at random locations on the screen every frame.

The number at the top is how long it takes to output the text. That value if you can’t read it is 0.000622, which means it takes 622 microseconds to output 100 numbers or 6.22 micro-seconds each.

This is the routine that does that.

void RenderEveryThing() {
	int atX, atY;

	renderTexture(textures[PLBACKDROP], 0, 0);
	startTimer(&s);
	for (int i=0;i<100;i++) {
		atX = Random(WIDTH-50) + 1;
		atY = Random(HEIGHT) + 20;
		TextAt(atX, atY, SDL_ltoa(i,buffer,10));
	}	
	stopTimer(&s);
	SDL_RenderPresent(renderer);
	frameCount++;
	UpdateCaption();
}

The most recent uploaded code version (chapter 37) lets you move the player’s ship around (press q, w or ctrl) , fire bullets (space bar), press a to see random asteroids rotating and moving round (and off) the screen. Press the b key to blow up a few asteroids with explosions and sounds. Enjoy!

Zipped up source code, graphics etc from the forthcoming Linux book can be downloaded from Github.

How pixel perfect collision detection works

How pixel perfect collision detection works

Asteroid and player ship about to collide near an explosionsThere are four types of moving object in the games. Asteroids in four sizes from 35×35, 70×70, 140×140 and 280×280 pixels, the player’s ship (fits in 64 x 64 pixels), alien ships (also in 64 x 64)  and a bullet which is solid 3×3 pixels with the four corners empty.

As these move around the screen at 60 frames per second, they will come into contact and the collision detection has to figure out when they hit or miss.

To make it more complicated, the asteroids and player’s ship come in 24 rotations, each by 15 degrees so detection has to take that into account. The image shows an asteroid just about to hit the player’s ship.. At the bottom you can see where another asteroid has been blown up (the 50 is the score) and there’s a bullet to the right.

The detection occurs in several stages. First each object has a bounding square.This shows the bounding boxes for the player's ship and an asteroid This is an invisible square that just fits round each object. For the player’s ship it’s 64 x 64 and it corresponds to the sizes of each asteroid. As the image shows, the two bounding boxes overlap and it’s in this overlap rectangle that we have to check for a possible collision.

A large asteroid and the cells it overlapsFirst things first. Every frame all objects are moved and we have to detect if there’s a chance of a collision. This is done by dividing the entire playing area (set in the book to 1024 x 768) into 64 x 64 pixels cells.  I chose that as a convenient size. Once the object’s new x,y location has been calculated, I determine which cells it overlaps.

The player’s ship can fit completely into one cell but most times it is either overlapping two or four cells. Even a 3 x 3 bullet will occasionally overlap two or four cells but most of the time it will fit completely in one.  The largest Asteroid (280 x 280) always overlaps five or six cells in each direction so it gets added into to 25,30 or 36 cells each frame.  The image shows the grid of 64 x 64 cells and the asteroid overlaps 25 cells, the player’s ship just overlaps 4 cells. The number is a count of the number of overlapping item in each cell.   It’s the bounding box size that determines if it overlaps which is why the top left and bottom right empty cells of the asteroid still show 1.

In each cell, I keep a list of objects that overlap that cell. The first step is scanning all cells with overlapping objects in to see if there are two or more objects overlapping in that cell. The SDL library includes a function SDL_IntersectRect()  You pass in the two bounding rectangles of overlapping objects and it returns a rectangle of the intersection, which corresponds to the overlap in the image above. If there are multiple objects in a cell e.g. four then you have to check to see if any of those (1,2), (1,3), (1,4), (2,3), (2,4), (3,4) overlap.

A text file representation of a maskThe next bit is what makes it pixel perfect. For every object and its rotations, I have created a mask. It’s a file of bytes with a 1 value corresponding to every coloured pixel in the object and 0 to empty pixels.

I have stretched this image to make it the same aspect ratio and it shows 0s and 1s in the player’s ship mask.

The collision detection algorithm processes the intersection rectangle and calculates where each pixel in that rectangle falls in the corresponding mask (adjusting for rotations) of each object.  If either mask pixel is 0 then no collision occurs but if both are 1 then bam!

Although I could have used a mask of bits, it was quicker to use bytes.

During development I wanted to verify that it was pixel perfect, so I disabled explosions and instead when two pixels overlapped, I output a green pixel to highlight it. The image shows the player’s ship passing through an asteroid!Showing pixel perfect touching

 

 

 

Learn C Games

Learn C Games

Learn C Games Programming Book coverThis blog is about C and Games programming (in C mainly) and now C# on mobile with MonoGame. It’s written by David Bolton, author of the Learn C Games Programming for beginners EBook. This is the Windows version, with a Raspberry Pi/Linux one due out isometime n 2021.  

The first 20 chapters introduce and teach C programming with many examples. This link is to an .mp4 of the asteroids game from the book. It’s about 90 seconds long and demonstrates all of the features of the game. High score table, rotating asteroids (four sizes), sound, explosions, ship hyper-jump and shields.

The remaining 30 chapters builds up to full source code, about 2,000 lines, in 13 stages and I explain how each feature works and is implemented.  All of the book’s source code is on GithubMore about me. Buy it on Amazon(UK), Amazon(US).