A card object

We're going to use a list to act as our deck of cards. But what about the cards themselves How should we store each one As a string An integer What things do we need to know about each card For card games, these are the three things we usually need to know about a card Suit Diamonds, Hearts, Spades, or Clubs. Rank Ace, 2, 3, . . . 10, Jack, Queen, King. Value For the numbered cards (2 through 10), this is usually the same as their rank. For Jack, Queen, and King, it's usually 10, and for the...

An example classHot Dog

For this example, we'll assume that hot dogs always have a bun. (It's too messy otherwise.) We'll give our hot dog some attributes and some methods. cooked_level A number that lets us know how long the hot dog has been cooked. We'll use 0-3 for raw, over 3 for medium, over 5 for well-done, and anything over 8 will be charcoal Our hot dogs will start out raw. cooked_string A string describing how well-done the hot dog is. condiments A list of what's on the hot dog, like ketchup, mustard, and so...

Sorting in reverse order

There are two ways to get a list sorted in reverse order. One is to sort the list the normal way, and then reverse the sorted list, like this Here we saw a new list method called reverse(), which reverses the order of items in a list. The other way is to add a parameter to sort() to make it sort in descending order (from largest to smallest). The parameter is called reverse, and it does exactly what you'd expect it makes the list sort in reverse order. Remember that all of the sorting and...

Test your knowledge

1 A random event is something that happens (an event) where you don't know ahead of time what the outcome will be. Two examples are flipping a coin (you don't know if it will come up heads or tails), and rolling a pair of dice (you don't know what numbers will come up on the dice). 2 Rolling an 11-sided die is different from rolling two 6-sided dice because, with an 11 -sided die, all numbers from 2 to 12 have an equal probability of coming up. With two 6-sided dice, some numbers (totals of the...

Try it out

I Here is a program that draws a few different shapes on the screen. You can also find it as TIO_CH16_1.py in the answers folder and on the web site. import pygame screen screen pygame 235) pygame 290) pygame 132) pygame pygame pygame pygame (60, 86), pygame 5) pygame.display.set_mode((64 0, 480)) fill((250, 120, 0)) draw.arc(screen, (255, 255, 0), pygame.rect.Rect(43, 368, 277, , -6.25, 0, 15) draw.rect(screen, (255, 0, 0), pygame.rect.Rect(334, 191, 190, .draw.rect(screen, (128, 64, 0),...

Your second program

It just printed some stuff on the screen. Let's try something a bit more interesting. The next code in listing1.2 is for a simple number-guessing game. Start a new file in the IDLE editor using File > New Window, just like you did the first time. Type in the code from listing 1.2 and then save it. You can call it whatever you want, as long as it ends with .py. NumGuess.py might be a good name. It's only 18 lines of Python instructions, plus a few blank lines...

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...

Starting pygamemixer

In order to play sounds, we have to initialize pygame.mixer. Remember what initializing means It means to get something ready at the start. Getting pygame.mixer ready is very easy. We just need to add the line after we initialize Pygame. So the code at the start of a program that uses Pygame for sound Now we're ready to play some sounds. There are two main types of sounds you'll use in your programs. The first is sound effects or sound clips. These are usually short, and they're most commonly...

Making our GUI do something

We now have a very basic GUI a window with a button and a very simple menu. The menu was added automatically for us. But it doesn't do anything. We haven't written any code to tell the program what to do when someone clicks the button. It's like having a car with four wheels and a body, but no engine. It looks nice, but it won't go anywhere. She's a realJbeauty'ain't she We need a little bit of code to make our program run. For a PythonCard program, the minimum you need is something like this '...

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...

Try try again

We'll be using another new thing in this program. It's called a try-except block. If a program is going to do something that could cause an error, it's nice to have some way to catch the error and deal with it, instead of having the program just stop. A try-except block does that. For example, if you try to open a file and the file doesn't exist, you'll get an error. If you don't handle this error, the program will just stop at this point. But maybe you want to ask the user to reenter the...

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...

Game over

The last thing we need to add is a Game Over message when the player uses up the last life. We'll make a couple of font objects that include our message and the player's final score, render them create surfaces with the text on them , and blit the surfaces to screen. We also need to stop the ball from reappearing after the last turn. To help with that, we'll make a done variable to tell us when we're at the end of the game. The following code will do that it goes inside the main while loop. if...

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...

Timer events

So far in this chapter, we have seen keyboard events and mouse events. Another kind of event that's very useful, especially in games and simulations, is a timer event. A timer generates an event at regular intervals, like your alarm clock. If you set it and leave the alarm on, it will ring at the same time every day. Pygame timers can be set for any interval. When the timer goes off, it creates an event that the event loop can detect. And what kind of event does it generate It generates...

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...

Rolling the dice

Almost everyone has played a game using dice. Whether it's Monopoly, Yahtzee, Trouble, Backgammon, or some other game, rolling dice is one of the most common ways to generate a random event in a game. Dice are very easy to simulate in a program, and Python's random module has a couple of ways to do it. One is the randint function, which picks a random integer. Because the number of spots on the sides of a die are integers 1, 2, 3, 4, 5, and 6 , rolling a single die could be simulated like this...

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...

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...

Smoother animation

So far, we have made our ball move once Let's see if we can get it moving in a more realistic way. When animating things on the screen, it's usually good to move them in small steps, so the motion appears smooth. Let's try moving our ball in smaller steps. We're not just going to make the steps smaller we're going to add a loop to move the ball because we want to make many small steps . Starting with listing 16.13, edit the code so it looks like listing 16.14. Listing 16.14 Moving a beach ball...

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...

Individual pixels

Sometimes we don't want to draw a circle or rectangle, but we want to draw individual dots or pixels. Maybe we're creating a math program and want to draw a sine wave, for example. Don't worry if you don't know what a sine wave is. For the purposes of this chapter, it is just a wavy shape. Also don't worry about the math formulas in the next few example programs. Just type them in as they appear in the listings. They are just a way to get a wavy shape that is a nice size to fill our Pygame...

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...