Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python to make Mini Game

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

How to use Python to do Mini Game, I believe that many inexperienced people do not know what to do, so this paper summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

Have you ever thought about how computer games are made? In fact, it is not as complicated as you think!

In this tutorial, you will learn to do a tower defense game called "Rabbit and Badger". As a hero, rabbits need to resist badger attacks in the castle.

To write the code for this game, you will use Python. Well, I'm not talking about a boa constrictor!

Python is a computer language. We chose Python in this tutorial because the language is easy to use, easy to learn and fun to learn.

If you are new to Python, you can read the book Think Python: How to Think Like a Computer Scientist before you start reading the tutorials. This will make it easier for you to read the tutorial.

Come back here after reading that book and get ready-there is a big war between the rabbit and the badger. Join us in this battle!

Getting started: installing Python

If you want to try what is covered in this tutorial on Windows PC, you need to install Python. Make sure you install version 2.7.3, not version 3.3.0! After the installer has run, there will be IDLE in "all programs" of the start button. Start IDLE first.

If you are using Mac, it already has Python installed on it! Open the terminal, type python, and then press enter

Note: if you installed the installation package downloaded from python.org, you can also start IDLE on Mac. It should be in the / Application/Python2.7 folder.

If you follow the steps above, you can see what you can see:

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 darwin Type "help", "copyright", "credits" or "license" for more information. > > >

Note: if you want to terminate Python quickly, you can type exit () and press enter, or press Control+D.

Now that the Python environment is configured very quickly, in order to test whether Python is working properly, type print 1 and press enter, 2 should be printed. You just wrote a simple Python program!

So, now that you know that Python is working properly, in order to write a game in Python, you need to install PyGame.

PyGame is a Python library that makes it easier for you to write a game. The features it provides include image processing and sound playback, and they can be easily integrated into your game.

Click here to download the PyGame installation package that suits you. Make sure you download the library for version 2.7.

Note: the PyGame installation package downloaded from the above link does not work with the Python installed on Mac. You need to download a Python installation package from python.org to use PyGame. Alternatively, you can use MacPorts to make your Python and PyGame work properly.

To determine if PyGame is installed, open IELD or run Python in the terminal, then type import pygame and enter. If no output is printed, there is no problem.

However, if the output from the following figure is typed, then PyGame is not installed.

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

If you find such an error and post the error to the forum, I will help you get it up and running.

Run the Python code in the file

Now that you can write some code in the Python shortcut terminal, if you want to write a larger program (such as a game), you need to save the code to a file.

There are several ways to run the Python code in a file. One way to do this is to use a simple text editor, such as nodepad on Windows or TextEdit on Mac. Open a new text file and enter the Python code (for example, print 1. 1). Then save it as XXX.py. (XXX represents file name)

On Windows, double-click the py file to run it. On Mac, open the terminal and type python, then drag the code file to the terminal and press enter.

Another way to run code is to use the IDLE editor, which is the main method used in this tutorial. To run IDLE, type idle in the terminal, select New text from the menu, and then use this text editor to write Python code. You can save the file through File/Save and run the code by clicking Run/Run (F5).

Note that the running menu is not available until the file is opened in the editor.

Add game resources

You are now basically ready to create a game. But which game doesn't have great images and sound effects? I saved the images and audio and video needed in the game in the zip file, click here to download.

After downloading the file, create a folder for the game, then extract the compressed file into a subfolder of this folder and name it resources, as shown below:

We can start the game of rabbit and badger now!

Step one: Hello, Rabbit.

Run IDLE to open a new text editing window. Enter the following code:

# 1-Import library import pygame from pygame.locals import * # 2-Initialize the game pygame.init () width, height = 640,480 screen=pygame.display.set_mode ((width, height)) # 3-Load images player = pygame.image.load ("resources/images/dude.png") # 4-keep looping through while 1: # 5-clear the screen before drawing it again screen.fill (0) # 6-draw the screen elements screen.blit (player (100100) # 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 the file to your game folder and name it game.py. Now let's take a look at what this code does:

Import the pygame library, which allows you to use the features provided in the library

Initialize pygame and set up the display window

Load a picture as a rabbit

Loop through the rest of the process

Fill in black before drawing anything on the screen

Add the rabbit picture you loaded at the (100100) coordinates of the screen

Update screen

Check for some new events and terminate the execution of the program if there is an exit command.

After running this code, you will see the following screen:

You can see a rabbit here, ready to fight!

But for the time being, the rabbit looks very lonely, and it is the only one in the background. Now is the time to take it a step further.

Step 2: add background

Let's now add some scenery to the background of the game. This can be achieved through some calls to screen.blit ().

At the end of # 3, after adding the player image, add the following code:

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

This code loads the pictures and puts them in variables. Now they need to be painted on the screen. But when you check the picture of the grass, you find that it will not cover the entire screen, its resolution is 640 x 480.

Add # 6 code to game.py:

For x in range (width/grass.get_width () + 1): for y in range (height/grass.get_height () + 1): screen.blit (grass, (Xerox 100)) screen.blit (castle, (0Mae 30)) screen.blit (castle, (0135)) screen.blit (castle, (0240)) screen.blit (castle, (0345))

As you can see, this code first loops through x in turn. It is another loop that passes through y in turn and draws the grass effect according to the values of x and y in the loop. The next few lines are to draw the castle on the screen.

If you run your code now, the effect should look like this:

Much better-- it's starting to look good now!

Step 3: let the rabbit move

Next you need to add some real game elements, such as allowing the rabbit to move along with the button.

To do this, first, you need to implement a method to record which key is pressed at a certain time. You can create a new queue of keystrokes to store every keystroke you want to use in the game.

Add the following code to game.py after # 2:

Keys = [False, False] playerpos= [100100]

This code is self-evident, the key queue is used to record a few keystrokes: WASD. Each item in the queue corresponds to a button-the first corresponds to W, the second corresponds to A, and so on.

The variable playerpos indicates that the program draws the location of the player. Because the game will make the player move in different directions, it is very appropriate to use a variable to represent the player's position and to be able to draw the player according to this variable.

Now you need to modify the current drawing player's code, you need to use the playerpos variable. Modify the code in part # 6:

From

Screen.blit (player, (100100))

Change it to:

Screen.blit (player, playerpos)

Next, update the keystroke record array according to the key pressed. PyGame detects keystrokes by adding events to them.

At the end of August, just after event.py = = pygame.QUIT, add the following code (indented at the same level as pygame.QUIT):

If event.type = = pygame.KEYDOWN: if event.key==K_w: keys [0] = True elif event.key==K_a: keys [1] = True elif event.key==K_s: keys [2] = True elif event.key==K_d: keys [3] = True if event.type = = pygame.KEYUP: if event.key==pygame.K_w: keys [0] = False elif event.key==pygame.K_a : keys [1] = False elif event.key==pygame.K_s: keys [2] = False elif event.key==pygame.K_d: keys [3] = False

Wow! With so much code added. But if you take a closer look at these expressions, they're not that complicated.

First, you check to see if a key is pressed or released. Then, check which key is pressed or released, and if the key is pressed or released by you, you update the variable of the record key.

Eventually, you need to update the playerpos variable as a response to the keystroke. This is actually very simple.

Add the following code to the end of the game.py: (keep it at the same level as the for loop)

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

This code simply checks which key is pressed, and then increases or decreases the player's x and y coordinates.

Run this game, then you should see the following screen. Try to press WASD, yeah! It works!

Step 4: turn the rabbit

OK, now your rabbit can move when you press the button, but wouldn't it be cooler if you could use the mouse to point the rabbit in the direction you chose? So it doesn't always face in one direction. It would be very easy to implement it with the trigonometric theorem.

Take a look at the following illustration:

In the image above, if (5) is the position of the rabbit and (2) is the position of the mouse, you can use the trigonometric theorem to figure out the angle you need to rotate. Then, after you know the angle of rotation, you can rotate your rabbit.

If you're a little confused about this part, don't worry-it doesn't matter. But that's why you need to concentrate in math class. It will be used in game programming.

Now, you need to accept the concepts in your game. To do this, you can use the PyGame Surface.rotate (degrees) function.

The atatn2 function is from the math library of Python. So add the following code to part # 1:

Import math

Then, replace the last line of part # 6 with the following code:

# 6.1-Set player position and rotation position = 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 look at the basic structure of the above code. First of all, get the mouse and the player's position. Then use them with the atan2 function. Then, get the angle and radians obtained by the atan2 function.

When the rabbit is rotated, its position will change. So you need to calculate the new location of the rabbit and display it on the screen.

Run the game again, and if you just press the WASD keys, the game will be the same as before. But if you move the mouse, the rabbit starts to rotate, which is pretty cool!

Step 5: shoot! Rabbit

Now that your rabbit can move around, it's time to add more features. How about rabbits shooting arrows at their enemies?

This step can be a little complicated because you need to track all the arrows, update them, rotate them, and delete them as they run off the screen.

First, add the necessary variable declaration to the part of the # 2 declaration.

Acc= [0,0] arrows= []

The first variable tracks the player's precision, and the second variable tracks the arrowhead. This precision variable is essentially a list of numbers, recording the number of arrows fired and the number of badgers hit. Then we will use this information to calculate the shooting accuracy.

Next, load the picture of the arrow at the end of part # 3.

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

Now, when the player clicks the mouse, he needs to shoot an arrow. Add the following code to section # 8:

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

This code will check whether the mouse has been clicked, and if so, it will get the position of the mouse and calculate the rotation angle of the arrow based on the position of the player and the cursor. The value of the rotation angle is stored in the arrows array.

Next, you need to actually draw arrows on the screen. Add the following code to section # 6:

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

The values of vely and velx are calculated according to the trigonometric theorem. 10 is the speed of the arrow. The if expression checks to see if the arrow is out of range of the screen, and if so, removes the arrow. The second for expression is a loop to draw the arrowhead according to the corresponding rotation.

Try to run the game. When you click the mouse, your rabbit can shoot a haircut: d

Step 6: badger, get your weapon!

Well, now there's a castle, and you have a hero who can move and shoot arrows. What else is missing? Enemies who attack the castle can be shot with arrows by heroes!

In this step, you will randomly create some badgers to rush to the castle. More and more badgers will emerge in the course of the game. So, let's make a list of things to do next.

Add a list of bad guys

Update the bad guys' information and check to see if they are out of the screen.

Show these bad guys.

The first step is to add the following code to part # 2:

Badtimer=100 badtimer1=0 badguys= [[640100]] healthvalue=194

A timer is defined in the above code so that the game can create a new badger after a period of time.

Add the following code at the end of section # 3:

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

The first line is similar to the previous code that loaded the picture. The second line declares a copy of the image.

Next, you need to update and show these bad guys. Add the following code to the # 6.2 section:

# 6.3-Draw badgers if badtimer==0: badguys.append ([640, random.randint (50430)]) badtimer=100- (badtimer1*2) if badtimer1 > = 35: badtimer1=35 else: badtimer1+=5 index=0 for badguy in badguys: if badguy [0]

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report