Pygame returns

We'll use Pygame again to make this simulation. The Pygame clock tick will be our unit of time. For every tick, we'll check the net force on the spacecraft and update the height, velocity, acceleration, and fuel remaining. Then we'll use that information to update the graphics and text. Because the animation is very simple, we won't use a sprite for the spaceship. But we'll use one for the throttle (the grey rectangle), because that makes it easy to drag it with the mouse. The fuel gauge is...

Wrapping the ball

Now let's look at the second option for keeping the ball moving. Instead of bouncing it off the side of the screen, we're going to wrap it around. That means, when the ball disappears off the right side of the screen, it'll reappear on the left side. To make things simpler, we'll go back to just moving the ball horizontally. The program is in listing 16.17. Listing 16.17 Moving a beach ball image with wrapping screen pygame.display.set_mode( 64 0,48 0 ) screen.fill( 255, 255, 255 ) my_ball...

Counting calories

Since everyone is concerned about nutrition these days, let's add a calorie count for each combination on the menu. You might not care about the calories, but I bet your parents do That will let us use some of Python's math abilities, which we learned about back in chapter 3. We already know which items are in each combination. All we need now are the calories for each item. Then we can add them all up in the innermost loop. Here's some code that sets how many calories are in each item Now we...

Using nested loops

So what can we do with all these nested loops Well, one of the things they're good for is figuring out all the possible permutations and combinations of a series of decisions. Permutation is a mathematical term that means a unique way of combining a set of things. Combination means something very similar. The difference is that, with a combination, the order doesn't matter, but with a permutation, the order does matter. If I asked you to pick three numbers from 1 to 20, you could pick and so...

Bump Collision detection

In most computer games, you need to know when one sprite hits another one. For example, you might need to know when the bowling ball hits the pins or when your missile hits the spaceship. You might be thinking that, if we know the position and size of every sprite, we could write some code to check those against the position and size of every other sprite, to see where they overlap. But the folks who wrote Pygame have already done that for us. Pygame has what's called collision detection built...

More wacky sounds

Now that we have the hit sound when the ball hits the paddle, let's add a few other sounds. We'll add sounds for these things when the ball hits the side walls when the ball hits the top wall and the player scores a point when the player misses the ball and the ball hits the bottom First we need to create sound objects for all of these. You can put the code anywhere after pygame.mixer. init but before the while loop hit_wall hit_wall.set_volume 0.4 get_point splat new_life new_life.set_volume...

Ten in a row

Let's do one more probability experiment before we move on. A few pages ago, we talked about flipping a coin and how likely it would be to get a bunch of heads in a row. Why don't we try an experiment to see how often we get 10 heads in a row It won't happen very often, so we're going to have to do a lot of coin flips before we see it. Why don't we try 1,000,000 With a real coin, that would take . . . a long time. If you could do one coin toss every 5 seconds, that would be 12 per minute, or...

Rect collision versus pixelperfect collision

Pygame Rect Sprite

One thing you'll notice is that the balls aren't always completely touching when they collide. That's because spritecollide doesn't use the round shape of the ball to detect collisions. It uses the ball's rect, the rectangle around the ball. If you want to see this, draw a rectangle around the ball image, and use that new image instead of the regular beach ball image. I've made one for you, so you can try it img_file b_ball_rect.png If you wanted the balls to bounce off each other only when the...

Virtual Pet Programming

We're going to make a very simplified Virtual Pet program, which, as we indicated, is a kind of simulation. You can buy virtual pet toys like a keychain with a small screen and download virtual pet software. There are also web sites like Neopets and Webkinz, which are forms of virtual pets. All of these, of course, are simulations as well. They mimic the behavior of a living thing and get hungry, lonely, tired, and so on. To keep them happy and healthy, you have to feed them, play with them, or...

Converting Fahrenheit to Celsius

The code for converting the other way from Fahrenheit to Celsius is very similar. The formula for that conversion is . ,c , It goes in the event handler for the Fahrenheit to Celsius button def on_btnFtoC_mouseClick self, event We need to get the Fahrenheit temperature from the spinner fahr self.components.spinFahr.value This value is already an integer, so we don't have to do any type conversion. Then we apply the formula , , . c . , 0 string and put it in the Celsius text box...

The numberguessing game again

Easygui Integerbox

In chapter 1, we made a simple number-guessing program. Now let's try the same thing, but using EasyGui for the input and output. Listing 6.5 has the code. Listing 6.5 Number-guessing game using EasyGui secret random.randint 1, 99 guess 0 tries 0 easygui.msgbox AHOY I'm the Dread Pirate Roberts, and I have a secret It is a number from 1 to 99. I'll give you 6 tries while guess secret and tries lt 6 guess easygui.integerbox What's yer guess, matey if not guess break if guess lt secret...

Connect the dots

Pygame Tutorial

If you look really closely, you might notice that the sine wave isn't continuous there are spaces between the points in the middle. That's because, at the steep part of the sine wave, we have to move up or down by 3 pixels when we move one pixel to the right. And because we're drawing individual points, not lines, there's nothing to fill the space in between. Let's try the same thing using a short line to join each plot point. Pygame has a method to draw a single line, but it also has a method...

Lunar Lander

We'll start with our spacecraft some distance above the moon's surface. The moon's gravity will start to pull it down, and we'll have to use the thrusters to slow its descent and make a soft landing. Here's what the program will look like The small grey bar on the left side is the throttle. You drag it up or down with the mouse to control the thrust of the engines. The fuel gauge tells you how much fuel you have left, and the text gives you information on your velocity, acceleration, height,...

Creating a deck of cards

Another kind of random event that's used a lot in games is drawing a card. It's random because the deck is shuffled, so you don't know what card is coming next. And every time the deck is shuffled, the order is different. With dice and coin tosses, we said that every toss has the same probability, because the coin or die has no memory. But that's not true with cards. As you draw cards from the deck, there are fewer and fewer cards left in most games, anyway . That changes the probability of...

Playing background music

Background music is meant to play in the background while the game is being played. So once you start the background song, Pygame has to get ready to do other things, like moving sprites around or checking the mouse and keyboard for input. It doesn't wait for the song to finish. But what if you want to know when the song ends Maybe you want to start a different song or play another sound like we want to do . How do you know when the music is done Pygame has a way to tell you you can ask the...

Images

Drawing shapes, lines, and individual pixels on the screen is one way to do graphics. But sometimes we want to use pictures that we get from somewhere else maybe from a digital photo, something we downloaded from the Web, or something created in an image-editing program. In Pygame, the simplest way to use images is with the image functions. Let's look at an example. We're going to display an image that is already on your hard drive if you installed Python from the book's installer. The...

Modern art

Modern Art Random Lines

Want to try making some computer-generated modern art Just for fun, try the code in listing 16.6. You can start with what you had from listing 16.5 and modify it, or just start from scratch. Listing 16.6 Using draw.rect to make art import pygame, sys, random pygame.init screen pygame.display.set_mode 64 0,48 0 screen.fill 255, 255, 255 for i in range 100 width random.randint 0, 250 height random.randint 0, 100 top random.randint 0, 4 00 left random.randint 0, 500 pygame.draw.rect screen, 0,0,0...

Colors in Pygame

The color system used in Pygame is a common one used in many computer languages and programs. It's called RGB. The R, G, and B stand for red, green, and blue. You might have learned in science class that you can make any color by combining or mixing the three primary colors of light red, green, and blue. That's the same way it works on computers. Each color gets a number from 0 to 255. If all the numbers are 0, there is none of any color, which is completely dark, so you get the color black. If...

Adding music to PyPong

There's just one thing left to do add the music. We need to load the music file, set the volume, and start it playing. We want it to keep repeating while the game is playing, so we'll use the special value of -1, like pygame.mixer.music.set_volume 0.3 pygame.mixer.music.play -1 This code can go anywhere before the main while loop. That will start the music playing. Now we just need to stop the music at the end, and there's a nice way to do this. pygame.mixer.music has a method called fadeout...

Crazy Eights

You might have heard of a card game called Crazy Eights. You might even have played it. One thing about card games on the computer is that it's difficult to have multiple players. That's because, in most card games, you're not supposed to see the other players' cards. If everyone is looking at the same computer, everybody will see everyone else's cards. So the best Jk Uses nested for loops to make a deck C Picks 5 cards from the deck to make a hand card games for playing on the computer are...

Python Skier Program

Pygame Skiers

Skier is a very simple skiing game, inspired by a game called SkiFree. You can find out all about SkiFree here en.wikipedia.org wiki SkiFree. You ski down a hill, trying to avoid trees and pick up flags. Picking up a flag earns 10 points. Crashing into a tree makes you lose 100 points. When you run the program, it should look something like this Skier uses something called Pygame to help with the graphics. Pygame is a Python module. We'll learn more about modules in chapter 15. If you ran the...

Controlling the paddle

Bouncing Balls Pygame

As I mentioned in the last section, we're going to control the paddle with the mouse. We'll use the mousemotion event, which means the paddle will move whenever the mouse moves inside the Pygame window. Because Pygame only sees the mouse when it's inside the Pygame window, the paddle will automatically be limited to the edges of the window. We'll make the center of the paddle follow the mouse. The code should look like this , _ elif event.type pygame.MOUSEMOTION event.pos is a list with the x,...

Checking the letter guesses

One of the trickiest parts of this program is checking the player s guessed letter to see if it appears in the secret word. What makes it tricky is that the letter could appear more than once in the word. For example, if the secret word is lever, and the player guesses e, you have to reveal both the second and fourth letters because they re both e. Carter needed a little help with this part, so I wrote a couple of functions that do this. The find_letters function finds all the places a...