Begin to Code with Python Videos

I've made some silly videos. They're for those sensible people who've bought copies of Begin to Code with Python (subtle plug on the left). 

They cover how to install Python, how to install PyGame and finally, how to obtain the demo programs and install the tiny Snaps framework. 

They were a giggle to make, with a bit of luck they will be a giggle to view. And maybe even useful.

How to install Python on a Windows 10 PC for the Begin To Code with Python book
Installing the Pygame framework for use in the book Begin to Code with Python
Installing and working with Snaps on a system for the Begin to Code with Python book

Begin to Code Python Snaps

 Creating pretty menu screens, Snaps style

Creating pretty menu screens, Snaps style

As you might know, I'm working on Begin to Code Python. You can order a copy below. It will be out once I've finished writing it....

When I wrote the Begin to Code with C# book (which you can buy now - see below) I wrote a library of functions I called Snaps. The idea was to use these to make it easy for people to create impressive applications right from the start. Snaps for C# became an enormous library that you can find on GitHub here. I'm using it for my Monday Snaps which you can read each, er, Monday. 

Anyhoo, when I started the Python book I wondered about writing a Snaps library for Python. I've always been concerned that people might think that they are getting a book about Snaps, not programming, and so I wasn't sure whether another library would be a good idea. And the libraries do take a while to build. 

To cut a long story short, I've decided to make some Snaps for Python. They're much more lightweight than the ones I wrote for C#. They're built on the pygame framework so that I can get some nice graphical and audio elements with minimal effort. I've put the first version of Python Snaps, along with all the sample programs for the first five chapter's worth of examples, on GitHub here.

I must admit I'm really (and I mean really) enjoying writing Python at the moment. As a language that lets you go quickly from idea to implementation I think it is very hard to beat. It requires a different approach to programming from a language like C#.  but that's not a bad thing. 

Monday Snaps: Steering the Cheese

Welcome to this week's Monday Snap. We're re-creating the game Cheese Lander using the Snaps game framework. You can find earlier episodes here. Last week we put the bread and the cheese at their start positions. This week we're going to get the cheese moving. 

Games work by repeatedly updating the game engine and then re-drawing the display. In a Snaps game we use a C# loop to do this:

void gameLoop()
{
    while (true)
    {
        SnapsEngine.DrawGamePage();
    }
}

At the moment the gameLoop method just repeatedly draws the game page. The DrawGamePage method also pauses the loop so that it runs at the selected frame rate, which for our game is 60Hz. I'm going to add a call of a method to update the cheese position.

void gameLoop()
{
    while (true)
    {
        updateCheese();
        SnapsEngine.DrawGamePage();
    }
}

The cheese is controlled by the player. The idea is to land it on the bread. This is my first version of the updateCheese method.

int cheeseXSpeed = 2;
int cheeseYSpeed = 2;

void updateCheese()
{
    if (SnapsEngine.GetRightGamepad())
        cheese.Left += cheeseXSpeed;
    if (SnapsEngine.GetLeftGamepad())
        cheese.Left -= cheeseXSpeed;

    if (SnapsEngine.GetDownGamepad())
        cheese.Top += cheeseYSpeed;
    if (SnapsEngine.GetUpGamepad())
        cheese.Top -= cheeseYSpeed;
}

The SnapsEngine exposes methods that  program can use to test the state of the gamepad.  You can use the cursor keys on the keypad, a connected Xbox 360/Xbox 1 controller. Alternatively you can use the on-screen touchpad with a mouse, lightpen or finger. If any of the methods return true a speed value is used to update the position of the cheese in that axis. Remember that the Y axis goes down the page. Increasing the Y value of the cheese position will move it down the screen. 

This method lets the player move the cheese right off the screen, so perhaps we should fix that. 

if (cheese.Left < 0)
    cheese.Left = 0;
if (cheese.Right > (SnapsEngine.GameViewportWidth))
    cheese.Right = SnapsEngine.GameViewportWidth;

if (cheese.Top < 0)
    cheese.Top = 0;
if (cheese.Bottom > SnapsEngine.GameViewportHeight)
    cheese.
Bottom = SnapsEngine.GameViewportHeight;

These statements "clamp" the cheese movement so that it can't move off the screen. Add them to the updateCheese method after you have updated the cheese position.

You can now steer the cheese around the screen and land it on the bread. Unfortunately this is far too easy. So next week we'll put on our scientists white coats and add some Physics. 

And remember, the Monday Snaps are brought to you by Begin to Code With C#, available from all good booksellers. 

Monday Snaps: Cheese Lander Game Reset

Welcome back to our weekly Snaps session, which has the ultimate aim of creating the awesome gaming experience that is Cheese Lander . Last week we got the bread, cheese and background screen drawing nicely, this week we are going to place the bread and cheese at their starting positions. So, if someone asks you "Who moved the cheese?" you can say it was you.

We're going to start with a bit of gentle re-factoring. Re-factoring is a posh word for "putting things in the place that they should have been from the start". Computer programmers are lucky in this respect. Doing "refactoring" in other professions means moving physical things around. Refactoring a brick wall is hard. But with code it's easy. What I want to do is create some methods that will deal with my game objects. To do this I'm going to have to move the game objects into the enclosing class, so that they are visible to all the methods in that class. 

public class MyProgram
{
    ImageSprite cheese, bread, background;

    void setupSprites()
    {
        SnapsEngine.StartGameEngine(fullScreen: false, framesPerSecond: 60);
        background = new ImageSprite(imageURL: "ms-appx:///Images/Background.png");
        background.Height = SnapsEngine.GameViewportHeight;
        background.Width = SnapsEngine.GameViewportWidth;

        cheese= new ImageSprite(imageURL: "ms-appx:///Images/cheese.png");
       
cheese.ScaleSpriteWidth(SnapsEngine.GameViewportWidth / 20);

        bread = new ImageSprite(imageURL: "ms-appx:///Images/bread.png");
        bread.ScaleSpriteWidth(SnapsEngine.GameViewportWidth / 8);

        SnapsEngine.AddSpriteToGame(background);
        SnapsEngine.AddSpriteToGame(bread);
        SnapsEngine.AddSpriteToGame(
cheese);
    }

    void gameLoop()
    {
        while (true)
        {
            SnapsEngine.DrawGamePage();
        }
    }

    public void StartProgram()
    {
        setupSprites();

        gameLoop();

    }
}

This is my re-factored game class. It now has two methods. One is called setupSprites, and it sets the sprites up. The other is called gameLoop. This runs the game loop (remember that a game is all about repeatedly drawing and updating. I've also renamed the ball object to cheese. It seemed the right thing to do.

Now things are all tidy I can start building up my methods that will make the game work. When the game resets (i.e. at the start of a new game) I want the bread to be placed somewhere on the bottom of the screen. The aim of the game is then to steer the cheese onto the bread. A method called resetBread would seem to make sense. If you're asking why I'm not calling it setupBread, then I hear you. The answer is that I'm being careful with my names here. setup is something that you do once in the lifetime of the program. Reset is something you do at the start of each game. This is just my standard, yours is allowed to be different, as long as you have a standard.

Moving the bread to the bottom of the screen is easy. We just set the bottom of the bread to the height of the screen:

 bread.Bottom = SnapsEngine.GameViewportHeight;

Moving the bread to a random position across the screen is a bit harder. For a start we'll need a random number. We can get random numbers from the Random class in the System namespace. I can create an instance of this in the class for the game to use:

System.Random breadRandom = new System.Random();

I'm going to use a different random number generator for each object that needs random behaviour. This is because that way I can convert any of them to produce the same sequence (simply by adding a seed):

System.Random breadRandom = new System.Random(1);

Now my bread would be placed at the same sequence of positions when the game is played. This is a good idea because it helps the player learn how the game plays, and encourages them to come back and have another go. In the case of the bread, I'll probably make it completely random.

Anyhoo, once I've got my random number generator I can place the bread somewhere random across the width of the screen:

 bread.Left = breadRandom.Next((int)(SnapsEngine.GameViewportWidth - bread.Width));

This code is a bit of a mess to be honest. The Next method of the Random class can generate an integer in a range from 0 to an upper limit. The upper limit I want is the width of the screen minus the width of the bread. I can calculate this, but Snaps graphics work with double precision numbers. So I have to convert the result of this calculation into an integer. 

void resetBread()
{
    bread.Bottom = SnapsEngine.GameViewportHeight;
    bread.Left = breadRandom.Next((int)(SnapsEngine.GameViewportWidth - bread.Width));

}

This is my resetBread method. It places the bread nicely at the bottom of the screen. I can now steal this technology (ooooh, that sounds so cool) to position the cheese at a random position on the top of the screen:

void resetCheese()
{
    cheese.Top = 0;
    cheese.Left = cheeseRandom.Next((int)(SnapsEngine.GameViewportWidth - cheese.Width));
}

After these reset behaviours I have a game screen that looks like this:

The entire program is here:

 using SnapsLibrary;

public class MyProgram
{
    ImageSprite cheese, bread, background;

    void setupSprites()
    {
        SnapsEngine.StartGameEngine(fullScreen: false, framesPerSecond: 60);
        background = new ImageSprite(imageURL: "ms-appx:///Images/Background.png");
        background.Height = SnapsEngine.GameViewportHeight;
        background.Width = SnapsEngine.GameViewportWidth;

        cheese = new ImageSprite(imageURL: "ms-appx:///Images/cheese.png");
        cheese.ScaleSpriteWidth(SnapsEngine.GameViewportWidth / 20);

        bread = new ImageSprite(imageURL: "ms-appx:///Images/bread.png");
        bread.ScaleSpriteWidth(SnapsEngine.GameViewportWidth / 8);

        SnapsEngine.AddSpriteToGame(background);
        SnapsEngine.AddSpriteToGame(bread);
        SnapsEngine.AddSpriteToGame(cheese);
    }

    System.Random breadRandom = new System.Random();

    void resetBread()
    {
        bread.Bottom = SnapsEngine.GameViewportHeight;
        bread.Left = breadRandom.Next((int)(SnapsEngine.GameViewportWidth - bread.Width));

    }
    System.Random cheeseRandom = new System.Random();

    void resetCheese()
    {
        cheese.Top = 0;
        cheese.Left = cheeseRandom.Next((int)(SnapsEngine.GameViewportWidth - cheese.Width));
    }

    void gameLoop()
    {
        while (true)
        {
            SnapsEngine.DrawGamePage();
        }
    }

    public void StartProgram()
    {
        setupSprites();

        resetBread();

        resetCheese();

        gameLoop();

    }
}

Come back next week for more. And remember that you can get the full details of gaming with Snaps from my book:

 

 

 

 

 

 

Creating Cheese Lander in Snaps

Yes. Cheese Lander is back! I'll be using the mostly world famous game in my Monday Games Snap series to demonstrate how to make a Windows program using Snaps that will almost certainly not make you rich and famous. But it might make you poor and notorious. The aim of the game is simple. Move the bread to catch the cheese before it reaches the bottom of the screen. If you miss the cheese, you lose. If your bread is moving too fast when it hits the cheese, you lose. If I'm in a bad mood, you lose (actually this might not be the case). 

Last week we took a look at one of the Snaps sample game programs (read that before you read this). This week we're going to take that game code and move it into the "startup" program that runs when a Snaps application starts running. Then we're going to add some bread, cheese and a suitably starry background with a view to getting things moving next week. 

Open up the BeginToCodeWithCSharp sample project and take a look at the Solution Explorer in the top right hand corner:

Open the BeginToCodeWithCSharp project and then find the My Snaps Apps folder. Inside that you'll find a source file called MyProgram.cs. Open this file.

This is the StartProgram method that runs when a Snaps application starts up. It's the one that runs first because it is in a class called MyProgram and that is always the one that contains the initial StartProgram. Let's replace this StartProgram with the game code that we created last time:

public void StartProgram()
    {
        SnapsEngine.StartGameEngine(fullScreen: false, framesPerSecond: 60);

        ImageSprite ball =

                new ImageSprite(imageURL: "ms-appx:///Images/ball.png");

        SnapsEngine.AddSpriteToGame(ball);

        while (true)
        {
            SnapsEngine.DrawGamePage();
        }
    }

Copy the above method out of this text and paste it over the StartProgram in the Visual Studio editor so that it looks like this.

Now, when we run the program we get a nice round ball in the top left hand corner:

Balls are OK, but we want cheese. I've put all the image assets for the game into a file you can download from here. The images include the cheese, the bread, the starfield background and the game message screens. Download the zip file and put the images from it somewhere (I put mine on the desktop). 

Now find the click on the cheese in your download folder and then drag it into the Images folder for the solution. 

If you do the drag correctly you'll get a warning message because the demo programs (like all my products) come with cheese pre-loaded. However, we want to use the newer cheese because it is the right way up, so click yes to overwrite:

Now we can change our program to draw cheese rather than a ball.

ImageSprite ball =

        new ImageSprite(imageURL: "ms-appx:///Images/cheese.png");

Now, when you run the program you'll see a piece of cheese, rather than a ball. Yay!

Now drag all the other images assets into the images folder.If you find that moving individual items is too much of a drag (ho ho) you can select multiple items and drag them all at once. 

Now you've got the image assets, lets add the background to the game. We can use a new ImagesSprite for that. We can call the new sprite background:

ImageSprite background =
    new ImageSprite(imageURL: "ms-appx:///Images/Background.png");
background.Height = SnapsEngine.GameViewportHeight;
background.Width = SnapsEngine.GameViewportWidth;

This creates a new sprite called background. It also sets the width and the height of the sprite to match the size of the game viewport, so that it exactly fills the screen, which is just what we want the background to do. We can add the new sprite to the game, remembering that sprites are drawn in the order that they are added to the game. So we draw the background first, and then put the cheese on top.

SnapsEngine.AddSpriteToGame(background);
SnapsEngine.AddSpriteToGame(ball);

 

The complete program looks like this:

using SnapsLibrary;

public class MyProgram
{
    public void StartProgram()
    {
        SnapsEngine.StartGameEngine(fullScreen: false, framesPerSecond: 60);
        ImageSprite background =
                new ImageSprite(imageURL: "ms-appx:///Images/Background.png");
        background.Height = SnapsEngine.GameViewportHeight;
        background.Width = SnapsEngine.GameViewportWidth;

        ImageSprite ball =

                new ImageSprite(imageURL: "ms-appx:///Images/cheese.png");

        SnapsEngine.AddSpriteToGame(background);
        SnapsEngine.AddSpriteToGame(ball);
        while (true)
        {
            SnapsEngine.DrawGamePage();
        }
    }
}

Run this and we'll see some cheese against a starry backdrop. But the cheese looks a bit big for the screen. Now it turns out that a recent meeting of the International Standards Organisation for Cheese Related Gaming has standardised cheese and bread sizes for the cheese landing games as a twentieth of the width of the screen and an eighth of the width of the screen respectively. Fortunately the Snaps framework provides a method that will scale a sprite and retain it's aspect ratio:

ball.ScaleSpriteWidth(SnapsEngine.GameViewportWidth / 20);

Add the statement to scale your cheese, and then add the bread sprite and scale that too. This will put bread and cheese on the screen. Next week we'll make them move about a bit. 

Monday Games Snap

You might have heard of my Snaps framework. Then again you might not. I created it for my Begin to Code with C# book

The idea behind Snaps is that learning to create Windows 10 Universal Applications is hard because it takes a while to get to the point where you understand enough to have a bit of fun writing C#. 

So I created a bunch of helper functions that grew into an entire library for app and game development. 

As a celebration of being awarded another year as an MVP (thanks Microsoft) I thought I'd put the whole Snaps framework up on GitHub and then people can download and play with it, and maybe even take it further. 

Every week I'll take a Snaps function and explain how to use it, along with a bit of detail about how it works. Monday is now officially "Snaps Day". I'm going to start with the games creation framework and go on from there. 

This week I'm going to tell you how to get started and make your first sprite. You need Visual Studio 2015 or Visual Studio 2017 (it works with either). You'll also need to be running Windows 10 64 bit edition.

You can download the entire framework from GitHub. It's a single Visual Studio Solution that you just have to open. You might get warnings about the dangers of loading projects downloaded from the internet. Ignore those in this case. 

If you run the solution you'll get the Snaps main menu:

On the left you can select the book chapter. On the right you can pick an exercise from the book to run. Pick the one you can see above (Ch15_04_CompleteGame from Chapter 15). It's a complete game with moving sprites and all sorts. Click "Run and App" and the game will start. 

The graphics aren't the best to be honest. But you can control the game by the cursor keys, or mouse/touch on the cursor pad on the lower right hand edge. One sprite will chase you while the others look on. Everything is running under WPF and I'm very impressed with the performance. 

If you want to get ahead of the game you can grab the book and see exactly how the code works. For now though, use Visual Studio to stop the game (go back to VS and press the red Stop button), and take a look at the Solution Explorer on the top right. If you open up the Chapters folder you can find a folder for each chapter:

Open up a chapter and you can find all the sample code. The names of the samples are keyed to the ones you can find when you run the program. Take a look in Chapter 15:

Open up the one indicated (Ch12_02_BallSprite) It creates a single ball sprite and displays it.:

    public void StartProgram()
    {
        SnapsEngine.StartGameEngine(fullScreen: false, framesPerSecond: 60);

        ImageSprite ball = new ImageSprite(imageURL: "ms-appx:///Images/ball.png");

        SnapsEngine.AddSpriteToGame(ball);

        while (true)
        {
            SnapsEngine.DrawGamePage();
        }
    }

All the action takes place in the StartProgram method. It starts the game engine, creates a sprite and adds it to the game. Then, once we've made the sprites, we start a game loop which continuously draws the game page. It does this 60 times a second, because that is the frame rate requested at the start. The image for the ball is an asset which is in the Images folder in the project:

You can use your own images if you like. Drag them to the images folder and make sure that their build action is set to Content (as below). Then use the appropriate name to draw them.

If you run the framework and select this example (Ch12_02_BallSprite) you can see the ball on the screen. If you change the above code and use the handy "Run That Again" button you can see your changes. Don't worry about breaking the examples. You can always download a fresh set from GitHub if it all goes horribly wrong.

You might like to add more sprites, or fiddle with the properties of the existing sprite, in which case Intellisense is your friend:

See what adding :

ball.CenterX++;

.. to the while loop does. You should have:

while (true)
 {
        ball.CenterX++;
        SnapsEngine.DrawGamePage();
 }

If you make anything especially impressive take a video of it, send me the link and I'll start a hall of fame on this page. Because this is a Universal Application it can run on any Windows 10 device, including Xbox One and Raspberry Pi (although it is not as fast on the Pi)

Of course the best way to find out all these things (and learn to program as well) is to buy my book. 

But if you don't want to do that, then I'll have another Monday Snap for you next week.

Long File Paths and Begin to Code with C#

I've had a few people hitting problems with the Begin To Code with C# example programs. 

The sample code is supplied as a Visual Studio Solution which you can download and then open. 

You get problems if you put the sample code folders inside other folders with long names, for example:

c:\users\rob\documents\2017\programming\csharp\learningtoprogram\book\BeginToCode\

When Visual Studio builds a program it creates quite a large number of subfolders which makes the paths to files in the application even longer. Some Windows filesystems restrict the maximum length of a filepath which means that the build process will fail.

If you get problems, particularly ones where the error complains that "Snaps.dll can't be found", you could try moving the sample code folder up the directory hierarchy, or putting it directly on your desktop. That might help.

Of course, if that doesn't work you can get in touch with me and I'll give you some help to get things going. 

Begin to Code - Get a Free Copy

I need your help. And I'm prepared to give things away to get it. I've had the above error reported to me when trying to use the Begin To Code with C# demo programs. I can't reproduce it, and I can't find out the circumstances in which it happens. 

This bothers me. 

I would love it if someone could get in touch and tell me how they managed to make the error occur. All you have to do is go to to the book site here and get the Snaps examples from the Downloads page. Unzip them and try to build and run them using Visual Studio 2015. There's a help document to tell you how to do this, or you can watch my screencast here

If you get the error error above, send me an email to ibrokebegintocode@robmiles.com so I can work with you to fix the problem. First person to do this gets a free copy of the book. If you get a different problem please get in touch too.

And if your version works send an email to begintocodeworksforme@robmiles.com and I'll draw a name at random in a couple of weeks and send them a free copy of the book too. 

Everyone who gets in touch will receive a "Certificate of Undying Appreciation" as well. 

I'm prepared to post around the world (which means it will cost me money) but I'm determined to find the source of this problem. 

How to Begin to Code

It turns out to be very hard to record videos when you've got jetlag. I found this out yesterday, when a ten minute recording session turned into a "fur lined copper bottomed ocean going disaster". Andrew had asked for a bit of help and I thought I'd oblige.

Anyhoo, it's done now. It's tells you how to install Visual Studio 2015, get hold of the example programs for my Begin To Code book and then run them. Let me know what you think. 

Subtle plug eh?

C# Yellow Book 2016 "Cheese Edition" Now Available

The latest release (or is that escape) of the C# Yellow Book is now available for download. No massive changes to the text, but a few tweaks and corrections here and there. And cheese. 

You can download it (along with sample code and whatnot) from here.

The Kindle version will be updated soon. I'm just grappling with adding an index. (why does making Kindle books have to be so hard?)

 

And, while we are on the subject of books what I wrote, you can now buy printed (or Kindle) copies of my lovely new "Begin to Code with C#", which was published a few weeks ago.

It's a great introduction to programming (said the author) and gets you creating useful and fun applications and games using my magical Snaps framework. 

Voice Powered Pizza Picking

I've been playing with the Voice Response in Windows 10. It works very well. The latest libraries allow you to write code that recognises one of a number of phrases. I've been working on this as part of "Begin To Code With C#", the book which, even as we speak is taking shape. 

I've written a "Snap" (one of my pre-built software components) that makes it dead easy to create your own voice controlled software. Above is a screen shot from the "Voice Enabled Pizza Picker" that I'm building. 

Fun fact: The word "Pepperoni" seems to be recognised very well, but for some reason "Vegetarian" doesn't get picked up half as well....