How to develop games using Python

Source: Internet
Author: User
How to use Python to develop games is an article published by Julian Meyer, a 12-year-old python developer, from the tutorial team. You can find him on Google + and Twitter.

Have you ever wondered how to create a video game? It is not as complicated as you think!

In this tutorial, you will create a simple game called rabbit and Badger, where the rabbit as a hero wants to defend the castle against the attacking Badger Group. : O

Write this game and you will use Python. No, I'm not referring to a big snake! :]

Python is a computer programming language. In this tutorial, we chose Python. Python is an easy-to-use, interesting, and easy-to-learn language.

If you are new to Python, check this book first-go deep into Python: How to Think Like a computer scientist will speed you up.

Then come back and prepare for the start-there is a battle between the Bunny and the badger that is about to happen. Continue reading. join the war!

Start: install Python

If you want to try this tutorial on a Windows computer, you need to install Python. remember to install version 2.7.3 instead of version 3.3.0! After the installation program is run, IDLE is displayed in the Start menu program folder to run IDL.

If you use Mac, Python has been installed! Open a Terminal (/Applications/Utilities/Terminal. app), input python, and press enter.

Note: If you install Python from python.org (if you want to obtain PyGame, you also need to enter IDLE on Mac. It should be in the "Applications/Python 2.7" folder.

If the operation is correct, you will see similar output:

Python 2.7.3 (v2.7.3:70274d53c1dd, Apr  9 2012, 20:52:43) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwinType "help", "copyright", "credits" or "license" for more information.>>>

Note: If you want to exit the Python prompt window (three angle brackets: >>>), you can enter exit () or press Ctrl + D in the prompt window.

Once you are in the Python prompt window, if you test whether Python works normally, input print 1 + 1 and press enter or line feed to output 2. You have written your first Python program.

Now you know that Python works normally. to write games using Python, you need to install PyGame.

PyGame is a Python library that makes writing games simple. It provides functions such as processing and sound playback. you can easily add all functions in the game.

Here, we will download the PyGame suitable for your system, and confirm that you are downloading a version of Python2.7.

Note: The PyGame installation file downloaded from the above link cannot work with the Python installed by default on Apple's Mac. to use PyGame, you need to download and install Python from python.org, alternatively, you can install Python and PyGame through MacPorts.

To check whether PyGame is correctly installed, open the IDLE or run Python on the terminal and enter import pygames at the Python prompt. If no output is displayed after the carriage return, the installation is successful.

If, on the other hand, a similar error is output below, PyGame is not correctly installed.

Python 2.7.2 (default, Jun 20 2012, 16:23:33) [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> import pygameTraceback (most recent call last):  File "
 
  ", line 1, in 
  
   ImportError: No module named pygame>>>
  
 

If you encounter a similar error, I will help you make it work on the forum.

Run Python code from a file

Although you can run short Python code at a Python prompt, if you work in a large program (such as a game), you may want to save your code to a file, in this way, you do not have to type it over and over again.

There are several methods to run Python program files. One way is to use a plain text editor, not as good as notepad (Windows) or TextEdit (Mac ). Open a new text file and enter your Python code (like print 1 + 1 ). Save it as asXXX. py (XXX can be any descriptive file name ).

If you are using Windows, double-click the file to run it. On Mac, open the terminal, input python, drag the file you saved to the terminal window, and press Enter.

Another method is to type the code class to IDLE, that is, the method you need to do in this tutorial. Run IDLE-enter IDLE on the terminal. Select File \ New Window. a text editor Window is displayed. You can Save your changed code through File \ Save and Run the code by running Run \ Run Module (F5.

Note that the running menu is only valid when an existing file is opened in the editor window.

Add game resources

You can almost start creating your game. But what are games that do not have shocking images or sound effects? I have collected the graphics and sound effects required by the game and compressed them into a ZIP file. you can download them here.

After downloading the file, create a folder for the game on your hard disk and decompress the resources folder to this folder. in this way, your game folder has a sub-folder named resources, various resources are grouped in the resources folder as follows:

You are ready for the rabbit and badger games. :]

Step 1: (simple) Hello Bunny (hey, rabbit)

Run the IDLE development environment and open a new text editing window as mentioned in the previous section. In the edit window, type the following code:

# 1 - Import libraryimport pygamefrom pygame.locals import * # 2 - Initialize the gamepygame.init()width, height = 640, 480screen=pygame.display.set_mode((width, height)) # 3 - Load imagesplayer = pygame.image.load("resources/images/dude.png") # 4 - keep looping throughwhile 1:    # 5 - clear the screen before drawing it again    screen.fill(0)    # 6 - draw the screen elements    screen.blit(player, (100,100))    # 7 - update the screen    pygame.display.flip()    # 8 - loop through the events    for event in pygame.event.get():        # check if the event is the X button         if event.type==pygame.QUIT:            # if it is quit the game            pygame.quit()             exit(0)

Save it to your game Directory (that is, the resource subdirectory) and name it itgame. py.

Let's analyze the above code one by one:

1. import the PyGame Library. This step allows you to use functions from the library in your program.

2. initialize PyGame and set the display window.

3. load the image you want to use for bunny.

4. execute the following indent code in a loop.

5. fill the screen in black before drawing.

6. display the previously loaded bunny image in the size of 100*100 on the screen.

7. update the screen.

8. check if any new events exist. Otherwise, go to the exit command and exit the program.

Note: According to PyGame documentation, you do not need to call pygame. quit () because it is automatically called when the parser is closed. However, at least on Mac OS, the game will be suspended upon exit unless pygame. quite is called.

If you Run this code now (click "Run \ Run Module" in the Idle menu bar), you can see a screen as shown below:

Yeah, the rabbit is displayed on the screen and ready to do the action!

But only one rabbit is displayed on a dark screen, and the game looks scary and lonely. The next step is to beautify it.

Step 2: Add a set

First, add background images to the game scenario. you can call a set of screen. bits () to add background images.

In section #3 of the code, add the following code after loading the role Image:

grass = pygame.image.load("resources/images/grass.png")castle = pygame.image.load("resources/images/castle.png")

The code loads the image, assigns it to the specified variables, and then draws them to the screen. However, if you check the lawn image, you will find that it does not cover the entire 640x480 screen, so you must tile to make the lawn picture completely overwrite the screen.

Add the following code to game. py at the beginning of section #6 (before the rabbit is painted on the screen:

for x in range(width/grass.get_width()+1):for y in range(height/grass.get_height()+1):screen.blit(grass,(x*100,y*100))screen.blit(castle,(0,30))screen.blit(castle,(0,135))screen.blit(castle,(0,240))screen.blit(castle,(0,345 ))

As you can see, first, the x coordinate increases through the for loop, then the y coordinate increases cyclically in this loop, and the grass is painted on the x and y coordinates generated by the loop. The subsequent code just draws the castle on the screen.

When you run this program, you will see the following results:

From now on, it's better to see it! :]

Step 3: Let the rabbit move

Next you need to add some real game elements, such as asking the rabbit to respond to the keyboard buttons.

To do this, you need to implement a method to record which key is pressed at a certain time. You can simply use an array to save it in the press state of the key required by the game.

Add the following code to the #2 section of game. py (after you set the screen height and width ):

keys = [False, False, False, False]playerpos=[100,100]

This code is very clear. The arrays keys record their states in the order of WASD. Each element of the array corresponds to A key. The first element is W, and the second element is.

The playerpos variable defines the starting position of the game role that the program begins to draw. This game moves a mobile game role to a different location, sets a variable to store the role location, and then you can simply draw the role to this location.

Now you need to modify the existing code to draw the role, use the new playerpos variable, and set the #6 program:

screen.blit(player, (100,100))

Changed:

screen.blit(player, playerpos)

Next, based on which buttons are pressed to the update key array, PyGame makes the detection button easy to implement by adding the event. key event.

Add the code after #8 detects event. type = pygame. QUIT (if there is a block indent, use the same indentation level as pygame. QUIT ):

if event.type == pygame.KEYDOWN:if event.key==K_w:keys[0]=Trueelif event.key==K_a:keys[1]=Trueelif event.key==K_s:keys[2]=Trueelif event.key==K_d:keys[3]=Trueif event.type == pygame.KEYUP:if event.key==pygame.K_w:keys[0]=Falseelif event.key==pygame.K_a:keys[1]=Falseelif event.key==pygame.K_s:keys[2]=Falseelif event.key==pygame.K_d:keys[3]=False

Wow! There are a lot of lines of code here. If you split it by the If statement, it is not very complicated.

First, you need to check whether a key is pressed or released, and then you need to check which key is pressed or released. if the key is pressed or released, update the corresponding key variable based on the key value.

Finally, you need to update the playerpos variable as the key-press response, which is too simple.

Add the following code to the end of game. py (use the same indentation level, use the same indentation level as the for loop)

# 9 - Move playerif keys[0]:playerpos[1]-=5elif keys[2]:playerpos[1]+=5if keys[1]:playerpos[0]-=5elif keys[3]:playerpos[0]+=5

This code only checks which key is pressed and then adds or removes the x or y position of the game role (depending on the key pressed) to move the game role.

Run this game and you will get the same role as before. Try pressing the WASD key. haha, it works!

Step 4: rotate the rabbit

Yes, your rabbit can now move with your buttons, but it's cool to use the mouse to rotate the rabbit in the direction you choose, so it's not always in the same direction. It is easy to use trigonometric functions.

Let's look at the diagram below:

If () is the rabbit position and () is the current mouse position, you can obtain the rotation angle (z) by applying the atan2 trigonometric function to the distance between two points ). Of course, once you know the rotation angle, you can easily rotate the rabbit accordingly. :]

If you are confused about this part, don't worry, you can continue. But that's why you should work hard in math! :] You will always use this item during game programming.

Now you need to apply this principle to your game. to do this, you can use the PyGameSurface. rotate (degree) function. By the way, remember that the Z value is a radian. :[

The atan2 function is used in the math library of Python. all functions are first added at the end of #1:

import math

Then, replace the last line of #6 (player. blit) with the following code:

# 6.1 - Set player position and rotationposition = pygame.mouse.get_pos()angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26))playerrot = pygame.transform.rotate(player, 360-angle*57.29)playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2)screen.blit(playerrot, playerpos1)

Let's sort out the basic process of the above code. First, get the location of the mouse and game role, then you apply the atan2 function to the two locations, and then you convert the radians returned by atan2 into degrees (multiply the radians by approximately 57.29 or 360/2 π ).

Because the rabbit rotates and its position changes. So now calculate the new location of the rabbit and display it on the screen.

Run the game again. If you only press the "WASD" key, the game should be exactly the same as before, but if you move your mouse and rabbit, it will also rotate, cool!

Step 5: shooting, rabbit!

Now your rabbit can be moved freely. it's time to add more actions to it. How can a rabbit use a sword to fire an enemy? It's not just a gentle rabbit!

This step is a little complicated because you have to record all the shots at swords, update their positions, rotate them, and delete them after they fly out of the screen.

First, add the necessary variables at the end of the initialization section (#2:

acc=[0,0]arrows=[]

The first variable records the player's shooting precision, and the second variable records all the swords. The precision variable acc is actually a list containing the number of shots and the number of hits. Finally, we can use this information to calculate the percentage of precision.

Next, load the bow and arrow images at the end of section #3:

arrow = pygame.image.load("resources/images/bullet.png")

Now, when a player clicks the mouse, the bow and arrow will be shot. Add the following code to the end of section #8 as the new event handler ):

if event.type==pygame.MOUSEBUTTONDOWN:position=pygame.mouse.get_pos()acc[1]+=1arrows.append([math.atan2(position[1]-(playerpos1[1]+32),position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos1[1]+32])

These codes check whether there is a mouse click. if there is a mouse click, it will read the mouse position and calculate the bow and arrow rotation based on the player's rotation and pointer position. This rotation is stored in the arrows array.

Next, you need to draw a bow and arrow on the screen. Insert the following code after section #6.1:

# 6.2 - Draw arrowsfor bullet in arrows:index=0velx=math.cos(bullet[0])*10vely=math.sin(bullet[0])*10bullet[1]+=velxbullet[2]+=velyif bullet[1]<-64 or bullet[1]>640 or bullet[2]<-64 or bullet[2]>480:arrows.pop(index)index+=1for projectile in arrows:arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29)screen.blit(arrow1, (projectile[1], projectile[2]))

The basic trigonometric functions can be used to calculate vely and velx. 10 is the bow speed. The if statement checks whether the bow and arrow fly out of the boundary. if yes, delete the bow and arrow. The second for statement loops through the arrows array and draws the corresponding rotation arrow.

Try running the program. You should have a rabbit launch a bow and arrow when you click the mouse. (。☉。)

Step 6: pick up the weapon! Badger!

Okay, you have a castle and a hero who can move and shoot. But what is missing? Attack the enemy of the castle!

(Blow up your castle !)

In this step, you will create several badges that are randomly generated and run to the castle. As the game progresses, there will be more and more badges. So, let's make a list to see what needs to be done.

1. add bad guys to an array list;

2. update the array for each frame and check whether they are on the screen;

3. show these bad guys.

It's easy, right? :]

First, add the following code to section #2:

badtimer=100badtimer1=0badguys=[[640,100]]healthvalue=194

The above code sets a timer (and other values) so that a new badger is added to the game every time. You reduce the badtimer of each frame until 0, and then generate a new badger.

Add the following code to section #3:

badguyimg1 = pygame.image.load("resources/images/badguy.png")badguyimg=badguyimg1

The first line of the above code is similar to the loading code of all the previous images. The second line of code sets a copy of the image so that the bad guy can be more easily moved.

Next, you must update and display this bad guy. Add the following code to section #6.2:

# 6.3 - Draw badgersif badtimer==0:badguys.append([640, random.randint(50,430)])badtimer=100-(badtimer1*2)if badtimer1>=35:badtimer1=35else:badtimer1+=5index=0for badguy in badguys:if badguy[0]<-64:badguys.pop(index)badguy[0]-=7index+=1for badguy in badguys:screen.blit(badguyimg, badguy)

Take a closer look at this code:] The first line checks whether badtimer is 0. based on the number of times badtimer has been running so far, create a new badtimer and set it again. The first for loop updates the X coordinate of the badger and checks whether it is on the screen. If it is no longer on the screen, it will be deleted. The second Buddha draws all badges in a loop.

To use random functions in the above code, we must introduce the random library:

import random

Finally, add the following code after the while Statement to reduce the badtimer value by 1:

badtimer-=1

Run the game again to test the above code. now you will see the real game. you can launch, move, and turn, and the Badger tries to run to you.

But wait. Why didn't the badger blow up the castle? Get it done now!

In section #6.3, add the following code before index + = 1 before each loop:

# 6.3.1 - Attack castlebadrect=pygame.Rect(badguyimg.get_rect())badrect.top=badguy[1]badrect.left=badguy[0]if badrect.left<64:healthvalue -= random.randint(5,20)badguys.pop(index)# 6.3.3 - Next bad guy

This code is very simple. if the x coordinate value of the badger is smaller than 64, delete this guy and randomly decrease the castle life value between 5 and 20. (You can display the life value to the screen later)

Now that you build and run the program, you will see a bunch of badges attacking the castle and then disappear. Although you can't see it, Badger actually lowered the castle's life.

Step 7: The collision between the badger and the Arrow

Now, badges can attack your castle, but your arrows have no effect on them! How can rabbits protect their homes?

It's time for an arrow to kill the badger so that you can protect your castle and win the game! First, you must check every bad guy cyclically. during the check, you must cyclically check whether all arrows are in conflict with the badger. If an arrow hits a badger, delete the arrow and Badger and increase the hit value.

Add the following code after section #6.3.1:

#6.3.2 - Check for collisionsindex1=0for bullet in arrows:bullrect=pygame.Rect(arrow.get_rect())bullrect.left=bullet[1]bullrect.top=bullet[2]if badrect.colliderect(bullrect):acc[0]+=1badguys.pop(index)arrows.pop(index1)index1+=1

Note that the if statement is a built-in function of PyGame to check whether two rectangles are intersecting. Other statements are only run as described above.

If you run the program now, you will find that you can shoot and kill the badger.

Step 8: add the lifecycle and clock display

The game is now in good progress, with attackers and defenders. Now you still need to display scores to see how these rabbits are doing.

The simplest way is to add a HUD (flat display) to display the health status of the current castle. You can also add a clock to show how long the castle has been protected.

First, add the clock and add the following code before section #7:

# 6.4 - Draw clockfont = pygame.font.Font(None, 24)survivedtext = font.render(str((90000-pygame.time.get_ticks())/60000)+":"+str((90000-pygame.time.get_ticks())/1000%60).zfill(2), True, (0,0,0))textRect = survivedtext.get_rect()textRect.topright=[635,5]screen.blit(survivedtext, textRect)

The code above simply uses the default PyGame font to create a font and set the size to 24. Then use the font to render the time to the surface. Then Guangxi is located and drawn to the screen.

Next, add a lifecycle. You need to load the background image of a lifecycle before creating it. Add the following code to the end of section #3:

healthbar = pygame.image.load("resources/images/healthbar.png")health = pygame.image.load("resources/images/health.png")

The first is the red graph used to fill the lifecycle. The second Green chart shows the current life value.

Now add the following code to section #6.4 (which you added in the previous step) and draw the lifecycle to the screen:

# 6.5 - Draw health barscreen.blit(healthbar, (5,5))for health1 in range(healthvalue):screen.blit(health, (health1+8,8))

The above code first draws a full red life bar, and then draws a green life bar based on the remaining life of the castle.

Now that you build and run the program, you can see the clock and lifecycle.

Step 9: determine whether to win or lose

What is this? If you have been playing for a long time, even if your command value drops to 0, the game continues! More than that, you can continue shooting badgers. This should not work, but now it is. You need to add a certain type of win/lose scenario to make the game worthwhile.

Therefore, we now add the winning and losing conditions and their respective pictures. You can exit the main game loop and enter the cycle on the win-or-lose page. In the win-or-lose cycle, you can check whether the user has lost or won, and display the corresponding interface.

The following is a basic method to determine whether to win or lose:

If the time exceeds (90000 MS or 90 s ):

  • Stop running the game


  • Set the game result to win

If the castle is destroyed:

  • Stop running the game


  • Set the game result to lost

The method for calculating the accuracy.

Note: Using acc [0] * 1.0 only converts acc [0] to float floating point type, the division operation returns an integer such as 1 or 2 instead of 1.5.

Add the following code to the end of game. py:

    #10 - Win/Lose check    if pygame.time.get_ticks()>=90000:        running=0        exitcode=1    if healthvalue<=0:        running=0        exitcode=0    if acc[1]!=0:        accuracy=acc[0]*1.0/acc[1]*100    else:        accuracy=0# 11 - Win/lose display        if exitcode==0:    pygame.font.init()    font = pygame.font.Font(None, 24)    text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0))    textRect = text.get_rect()    textRect.centerx = screen.get_rect().centerx    textRect.centery = screen.get_rect().centery+24    screen.blit(gameover, (0,0))    screen.blit(text, textRect)else:    pygame.font.init()    font = pygame.font.Font(None, 24)    text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0))    textRect = text.get_rect()    textRect.centerx = screen.get_rect().centerx    textRect.centery = screen.get_rect().centery+24    screen.blit(youwin, (0,0))    screen.blit(text, textRect)while 1:    for event in pygame.event.get():        if event.type == pygame.QUIT:            pygame.quit()            exit(0)    pygame.display.flip()

This is the longest code block as of now, but it is not the most complex.

The first if statement checks whether the time is up, the second checks whether the castle is destroyed, and the third calculates your accuracy. Then, a quick if statement checks whether you have succeeded or failed, and displays the correct image.

Of course, if you want to display screen images of victory and failure, these images must be loaded first. Add the following code to the end of #3:

gameover = pygame.image.load("resources/images/gameover.png")youwin = pygame.image.load("resources/images/youwin.png")

Another point: Change #4:

# 4 - keep looping throughwhile 1:    badtimer-=1

Changed:

# 4 - keep looping throughrunning = 1exitcode = 0while running:    badtimer-=1

The running variable tracks whether the game is over. The exitcode variable tracks whether the player wins or loses.

Run the game again. now you can try to win or die! Cool! :]

Step 2: free music and sound effects!

This game looks pretty good, but is there sound? Is it too quiet? Adding a little bit of sound will make the entire game feel better.

PyGame is easy to load and play sound. First, you need to initialize the mixer. the code is as follows:

pygame.mixer.init()

Load the sound to be played and set the volume:

# 3.1 - Load audiohit = pygame.mixer.Sound("resources/audio/explode.wav")enemy = pygame.mixer.Sound("resources/audio/enemy.wav")shoot = pygame.mixer.Sound("resources/audio/shoot.wav")hit.set_volume(0.05)enemy.set_volume(0.05)shoot.set_volume(0.05)pygame.mixer.music.load('resources/audio/moonlight.wav')pygame.mixer.music.play(-1, 0.0)pygame.mixer.music.set_volume(0.25)

Most of the code above is simple loading of audio files and the configured audio volume, but pay attention to pygame. mixer. music. load this line-this line loads the background music of the game, and the next line sets the background music to be repeated all the time.

Pay attention to audio configuration. :] Now, all you need to do is play all kinds of sound effects as needed. Perform the following operations as per the annotation code below:

# section 6.3.1 after if badrect.left<64:hit.play()# section 6.3.2 after if badrect.colliderect(bullrect):enemy.play()# section 8, after if event.type==pygame.MOUSEBUTTONDOWN:shoot.play()

When you run the game multiple times, you will find that you have a collision of background music and shooting sound effects. The game makes people feel more realistic! :]

Where to start?

You should be proud of yourself: you have just created an interesting game that is filled with music, sound effects, a killer rabbit, a fantastic attacking team, and more. I told you can do it! :]

You can download the final game source code here.

In this case, expand your creativity in the game at will! Maybe you can try to change to your own painting style, or add different weapons or different types of monsters to the game!

Do you have any questions or comments after completing this tutorial? If so, join our forum! I look forward to hearing from you.

Original article address: beginning-game-programming-for-teens-with-python

The above describes how to develop a game using Python. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.