What is TypeScript?

Transcript:

So what is TypeScript?

At a super high level TypeScript is JavaScript with static type checking. What that really means is that you no longer have to write JavaScript code purely based on faith and good guesses that the variables and objects you’re using are what you think they are.

TypeScript is going to come along side you and enforce that “hey this is a string this is a number this is you know some object with a certain felds” TypeScript is going to add those guarantees so that you can code with more confidence.

In practice you’ll find that you’ll have fewer dumb errors; If you’re working on a team, it becomes vastly easier to communicate what certain code does because they can see right there what the types are and when they go to use them TypeScript is going to tell them if they’re using them erroneously.

It is easier to communicate with your future self so that when you come back to your code it’s easier to tell how things work. You can just look and see what the types of various objects are without having to go back and actually run the program to see if the guesses you’re making about the program are actually true.

In short, the code has become much more self-documenting

If you go to the TypeScript website you’ll see Microsoft describes TypeScript as “JavaScript that scales”. What does that really mean?

What it has meant in my experience is that you can bring a team of people together or you can work on something yourself and you can build programs and applications that very large and complex and you’ll going to have much more confidence in what your building and in and how you’re managing the complexity then you would be if it was just plain JavaScript.

I can recall numerous times on plain JavaScript projects before we started using TypeScript that I would go to refactor something or move some code around or change some logic or whatever and I could never be entirely sure that I hadn’t broken something. Even if my tests pass even if in my manual testing everything was working right, I was never able to be fully confident in the changes I had made. It seems like there would always be something flew under the radar that got missed.With TypeScript that happens far far less often, in fact I’d say almost never.

TypeScript is a strict superset of JavaScript. What that means is that anything you know about JavaScript you can transfer into your knowledge of TypeScript. There are definitely new things to learn, but it’s not a whole new world that you’ll be completely lost and confused in. If you already know JavaScript, you’ll be good to go.

In a lot of cases you can take code that you’ve already written in JavaScript change the file extension from .js to .ts and everything will work, or most of it will work with maybe a few extra type annotations that you need to add in. So it’s very straightforward to get started and to jump in.

Another great thing about TypeScript is that it compiles directly to JavaScript. In practice that means that you don’t have to install any extra runtime or ship any additional library to your users in order to start using TypeScript in your application. In development, you’ll just run the TypeScript compiler and then away you go.

Since it’s just plain JavaScript you can use the same debugging tools that you’re already used to. You can also graudually introduce TypeScript into an existing JavaScript project, slowly converting files to TypeScript bit by bit as you go along.

If you’ve used other languages that compile to JavaScript, you might be used to the compiled code looking unintelligible, very much like a machine wrote it. In most caess, TypeScript is merely erasing your type annotations, so your original code remains. In cases where it does have to manipulate things, I’ve found it makes very readable choices about the code it produces.

Anothing great thing about TypeScript too is that it supports many of the new features that have been added to JavaScript in ES6 and other newer JavaScript versions. Not only that, but you can have TypeScript compile to older JavaScript versions so that you can use the latest features in TypeScript, but still support older browsers.

One thing I wanted to mention as well is that the types are in a lot of cases optional, or what you might call a gradual, or can be inferred by TypeScript. That means there’s a lot of cases where you don’t really need to tell it what the type of something is, it’ll see “hey I’m setting this variable to a string so that must be a string”, and you don’t have to do the redundant typings that you might have gotten used to if you came from a C# for a Java background, and that’s really nice.

Also, depending on the configuration flags you set and how much you use the catch-all “any” type, you can use the type checking as much or as little as you want. If you want it to be super strict and have types everywhere, you can, or if you want to write JavaScript in the more dynamic untyped way that you’re used to, you totally can.

I think TypeScript helps enforce some good habits in a few different ways. First, once you get used to the typings, it becomes very natural when writing new code to sketch out the interfaces and relationships between data before you start writing code, because you can use those right away when you start actually implementing your program, rather than just leaving them as inert comments or notes or thoughts in your head.

Second, depending on how you configure TypeScript you can make it so it’s much more strict about checking for null and undefined, which is a really good habit to get into.I’ve been guilty myself of getting lazy and thinking “well this could fail as null or undefined, but I’m just going to ignore it because it makes my code a lot simpler.” But if TypeScript is yelling at me I’m much more likely to do the proper thing and that’s really good.

Third, if you’re defining a type and it becomes hard to think about or it hard to describe a lot of times that’s been an indication to me that “hey I’m making this more complicated than it needs to be” or I’m I’m trying to do this in a way that might be clever now but it isn’t going to stand up to the test of time. I’m going to come back to this later be super confused or I’m going to have to hand this off to a co-worker and they’re going to be super confused.

Better IDE support is one thing that’s great is if you’re using something like Visual Studio Code or JetBrains WebStorm or any other IDE or Smart Text Editor with TypeScript. You get way better auto completion so you can access things or call functions and it’s going to tell you “hey this is how you call this thing” or “hey that’s an error you missed a parameter here” and that kind of thing.

If you’ve used just plain JavaScript in the past, you’ll know that IDEs can be pretty good about guessing what things might be, but there’s a lot of times where you’ll start typing a piece of code and it does the auto-completion and gives you every possible field name that I’ve defined in my project as an option. Which is massively unhelpful. With TypeScript you avoid that issue entirely, since it knows what the types of things are, you get vastly better auto completion support. Which makes you a much happier and more productive programmer.

So that’s a general overview of what TypeScript is. I hope that was helpful to you! I’ve got other videos out there on TypeScript, so if you want to learn more, please check them out!

If you visit https://typescriptbyexample.com you’ll see some info on a course that I’m building for TypeScript. You can put your email address in at the bottom of the page and you’ll be notified when that’s ready. I’d love to hear from you, and I’d love to have you be a part of the course. Thank you so much for watching! Goodbye!

How to Install TypeScript on Linux

Transcript:

Alright! Hello everybody! So, I wanted to show you how to install TypeScript on Linux. Before we get started, a word of caution. Every Linux distribution is a little bit different, in theory everything I show you here should work across most distributions, but it’s possible that yours might do something a little different. For reference, I’m using Ubuntu 18.04.1 LTS release for this video.

One thing I want to point out before I get started is that most Linux distributions have some sort of package management system that you may be able to use to install TypeScript. For example, Ubuntu offers the node-typescript package, which you can install via apt.

The problem is that these package managers often contain old versions of TypeScript, and TypeScript releases quite frequently, so today I’m going to be showing you how to install TypeScript directly from the source so you can be running the latest and greatest version.

So, to get started we’re going to open up whatever your favorite browser is, or whatever browser you have installed. Here I’m going to be using Firefox.

We are going to head over to https://nodejs.org Now, you’ll see a page like this. It’ll give you a couple of different download options and you can opt for either the LTS or the current release.

Either one of those works. I’m going to say go for the LTS version. That’s because that stands for long-term support, so this is the version that’s going to keep getting security updates and things like that.

That’s probably the one you’ll want to go with. If you want to be on the bleeding edge, and have the latest and greatest feel free to go with the other one, it will work just as well.

For this video I’m going to go with 10.15.1. Very likely if you’re watching this at any point in the future these version numbers are going to be different. Node.js does a lot of releases so, it’s totally okay if you’re on a later version than I am. Everything should work just as well.

Download it.

Alright, it has finished downloading, so let’s open a Terminal and extract the files and get started.

Here I’ve opened the default Terminal that comes with Ubuntu. We’re going to do:

cd Downloads

to get to our downloads folder.

We’re then going to type:

tar xvf node-v10.15.1-linux-x64.tar.xz

Hit enter. It’ll print out the files it unzipped and then we should be able to see the new folder.

Next we need to add Node.js to our PATH. We can do this by typing:

export PATH=~/Downloads/node-v10.15.1-linux-x64/bin:$PATH

Now that Node.js is on our PATH, we can test if Node.js is installed properly by typing:

node

and hitting enter.

And this little angle bracket should appear. And we can start entering JavaScript code here.

So, two plus two is four. Let’s see, we could do a setTimeout. So in 5 seconds that should display something. There it is.

If you want to get out of here just hit CTRL+C. Twice. And then you’re back on the normal Terminal prompt.

In order to use Node.js and TypeScript in future Terminal sessions, we’ll need to put that PATH line at the end of your .bashrc or .bash_profile file, or whatever profile file your shell of choice uses if you’re not on bash. To do that I’m going to open up Ubuntu’s default text editor.

We’ll hit open, and navigate to our home directory. Note that you’ll need to ensure that hidden files are showing. I can do that here by pressing CTRL+H. I’ll open .bashrc, copy that line from before, paste it to the bottom, and then save the file. And then, hey presto, any subsequent Terminals we open will have Node.js available to us.

So, all that out of the way, let’s install TypeScript! In order to install TypeScript we’re going to use something called npm. If you’re unfamiliar with npm that stands for the node package manager and that’s how lots of different Node.js based libraries and programs are distributed, TypeScript among them.

How do we use npm to install it? Well, here in this Terminal we’re going to type:

npm install --global typescript

And hit enter.

Note that if you’ve installed Node.js and npm from your package manager, you may need to prefix the previous command with sudo to run it with root priviledges

And you’ll see here it says added one package from one contributor in 1 second.

Now it’s very likely that you’ll see a different version number here. TypeScript also like Node.js releases fairly frequently. TypeScript is really good about backwards compatibility, so you shouldn’t have to worry about anything you see in this video or any later video being incompatible.

If you wanted to be on the exact version that I am going to show you, though, what you can do is go back to the Terminal and run:

npm uninstall --global typescript

to get rid of what we just installed.

And we’ll then run a command similar to what we did before:

npm install --global typescript@3.3.3

When you add that @ sign and then the version number, it’s going to guarantee that that’s the version you’re going to install rather than whatever the latest is (which is the default).

There we go. We’ve got that working.

So now what I’m going to do is create a new folder on the desktop. We’re going to call it “test” and we’re just going to see if TypeScript is working.

Let’s open up “test”.

We’re going navigate our Terminal to this new folder as well. You can do this by typing:

cd ~/Desktop/test

Once you’ve done that we’re going to create a file named main.ts. All TypeScript files end in .ts.

You can do this by entering the comand:

touch main.ts

You’ll see the file appears in the folder.

Now let’s put something in this main.ts file for TypeScript to compile. So, we’re going to open up the default text editor that comes with Ubuntu. If you have a particular text editor that you prefer, feel free to use it.

I’m going to go to Open and find main.ts in the folder on my Desktop.

And then we’ll put in the simplest possible “Hello, World!” program and save it.

console.log("Hello, World!");

Now in order for TypeScript to compile our “Hello, World!” program it needs a configuration file.

We can create the default one by going back to our Terminal and running:

 tsc --init

When we hit enter, it’s going to create that file for us. So, you can see this tsconfig.json file has been created.

Don’t worry too much about that file I will be creating a video explaining exactly what it is, why we use it, how to use it, what the different options inside it mean for now all we need to know is that we need it there and now we have it.

And to get TypeScript to compile our main.ts file, just run:

tsc

and hit enter. It will find all the TypeScript files in this folder and compile them. You see we now have a main.js file.

We’ll run that main.js file through Node.js:

node main.js

And see we’ve got “Hello, world!”

Awesome! Exactly what we wanted.

So everything’s working. If you’re seeing the same thing, hey you’re good to go, you’ve got TypeScript installed.

There is one other thing I wanted to show you: You can have TypeScript watch for changes, rather than having to rerun it each time you change something. So, what we’re going to do is do is go back to our Terminal and enter:

tsc --watch

See it gives us a little message “starting compilation in watch mode”.

And then I’m going to go back to our file and say “Hello World! Again!” and I’m going to save it. And you see that flashed a bit. It said “file change detected”, “0 errors”.

We’re going to open up another Terminal and do the same:

cd ~/Desktop/test"

that we did before.

You can see if we run our main.js, hey! It says “Hello World! Again!” just like we wanted.

One thing that’s really nice about this is that if you make a mistake, here I’m going to forget to have the closing parenthesis and semicolon, if we save this TypeScript is going to give us an error and say “hey! I expected a closing parenthesis here!”

So we can add that back in and save it and everything’s happy again.

Very cool! That’s it! You’ve got TypeScript installed!

By the way if you’re interested in going deep into learning TypeScript I’ve got this TypeScript by Example course that I’m working on now. You can head on over to https://typescriptbyexample.com Scroll down to the bottom, and you can put in your email address to be notified when the course is released. Also, stay tuned to this YouTube channel for future updates. Thank you so much for watching!

How to Install TypeScript on macOS

Transcript:

Alright! Hello everybody!

So, I wanted to show you how to install TypeScript on macOS.

So, first things first we’re going to open up whatever your favorite browser is, or whatever browser you have installed. Here I’m going to be using Safari.

We are going to head over to https://nodejs.org

Now, you’ll see a page like this. It’ll give you a couple of different download options and you can opt for either the LTS or the current release.

Either one of those works. I’m going to say go for the LTS version. That’s because that stands for long-term support, so this is the version that’s going to keep getting security updates and things like that.

That’s probably the one you want to go with.

If you want to be on the bleeding edge, and have the latest and greatest feel free to go with the other one, it will work just as well. For this video I’m going to go with 10.15.1.

Very likely if you’re watching this at any point in the future these version numbers are going to be different. Node.js does a lot of releases so, it’s totally okay if you’re on a later version than I am. Everything should work just as well.

Download it.

Alright, it has finished downloading, so I’m going to go to my Downloads folder and open it.

We’re just going to click through here.

We’ll hit continue.

We’ll hit continue again. It’ll prompt us to agree to the license, click agree.

It’ll take 60 megabtyes of space, that’s fine by me, hit Install.

Enter your account password at the authorization prompt and hit Install Software.

Give that a few moments. Alright, and Node.js has been installed! Hit Close.

We don’t need the installer any more, so just hit “Move to Trash” here.

So, how can we verify that things are working here?

Well, let’s go to the application search in the top-right corner of the screen and look for “Terminal”.

Here we’ve got our Terminal. The way we can test if Node.js is installed properly is to type:

node

and hit enter.

And this little angle bracket should appear.

And we can start entering JavaScript code here. So, two plus two is four. Let’s see, we could do a setTimeout. So in 5 seconds that should display something. There it is.

If you want to get out of here just hit CTRL+C. Twice.

And then you’re back on the normal Terminal prompt.

So, let’s install TypeScript.

In order to install TypeScript we’re going to use something called npm. If you’re unfamiliar with npm that stands for the node package manager and that’s how lots of different Node.js based libraries and programs are distributed, TypeScript among them.

So, how do we use npm to install it? Well, here in this Terminal we’re going to type:

sudo npm install --global typescript

And hit enter.

Enter our password. Give that a few moments to do its thing.

And you’ll see here it says added one package from one contributor in 6 seconds.

Now it’s very likely that you’ll see a different version number here. TypeScript also like Node.js releases fairly frequently. TypeScript is really good about backwards compatibility, so you shouldn’t have to worry about anything you see in this video or any later video being incompatible.

If you wanted to be on the exact version that I am going to show you, though, what you can do is go back to the Terminal and run:

sudo npm uninstall --global typescript

To get rid of what we just installed. And we’ll then run a command similar to what we did before:

sudo npm install --global typescript@3.3.3

When you add that @ sign and then the version number, it’s going to guarantee that that’s the version you’re going to install rather than whatever the latest is (which is the default).

There we go. We’ve got that working.

So now what I’m going to do is create a new folder on the desktop. We’re going to call it “test” and we’re just going to see if TypeScript is working. It’s installed but is it actually working?

Let’s open up “test”. We’re going navigate our Terminal to this new folder as well. You can do this by typing:

cd Desktop/test

Once you’ve done that we’re going to create a file named main.ts. All TypeScript files end in .ts.

You can do this by entering the comand:

touch main.ts

You’ll see the file appears in the folder.

Now let’s put something in this main.ts file for TypeScript to compile.

So, we’re going to open up TextEdit. If you have a particular text editor that you prefer, feel free to use it. TextEdit is all I’ve got on this particular machine at the moment. I’m going to go to File -> Open and find main.ts in the folder on my Desktop.

And then we’ll put in the simplest possible “Hello, World!” program and save it.

Now in order for TypeScript to compile our “Hello, World!” program it needs a configuration file.

We can create the default one by going back to our Terminal and running:

tsc --init

If we hit enter, it’s going to create that file for us. So, you can see this tsconfig.json file has been created.

Don’t worry too much about that file I will be creating a video explaining exactly what it is, why we use it, how to use it, what the different options inside it mean for now all we need to know is that we need it there and now we have it.

And to get TypeScript to compile our main.ts file, just run:

tsc

It will find all the TypeScript files in this folder and compile them. You see we now have a main.js file.

We run that main.js file through Node.js, and see we’ve got “Hello, world!”

Awesome! Exactly what we wanted.

So everything’s working. If you’re seeing the same thing, hey you’re good to go, you’ve got TypeScript installed.

There is one other thing I wanted to show you: You can have TypeScript watch for changes, rather than having to rerun it each time you change something.

So, what we’re going to do is do is go back to our Terminal and enter:

tsc --watch

See it gives us a little message “starting compilation in watch mode”.

And then I’m going to go back to our file and say “Hello World! Again!” and I’m going to save it. And you see that flashed a bit. It said “file change detected”, “0 errors”.

We’re going to open up another Terminal and do the same “cd Desktop/test” that we did before.

You can see if we run our main.js, hey it says “Hello World! Again!” just like we wanted.

One thing that’s really nice about this is that if you make a mistake, here I’m going to forget to have the closing parenthesis and semicolon, if we save this TypeScript is going to give us an error and say “hey! I expected a closing parenthesis here!”

So we can add that back in and save it and everything’s happy again.

Very cool! That’s it!

You’ve got TypeScript installed!

By the way if you’re interested in going deep into learning TypeScript I’ve got this TypeScript by Example course that I’m working on now.
You can head on over to https://typescriptbyexample.com

Scroll down to the bottom, and you can put in your email address to be notified when the course is released.

Also, stay tuned to this YouTube channel for future updates. Thank you so much for watching!

How to Install TypeScript on Windows

Transcript:

Alright! Hello everybody! So, I wanted to show you how to install TypeScript. So, first things first we’re going to open up whatever your favorite browser is, or whatever browser you have installed.

We are going to head over to nodejs.org. Now, you’ll see a page like this. It’ll give you a couple of different download options and you can opt for either the LTS or the current release.

Either one of those works. I’m going to say go for the LTS version. That’s because that stands for long-term support, so this is the version that’s going to keep getting security updates and things like that. That’s probably the one you want to go with. If you want to be on the bleeding edge, and have the latest and greatest feel free to go with the other one, it will work just as well. For this video I’m going to go with 10.15.1.

Very likely if you’re watching this at any point in the future these version numbers are going to be different.

Node.js does a lot of releases so, it’s totally okay if you’re on a later version than I am. Everything should work just as we;ll.

Download it.

Antivirus just finished scanning it, and here it is it’s open.

You might need to go find it in your downloads folder and double-click on it. I just had it run when I download it.

We’re just going to click through here. We’re going to accept the license agreement. We’re going to accept the default install path.

We’re going to leave all these things on the defaults.

Install.

We get our security prompt here will say yes so that it can install.

Give that a few moments. Alright, and Node.js has been installed.

So, how can we verify that things are working here? Well, let’s go to the start menu there should be something called Node.js command prompt in there and Node.js itself in your start menu. You might have to search for it. Here it’s showing up under my recently added.

So if we go in here we have an Node.js command prompt. This looks very much like any other command prompt you may have seen. Just for comparison,

Let’s open up the other one. You can see normally for just a plain old command prompt we get the windows version information.

But here we’re actually getting the Node.js version information. So, we can tell that things are working already. The way you can test Node.js is type node and hit enter.

And this little angle bracket should appear.

And we can start entering JavaScript code here. So, two plus two is four. Let’s see, we could do a setTimeout.

So in 5 seconds that should display something.

There it is.

If you want to get out of here just hit CTRL+C.

Twice.

And then you’re back on the normal command prompt. So, let’s. install TypeScript.

So, alright so to install TypeScript we’re going to use something called npm. If you’re unfamiliar with npm that stands for the node package manager and that’s how lots of different Node.js based libraries and programs are distributed, TypeScript among them. So TypeScript is written in JavaScript and it is distributed

Via npm because it runs on Node.js. So, how do we use npm to install it? Well, here in this Node.js Command Prompt we’re going to type npm install –global typescript . Going to hit enter.

Give that a few moments to do its thing.

And you’ll see here it says added one package from one contributor in one second.

Now it’s very likely that you’ll see a different version number here. TypeScript also like Node.js releases fairly frequently. TypeScript is really good about backwards compatibility, so you shouldn’t have to worry about anything you see in this video or any later video being incompatible. If you wanted to be on the exact version that I am going to show you, though, what you can do is we’re going to do:

npm uninstall --global typescript

And similar to before we’re going to do:

npm install typescript@3.3.3

and so if you add that @ sign and then the version number, that’s going to guarantee that that’s the version you’re going to install rather than whatever the latest is which is the default.

There we go. We’ve got that working.

So now what I’m going to do is create a new folder on the desktop. We’going to call it “test” and we’re just going to see if TypeScript is working. It’s installed but is it actually working? We’re going to open up “test”.

We’re going to create a new file.

We’re going to call this main.ts. All TypeScript files end in .ts So, if you do what I did there and go to “New Text Document” it might not let you edit the file extension depending on what you’re doing, and you could end up with something that’s actually.ts.txt, which really isn’t what you want. The way you can check for this is you can go to this View tab that’s up here and make sure this “file name extensions” checkbox is checked.

You can see if I uncheck it the file extension goes away, and you can’t tell what it is. If I check it it tells me we’ve got main.ts which is what we want.

So we’re going to move our Command Prompt into this folder. How do you do that?

I’m going to click here to get the full path to this folder. Then type cd which stands for “change directory” and do a quote.

If you right click it’s going to paste what you just copied.

We’re going to do an end quote.

And here we are in that folder.

Now in order for TypeScript to compile something it needs a configuration file.

We can create the default one by running:

tsc --init

If we hit enter, it’s going to create that file for us. So, you can see this tsconfig.json file has been created. Don’t worry too much about that file I will be creating a video explaining exactly what it is.

Why we use it, how to use it, what the different options inside it mean for now all we need to know is that we need it there and now we have it.

Now before we go compiling anything with TypeScript we should probably put something in this main.ts file for TypeScript to compile. So, we’re going to open up notepad. Feel free to use any other text editor of your choice. That’s just all I’ve got on this particular machine at the moment.

And we’re going to go in, and I’m going to switch this over to “all files” so I can see my main.ts and we’re just going to write a super simple “Hello, world!” program.

There you go, there’s your “hello world”.

Hit CTRL+S to save it. Minimize that.

And then to get TypeScript to compile your files.

Just run tsc.

It will find all the TypeScript files in the folder and compile them. You see we now have a main.js file.

We run that made that main.js file through Node.js.

And see we’ve got “Hello, world!” Awesome! Exactly what we wanted.

So everything’s working. If you’re seeing the same thing, hey you’re good to go, you’ve got TypeScript installed.

One other thing I wanted to show you.

Was that you can have TypeScript, rather than having to rerun it each time you change something, you can have TypeScript watch for changes. So, what we’re going to do is do:

tsc --watch

We’re going to hit enter.

See it gives us a little message “starting compilation in watch mode”.

I’ll move this so you can see it, and then I’m going to say “Hello World! Again!” and I’m going to hit CTRL+S to save right now.

And you see that flashed a bit. It said “file change detected”, “0 errors”.

We’re going to open up another Node.js Command Prompt.

Do the same thing we did before so we can run this.

You can see if we run our main.js, hey it says hello world again just like we wanted.

One thing that’s really nice about this is that if you make a mistake, here I’m going to forget to have the closing parenthesis and semicolon, if we save this TypeScript is going to give us an error and say “hey! I expected a closing parenthesis here!”

So we can add that back in and save it and everything’s happy again.

Very cool, you’ve got TypeScript installed!

By the way if you’re interested in going deep into learning TypeScript I’ve got this TypeScript by Example course that I’m working on now. You can head on over to typescriptbyexample.com. Scroll down to the bottom, and you can put in your email address to be notified when the course is released. Also, stay tuned to this YouTube channel for future updates. Thank you so much for watching!

Making Games with Ruby Ep. 3 – Basics

Covered In This Episode:

  • Creating a Window
  • Basic Event Handling

Transcript:

Hello Everybody and welcome to making games with Ruby episode 3, Basics. I’m Tyler and these videos are brought to you by manwithcode.com.

Today we’re just going to be talking about the very basics of game creation, just getting a window on the screen. The code for this episode is on manwithcode.com, if you’re not there already. https://manwithcode.com/322/making-games-with-ruby-ep-3-basics

Lets get started!

We’re going to start by requiring in the libraries we need, which for now is only rubygems and rubygame:

require 'rubygems'
require 'rubygame'

Then we’re going to create the main Game class, and stub out all the methods in it:

class Game
	def initialize
	end

	def run!
	end

	def update
	end

	def draw
	end
end

And after that we’re going to add the code to run the game:

g = Game.new
g.run!

So far this is just some very basic structure, nothing really happens yet. I’m going to run the code just to double check we have no syntax errors…

The first thing we’re going to do is initialize everything we’ll need:

def initialize
	@screen = Rubygame::Screen.new [640, 480], 0, [Rubygame::HWSURFACE, Rubygame::DOUBLEBUF]
	@screen.title = "Pong"

	@queue = Rubygame::EventQueue.new
	@clock = Rubygame::Clock.new
	@clock.target_framerate = 60
end

Some of this is self explaitory, but let’s break it down. The first line of initialize creates the window for our game, Rubygame calls this a Screen. The first argument [640, 480] is the size of the screen, the second is the screen depth (you don’t need to worry about this), the last one is a list of flags we pass to rubygame. HWSURFACE means we want it to be accelerated on the graphics card if available, and DOUBLEBUF means we want the screen to be double buffered. Double buffering is a way of drawing to the screen. I won’t go into too much detail right now to explain double buffering, but I will in a later episode.

The second line has an obvious purpose, it sets the title at the top of the screen to Pong

The fifth line is setup so we can handle events, I’ll talk more about this later.

The last two lines are the setup so we can limit the framerate to 60 frames per second. The frame rate is how many times the screen is drawn every second (we’ll be doing our drawing in the Game#draw method). If we let this go unchecked, our game will run as fast as possible which isn’t desireable since top speed will be different on different computers, and depending on what the game is doing at a particular moment in time. I think 60 is a good number, but we can easily change it later if we want.

Next we’re going to setup the main game loop:

def run!
	loop do
		update
		draw
		@clock.tick
	end
end

This loops indefinately until we decide in a different part of the code to end the game. @clock.tick is what allows us to limit our framerate. You can now run the game, it should just be a black screen. You can see the title at the top, like we set in the initialize function.

But if you try to close the window… Nothing happens!!! To close it try pressing CTRL+C in the command prompt window, or you may have to go to the task manager and kill it from there. To fix this problem, we need to talk about the event queue.

We’re going to start by defining the update method:

def update
	@queue.each do |ev|
		case ev
			when Rubygame::QuitEvent
				Rubygame.quit
				exit
		end
	end
end

Whenever the user gives us some input, presses a key, moves the mouse, etc. the Rubygame adds an event for this input onto the queue. We handle these events in our update method.

@queue.each loops over each event, and we have a case statement that handles the event depending on the type. For closing the window, the event type is Rubygame::QuitEvent, which is generated whenever the user presses the close window button or ALT+F4.

Now if you run the game, the window should appear and you should be able to close it now! Yay!

This is the final source listing for this episode:

require 'rubygems'
require 'rubygame'

class Game
	def initialize
		@screen = Rubygame::Screen.new [640, 480], 0, [Rubygame::HWSURFACE, Rubygame::DOUBLEBUF]
		@screen.title = "Pong"

		@queue = Rubygame::EventQueue.new
		@clock = Rubygame::Clock.new
		@clock.target_framerate = 60
	end

	def run!
		loop do
			update
			draw
			@clock.tick
		end
	end

	def update
		@queue.each do |ev|
			case ev
				when Rubygame::QuitEvent
					Rubygame.quit
					exit
			end
		end
	end

	def draw
	end
end

g = Game.new
g.run!

This brings us to the end of the episode.

If you have any questions, comments, or suggestions, leave a comment on this page or email me at tyler@manwithcode.com.

Thank you very much for watching! Goodbye!