程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Hundreds of lines of Python code developed the game. It turns out that Python can be so powerful!

編輯:Python

Hello everyone , I am a Jiejie. Today I'd like to introduce you to a small project , A game that can be developed with only 100 lines of code

install pygame

Download the corresponding python Version of pygame Run the following command

establish Pygame Window and response to user input

Create a new folder alien_invasion, And create a new alien_invasion.py file , Enter the following code .

Run the above code , We can get a window with a gray interface :

Create settings class

In order to create some new functions conveniently in the process of writing games , Here's an extra settings modular , There is one Settings class , Used to store all settings in one place . In this way, it will be easier to modify the appearance of the game when the project increases in the future .

Let's start with alien_invasion.py The display screen size and color of the display screen in .

First, in the alien_invasion New under folder python file settings.py, And add the following code to it

And then in alien_invasion.py Import Settings class , And use the relevant settings , Revised as follows :

Add ship image

Next , We need to add spaceships to the game . In order to draw the player's ship on the screen , We're going to load an image , Reuse Pygame() Method blit() Draw it .

Almost all kinds of image files can be used in the game , But using bitmaps (.bmp) The file is the simplest , This is because Pygame Load bitmap by default .

Although other types of images can also be loaded , But additional libraries need to be installed .

We recommend looking for images on the free image material website :https://pixabay.com/

We're in the main project folder (alien_invasion) Create a new folder called images, Will be as follows bmp Put the picture in it .

Next , We create the spaceship class ship.py:

restructure : modular game_functions

In large projects , It is often necessary to refactor existing code before adding new code . The purpose of refactoring is to simplify the structure of the code , Make it easier to scale .

We will achieve a game_functions modular , It's going to store a lot of games Alien invasion Running functions . By creating modules game_functions, Avoidable alien_invasion.py Too long , Make the logic easier to understand .

function check_events()

First, we'll move the code for managing events to a place called check_events() The function of , The purpose is to isolate the event loop

And then we modify it alien_invasion.py Code , Import game_functions modular , And replace the event loop with a function check_events() Call to :

function update_screen()

Move the code that updates the screen to a file named update_screen() Function , And put this function in the module game_functions in :

among alien_invasion Revised as follows :

Go down from the above process , We found that : In the actual development process , We started by writing the code as simple as possible , And refactor as the project becomes more and more complex . Next, let's deal with the dynamic aspects of the game .

Fly the ship

What we want to achieve here is to make the player control the left and right movement of the spacecraft through the left and right arrow keys .

Response button

Because in pygame in , Each key is registered as KEYDOWN event , stay check_events() in , We go through event.type detected KEYDOWN After the event, it is necessary to further judge which button it is . The code is as follows :

Allow constant movement

When the player holds down the right arrow , We want the ship to move constantly , Until the player releases . Here we go through KETUO Events . So we set a flag bit moving_right To achieve continuous mobility . The principle is as follows :

When the ship doesn't move , sign moving_right Will be for false. When the player presses the right arrow , We set this flag to True; When the player releases , We reset the flag to False.

This movement attribute is a kind of spaceship attribute , We use it ship Class to control , So we add an attribute name to this class called ,moving_right And one. update() Method to detect the flag moving_right The state of .

ship

game_functions

Last in alien_invasion Call in update() Method

Or so mobile

Previously, we realized moving to the right , Next, move to the left , Logical analogous , The code is not posted .

Adjust the speed of the ship

At present , Every time you execute while loop , The spacecraft can move up to one pixel , We can do it in Settings Add ship_speed_factor, Used to control the speed of the spacecraft . Based on this property, we will determine the maximum distance the spacecraft can move in each cycle .

Settings:

Ship:

Limit the range of the spacecraft

If the player holds down the arrow for too long , The ship will disappear , So how to make the spacecraft stop moving when it reaches the edge of the screen ? Here we just need to modify Ship Class update Method , Add a logical judgment .

restructure

Here we mainly talk about check_events() Function , Divide some of the code into two parts , Part of the process KEYDOWN event , Part of the process KEYUP event .

game_functions:

Shooting

Next, add shooting function , Make players fire bullets when they press the spacebar , The bullet will travel up the screen , When you reach the screen, it disappears .

Add bullet settings

stay Settings Add some bullet attributes to the class , Here we create a wide 3 Pixels , high 15 Pixel dark gray bullet . The speed of the bullet is slightly lower than that of the ship .

establish Bullet class

Store bullets in group in

We defined Bullet Class and necessary settings , You can write code , Every time the player presses the spacebar, a bullet will be fired .

First , We are alien_invasion Create a group, Used to store all valid bullets .

FireStarter

Here we modify check_keydown_events() function , To monitor the event that players press the space bar . It needs to be modified here update_screen() function , Make sure that every time the screen is updated , Can redraw every bullet .

Let's look at the effect :

Delete the missing bullet

stay alien_invasion Delete the missing bullet .

Limit the number of bullets

In order to encourage players to shoot with goals , We stipulate that there can only be... On the screen at the same time 3 Bullet , We just need to check whether the number of bullets that have not disappeared is less than... Before each bullet creation 3 that will do .

establish update_bullets() function

In order to make alien_invasion The code in is simpler , We'll check the bullet management code , Move to game_functions Module :

establish fire_bullet() function

Here we move the code for firing bullets into a separate function :

Add aliens , And detect collisions

Before we finish our new task , Let's first add a shortcut to the game to end the game Q:

Create the first alien

It's the same way to create a spaceship

Create a group of aliens

Here, we first determine how many aliens a line can hold and how many lines to draw . There are many code changes here , See the effect directly :

Mobile aliens

What we created earlier is a static Alien , Now we need to get the aliens moving . Here we are Settings Class to set the speed of alien movement , And then through Alien Class update Methods to achieve mobile

Shoot aliens

To shoot aliens , You must first detect whether there is a collision between two group members , In the game , Collision is the overlapping of game elements .

Here we use sprite.groupcollide() To detect collisions between members of two groups .

When a bullet hits an alien , Need to know immediately , And at the same time make the collided aliens disappear immediately , Therefore, we need to detect the collision immediately after updating the bullet position .

End the game

Here we also need to know when to end the game , There are several situations :

All the ships were destroyed

Aliens reach the bottom of the screen

The actual effect :

scoring

Finally, we will add a to the game Play Button , Used to start the game as needed and restart the game after the game is over .

We will also implement a scoring system , Can speed up the pace when the player's level increases .

add to Play Button

Here you can initialize the game to an inactive state , When we hit the button , Start the game .

because Pygame There is no built-in method to create buttons in . So we can create a Button Class to create a solid rectangle with its own label .

We determine whether a click event has occurred by detecting whether the coordinates of the mouse click collide with the buttons we draw .

Raise grade

In order to make the player eliminate the enemy and improve the difficulty of the game , Add fun , Here we can go to Settings Class , Increase the static initial value , Dynamic initial value .

Score 、 Grade 、 Remaining spacecraft

Pack it up exe Executable file

In this way, the above game development is completed !!

Small partners with strong hands-on ability can try to do it by themselves , You can write to me “ game ” Get the complete source code


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved