Hi, I’m Jiejie. Today I’m going to introduce you to a small project that can be developed in a hundred lines of code
Install pygame
Download the corresponding Python version of PyGame and run the following command
Create a Pygame window and respond to user input
Create a new folder alien_invasion and create a new alien_invasion.
Running the code above, we get a gray window:
Creating a Settings class
To make it easy to create new features while writing the game, we’ll write an additional Settings module that contains a Settings class to store all Settings in one place. This makes it easier to change the look of the game later when the project gets bigger.
We first modified the size and color of the display in alien_invastion. py.
First create a New Python file settings.py under the alien_invasion folder and add the following code to it
Then import the Settings class in alien_invastion. py and use the relevant Settings as follows:
Add ship image
Next, we need to add ships to the game. To draw the player’s ship on the screen, we will load an image and draw it using the Pygame() method blit().
Almost any type of image file can be used in a game, but bitmap (.bmp) files are the easiest because Pygame loads bitmaps by default.
Although other types of images can be loaded, additional libraries need to be installed.
We recommend going to pixabay.com/, a free source site for images
We created a folder called images in the main project folder (alien_invasion) and put the following BMP images into it.
Next, we create the ship class ship.py:
Refactoring: module 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 and make it easier to extend.
We’ll implement a game_functions module that will store a large number of functions for the game Alien Invasion to run. By creating the module game_functions, you can avoid alien_invastion. py being too long and make the logic easier to understand.
Function check_events ()
First we move the code for managing events into a function called check_events() to isolate the event loop
Then we modify the alien_invasion. Py code to import the game_functions module and replace the event loop with a call to the function check_events() :
Function update_screen ()
Move the code to update the screen into a function called update_screen() and place this function in the module game_functions:
Alien_invasion is modified as follows:
Following the above process, we found that in actual development, we started as simple as possible and refactored as the project got more complex. Let’s move on to the dynamic aspects of the game.
Driving the spacecraft
What we want to achieve here is to allow the player to use the left and right arrow keys to control the ship to move left and right.
The response buttons
In PyGame, each keystroke is registered as a KEYDOWN event. In check_Events (), we need to determine which keystroke is the KEYDOWN event detected by event.type. The code is as follows:
Allow constant movement
When the player holds down the right arrow, we want the ship to keep moving until the player releases it. Here we judge by the KETUO incident. So we set a flag bit moving_right to keep moving. The principle is as follows:
When the ship is not moving, the flag moving_right will be false. We set this flag to True when the player presses the right arrow; When the player releases, we reset the flag to False.
The movement property is one of the ship properties, and we use the ship class to control it, so we add a property called moving_right and an update() method to check the status of the flag moving_right.
ship
game_functions
Finally, call the update() method in alien_invasion
Or so mobile
We did move to the right, then we did move to the left, similar logic, so the code won’t stick.
Adjust the speed of the ship
Currently, the ship moves at most one pixel each time we execute the while loop, and we can add ship_speed_factor to the Settings to control the ship’s speed. We will use this property to determine the maximum distance the ship can travel per cycle.
Settings:
The Ship:
Limit the ship’s range of movement
If the player holds down the arrow too long and the ship disappears, how do you stop the ship when it reaches the edge of the screen? Here we just need to modify the UPDATE method in the Ship class to add a logical judgment.
refactoring
The check_events() function is refactored into two parts, one that handles KEYDOWN events and one that handles KEYUP events.
game_functions:
shooting
Next, add a shooting feature that lets the player hit the space bar and fire a bullet, which will travel up the screen and disappear when it reaches the screen.
Add bullet Settings
Add some bullet properties to the Settings class. Here we create a dark gray bullet that is 3 pixels wide and 15 pixels high. The bullet is traveling slightly slower than the ship.
Create a Bullet class
Store bullets in the group
Once you’ve defined the Bullet class and the necessary Settings, you can write code that fires a Bullet every time the player presses the space bar.
First, we created a group in alien_invasion to store all valid bullets.
fire
Here we modify the check_keydown_events() function to listen for events when the player presses the space bar. You also need to modify the update_screen() function to ensure that each bullet is redrawn every time the screen is updated.
Let’s take a look at the effect:
Remove missing bullets
Remove missing bullets in alien_invasion.
Limit the number of bullets
To encourage targeted shooting, we limited the number of bullets on the screen to three at a time, and we only needed to check that the number of bullets that did not disappear was less than three before each bullet creation.
Create the update_Bullets () function
To make the code in alien_invasion simpler, we moved the code that checks for bullet management into the game_functions module:
Create the fire_bullet() function
Here we move the bullet firing code into a separate function:
Add aliens and detect collisions
Before we complete the new mission, let’s add an end game shortcut Q:
Create the first alien
It’s the same thing as building a spaceship
Create a group of aliens
Here we first determine how many aliens can fit in a row and how many rows to draw. Here changes the code more, directly see the effect:
Mobile alien
Previously we created static aliens, now we need to get the aliens moving. Here we set the speed at which the Alien moves in the Settings class, and then use the Update method in the Alien class to move
Shooting aliens
In order to shoot an alien, two crew members must first be detected for collisions, which in the game is when game elements overlap.
Here we use sprite.groupCollide () to check for collisions between the members of two groups.
When a bullet hits an alien, it needs to be known immediately, and the alien being hit will disappear immediately, so we need to detect the collision as soon as we update the bullet’s location.
End of the game
Here we also need to know when to end the game, in the following cases:
The ship was destroyed
Aliens arrive at the bottom of the screen
Actual effect:
The scoring
Finally, we will add a Play button to the game, which can be used to start the game on demand and restart the game when it is finished.
We will also implement a scoring system to speed up the pace as the player levels up.
Add Play button
Here we can initialize the game to be inactive, and when we click the button, the game starts.
There is no built-in way to create buttons in Pygame. So we can create a solid rectangle with a label by creating a Button class.
We determine whether a click event has occurred by detecting whether the coordinates after the mouse click collide with the button we draw.
Improve the level of
In order to make the game more difficult and interesting after the player has eliminated the enemies, we can change the Settings class to add static initials and dynamic initials.
Score, rank, remaining ships
Package as an exe executable file
So above game development finished!!
Hands-on ability of small partners can try to do oh, you can private message my “game” to obtain the complete source oh